Reputation: 435
I have a spring batch where it executes multiple threads using executor service. All threads access below method. I tried to cache the method using @Cacheable. But it is not working. Everythread executes this method without caching. I found that out using sysouts. Much worse, even the same thread goes inside the method multiple times without caching (inside for loop).
Can you please tell me what is it im doing wrong here.
@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;
}
Upvotes: 2
Views: 1549
Reputation: 1112
To make Spring Caching work, make sure you have:
@EnableCaching
@Cacheable(cacheNames = "name of your cache")
Example :
@Bean
public SimpleCacheManager simpleCacheManager() {
SimpleCacheManager simpleCacheManager = new SimpleCacheManager();
simpleCacheManager.setCaches(Collections.singletonList(new ConcurrentMapCache("myCacheName")));
return simpleCacheManager;
}
And:
@Cacheable(key="#userID",sync=true, cacheNames ="myCacheName")
public String getPassword(String userID) throws Exceptions
Upvotes: 4