【问题标题】:Remove cache name from generated cache key从生成的缓存键中删除缓存名称
【发布时间】:2019-06-26 10:01:43
【问题描述】:

我想知道是否有某种方法可以从 Spring boot 2 上生成的缓存键中删除缓存名称。

这是我目前用来缓存数据的代码:

@Cacheable(value = "products", key = "#product.id")
public SimilarProducts findSimilarProducts(Product product){}

Spring boot 将字符串“products”连接到我生成的每个键,以保存在缓存中。我已经尝试过制作自己的密钥生成器,但弹簧靴不断将字符串“products”连接到生成的密钥。感谢您的关注。

例如当我使用:

Product p = new Product();
p.setId("12345");
findSimilarProducts(p);

生成的密钥将是:

products::12345

我希望它只有 12345。

【问题讨论】:

  • 你能提供工作代码吗?你的预期输出是什么?它现在是如何工作的?
  • 我刚刚编辑了这个问题,这是默认行为,我只有一个带有 id 的产品类。
  • 你是怎么得到结果的?
  • 在 sprint boot 插入后,我在 Redis 服务器上看到了我的结果。

标签: java spring-boot caching


【解决方案1】:

spring boot 不断将字符串“products”连接到生成的密钥。

Spring Boot(或与此相关的缓存抽象)不会这样做,但特定的 Cache 实现可能会这样做。分享更多有关您的设置的详细信息会很有趣,但我只能猜测您正在使用 Redis 作为缓存存储,并且默认的 CacheKeyPrefix 确实添加了缓存的名称。

请查看the documentation

【讨论】:

【解决方案2】:

您可以(也许您需要)像这样禁用键前缀。

@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
    RedisCacheManager cacheManager = RedisCacheManager.builder(connectionFactory)
            .cacheDefaults(defaultCacheConfig().disableKeyPrefix())
            .build();
    return cacheManager;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-09
    • 2014-10-07
    • 2013-01-14
    相关资源
    最近更新 更多