首页 > 编程 > Java > 正文

Spring boot redis cache的key的使用方法

2019-11-26 09:01:50
字体:
来源:转载
供稿:网友

在数据库查询中我们往往会使用增加缓存来提高程序的性能,@Cacheable 可以方便的对数据库查询方法加缓存。本文主要来探究一下缓存使用的key。

搭建项目

数据库

mysql> select * from t_student;+----+--------+-------------+| id | name  | grade_class |+----+--------+-------------+| 1 | Simone | 3-2     |+----+--------+-------------+1 row in set (0.01 sec)

spring boot 配置

#jpaspring.jpa.hibernate.ddl-auto=nonespring.datasource.url=jdbc:mysql://127.0.0.1:3306/praticespring.datasource.username=rootspring.datasource.password=123456#redisspring.redis.host=localhostspring.redis.lettuce.pool.maxActive=5spring.redis.lettuce.pool.maxIdle=5#cachespring.cache.cache-names=Cachespring.cache.redis.time-to-live=300000

数据访问层

public interface StudentDao extends CrudRepository<Student, Long> {  @Cacheable(value = "Cache")  @Override  Optional<Student> findById(Long aLong);  @Cacheable(value = "Cache")  Optional<Student> findByName(String name);}

启动调用数据访问层方法观察

@Overridepublic void run(ApplicationArguments args) throws Exception { Optional<Student> optional = studentDao.findById(1L); System.out.println(optional);}

当默认使用 @Cacheable(value = "Cache") 的时候查看 redis 中缓存的 key

127.0.0.1:6379> keys *1) "Cache::1"

可以知道 key是由缓存的名字和参数值生成的,key 的生成和方法的名字无关,如果两个方法的参数相同了,就会命中同一个缓存,这样显然是不行的。使用相同的参数调用 findById 和 findByName 观察查询结果

@Overridepublic void run(ApplicationArguments args) throws Exception { Optional<Student> optional = studentDao.findById(1L); System.out.println(optional); Optional<Student> optionalByName = studentDao.findByName("1"); System.out.println(optionalByName);}//输出结果//Optional[Student(id=1, name=Simone, gradeClass=3-2)]//Optional[Student(id=1, name=Simone, gradeClass=3-2)]

从数据库的数据看 studentDao.findByName("1") 应该是查询出空的,但是取命中了缓存,所以我们需要给缓存的 key 加上方法的名字。

@Cacheable(value = "Cache", key = "{#root.methodName, #aLong}")@OverrideOptional<Student> findById(Long aLong);@Cacheable(value = "Cache", key = "{#root.methodName, #name}")Optional<Student> findByName(String name);//Optional[Student(id=1, name=Simone, gradeClass=3-2)] //Optional.empty

Redis 中的 Key 也有了方法的名字

127.0.0.1:6379> keys *1) "Cache::findById,1"2) "Cache::findByName,1"

在实际项目中我们肯定不是只有一张表,如果其他表使用缓存的名字也是 Cache,很有可能产生相同的 key,比如我还有一个如下的 dao

public interface TeacherDao extends CrudRepository<Teacher, Long> {  @Cacheable(value = "Cache", key = "{#root.methodName, #aLong}")  @Override  Optional<Teacher> findById(Long aLong);  @Cacheable(value = "Cache", key = "{#root.methodName, #name}")  Optional<Teacher> findByName(String name);}

如果在调用 TeacherDao 中的方法命中了 StudentDao 中的方法会产生 ClassCastException ,这里就两种方式来解决这个问题。第一种办法是每个 dao 中都使用不同的缓存名字。第二是给 key 加上类的名字。

我 google 了一下,没有找到使用 Spel 或取到类名的方法(或许有),所以这里通过配置 @Cacheable 的 key参数就不行了。那就只能实现自定义的生成器。

@Bean("customKeyGenerator")public KeyGenerator keyGenerator() { return new KeyGenerator() {  @Override  public Object generate(Object o, Method method, Object... objects) {   return method.getDeclaringClass().getName() + "_"    + method.getName() + "_"    + StringUtils.arrayToDelimitedString(objects, "_");  } };}

设置 @Cacheable 的 keyGenerator 参数

@Cacheable(value = "Cache", keyGenerator = "customKeyGenerator")@OverrideOptional<Student> findById(Long aLong);@Cacheable(value = "Cache", keyGenerator = "customKeyGenerator")Optional<Student> findByName(String name);

查看 Redis 中的 key

127.0.0.1:6379> keys *1) "Cache::me.action.dao.StudentDao_findById_1"2) "Cache::me.action.dao.StudentDao_findByName_1"

Key 由缓存名、类名、方法名和参数构成,这样足够保险了。在实际开发中可以根据实际情况构造 key 满足需求。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表