没有明确的方法可以更改 a 的默认到期策略Cache
(在 JCache 或 Hazelcast 特定的 API 中)。
您可以通过Cache
使用自定义配置来实现相同的效果Factory<ExpiryPolicy>
。在您的ExpiryPolicy
实现中,您可以咨询您的外部服务来查询当前的到期持续时间并返回,以便 JCache 实现应用它。请注意,由于在每个条目创建/访问/更新时都会查询到期策略,因此ExpiryPolicy
方法实现最好不要涉及任何远程服务查询或数据库访问,否则您将遇到高延迟。例如,最好将您的到期策略注册为外部服务的侦听器(如果支持),或者有一个单独的执行程序来安排对外部服务的查询以进行更新。
使用 JCache API 的示例实现:
class Scratch {
public static void main(String[] args)
throws InterruptedException {
MutableConfiguration<String, String[]> roleCacheConfig = new MutableConfiguration<>();
// other config here...
roleCacheConfig.setExpiryPolicyFactory(new CustomExpiryPolicyFactory());
CachingProvider provider = Caching.getCachingProvider();
CacheManager manager = provider.getCacheManager();
Cache<String, String[]> cache = manager.createCache("test", roleCacheConfig);
cache.put("a", new String[]{}); // consults getExpiryForCreation
Thread.sleep(1000);
cache.get("a"); // consults getExpiryForAccess
Thread.sleep(1000);
cache.put("a", new String[]{}); // consults getExpiryForUpdate
}
public static class CustomExpiryPolicyFactory implements Factory<ExpiryPolicy>, Serializable {
@Override
public ExpiryPolicy create() {
// initialize custom expiry policy: at this point
// the custom expiry policy should be registered as listener to
// external service publishing expiry info or otherwise configured
// to poll the external service for new expiry info
CustomExpiryPolicy expiryPolicy = new CustomExpiryPolicy(120, 30, 120);
return expiryPolicy;
}
}
public static class CustomExpiryPolicy implements ExpiryPolicy {
private volatile Duration expiryForCreation;
private volatile Duration expiryForAccess;
private volatile Duration expiryForUpdate;
public CustomExpiryPolicy(long secondsForCreation,
long secondsForAccess,
long secondsForUpdate) {
this.expiryForCreation = new Duration(TimeUnit.SECONDS, secondsForCreation);
this.expiryForAccess = new Duration(TimeUnit.SECONDS, secondsForAccess);
this.expiryForUpdate = new Duration(TimeUnit.SECONDS, secondsForUpdate);
}
// assuming this is invoked from external service whenever there is a change
public void onExpiryChanged(long secondsForCreation,
long secondsForAccess,
long secondsForUpdate) {
this.expiryForCreation = new Duration(TimeUnit.SECONDS, secondsForCreation);
this.expiryForAccess = new Duration(TimeUnit.SECONDS, secondsForAccess);
this.expiryForUpdate = new Duration(TimeUnit.SECONDS, secondsForUpdate);
}
@Override
public Duration getExpiryForCreation() {
return expiryForCreation;
}
@Override
public Duration getExpiryForAccess() {
return expiryForAccess;
}
@Override
public Duration getExpiryForUpdate() {
return expiryForUpdate;
}
}
}
您可以在声明性 Hazelcast XML 配置中提供自定义到期策略工厂类名称,如下所示:
<cache name="toto">
<async-backup-count>1</async-backup-count>
<backup-count>1</backup-count>
...
<expiry-policy-factory class-name="com.example.cache.CustomExpirePolicyFactory" />
...
</cache>
作为旁注,ICache
Hazelcast 特定的扩展Cache
接口中的一些方法允许您使用为每个键指定的自定义到期策略对一个键或一组键执行操作(但不更改缓存范围内的适用到期政策)。