【问题标题】:@Cacheable in Spring Cache Stores value in redis outside cache . How do i put it inside cache in redis?Spring Cache 中的 @Cacheable 将值存储在缓存之外的 redis 中。我如何将它放在redis的缓存中?
【发布时间】:2019-06-22 13:37:16
【问题描述】:
@Override
@Cacheable("stu")
public EmployeeEntity getEmployee(Integer id) {

    return employeeDAO.findById(id).get(); 
} 

以上代码以“stu::7”这种格式将密钥保存在redis中 这里的“stu”是缓存的名字,7是key,但是它将缓存的名字和id存储为一个key。

但我想以这种格式存储在 redis STU ->7 Stu 应该是缓存的名称,其中包含所有键值对。

【问题讨论】:

    标签: java spring-boot caching redis spring-cache


    【解决方案1】:

    您可以将自定义密钥生成器设置为 @Cacheable 注释,您可以根据需要对其进行自定义:https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/cache/annotation/Cacheable.html#keyGenerator--

    @Cacheable(value = "stu", keyGenerator = "customKeyGenerator")
    

    customKeyGenerator 是您的自定义密钥生成器 bean 的名称。

    【讨论】:

    • 是的,但它只会更改不会生成缓存存储的键的名称。我想要这样的结构(这是 Cashe)employe -> (它的地图)。相反,它在外部创建密钥,例如 "employee:id" :name
    【解决方案2】:

    这很奇怪,因为文档告诉我们

    默认为“”,表示所有方法参数都被视为一个键,除非配置了自定义 keyGenerator()。

    这很简单,但是如果您之前没有尝试过,请尝试显式设置键和缓存名称

    @Cacheable(value = "stu", key = "{#id}")
    public EmployeeEntity getEmployee(Integer id) {
        return employeeDAO.findById(id).get(); 
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-16
      • 2020-04-25
      • 2021-04-24
      • 1970-01-01
      • 2014-11-13
      • 2022-09-23
      • 1970-01-01
      相关资源
      最近更新 更多