springboot使用@EnableCaching,@CacheConfig,@Cacheable,@CachePut,@CacheEvict

spring自带了cache接口,@EnableCaching表示使用cache,我们通过覆盖CachingConfigurerSupport类的cacheManager方法指定用哪种缓存。例如ehcacherediscache
@Cacheable不要写在同一方法里面
@Cacheable不要写在同一方法里面,否则无效。例如写在controller里面无效,是因为 @Cacheable基于代理,同类方法直接调用,并没有用到代理,所以cache无效。
@CacheConfig 是类级别的注解,这里不详述
@Cacheable,@CachePut 的value就是作用的cache名称,返回值就是cache值。

RedisConfig代码:

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport{
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofHours(1)); // 设置缓存有效期一小时
        return RedisCacheManager
                .builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
                .cacheDefaults(redisCacheConfiguration).build();
    }
}

CacheServiceImpl代码:

@Service
public class CacheServiceImpl {
    @Cacheable(value="cache1")// cache1
    public int get() {
        int num = new Random().nextInt();
        return num;
    }
    @Cacheable(value="cache2")// cache2
    public int get2() {
        int num = new Random().nextInt();
        return num;
    }
    @CachePut(value={"cache1"})// 更新
    public int put() {
        return new Random().nextInt();
    }
    @CacheEvict(value={"cache1,cache2"})// 清空
    public void evict() {
    }
}

LoginController代码:

@RestController
@RequestMapping("")
public class LoginController {
    @Autowired
    private CacheServiceImpl cacheService;
    @RequestMapping("/login")
    public String login(HttpServletRequest request){
        int cache1 = cacheService.get();
        System.out.println(cache1);
        System.out.println(cacheService.get2());
        return "fail";
    }
    @RequestMapping("/put")
    public String put(HttpServletRequest request){
        cacheService.put();
        return "fail";
    }
    @RequestMapping("/evict")
    public String evict(HttpServletRequest request){
        cacheService.evict();
        return "fail";
    }
}

http://localhost:8080/login 刷新2次,发现2次值一样,说明缓存了
先 http://localhost:8080/put 然后 http://localhost:8080/login 发现 1的值变了
http://localhost:8080/evicthttp://localhost:8080/login 发现原来的值被清空了,都是新值

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值