springboot cache的使用

springboot cache的使用

1.开始使用前需要导入依赖

<dependency>   
    <groupId>org.springframework.boot</groupId>    
    <artifactId>spring-boot-starter-cache</artifactId>     
</dependency>

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<NewJob> 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();
    }

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值