【发布时间】:2019-05-02 01:11:24
【问题描述】:
我一直在尝试将 Hazelcast 集成到我的应用程序中,但在使用 onExpired 与 onRemoved 侦听器时遇到了我没有预料到的行为。
理想情况下,我希望在从缓存中删除某个值时执行一些代码。我在缓存上配置了过期策略,并希望我的 onRemoved 监听器会在我的缓存值过期后跟随,但似乎并非如此。
Hazelcast 是在从缓存中删除过期值之后调用 onRemoved 侦听器,还是仅在显式调用 cache.remove() 时调用?
我的配置是:
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));
}
}
}
我的 Listener 相当简单:
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 秒后的某个时候,我的 onRemoved 方法会被 Hazelcast 调用,因为它会从缓存中删除过期值,但似乎从来没有。
这是预期的行为吗?我的缓存配置中是否缺少某些内容?
【问题讨论】: