我必须缓存执行以下查询时返回的所有文档
select * from `contact` where type="org"
什么是最好的方法?
答案 0 :(得分:1)
使用spring缓存并在应用程序配置类上添加@EnableCaching,并声明一个将返回CacheManager bean的方法,
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
private static final String cacheName ="YourCacheMap";
private static final String cacheManager ="AppCacheManager";
@Bean(name = "AppCacheManager")
public CacheManager cacheManager(){
final SimpleCacheManager cacheManager = new SimpleCacheManager();
final List<AbstractValueAdaptingCache> caches = new ArrayList<>();
final ConcurrentMapCache cacheMap = new ConcurrentMapCache("YourCacheMap",
CacheBuilder.newBuilder().expireAfterWrite(60, TimeUnit.MINUTES).maximumSize(100).build().asMap(), false);
caches.add(cacheMap);
cacheManager.setCaches(caches);
return cacheManager;
}
在您的存储库服务类中,对要缓存的方法使用@Cacheable注释
@Cacheable(value = cacheName, cacheManager = cacheManager, key = "#p0"
,unless = "#result == null || #p0==null")
public List<YourDataType> getResult(String type) {
// here you will return your results
return new ArrayList<YourDataType>();
}