Luk*_*son 7 java spring caching asynchronous spring-cache
使用Spring的缓存抽象,如何在仍然返回旧条目的同时异步刷新条目?
我正在尝试使用Spring的缓存抽象来创建一个缓存系统,在相对较短的"软"超时之后,缓存条目可以进行刷新.然后,在查询它们时,返回缓存的值,并启动异步更新操作以刷新条目.我也会
Guava的缓存构建器允许我指定缓存中的条目应在一定时间后刷新.然后可以使用异步实现覆盖缓存加载器的reload()方法,允许返回过时的缓存值,直到检索到新的缓存值.但是,spring缓存似乎不使用底层Guava缓存的CacheLoader
是否可以使用Spring的缓存抽象来进行这种异步缓存刷新?
编辑澄清:使用Guava的CacheBuilder,我可以使用refreshAfterWrite()来获取我想要的行为.例如来自Guava Caches解释:
LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder()
.maximumSize(1000)
.refreshAfterWrite(1, TimeUnit.MINUTES)
.build(
new CacheLoader<Key, Graph>() {
public Graph load(Key key) { // no checked exception
return getGraphFromDatabase(key);
}
public ListenableFuture<Graph> reload(final Key key, Graph prevGraph) {
if (neverNeedsRefresh(key)) {
return Futures.immediateFuture(prevGraph);
} else {
// asynchronous!
ListenableFutureTask<Graph> task = ListenableFutureTask.create(new Callable<Graph>() {
public Graph call() {
return getGraphFromDatabase(key);
}
});
executor.execute(task);
return task;
}
}
});
Run Code Online (Sandbox Code Playgroud)
但是,我看不到使用Spring的@Cacheable抽象来获取refreshAfterWrite()行为的方法.
也许您可以尝试以下操作:
配置缓存:
@Configuration
@EnableCaching
public class CacheConfig {
@Bean
public CacheManager cacheManager() {
SimpleCacheManager simpleCacheManager = new SimpleCacheManager();
GuavaCache chache= new GuavaCache("cacheKey", CacheBuilder.newBuilder().build());
simpleCacheManager.setCaches(Arrays.asList(cacheKey));
return simpleCacheManager;
}
}
Run Code Online (Sandbox Code Playgroud)读取要缓存的值,假设是一个字符串(我以 a@Service为例)
@Service
public class MyService{
@Cacheable("cacheKey")
public String getStringCache() {
return doSomething();
}
@CachePut("cacheKey")
public String refreshStringCache() {
return doSomething();
}
...
}
Run Code Online (Sandbox Code Playgroud)
无论getStringCache()和refreshStringCache()调用,以中检索值相同的功能被缓存。该controller调用只 getStringCache()。
使用计划任务文档刷新缓存
@Configuration
@EnableScheduling
public class ScheduledTasks {
@Autowired
private MyService myService;
@Scheduled(fixedDelay = 30000)
public void IaaSStatusRefresh(){
myService.refreshStringCache();
}
}
Run Code Online (Sandbox Code Playgroud)
通过这种方式,计划任务每 30 秒强制刷新一次缓存。任何访问过的人getStringCache()都会在缓存中找到更新的数据。
| 归档时间: |
|
| 查看次数: |
8161 次 |
| 最近记录: |