我一直试图将Hazelcast集成到我的应用程序中,但是遇到了onExpired与onRemoved侦听器无法预料的行为。
理想情况下,每当从缓存中删除一个值时,我都希望执行一些代码。我在缓存上配置了Expiry策略,并希望在缓存值过期后可以使用onRemoved侦听器,但事实并非如此。
Hazelcast是在从缓存中删除过期值之后还是仅在显式cache.remove()
调用中调用onRemoved侦听器吗?
我的配置是:
hazelcastInstance = HazelcastInstanceFactory.getOrCreateHazelcastInstance(getHazelcastConfig());
// Add cache used by adams
CacheSimpleConfig cacheSimpleConfig = new CacheSimpleConfig()
.setName(CACHE_NAME)
.setKeyType(UserRolesCacheKey.class.getName())
.setValueType((new String[0]).getClass().getName())
.setReadThrough(true)
.setInMemoryFormat(InMemoryFormat.OBJECT)
.setEvictionConfig(new EvictionConfig()
.setEvictionPolicy(EvictionPolicy.LRU)
.setSize(1000)
.setMaximumSizePolicy(EvictionConfig.MaxSizePolicy.ENTRY_COUNT))
.setExpiryPolicyFactoryConfig(
new ExpiryPolicyFactoryConfig(
new TimedExpiryPolicyFactoryConfig(ACCESSED,
new DurationConfig(
120,
TimeUnit.SECONDS))));
hazelcastInstance.getConfig().addCacheConfig(cacheSimpleConfig);
ICache<UserRolesCacheKey, String[]> userRolesCache = hazelcastInstance.getCacheManager().getCache(CACHE_NAME);
userRolesCache.registerCacheEntryListener(new MutableCacheEntryListenerConfiguration<>(
new UserRolesCacheListenerFactory(), null, false, false));
}
}
}
我的听众很简单:
public class UserRolesCacheListenerFactory implements Factory<CacheEntryListener<UserRolesCacheKey, String[]>> {
@Override
public CacheEntryListener create() {
return new UserRolesCacheEntryListener();
}
}
并且:
public class UserRolesCacheEntryListener implements CacheEntryRemovedListener<UserRolesCacheKey, String[]>{
private final static Logger LOG = LoggerFactory.getLogger(UserRolesCacheEntryListener.class);
@Override
public void onRemoved(Iterable<CacheEntryEvent<? extends UserRolesCacheKey, ? extends String[]>> cacheEntryEvents) throws CacheEntryListenerException {
cacheEntryEvents.forEach(this::deleteDBData);
}
我希望在120秒后的某个时候,Hazelcast会调用我的onRemoved
方法,因为它会从缓存中删除过期的值,但似乎从未如此。
这是预期的行为吗?缓存配置中缺少某些内容吗?