下面列出了org.springframework.boot.autoconfigure.cache.JCacheManagerCustomizer#javax.cache.expiry.CreatedExpiryPolicy 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* @param ttl Time to live in ms.
*/
private <T> Future<T> executeWithTtl(Function<IgniteCache<K, V>, IgniteFuture<T>> cacheOp, long ttl) {
ContextInternal ctx = vertx.getOrCreateContext();
Promise<T> promise = ctx.promise();
IgniteCache<K, V> cache0 = ttl > 0 ?
cache.withExpiryPolicy(new CreatedExpiryPolicy(new Duration(TimeUnit.MILLISECONDS, ttl))) : cache;
IgniteFuture<T> future = cacheOp.apply(cache0);
future.listen(fut -> {
try {
promise.complete(unmarshal(future.get()));
} catch (IgniteException e) {
promise.fail(new VertxException(e));
}
});
return promise.future();
}
public static void main(String[] args) {
ClientConnectorConfiguration connectorConfiguration = new ClientConnectorConfiguration().setPort(10890);
TcpDiscoveryVmIpFinder ipFinder = new TcpDiscoveryVmIpFinder()
.setAddresses(Collections.singleton("127.0.0.1:47500"));
TcpDiscoverySpi discoSpi = new TcpDiscoverySpi()
.setIpFinder(ipFinder)
.setSocketTimeout(300)
.setNetworkTimeout(300);
CacheConfiguration expiryCacheCfg = new CacheConfiguration("twoSecondCache")
.setExpiryPolicyFactory(FactoryBuilder.factoryOf(
new CreatedExpiryPolicy(new Duration(TimeUnit.SECONDS, 2))));
IgniteConfiguration cfg = new IgniteConfiguration()
.setClientConnectorConfiguration(connectorConfiguration)
.setDiscoverySpi(discoSpi)
.setCacheConfiguration(expiryCacheCfg)
.setLocalHost("127.0.0.1");
Ignition.start(cfg);
}
/** {@inheritDoc} */
@Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
IgniteConfiguration cfg = super.getConfiguration(gridName);
CacheConfiguration ccfg = defaultCacheConfiguration();
ccfg.setName(CACHE_NAME);
ccfg.setAtomicityMode(CacheAtomicityMode.ATOMIC);
ccfg.setCacheMode(CacheMode.PARTITIONED);
ccfg.setBackups(1);
ccfg.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.MINUTES, 10)));
cfg.setCacheConfiguration(ccfg);
return cfg;
}
/** {@inheritDoc} */
@Override public void run() {
try {
barrier.await();
ExpiryPolicy plc1 = new CreatedExpiryPolicy(new Duration(MILLISECONDS, expirationDuration));
int keyStart = keysRangeGenerator.getAndIncrement() * cnt;
for (int i = keyStart; i < keyStart + cnt; i++)
cache.withExpiryPolicy(plc1).put("key" + i, 1);
barrier.await();
}
catch (Exception e) {
throw new IgniteException(e);
}
}
/** {@inheritDoc} */
@Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
IgniteConfiguration cfg = super.getConfiguration(gridName);
CacheConfiguration ccfg = new CacheConfiguration();
ccfg.setName(CACHE_NAME);
ccfg.setGroupName("Group1");
ccfg.setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL);
ccfg.setWriteSynchronizationMode(CacheWriteSynchronizationMode.FULL_SYNC);
ccfg.setAffinity(new RendezvousAffinityFunction(false, 128));
ccfg.setBackups(2);
ccfg.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.SECONDS, 1)));
cfg.setCacheConfiguration(ccfg);
return cfg;
}
/**
* @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 ccfg = new CacheConfiguration(DEFAULT_CACHE_NAME);
ccfg.setCacheMode(cacheMode);
ccfg.setEagerTtl(true);
ccfg.setEvictionPolicy(new FifoEvictionPolicy(ENTRIES_LIMIT, 100));
ccfg.setOnheapCacheEnabled(true);
ccfg.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.HOURS, 12)));
cfg.setCacheConfiguration(ccfg);
return cfg;
}
/** {@inheritDoc} */
@Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
IgniteConfiguration cfg = super.getConfiguration(gridName);
CacheConfiguration<Integer, Integer> ccfg =
new CacheConfiguration<Integer, Integer>()
.setName("config")
.setAtomicityMode(CacheAtomicityMode.ATOMIC)
.setBackups(0) // No need for backup, just load from the store if needed
.setCacheStoreFactory(new CacheStoreFactory())
.setOnheapCacheEnabled(true)
.setEvictionPolicy(new LruEvictionPolicy(100))
.setNearConfiguration(new NearCacheConfiguration<Integer, Integer>()
.setNearEvictionPolicy(new LruEvictionPolicy<Integer, Integer>()));
ccfg.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.MINUTES, 1)))
.setReadThrough(true)
.setWriteThrough(false);
cfg.setCacheConfiguration(ccfg);
return cfg;
}
/** {@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;
}
/**
* @param async If {@code true} uses asynchronous method.
* @throws Exception If failed.
*/
private void checkLoad(boolean async) throws Exception {
IgniteCache<String, Integer> cache = jcache(0)
.withExpiryPolicy(new CreatedExpiryPolicy(new Duration(MILLISECONDS, TIME_TO_LIVE)));
List<Integer> keys = new ArrayList<>();
keys.add(primaryKey(jcache(0)));
keys.add(primaryKey(jcache(1)));
keys.add(primaryKey(jcache(2)));
if (async)
cache.loadCacheAsync(null, keys.toArray(new Integer[3])).get();
else
cache.loadCache(null, keys.toArray(new Integer[3]));
assertEquals(3, cache.size(CachePeekMode.PRIMARY));
Thread.sleep(TIME_TO_LIVE + WAIT_TIME);
assertEquals(0, cache.size());
}
/**
* @param async If {@code true} uses asynchronous method.
* @throws Exception If failed.
*/
private void checkLocalLoad(boolean async) throws Exception {
final IgniteCache<String, Integer> cache = jcache(0)
.withExpiryPolicy(new CreatedExpiryPolicy(new Duration(MILLISECONDS, TIME_TO_LIVE)));
List<Integer> keys = primaryKeys(cache, 3);
if (async)
cache.localLoadCacheAsync(null, keys.toArray(new Integer[3])).get();
else
cache.localLoadCache(null, keys.toArray(new Integer[3]));
assertEquals(3, cache.localSize());
boolean res = GridTestUtils.waitForCondition(new PA() {
@Override public boolean apply() {
return cache.localSize() == 0;
}
}, TIME_TO_LIVE + WAIT_TIME);
assertTrue(res);
}
@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"));
}
@Test
public void testExpiryConfiguration() {
final AtomicBoolean expiryCreated = new AtomicBoolean(false);
MutableConfiguration<String, String> configuration = new MutableConfiguration<>();
configuration.setTypes(String.class, String.class);
configuration.setExpiryPolicyFactory(() -> {
expiryCreated.set(true);
return new CreatedExpiryPolicy(Duration.FIVE_MINUTES);
});
Cache<String, String> cache = cacheManager.createCache("cache", configuration);
cache.putIfAbsent("42", "The Answer");
cache.putIfAbsent("42", "Or not!?");
assertThat(expiryCreated.get(), is(true));
}
@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"));
}
@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"));
}
public JCache(URL url) {
String method = url.getParameter(Constants.METHOD_KEY, "");
String key = url.getAddress() + "." + url.getServiceKey() + "." + method;
// jcache parameter is the full-qualified class name of SPI implementation
String type = url.getParameter("jcache");
CachingProvider provider = type == null || type.length() == 0 ? Caching.getCachingProvider() : Caching.getCachingProvider(type);
CacheManager cacheManager = provider.getCacheManager();
Cache<Object, Object> cache = cacheManager.getCache(key);
if (cache == null) {
try {
//configure the cache
MutableConfiguration config =
new MutableConfiguration<Object, Object>()
.setTypes(Object.class, Object.class)
.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.MILLISECONDS, url.getMethodParameter(method, "cache.write.expire", 60 * 1000))))
.setStoreByValue(false)
.setManagementEnabled(true)
.setStatisticsEnabled(true);
cache = cacheManager.createCache(key, config);
} catch (CacheException e) {
// concurrent cache initialization
cache = cacheManager.getCache(key);
}
}
this.store = cache;
}
/**
* Prep cache configuration.
*
* @param expiryDuration the expiry duration
* @return the mutable configuration
*/
protected static MutableConfiguration<String, Map<String, Object>> createCacheConfiguration(final Duration expiryDuration) {
final MutableConfiguration<String, Map<String, Object>> config = new MutableConfiguration<>();
config.setStatisticsEnabled(true);
config.setManagementEnabled(true);
config.setStoreByValue(true);
config.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(expiryDuration));
return config;
}
<K, T> Configuration<K, T> createConfiguration(final CacheSizeManager<K, T> listener) {
return new MutableConfiguration<K, T>()
.setStoreByValue(false)
.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(SECONDS, cacheExpiry)))
.setManagementEnabled(cacheManagement)
.setStatisticsEnabled(cacheStatistics)
.addCacheEntryListenerConfiguration(new MutableCacheEntryListenerConfiguration<>(
new FactoryBuilder.SingletonFactory<>(listener), null, false, false));
}
public IgniteCache(String name, long maxSize, long maxLifetime) {
this.name = name;
this.maxCacheSize = maxSize;
this.maxLifetime = maxLifetime;
CacheConfiguration<K, V> config = new CacheConfiguration<K, V>();
config.setName(name);
config.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.MILLISECONDS, maxLifetime)));
map = IgniteInstance.getInstance().getIgnite().getOrCreateCache(config);
}
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 void maybeCreateCache() {
if (cache == null) {
log.debug("Creating {} for: {}", CACHE_NAME, getRepository());
cache = cacheHelper.maybeCreateCache(CACHE_NAME, AuditComponent.class, VulnerabilityList.class,
CreatedExpiryPolicy.factoryOf(CACHE_DURATION));
log.debug("Created {}: {}", CACHE_NAME, cache);
}
}
@VisibleForTesting
<K, V> javax.cache.Cache<K, V> maybeCreateCache(final String name) {
if (Objects.equals(ACTIVE_SESSION_CACHE_NAME, name)) {
// shiro's session cache needs to never expire:
// http://shiro.apache.org/session-management.html#ehcache-session-cache-configuration
return cacheHelperProvider.get().maybeCreateCache(name, EternalExpiryPolicy.factoryOf());
}
else {
Time timeToLive = Optional.ofNullable(System.getProperty(name + ".timeToLive"))
.map(Time::parse)
.orElse(defaultTimeToLive.get());
return cacheHelperProvider.get().maybeCreateCache(name,
CreatedExpiryPolicy.factoryOf(new Duration(timeToLive.getUnit(), timeToLive.getValue())));
}
}
private void maybeCreateCache() {
if (cache == null) {
log.debug("Creating negative-cache for: {}", getRepository());
cache = cacheHelper.maybeCreateCache(getCacheName(), NegativeCacheKey.class, Status.class,
CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.MINUTES, config.timeToLive)));
log.debug("Created negative-cache: {}", cache);
}
}
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);
}
/**
* Put values into the table with expire policy. Inserted row become expired in {@link #EXPIRE_IN_MS_FROM_CREATE}
* milliseconds.
*
* @param cache cache to put values in.
* @param key key of the row.
* @param val value of the row.
*/
private void putExpiredSoon(IgniteCache cache, Integer key, Integer val) {
CreatedExpiryPolicy expireSinceCreated = new CreatedExpiryPolicy(new Duration(TimeUnit.MILLISECONDS,
EXPIRE_IN_MS_FROM_CREATE));
IgniteCache<Integer, Integer> expCache = cache.withExpiryPolicy(expireSinceCreated);
expCache.put(key, val);
}
/**
* Put values into the table with expire policy.
*
* @param cache cache to put values in.
* @param key key of the row.
* @param val value of the row.
*/
private void putExpireInYear(IgniteCache cache, Integer key, Integer val) {
CreatedExpiryPolicy expireSinceCreated = new CreatedExpiryPolicy(new Duration(TimeUnit.MILLISECONDS,
TimeUnit.DAYS.toMillis(365)));
IgniteCache<Integer, Integer> expCache = cache.withExpiryPolicy(expireSinceCreated);
expCache.put(key, val);
}
/**
* @throws Exception If failed.
*/
@Test
public void testZeroOnCreate() throws Exception {
factory = CreatedExpiryPolicy.factoryOf(Duration.ZERO);
startGrids();
for (final Integer key : keys()) {
log.info("Test zero duration on create, key: " + key);
zeroOnCreate(key);
}
}
/**
* Configure streaming cache.
*/
public static CacheConfiguration<AffinityUuid, String> wordCache() {
CacheConfiguration<AffinityUuid, String> cfg = new CacheConfiguration<>("words");
// Index all words streamed into cache.
cfg.setIndexedTypes(AffinityUuid.class, String.class);
// Sliding window of 1 seconds.
cfg.setExpiryPolicyFactory(FactoryBuilder.factoryOf(new CreatedExpiryPolicy(new Duration(SECONDS, 1))));
return cfg;
}
@Test
public void test107ExpiryOverriddenByEhcacheTemplateExpiry() {
final AtomicBoolean expiryFactoryInvoked = new AtomicBoolean(false);
MutableConfiguration<Long, Product> configuration = new MutableConfiguration<>();
configuration.setTypes(Long.class, Product.class);
configuration.setExpiryPolicyFactory(() -> {
expiryFactoryInvoked.set(true);
return new CreatedExpiryPolicy(Duration.FIVE_MINUTES);
});
cacheManager.createCache("productCache3", configuration);
assertThat(expiryFactoryInvoked.get(), is(false));
}
@Test
public void jsr107ExpiryGetsRegistered() {
MutableConfiguration<Object, Object> configuration = new MutableConfiguration<>();
RecordingFactory<CreatedExpiryPolicy> factory = factoryOf(new CreatedExpiryPolicy(javax.cache.expiry.Duration.FIVE_MINUTES));
configuration.setExpiryPolicyFactory(factory);
ConfigurationMerger.ConfigHolder<Object, Object> configHolder = merger.mergeConfigurations("Cache", configuration);
assertThat(factory.called, is(true));
org.ehcache.expiry.ExpiryPolicy<Object, Object> resourcesExpiry = configHolder.cacheResources.getExpiryPolicy();
org.ehcache.expiry.ExpiryPolicy<Object, Object> configExpiry = configHolder.cacheConfiguration.getExpiryPolicy();
assertThat(configExpiry, sameInstance(resourcesExpiry));
}