栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot cache的使用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot cache的使用

springboot cache的使用 1.开始使用前需要导入依赖
   
    org.springframework.boot    
    spring-boot-starter-cache     

2.然后在启动类注解@EnableCaching开启缓存
@SpringBootApplication
@EnableCaching  //开启缓存
public class DemoApplication{
 
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
 
}
3.缓存@Cacheable

实现效果第一次访问查询数据库,第二次刷新就不会再查询数据库了

@Cacheable注解会先查询是否已经有缓存,有会使用缓存,没有则会执行方法并缓存。

//有参数就加上+#p0 没参数就不要加
@Cacheable(value = "emp" ,key = "targetClass + methodName +#p0")
public List queryAll(User uid) {
    return newJobDao.findAllByUid(uid);
}


@GetMapping("/file/front/all")
@Cacheable(value = "files" ,key = "targetClass + methodName")
public Result frontAll(){
    return Result.success(fileMapper.selectList(null));
}


@Cacheable(value = "files" ,key = "'frontAll'")

此处的value是必需的,它指定了你的缓存存放在哪块命名空间。

//注意
使用方法参数时我们可以直接使用“#参数名”或者“#p参数index”。 如:
@Cacheable(value="users", key="#id")
@Cacheable(value="users", key="#p0")
缓存的一个问题

数据删除或更新 缓存没有及时的改变

解决方法

    //更新后清空缓存
    @CachePut(value = "files", key = "'frontAll'")  //注意key要和缓存的key一样
    @PostMapping("/update")  
    public Result updata(@RequestBody Files files) {
            return  Result.success(fileMapper.selectList(null));
        }
    }


 //清除一条缓存,key为要清空的数据
    @CacheEvict(value="emp",key="'frontAll'")
	@DeleteMapping("/{id}")
    public void delect(@PathVariable int id) {
        newJobDao.deleteAllById(id);
    }
 
    //方法调用后清空所有缓存
    @CacheEvict(value="accountCache",allEntries=true)
    public void delectAll() {
        newJobDao.deleteAll();
    }
 
    //方法调用前清空所有缓存
    @CacheEvict(value="accountCache",beforeInvocation=true)
    public void delectAll() {
        newJobDao.deleteAll();
    }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1036596.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号