下面列出了org.springframework.boot.autoconfigure.cache.JCacheManagerCustomizer#javax.cache.expiry.Duration 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@SuppressWarnings("unchecked")
@Override
public boolean replace(K key, final V oldValue, final V newValue) {
checkClosed();
checkNullValue(newValue);
checkNullValue(oldValue);
return
c2kCache.invoke(key, new EntryProcessor<K, V, Boolean>() {
@Override
public Boolean process(final MutableCacheEntry<K, V> e) {
if (e.exists()) {
if (oldValue.equals(e.getValue())) {
e.setValue(newValue);
return true;
} else {
Duration d = expiryPolicy.getExpiryForAccess();
if (d != null) {
e.setExpiryTime(calculateExpiry(d));
}
}
}
return false;
}
});
}
private ICacheElement<K, V> updateElement(final K key, final V v, final Duration duration, final IElementAttributes attrs)
{
final ICacheElement<K, V> element = new CacheElement<>(name, key, v);
if (duration != null)
{
attrs.setTimeFactorForMilliseconds(1);
final boolean eternal = duration.isEternal();
attrs.setIsEternal(eternal);
if (!eternal)
{
attrs.setLastAccessTimeNow();
}
// MaxLife = -1 to use IdleTime excepted if jcache.ccf asked for something else
}
element.setElementAttributes(attrs);
return element;
}
/** {@inheritDoc} */
@Override public ExpiryPolicy create() {
return new ExpiryPolicy() {
@Override public Duration getExpiryForCreation() {
return new Duration(TimeUnit.MILLISECONDS, TIMEOUT);
}
/** {@inheritDoc} */
@Override public Duration getExpiryForAccess() {
return new Duration(TimeUnit.MILLISECONDS, TIMEOUT);
}
/** {@inheritDoc} */
@Override public Duration getExpiryForUpdate() {
return new Duration(TimeUnit.MILLISECONDS, TIMEOUT);
}
};
}
@Test
public void testCacheStatisticsRemoveAllNoneExpired() throws Exception {
ExpiryPolicy policy = new CreatedExpiryPolicy(Duration.ETERNAL);
expiryPolicyServer.setExpiryPolicy(policy);
MutableConfiguration<Integer, Integer> config = new MutableConfiguration<>();
config.setExpiryPolicyFactory(FactoryBuilder.factoryOf(expiryPolicyClient))
.setStatisticsEnabled(true);
Cache<Integer, Integer> cache = getCacheManager().createCache(getTestCacheName(), config);
for (int i = 0; i < 100; i++) {
cache.put(i, i+100);
}
cache.removeAll();
assertEquals(100L, lookupManagementAttribute(cache, CacheStatistics, "CachePuts"));
assertEquals(100L, lookupManagementAttribute(cache, CacheStatistics, "CacheRemovals"));
}
@Override
public long calculateExpiryTime(K _key, V _value, long _loadTime, CacheEntry<K, V> _oldEntry) {
if (_value == null) {
return NO_CACHE;
}
Duration d;
if (_oldEntry == null || _oldEntry.getException() != null) {
d = policy.getExpiryForCreation();
} else {
d = policy.getExpiryForUpdate();
}
if (d == null) {
return ExpiryTimeValues.NEUTRAL;
}
if (d.equals(Duration.ETERNAL)) {
return ExpiryTimeValues.ETERNAL;
}
if (d.equals(Duration.ZERO)) {
return ExpiryTimeValues.NO_CACHE;
}
return _loadTime + d.getTimeUnit().toMillis(d.getDurationAmount());
}
/** */
private static CacheConfiguration[] getCacheConfigurations() {
CacheConfiguration[] cfgs = cacheConfigurations();
List<CacheConfiguration> newCfgs = new ArrayList<>(cfgs.length);
for (CacheConfiguration cfg : cfgs) {
if (cfg.getAtomicityMode() == CacheAtomicityMode.TRANSACTIONAL_SNAPSHOT) {
// Expiry policy cannot be used with TRANSACTIONAL_SNAPSHOT.
continue;
}
cfg.setExpiryPolicyFactory(AccessedExpiryPolicy.factoryOf(new Duration(SECONDS, EXPIRATION_TIMEOUT)));
cfg.setEagerTtl(true);
newCfgs.add(cfg);
}
return newCfgs.toArray(new CacheConfiguration[0]);
}
@Test
public void testCacheStatisticsRemoveAll() throws Exception {
long _EXPIRY_MILLIS = 3;
//cannot be zero or will not be added to the cache
ExpiryPolicy policy = new CreatedExpiryPolicy(new Duration(TimeUnit.MILLISECONDS, _EXPIRY_MILLIS));
expiryPolicyServer.setExpiryPolicy(policy);
MutableConfiguration<Integer, Integer> config = new MutableConfiguration<>();
config.setExpiryPolicyFactory(FactoryBuilder.factoryOf(expiryPolicyClient)).setStatisticsEnabled(true);
Cache<Integer, Integer> cache = getCacheManager().createCache(getTestCacheName(), config);
for (int i = 0; i < 100; i++) {
cache.put(i, i+100);
}
//should work with all implementations
Thread.sleep(_EXPIRY_MILLIS);
cache.removeAll();
assertEquals(100L, lookupManagementAttribute(cache, CacheStatistics, "CachePuts"));
//Removals does not count expired entries
assertEquals(0L, lookupManagementAttribute(cache, CacheStatistics, "CacheRemovals"));
}
/**
* @param duration Duration.
* @return TTL.
*/
public static long toTtl(Duration duration) {
if (duration == null)
return TTL_NOT_CHANGED;
if (duration.getDurationAmount() == 0) {
if (duration.isEternal())
return TTL_ETERNAL;
assert duration.isZero();
return TTL_ZERO;
}
assert duration.getTimeUnit() != null : duration;
return duration.getTimeUnit().toMillis(duration.getDurationAmount());
}
/**
* Returns the time when the entry will expire.
*
* @param created if the write is an insert or update
* @return the time when the entry will expire, zero if it should expire immediately,
* Long.MIN_VALUE if it should not be changed, or Long.MAX_VALUE if eternal
*/
protected final long getWriteExpireTimeMS(boolean created) {
try {
Duration duration = created ? expiry.getExpiryForCreation() : expiry.getExpiryForUpdate();
if (duration == null) {
return Long.MIN_VALUE;
} else if (duration.isZero()) {
return 0L;
} else if (duration.isEternal()) {
return Long.MAX_VALUE;
}
return duration.getAdjustedTime(currentTimeMillis());
} catch (Exception e) {
logger.log(Level.WARNING, "Failed to get the policy's expiration time", e);
return Long.MIN_VALUE;
}
}
/**
* @throws Exception If failed.
*/
@Test
public void testEvict() throws Exception {
Ignite ignite1 = startGrid(1);
IgniteCache<Object, Object> cache = ignite1.cache(DEFAULT_CACHE_NAME).withExpiryPolicy(new CreatedExpiryPolicy(
new Duration(TimeUnit.MILLISECONDS, 100L)));
// Putting entry.
for (int i = 0; i < KEYS; i++)
cache.put(i, i);
// Wait when entry
U.sleep(200);
// Check that entry is evicted from cache, but local store does contain it.
for (int i = 0; i < KEYS; i++) {
cache.localEvict(Arrays.asList(i));
assertNull(cache.localPeek(i));
assertEquals(i, (int)LOCAL_STORE_1.load(i).get1());
assertEquals(i, cache.get(i));
}
}
/** {@inheritDoc} */
@Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);
CacheConfiguration<String, Long> ccfg = new CacheConfiguration<>(DEFAULT_CACHE_NAME);
ccfg.setAtomicityMode(CacheAtomicityMode.ATOMIC);
ccfg.setCacheMode(CacheMode.PARTITIONED);
ccfg.setBackups(1);
ccfg.setReadFromBackup(true);
ccfg.setCopyOnRead(false);
ccfg.setName(THROTTLES_CACHE_NAME);
Duration expiryDuration = new Duration(TimeUnit.MINUTES, 1);
ccfg.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(expiryDuration));
ccfg.setReadThrough(false);
ccfg.setWriteThrough(true);
ccfg.setCacheStoreFactory(new FactoryBuilder.SingletonFactory<>(new TestCacheStore()));
cfg.setCacheConfiguration(ccfg);
return cfg;
}
@Test
public void basicConfiguration() throws Exception {
// tag::basicConfigurationExample[]
CachingProvider provider = Caching.getCachingProvider(); // <1>
CacheManager cacheManager = provider.getCacheManager(); // <2>
MutableConfiguration<Long, String> configuration =
new MutableConfiguration<Long, String>() // <3>
.setTypes(Long.class, String.class) // <4>
.setStoreByValue(false) // <5>
.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(Duration.ONE_MINUTE)); // <6>
Cache<Long, String> cache = cacheManager.createCache("jCache", configuration); // <7>
cache.put(1L, "one"); // <8>
String value = cache.get(1L); // <9>
// end::basicConfigurationExample[]
assertThat(value, is("one"));
}
/**
* Sets the access expiration time.
*
* @param expirable the entry that was operated on
* @param currentTimeMS the current time, or 0 if not read yet
*/
protected final void setAccessExpirationTime(Expirable<?> expirable, long currentTimeMS) {
try {
Duration duration = expiry.getExpiryForAccess();
if (duration == null) {
return;
} else if (duration.isZero()) {
expirable.setExpireTimeMS(0L);
} else if (duration.isEternal()) {
expirable.setExpireTimeMS(Long.MAX_VALUE);
} else {
if (currentTimeMS == 0L) {
currentTimeMS = currentTimeMillis();
}
long expireTimeMS = duration.getAdjustedTime(currentTimeMS);
expirable.setExpireTimeMS(expireTimeMS);
}
} catch (Exception e) {
logger.log(Level.WARNING, "Failed to set the entry's expiration time", e);
}
}
/**
* @param atomicityMode Atomicity mode.
* @param heapCache Heap cache flag.
* @param expiryPlc Expiry policy flag.
* @return Cache configuration.
*/
private CacheConfiguration cacheConfiguration(CacheAtomicityMode atomicityMode,
boolean heapCache,
boolean expiryPlc) {
CacheConfiguration ccfg = new CacheConfiguration();
ccfg.setAtomicityMode(atomicityMode);
ccfg.setOnheapCacheEnabled(heapCache);
ccfg.setWriteSynchronizationMode(FULL_SYNC);
ccfg.setName("testCache");
if (expiryPlc)
ccfg.setExpiryPolicyFactory(ModifiedExpiryPolicy.factoryOf(Duration.FIVE_MINUTES));
return ccfg;
}
public static void sleepDurationTwice(Logger logger, Duration duration) {
if (duration.isEternal() || duration.isZero()) {
return;
}
TimeUnit timeUnit = duration.getTimeUnit();
long timeout = duration.getDurationAmount() * 2;
logger.info(format("Sleeping for %d %s...", timeout, timeUnit));
sleepTimeUnit(timeUnit, timeout);
}
public <K, V> Cache<K, V> getCache(String alias, Class<K> keyClass, Class<V> valueClass) {
checkInitilized();
Cache<K, V> cache = manager.getCache(alias, keyClass, valueClass);
if(isNull(cache)) {
cache = manager.createCache(alias, new MutableConfiguration<K, V>().setTypes(keyClass, valueClass).setStoreByValue(false).setExpiryPolicyFactory(TouchedExpiryPolicy.factoryOf(Duration.ONE_HOUR)));
}
return cache;
}
/**
* {@inheritDoc}
*/
@Override
public Duration getExpiryForAccess() {
if (isDirectCallable()) {
return forwardPolicy.getExpiryForAccess();
}
return getClient().invoke(new GetExpiryOperation(ExpiryPolicyServer.EntryOperation.ACCESSED));
}
/**
* {@inheritDoc}
*/
@Override
public Duration getExpiryForUpdate() {
updatedCount.incrementAndGet();
return null;
}
@Test
public void testExpiration() throws InterruptedException, IllegalArgumentException, URISyntaxException, FailedToStartRedisException, IOException {
RedisProcess runner = new RedisRunner()
.nosave()
.randomDir()
.port(6311)
.run();
MutableConfiguration<String, String> config = new MutableConfiguration<>();
config.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.SECONDS, 1)));
config.setStoreByValue(true);
URI configUri = getClass().getResource("redisson-jcache.json").toURI();
Cache<String, String> cache = Caching.getCachingProvider().getCacheManager(configUri, null)
.createCache("test", config);
CountDownLatch latch = new CountDownLatch(1);
String key = "123";
ExpiredListener clientListener = new ExpiredListener(latch, key, "90");
MutableCacheEntryListenerConfiguration<String, String> listenerConfiguration =
new MutableCacheEntryListenerConfiguration<String, String>(FactoryBuilder.factoryOf(clientListener), null, true, true);
cache.registerCacheEntryListener(listenerConfiguration);
cache.put(key, "90");
Assert.assertNotNull(cache.get(key));
latch.await();
Assert.assertNull(cache.get(key));
cache.close();
runner.stop();
}
public void run(int numberOfIteration, int numberOfObjectPerIteration, int sleepTimeMillisBetweenIterations) throws Exception {
LOGGER.info("JCache testing BEGIN - Creating JCache Programmatically without any XML config");
//finds ehcache provider automatically if it is in the classpath
CachingProvider cachingProvider = Caching.getCachingProvider();
// If there are multiple providers in your classpath, use the fully qualified name to retrieve the Ehcache caching provider.
//CachingProvider cachingProvider = Caching.getCachingProvider("org.ehcache.jsr107.EhcacheCachingProvider");
try (CacheManager cacheManager = cachingProvider.getCacheManager()) {
Cache<Long, String> myJCache = cacheManager.createCache(
CACHE_NAME,
new MutableConfiguration<Long, String>()
.setTypes(Long.class, String.class)
.setStoreByValue(false)
.setStatisticsEnabled(true)
.setExpiryPolicyFactory(FactoryBuilder.factoryOf(new CreatedExpiryPolicy(new Duration(TimeUnit.SECONDS, 5)))));
simpleGetsAndPutsCacheTest(myJCache, numberOfIteration, numberOfObjectPerIteration, sleepTimeMillisBetweenIterations, new KeyValueGenerator<Long, String>() {
@Override
public Long getKey(Number k) {
return new Long(k.longValue());
}
@Override
public String getValue(Number v) {
return String.format("Da One %s!!", v.toString());
}
});
}
LOGGER.info("JCache testing DONE - Creating JCache Programmatically without any XML config");
}
private MutableConfiguration<BlobId, String> getCacheConfiguration() {
return new MutableConfiguration<BlobId, String>()
.setStoreByValue(false)
.setExpiryPolicyFactory(
CreatedExpiryPolicy.factoryOf(new Duration(blobIdCacheTimeout.unit(), blobIdCacheTimeout.value()))
)
.setManagementEnabled(true)
.setStatisticsEnabled(true);
}
/**
* Constructs an {@link ParameterizedExpiryPolicy}.
*
* @param createdExpiryDuration the {@link Duration} to expire when an
* entry is created (must not be <code>null</code>)
* @param accessedExpiryDuration the {@link Duration} to expire when an
* entry is accessed (<code>null</code> means don't change the expiry)
* @param updatedExpiryDuration the {@link Duration} to expire when an
* entry is updated (<code>null</code> means don't change the expiry)
*/
public ParameterizedExpiryPolicy(Duration createdExpiryDuration,
Duration accessedExpiryDuration,
Duration updatedExpiryDuration) {
if (createdExpiryDuration == null) {
throw new NullPointerException("createdExpiryDuration can't be null");
}
this.createdExpiryDuration = createdExpiryDuration;
this.accessedExpiryDuration = accessedExpiryDuration;
this.updatedExpiryDuration = updatedExpiryDuration;
}
@Override
public Builder<K,V> setMaxIdleTime(int maxIdleTime, TimeUnit timeUnit)
{
if (maxIdleTime <= 0)
throw new IllegalArgumentException("Invalid maxIdleTime: " + maxIdleTime);
TouchedExpiryPolicy ep = new TouchedExpiryPolicy(new Duration(timeUnit, maxIdleTime));
SingletonFactory<ExpiryPolicy> singletonFactory = new FactoryBuilder.SingletonFactory<ExpiryPolicy>(ep);
this.expiryPolicyFactory = (Factory<ExpiryPolicy>)singletonFactory;
return this;
}
/**
* Entry was accessed update expiry if value is non null.
*/
private V returnValue(K key, V _value) {
if (_value != null) {
Duration d = expiryPolicy.getExpiryForAccess();
if (d != null) {
c2kCache.expireAt(key, calculateExpiry(d));
}
return _value;
}
return null;
}
/**
* {@inheritDoc}
*/
@Override
public Duration getExpiryForAccess() {
accessedCount.incrementAndGet();
return null;
}
/**
* Tests that partitions validation is not triggered when custom expiry policy is explicitly used.
*
* @throws Exception If failed.
*/
@Test
public void shouldNotPrintMessageIfPartitionHasOtherCounterButHasCustomExpiryPolicy() throws Exception {
doTest(
new CacheConfiguration<Integer, Integer>(CACHE_1)
.setBackups(1)
.setExpiryPolicyFactory(AccessedExpiryPolicy.factoryOf(new Duration(TimeUnit.SECONDS, 1))),
false
);
}
private long expireTimeMS() {
try {
Duration duration = expiry.getExpiryForCreation();
if (duration.isZero()) {
return 0;
} else if (duration.isEternal()) {
return Long.MAX_VALUE;
}
long millis = TimeUnit.NANOSECONDS.toMillis(ticker.read());
return duration.getAdjustedTime(millis);
} catch (Exception e) {
return Long.MAX_VALUE;
}
}
@Override
public java.time.Duration getExpiryForUpdate(K key, Supplier<? extends V> oldValue, V newValue) {
try {
Duration duration = expiryPolicy.getExpiryForUpdate();
if (duration == null) {
return null;
}
return convertDuration(duration);
} catch (Throwable t) {
return java.time.Duration.ZERO;
}
}
/**
* Convert encoded duration to actual duration.
*
* @param dur Encoded duration.
* @return Actual duration.
*/
private static Duration convert(long dur) {
if (dur == DUR_UNCHANGED)
return null;
else if (dur == DUR_ETERNAL)
return Duration.ETERNAL;
else if (dur == DUR_ZERO)
return Duration.ZERO;
else {
assert dur > 0;
return new Duration(TimeUnit.MILLISECONDS, dur);
}
}
public static void sleepDurationTwice(Logger logger, Duration duration) {
if (duration.isEternal() || duration.isZero()) {
return;
}
TimeUnit timeUnit = duration.getTimeUnit();
long timeout = duration.getDurationAmount() * 2;
logger.info(format("Sleeping for %d %s...", timeout, timeUnit));
sleepTimeUnit(timeUnit, timeout);
}