Spring boot redis cache 的 key

栏目: Java · 发布时间: 6年前

内容简介:在数据库查询中我们往往会使用增加缓存来提高程序的性能,数据库spring boot 配置

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

搭建项目

数据库

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

spring boot 配置

#jpa
spring.jpa.hibernate.ddl-auto=none
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/pratice
spring.datasource.username=root
spring.datasource.password=123456
#redis
spring.redis.host=localhost
spring.redis.lettuce.pool.maxActive=5
spring.redis.lettuce.pool.maxIdle=5
#cache
spring.cache.cache-names=Cache
spring.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);
}

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

@Override
public 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 的生成和方法的名字无关,如果两个方法的参数相同了,就会命中同一个缓存,这样显然是不行的。使用相同的参数调用 findByIdfindByName 观察查询结果

@Override
public 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}")
@Override
Optional<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 或取到类名的方法(或许有),所以这里通过配置 @Cacheablekey 参数就不行了。那就只能实现自定义的生成器。

@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, "_");
    }
  };
}

设置 @CacheablekeyGenerator 参数

@Cacheable(value = "Cache", keyGenerator = "customKeyGenerator")
@Override
Optional<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 满足需求。


以上所述就是小编给大家介绍的《Spring boot redis cache 的 key》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

修改代码的艺术

修改代码的艺术

Michael Feathers / 刘未鹏 / 人民邮电出版社 / 2007-09-25 / 59.00元

我们都知道,即使是最训练有素的开发团队,也不能保证始终编写出清晰高效的代码。如果不积极地修改、挽救,随着时间流逝,所有软件都会不可避免地渐渐变得复杂、难以理解,最终腐化、变质。因此,理解并修改已经编写好的代码,是每一位程序员每天都要面对的工作,也是开发程序新特性的基础。然而,与开发新代码相比,修改代码更加令人生畏,而且长期以来缺乏文献和资料可供参考。 本书是继《重构》和《重构与模式》之后探讨......一起来看看 《修改代码的艺术》 这本书的介绍吧!

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具