java - Spring @Cacheable 不起作用 - 多线程
问题描述
我有一个弹簧批处理,它使用执行器服务执行多个线程。所有线程都访问下面的方法。我尝试使用@Cacheable 缓存该方法。但它不起作用。每个线程都在不缓存的情况下执行此方法。我使用 sysouts 发现了这一点。更糟糕的是,即使同一个线程在没有缓存的情况下多次进入方法内部(在 for 循环内)。
你能告诉我我在这里做错了什么吗?
@Cacheable(key="#userID",sync=true)
public String getPassword(String userID) throws Exceptions{
logger.info("cache not working");
SecurityTokenClientResponse password=client.getPassword(req, true, notify.getEnv());
byte[] encryptedPassword=password.getPasswordByteArray();
if (encryptedPassword!=null)
{
try {
return retrieveCreds(client, encryptedPassword);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}else {
password.getBusinessError();
}
return null;
}
解决方案
要使 Spring Caching 工作,请确保您具有:
- 利用
@EnableCaching
- 创建一个 CacheManager bean
- 告诉你的方法应该使用哪个缓存:
@Cacheable(cacheNames = "name of your cache")
例子 :
@Bean
public SimpleCacheManager simpleCacheManager() {
SimpleCacheManager simpleCacheManager = new SimpleCacheManager();
simpleCacheManager.setCaches(Collections.singletonList(new ConcurrentMapCache("myCacheName")));
return simpleCacheManager;
}
和:
@Cacheable(key="#userID",sync=true, cacheNames ="myCacheName")
public String getPassword(String userID) throws Exceptions