Hazelcast is configured in the spring boot (embedded hazelcast one)
@Bean
CacheManager hazelcastCacheManager() {
return new HazelcastCacheManager(Hazelcast.newHazelcastInstance());
}
@Bean
public Config hazelCastConfig() {
Config cacheConfig = new Config().setInstanceName("cache-instance");
MapConfig userCache = new MapConfig().setName("users")
.setMaxSizeConfig(new MaxSizeConfig(500, MaxSizeConfig.MaxSizePolicy.FREE_HEAP_SIZE))
.setTimeToLiveSeconds(12);
cacheConfig.addMapConfig(userCache);
}
When I am using @Cacheable in the service layer, it is working fine (it remove key from cache after 12 sec)
@Cacheable(key = "#name", value = "users")
But, once I add CacheManager to the same service class. This cache value is never getting removed (above one). My final requirement is to use cache manager to get the cache & check if the value exists. (block user after 2nd try & allow after 12 sec. So, Cache will store it for 12 sec & I can check if not in the cache, proceed, else inform to wait)
import org.springframework.cache.CacheManager;
@Autowired
private CacheManager cacheManager;
@Override
public void doCachingOperation() throws InterruptedException {
Cache userCache = cacheManager.getCache("users");
System.out.println(CalendarUtils.getCurrentDate());
userCache.put("Satish", 1);
System.out.println(Integer.valueOf(userCache.get("Satish").get().toString()));
Thread.sleep(2000);
System.out.println("2 sec passed");
System.out.println(Integer.valueOf(userCache.get("Satish").get().toString()));
Thread.sleep(14000);
System.out.println("16 sec passed");
System.out.println(CalendarUtils.getCurrentDate());
System.out.println(Integer.valueOf(userCache.get("Satish").get().toString()));
}
Now, this value is still available after 16sec, whereas it was supposed to be removed with the key "Satish" after 12 seconds.