【问题标题】:Spring share @Cachable and @CachePut keySpring 共享 @Cachable 和 @CachePut 键
【发布时间】:2020-09-12 19:28:47
【问题描述】:

我正在尝试将 Spring 缓存集成到我的项目中。我已经设置了一个 Redis 缓存管理器,它确实有效。但是,这是我的场景:我有一个 Setting 实体。我想创建一个可以返回所有设置的findAll 方法和一个允许设置特定设置的setSetting

这是我为getSettingssetSetting 定义的代码:

  @Cacheable(value = "setting")
  public List<Setting> getSettings() {
    return repository.findAll();
  }

  @CachePut("setting")
  public Optional<Setting> setSetting(String key, Object value) {
    var setting = this.repository.findByIdentifier(key);
    if (setting.isEmpty()) {
      return Optional.empty();
    }

    try {
      setting.get().setValue(mapper.writeValueAsString(value));
    } catch (JsonProcessingException e) {
      LOG.error("Could not serialize the value: {}", value);
      return Optional.empty();
    }

    this.repository.save(setting.get());
    return setting;
  }

当我打电话给getSettings 时,我的 Redis 中有一个 setting::SimpleKey [] 键(这是我的预期行为)。但是,当我调用setSetting 时,由于额外的参数,我没有覆盖setting::SimpleKey [] 键,而是在Redis 中得到另一个键:"setting::SimpleKey [name, foobar]" (where name and foobar are the arguments I've sent to setSetting`)。

我知道kecusyGenerator 是这样工作的,但这似乎很意外,我完全不明白如何设置我在findAll 中使用的原始密钥。我是否必须制作自定义密钥生成器?

我会给予任何帮助!

【问题讨论】:

  • 我想知道为什么我有两个不同的键,很好解释,谢谢。

标签: java spring-boot spring-cache


【解决方案1】:

为了让setSetting 覆盖从getSettings 返回的缓存值,两种方法都应该返回List&lt;Setting&gt;。您确实需要在每次更新设置之前逐出现有的缓存值,例如

@Cacheable(value = "setting")
public List<Setting> getSettings() {
  return repository.findAll();
}

@CacheEvict(value = "setting", allEntries = true, beforeInvocation = true)
@Cacheable(value = "setting", key = "T(org.springframework.cache.interceptor.SimpleKey).EMPTY")
public List<Setting> setSetting(String key, Object value) {
  // 1. update the setting value (as already done in your code) and save changes
  ...
  this.repository.save(setting.get());

  // 2. Return the list of settings
  return repository.findAll();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-15
    • 2013-04-20
    • 1970-01-01
    • 1970-01-01
    • 2015-03-24
    • 2010-12-09
    • 1970-01-01
    • 2018-05-27
    相关资源
    最近更新 更多