2012-11-13 32 views
1

我用querydsl使用spring数据jpa。我有一个方法返回包含总数的页面查询结果。获得总数是昂贵的,我想缓存它。这怎么可能?spring-data:缓存查询总数

我幼稚的做法

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

不起作用(使它发挥他们的方式想为缓存不应该是整个查询,只是标准的实际键)。无论如何测试它,没有工作,然后我发现这一点:Spring 3.1 @Cacheable - method still executed

我明白这一点,我只能缓存公共接口方法。然而在所述方法中,我需要缓存返回值的属性,例如。

Page<T> findByComplexProperty(...) 

我需要缓存

page.getTotalElements(); 

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

我该怎么做?

回答

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(); 
}