Redis

关注公众号 jb51net

关闭
首页 > 数据库 > Redis > redis的Cacheable注解

redis的Cacheable注解使用及说明

作者:我曾遇到一束光

文章介绍了如何在Java应用中使用Spring的@Cacheable注解进行缓存配置,包括注解的使用、key的生成方式、触发条件(condition)和排除条件(unless)的设置,并强调了缓存的持久性和清除机制

引入依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <version>2.1.1.RELEASE</version>
</dependency>

导入的使用较多的2.1.1依赖,版本过高可能会导致找不到加载类.

添加注解

主类中中加入注解@EnableCaching,

然后就可以在方法或者类上边使用@Cacheable

value

key

keyGenerator

@Component("myKeyGenerator")
public class MyKeyGenerator implements KeyGenerator {
    @Override
    public Object generate(Object target, Method method, Object... params) {
        return "method.getName()" + "["+ Arrays.asList(params).toString()+"]";
    }
}
@Cacheable(value ="provinceCount",keyGenerator = "myKeyGenerator",sync = true)

condition

unless

注意点

使用@Cacheable生成的缓存是不会清除的,同时当redis中已经存在相同的key时,@Cacheable默认不生成缓存

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文