【问题标题】:spring-data: cache a queries total countspring-data:缓存一个查询总数
【发布时间】:2012-11-13 08:12:17
【问题描述】:

我正在使用带有 querydsl 的 spring data jpa。我有一种方法可以在包含总计数的页面中返回查询结果。获取总数很昂贵,我想缓存它。这怎么可能?

我的幼稚做法

@Cacheable("queryCount")
private long getCount(JPAQuery query){
    return query.count();
}

不起作用(为了使其正常工作,他们希望缓存的实际键不应该是整个查询,而只是条件)。无论如何测试它,没有工作,然后我发现了这个:Spring 3.1 @Cacheable - method still executed

按照我的理解,我只能缓存公共接口方法。但是在上述方法中,我需要缓存返回值的属性,例如。

Page<T> findByComplexProperty(...)

我需要缓存

page.getTotalElements();

注释整个方法有效(它被缓存)但不是我想要的方式。假设获取总数需要 30 秒。因此,对于每个新页面请求,用户需要等待 30 秒。如果他返回一个页面,则使用缓存,但我希望计数只运行一次,然后从缓存中获取计数。

我该怎么做?

【问题讨论】:

    标签: caching spring-data


    【解决方案1】:

    我的解决方案是在创建复杂查询的类中自动装配缓存管理器:

    @Autowired
    private CacheManager cacheManager;
    

    然后创建一个简单的私有方法getCount

    private long getCount(JPAQuery query) {
        Predicate whereClause = query.getMetadata().getWhere();
        String key = whereClause.toString();        
        Cache cache = this.cacheManager.getCache(QUERY_CACHE);        
        Cache.ValueWrapper value = cache.get(key);
        if (value == null) {
            Long result = query.count();
            cache.put(key, result);
            return result;
        }
        return (Long)value.get();
    }
    

    【讨论】:

      猜你喜欢
      • 2013-09-23
      • 2020-04-08
      • 2017-11-22
      • 2013-08-24
      • 2014-12-02
      • 2017-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多