【问题标题】:What is the difference between CacheResolver and KeyGenerator and when to use each one of themCacheResolver 和 KeyGenerator 有什么区别以及何时使用它们中的每一个
【发布时间】:2018-07-01 13:36:34
【问题描述】:

我正在向我的 Web 应用程序添加缓存机制。 经过研究,我决定在 Spring 中使用 Ehcache

向方法添加@Cachable 注释将执行该方法一次,对于任何进一步的调用,响应将从缓存中返回。

问题是我需要在运行时决定(假设根据登录的用户)我想使用哪个缓存。

我已经到了需要决定是使用KeyGenerators还是cacheResolver的地步。

我搜索了最佳实践,何时使用它们中的每一个,但没有找到任何好的阅读材料。我希望如果有人可以澄清差异并详细说明最佳做法以及该做和不该做的事情。

密钥生成器:

  @Bean
  public KeyGenerator keyGenerator() {
    return new KeyGenerator() {
      @Override
      public Object generate(Object o, Method method, String loggedInUserId) {
        StringBuilder sb = new StringBuilder();
        sb.append("cache_");
        sb.append(loggedInUserId);
        return sb;
      }
    };

缓存解析器

class loggedInUserCacheResolver implements CacheResolver {
@Override
    public Collection<? extends Cache> resolveCaches(CacheOperationInvocationContext<?> context) {
        Collection<Cache> caches = new ArrayList<>();
        // do some logic and return caches to use.
        return caches;
    }
}

【问题讨论】:

    标签: java spring caching ehcache


    【解决方案1】:

    KeyGenerator 只允许您操作缓存键的创建。然而,所有键仍然属于单个缓存,即使它们不会发生任何冲突。

    CacheResolver 允许您使用逻辑来选择要使用的 Cache

    根据您的初始声明,您的用例需要CacheResolver。请注意,我没有仔细检查缓存是否被解析一次每个调用。

    请注意,您可以将这两个注解组合起来,以获得自定义缓存和自定义键定义。

    【讨论】:

    • 在 SO 中想了大约 2 个月才能找到这个解释
    猜你喜欢
    • 2020-05-02
    • 2017-05-18
    • 2014-10-25
    • 2016-03-21
    • 2023-03-17
    • 2020-04-29
    • 2020-02-26
    • 1970-01-01
    • 2010-09-06
    相关资源
    最近更新 更多