org.cache2k.Cache2kBuilder Java Examples
The following examples show how to use
org.cache2k.Cache2kBuilder.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Cache2kCacheFactory.java From joyrpc with Apache License 2.0 | 6 votes |
@Override public <K, V> Cache<K, V> build(final String name, final CacheConfig<K, V> config) { Cache2kBuilder<K, CacheObject<V>> builder = Cache2kBuilder.forUnknownTypes(); if (config.getKeyClass() != null) { builder.keyType(config.getKeyClass()); } builder.valueType(CacheObject.class); builder.permitNullValues(config.isNullable()); builder.entryCapacity(config.getCapacity() > 0 ? config.getCapacity() : Long.MAX_VALUE); if (config.getExpireAfterWrite() > 0) { builder.expireAfterWrite(config.getExpireAfterWrite(), TimeUnit.MILLISECONDS); } else { builder.eternal(true); } return new Cache2kCache<>(builder.build(), config); }
Example #2
Source File: JmxSupportTest.java From cache2k with Apache License 2.0 | 6 votes |
@Test public void testDisabled() throws Exception { String _name = getClass().getName() + ".testInitialProperties"; Cache c = new Cache2kBuilder<Long, List<Collection<Long>>> () {} .name(_name) .disableStatistics(true) .eternal(true) .build(); objectName = constructCacheObjectName(_name); try { retrieve("Alert"); fail("exception expected"); } catch (InstanceNotFoundException ex) { } c.close(); }
Example #3
Source File: Cache2kBuilderTest.java From cache2k with Apache License 2.0 | 6 votes |
@Test public void duplicateCacheName() { String _managerName = getClass().getName() + ".duplicateCacheName"; Log.registerSuppression(CacheManager.class.getName() + ":" + _managerName, new Log.SuppressionCounter()); CacheManager mgr = CacheManager.getInstance(_managerName); try { Cache c0 = Cache2kBuilder.forUnknownTypes() .manager(mgr) .eternal(true) .name(this.getClass(), "same") .build(); Cache c1 = Cache2kBuilder.forUnknownTypes() .manager(mgr) .eternal(true) .name(this.getClass(), "same") .build(); fail("exception expected"); } catch (IllegalStateException ex) { } mgr.close(); }
Example #4
Source File: Cache2kBuilderTest.java From cache2k with Apache License 2.0 | 6 votes |
private void cacheClosedEventFired(boolean _wiredCache) { final AtomicBoolean _FIRED = new AtomicBoolean(); Cache2kBuilder _builder = Cache2kBuilder.forUnknownTypes(); _builder = _builder.addCacheClosedListener(new CacheClosedListener() { @Override public void onCacheClosed(final Cache cache) { _FIRED.set(true); } }); if (_wiredCache) { StaticUtil.enforceWiredCache(_builder); } Cache c = _builder.build(); c.close(); assertTrue(_FIRED.get()); }
Example #5
Source File: BasicTimingTest.java From cache2k with Apache License 2.0 | 6 votes |
@Test public void testBigCacheTimingWithUpdate() { final int _CACHE_SIZE = 1000000; Cache<Integer,Integer> c = Cache2kBuilder.of(Integer.class, Integer.class) .entryCapacity(_CACHE_SIZE) .eternal(true) .build(); for (int i = 0; i < _CACHE_SIZE; i++) { c.put(i, i); } for (int i = 0; i < _CACHE_SIZE; i++) { c.put(i, i); } assertNotNull(c.toString()); }
Example #6
Source File: TimingHandlerTest.java From cache2k with Apache License 2.0 | 6 votes |
/** * Maximum expiry is limited when sharp expiry requested. * Corner case if expiry will happen close to requested point in time. */ @Test public void expireAfterWrite_policy_limit_sharp_close() { long _DURATION = 100; final long _SHARP_POINT_IN_TIME = NOW + 5000; TimingHandler h = TimingHandler.of( CLOCK, Cache2kBuilder.forUnknownTypes() .expiryPolicy(new ExpiryPolicy() { @Override public long calculateExpiryTime(Object key, Object value, long loadTime, CacheEntry oldEntry) { return -_SHARP_POINT_IN_TIME; } }) .expireAfterWrite(_DURATION, TimeUnit.MILLISECONDS) .toConfiguration() ); Entry e = new Entry(); long _later = _SHARP_POINT_IN_TIME - _DURATION - 1; long t = h.calculateNextRefreshTime(e, null, _later); assertTrue("expect gap bigger then duration", HeapCache.TUNABLE.sharpExpirySafetyGapMillis > _DURATION); assertNotEquals(_SHARP_POINT_IN_TIME - HeapCache.TUNABLE.sharpExpirySafetyGapMillis, t); assertTrue(Math.abs(t) > NOW); assertTrue(Math.abs(t) < _SHARP_POINT_IN_TIME); }
Example #7
Source File: ProductHelperWithEventListener.java From tutorials with MIT License | 6 votes |
public ProductHelperWithEventListener() { cachedDiscounts = Cache2kBuilder.of(String.class, Integer.class) .name("discount-listener") .expireAfterWrite(10, TimeUnit.MILLISECONDS) .entryCapacity(100) .loader((key) -> { cacheMissCount++; return "Sports".equalsIgnoreCase(key) ? 20 : 10; }) .addListener(new CacheEntryCreatedListener<String, Integer>() { @Override public void onEntryCreated(Cache<String, Integer> cache, CacheEntry<String, Integer> entry) { LOGGER.info("Entry created: [{}, {}].", entry.getKey(), entry.getValue()); } }) .build(); }
Example #8
Source File: ListenerTest.java From cache2k with Apache License 2.0 | 6 votes |
@Test public void evictedListenerCalled() { target.run(new CountSyncEvents() { @Override public void extend(final Cache2kBuilder<Integer, Integer> b) { super.extend(b); b.entryCapacity(1); } @Override public void run() { assertEquals(0, evicted.get()); cache.put(1, 2); assertEquals(0, evicted.get()); cache.put(2, 2); assertEquals(1, evicted.get()); } }); }
Example #9
Source File: CacheLoaderTest.java From cache2k with Apache License 2.0 | 6 votes |
@Test public void testAdvancedLoader() { Cache<Integer,Integer> c = target.cache(new CacheRule.Specialization<Integer, Integer>() { @Override public void extend(final Cache2kBuilder<Integer, Integer> b) { b .loader(new AdvancedCacheLoader<Integer, Integer>() { @Override public Integer load(final Integer key, long startTime, CacheEntry<Integer,Integer> e) throws Exception { return key * 2; } }); } }); assertEquals((Integer) 10, c.get(5)); assertEquals((Integer) 20, c.get(10)); assertFalse(c.containsKey(2)); assertTrue(c.containsKey(5)); }
Example #10
Source File: CacheLoaderTest.java From cache2k with Apache License 2.0 | 6 votes |
@Test public void testLoadNull() { Cache<Integer,Integer> c = target.cache(new CacheRule.Specialization<Integer, Integer>() { @Override public void extend(final Cache2kBuilder<Integer, Integer> b) { b .loader(new CacheLoader<Integer, Integer>() { @Override public Integer load(final Integer key) throws Exception { return null; } }) .permitNullValues(true); } }); assertNull(c.get(5)); assertTrue(c.containsKey(5)); }
Example #11
Source File: EntryProcessorTest.java From cache2k with Apache License 2.0 | 6 votes |
@Test public void setException_propagation() { final String _TEXT = "set inside process"; Cache<Integer, Integer> c = target.cache(new CacheRule.Specialization<Integer, Integer>() { @Override public void extend(final Cache2kBuilder<Integer, Integer> b) { b.retryInterval(Long.MAX_VALUE, TimeUnit.MILLISECONDS); } }); c.invoke(KEY, new EntryProcessor<Integer, Integer, Object>() { @Override public Object process(final MutableCacheEntry<Integer, Integer> e) throws Exception { e.setException(new IllegalStateException(_TEXT)); return null; } }); try { c.get(KEY); fail(); } catch (CacheLoaderException ex) { assertTrue(ex.getCause().toString().contains(_TEXT)); } }
Example #12
Source File: CacheLoaderTest.java From cache2k with Apache License 2.0 | 6 votes |
/** * Check that non runtime exceptions from the async loader are wrapped. */ @Test public void testAsyncLoaderExceptionWrapped() { final AtomicInteger loaderCalled = new AtomicInteger(); Cache<Integer,Integer> c = target.cache(new CacheRule.Specialization<Integer, Integer>() { @Override public void extend(final Cache2kBuilder<Integer, Integer> b) { b.loader(new AsyncCacheLoader<Integer, Integer>() { @Override public void load(final Integer key, final Context<Integer, Integer> ctx, final Callback<Integer> callback) throws Exception { loaderCalled.incrementAndGet(); throw new IOException("test exception"); } }); } }); try { Integer v = c.get(1); fail("exception expected"); } catch (CacheLoaderException expected) { } catch (Throwable other) { assertNull("unexpected exception", other); } }
Example #13
Source File: CacheLoaderTest.java From cache2k with Apache License 2.0 | 6 votes |
@Test public void testAsyncLoaderContextProperties() { final AtomicInteger loaderCalled = new AtomicInteger(); Cache<Integer,Integer> c = target.cache(new CacheRule.Specialization<Integer, Integer>() { @Override public void extend(final Cache2kBuilder<Integer, Integer> b) { b.loader(new AsyncCacheLoader<Integer, Integer>() { @Override public void load(final Integer key, final Context<Integer, Integer> ctx, final Callback<Integer> callback) { int cnt = loaderCalled.getAndIncrement(); if (cnt == 0) { assertNull(ctx.getCurrentEntry()); } else { assertEquals(key, ctx.getCurrentEntry().getValue()); assertNull(ctx.getCurrentEntry().getException()); } callback.onLoadSuccess(key); } }); } }); Integer v = c.get(1); assertEquals(1, (int) v); reload(c, 1); }
Example #14
Source File: JmxSupportTest.java From cache2k with Apache License 2.0 | 5 votes |
@Test(expected = InstanceNotFoundException.class) public void testCacheCreated_notFound() throws Exception { String _name = getClass().getName() + ".testCacheCreated"; Cache c = Cache2kBuilder.of(Object.class, Object.class) .name(_name) .eternal(true) .build(); MBeanInfo i = getCacheInfo(_name); assertEquals(CacheMXBeanImpl.class.getName(), i.getClassName()); c.close(); }
Example #15
Source File: ExpiryTest.java From cache2k with Apache License 2.0 | 5 votes |
/** * Refresh by manual expiry trigger. Use async loader and check that no more than one thread is * needed to execute in parallel. */ @Test public void manualExpire_refresh_refreshImmediately_async() throws Exception { new ManualExpireFixture() { @Override protected void addLoader(final Cache2kBuilder<Integer, Integer> b) { b.loaderExecutor(Executors.newSingleThreadExecutor()); b.loader(new AsyncCacheLoader<Integer, Integer>() { @Override public void load(final Integer key, final Context<Integer, Integer> context, final Callback<Integer> callback) throws Exception { context.getLoaderExecutor().execute(new Runnable() { @Override public void run() { try { callback.onLoadSuccess(waitForSemaphoreAndLoad(key)); } catch (Exception ex) { callback.onLoadFailure(ex); } } }); } }); } @Override void test() throws Exception { cache.put(1, 2); sem.acquire(); cache.expireAt(1, ExpiryTimeValues.REFRESH); likeRefreshImmediately(); } }.test(); }
Example #16
Source File: ExpiryTest.java From cache2k with Apache License 2.0 | 5 votes |
@Test public void testFetchAlwaysWithVariableExpiryInPastAfterLoad() { IntCountingCacheSource g = new IntCountingCacheSource(); final Cache<Integer, Integer> c = cache = Cache2kBuilder.of(Integer.class, Integer.class) .loader(g) .expiryPolicy(new ExpiryPolicy<Integer, Integer>() { @Override public long calculateExpiryTime(final Integer key, final Integer value, final long loadTime, final CacheEntry<Integer, Integer> oldEntry) { sleep(3); return loadTime + 1; } }) .expireAfterWrite(0, TimeUnit.SECONDS).build(); checkAlwaysLoaded(g, c); }
Example #17
Source File: IntegrationTest.java From cache2k with Apache License 2.0 | 5 votes |
@Test public void notSerializableSection() { try { new Cache2kBuilder<String, String>() { } .manager(CacheManager.getInstance("notSerializable")) .name("notSerializable") .build(); fail("expect exception"); } catch (Exception ex) { assertThat(ex.toString(), containsString("Copying default cache configuration")); assertThat(ex.getCause(), CoreMatchers.<Throwable>instanceOf(Serializable.class)); } }
Example #18
Source File: IntegrationTest.java From cache2k with Apache License 2.0 | 5 votes |
@Test public void notPresent() { Cache c = new Cache2kBuilder<String, String>() { } .manager(CacheManager.getInstance("notPresent")) .name("anyCache") .build(); c.close(); }
Example #19
Source File: IntegrationTest.java From cache2k with Apache License 2.0 | 5 votes |
@Test(expected = ConfigurationException.class) public void typeMismatch() { Cache c = new Cache2kBuilder<String, String>() { } .manager(CacheManager.getInstance("specialCases")) .name("typeMismatch") .build(); c.close(); }
Example #20
Source File: IntegrationTest.java From cache2k with Apache License 2.0 | 5 votes |
@Test public void parseError() { try { new Cache2kBuilder<String, String>() { } .manager(CacheManager.getInstance("parseError")) .entryCapacity(1234); fail("expect exception"); } catch (Exception ex) { assertThat(ex.toString(), containsString("type missing or unknown")); } }
Example #21
Source File: JmxSupportTest.java From cache2k with Apache License 2.0 | 5 votes |
@Test(expected = InstanceNotFoundException.class) public void testCacheDestroyed() throws Exception { String _name = getClass().getName() + ".testCacheDestroyed"; Cache c = Cache2kBuilder.of(Object.class, Object.class) .name(_name) .eternal(true) .build(); MBeanInfo i = getCacheInfo(_name); assertEquals(CacheMXBeanImpl.class.getName(), i.getClassName()); c.close(); getCacheInfo(_name); }
Example #22
Source File: CacheLoaderTest.java From cache2k with Apache License 2.0 | 5 votes |
@Test public void testAsyncLoaderWithExecutorWithAsync() { final AtomicInteger loaderCalled = new AtomicInteger(); final AtomicInteger loaderExecuted = new AtomicInteger(); Cache<Integer,Integer> c = target.cache(new CacheRule.Specialization<Integer, Integer>() { @Override public void extend(final Cache2kBuilder<Integer, Integer> b) { b.loader(new AsyncCacheLoader<Integer, Integer>() { @Override public void load(final Integer key, final Context<Integer, Integer> ctx, final Callback<Integer> callback) { loaderCalled.incrementAndGet(); ctx.getLoaderExecutor().execute(new Runnable() { @Override public void run() { loaderExecuted.incrementAndGet(); callback.onLoadSuccess(key); } }); } }); } }); CompletionWaiter w = new CompletionWaiter(); c.loadAll(TestingBase.keys(1, 2, 1802), w); w.awaitCompletion(); assertEquals(1, (int) c.peek(1)); Object o1 = c.peek(1802); assertTrue(c.peek(1802) == o1); w = new CompletionWaiter(); c.reloadAll(TestingBase.keys(1802, 4, 5), w); w.awaitCompletion(); assertNotNull(c.peek(1802)); assertTrue(c.peek(1802) != o1); }
Example #23
Source File: RedissonClient.java From bidder with Apache License 2.0 | 5 votes |
/** * Instantiate the Redisson object using the Cache2k systen (embedded cache, single server system). */ public RedissonClient() { cache = new Cache2kBuilder<String, Object>() { }.expireAfterWrite(300, TimeUnit.SECONDS).build(); cacheDb = new Cache2kBuilder<String, Object>() { }.build(); cacheDb.put("users-database", new ArrayList<Campaign>()); }
Example #24
Source File: CacheManagerAndCacheLifeCycleTest.java From cache2k with Apache License 2.0 | 5 votes |
@Test public void testToStringWithManager() { String _managerName = this.getClass().getSimpleName(); CacheManager cm = CacheManager.getInstance(_managerName); Cache<Integer, Integer> c = Cache2kBuilder.of(Integer.class, Integer.class) .manager(cm) .name("testToString") .eternal(true) .build(); assertThat(c.toString(), containsString("Cache(name='testToString', manager='" + _managerName + "'" )); c.close(); cm.close(); assertThat(c.toString(), containsString("Cache(name='testToString', manager='" + _managerName + "'" )); }
Example #25
Source File: CacheTest.java From cache2k with Apache License 2.0 | 5 votes |
@Test public void testPeekAndPut() { Cache<String,String> c = Cache2kBuilder.of(String.class, String.class) .eternal(true) .build(); String val = c.peek("something"); assertNull(val); c.put("something", "hello"); val = c.get("something"); assertNotNull(val); c.close(); }
Example #26
Source File: DefaultResiliencePolicyTest.java From cache2k with Apache License 2.0 | 5 votes |
/** * This is values=eternal, exceptions=immediate. */ @Test public void eternal_retry0s() { Cache<Integer, Integer> c = new Cache2kBuilder<Integer, Integer>() {} .eternal(true) .retryInterval(0, TimeUnit.SECONDS) /* ... set loader ... */ .build(); target.setCache(c); assertTrue(extractHandler() instanceof TimingHandler.EternalImmediate); }
Example #27
Source File: EntryProcessorTest.java From cache2k with Apache License 2.0 | 5 votes |
/** * Set expiry which keeps exceptions */ CacheWithLoader cacheWithLoaderKeepExceptions() { final CacheWithLoader c = new CacheWithLoader(); c.cache = target.cache(new CacheRule.Specialization<Integer, Integer>() { @Override public void extend(final Cache2kBuilder<Integer, Integer> b) { b.loader(c.loader); b.expireAfterWrite(999, TimeUnit.DAYS); } }); return c; }
Example #28
Source File: Cache2kBuilderTest.java From cache2k with Apache License 2.0 | 5 votes |
@Test(expected = IllegalStateException.class) public void managerAfterOtherStuff() { Cache2kBuilder.forUnknownTypes() .eternal(true) .manager(CacheManager.getInstance()) .build(); }
Example #29
Source File: TimingHandlerTest.java From cache2k with Apache License 2.0 | 5 votes |
@Test public void eternalNotSpecified() { TimingHandler h = TimingHandler.of( CLOCK, Cache2kBuilder.forUnknownTypes() .toConfiguration() ); assertEquals(TimingHandler.ETERNAL_IMMEDIATE.getClass(), h.getClass()); }
Example #30
Source File: CacheTest.java From cache2k with Apache License 2.0 | 5 votes |
@Test public void testGetEntry() { Cache<String,String> c = Cache2kBuilder.of(String.class, String.class) .eternal(true) .build(); String val = c.peek("something"); assertNull(val); c.put("something", "hello"); CacheEntry<String, String> e = c.getEntry("something"); assertNotNull(e); assertEquals("hello", e.getValue()); c.close(); }