org.ehcache.config.builders.CacheConfigurationBuilder Java Examples

The following examples show how to use org.ehcache.config.builders.CacheConfigurationBuilder. 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: Tiering.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void byteSizedTieredCache() {
  // tag::byteSizedTieredCache[]
  CacheConfiguration<Long, String> usesConfiguredInCacheConfig = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
    ResourcePoolsBuilder.newResourcePoolsBuilder()
      .heap(10, MemoryUnit.KB) // <1>
      .offheap(10, MemoryUnit.MB)) // <2>
    .withSizeOfMaxObjectGraph(1000)
    .withSizeOfMaxObjectSize(1000, MemoryUnit.B) // <3>
    .build();

  CacheConfiguration<Long, String> usesDefaultSizeOfEngineConfig = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
    ResourcePoolsBuilder.newResourcePoolsBuilder()
      .heap(10, MemoryUnit.KB))
    .build();

  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
    .withDefaultSizeOfMaxObjectSize(500, MemoryUnit.B)
    .withDefaultSizeOfMaxObjectGraph(2000) // <4>
    .withCache("usesConfiguredInCache", usesConfiguredInCacheConfig)
    .withCache("usesDefaultSizeOfEngine", usesDefaultSizeOfEngineConfig)
    .build(true);
  // end::byteSizedTieredCache[]
}
 
Example #2
Source File: TerminatedServerTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testTerminationBeforeCacheManagerCloseWithCaches() throws Exception {
  CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder =
      CacheManagerBuilder.newCacheManagerBuilder()
          .with(ClusteringServiceConfigurationBuilder.cluster(CLUSTER.get().getConnectionURI().resolve("/").resolve(testName.getMethodName()))
                  .autoCreate(server -> server.defaultServerResource("primary-server-resource")))
          .withCache("simple-cache",
              CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
                  ResourcePoolsBuilder.newResourcePoolsBuilder()
                      .with(ClusteredResourcePoolBuilder.clusteredDedicated(4, MemoryUnit.MB))));
  PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(false);
  cacheManager.init();

  CLUSTER.get().getClusterControl().terminateAllServers();

  cacheManager.close();

}
 
Example #3
Source File: GettingStarted.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void clusteredCacheManagerWithServerSideConfigExample() throws Exception {
  // tag::clusteredCacheManagerWithServerSideConfigExample[]
  CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder =
      CacheManagerBuilder.newCacheManagerBuilder()
          .with(ClusteringServiceConfigurationBuilder.cluster(URI.create("terracotta://localhost/my-application")).autoCreateOnReconnect(server -> server
              .defaultServerResource("primary-server-resource") // <1>
              .resourcePool("resource-pool-a", 8, MemoryUnit.MB, "secondary-server-resource") // <2>
              .resourcePool("resource-pool-b", 10, MemoryUnit.MB))) // <3>
          .withCache("clustered-cache", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, // <4>
              ResourcePoolsBuilder.newResourcePoolsBuilder()
                  .with(ClusteredResourcePoolBuilder.clusteredDedicated("primary-server-resource", 8, MemoryUnit.MB)))) // <5>
          .withCache("shared-cache-1", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
              ResourcePoolsBuilder.newResourcePoolsBuilder()
                  .with(ClusteredResourcePoolBuilder.clusteredShared("resource-pool-a")))) // <6>
          .withCache("shared-cache-2", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
              ResourcePoolsBuilder.newResourcePoolsBuilder()
                  .with(ClusteredResourcePoolBuilder.clusteredShared("resource-pool-a")))); // <7>
  PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(true); // <8>

  cacheManager.close();
  // end::clusteredCacheManagerWithServerSideConfigExample[]
}
 
Example #4
Source File: ClusteredConcurrencyTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
private Runnable content(final CountDownLatch latch) {
  return () -> {
    try {
      CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder = CacheManagerBuilder.newCacheManagerBuilder()
        .with(ClusteringServiceConfigurationBuilder.cluster(CLUSTER_URI)
          .autoCreate(server -> server.defaultServerResource("primary-server-resource")
            .resourcePool("resource-pool-a", 8, MemoryUnit.MB)
            .resourcePool("resource-pool-b", 8, MemoryUnit.MB, "secondary-server-resource")))
        .withCache(CACHE_NAME, CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
          ResourcePoolsBuilder.newResourcePoolsBuilder()
            .with(ClusteredResourcePoolBuilder.clusteredDedicated("primary-server-resource", 8, MemoryUnit.MB)))
          .withService(new ClusteredStoreConfiguration(Consistency.STRONG)));

      latch.countDown();
      try {
        latch.await();
      } catch (InterruptedException e) {
        // continue
      }

      clusteredCacheManagerBuilder.build(true).close();
    } catch (Throwable t) {
      exception.compareAndSet(null, t); // only keep the first exception
    }
  };
}
 
Example #5
Source File: TestEviction.java    From jframe with Apache License 2.0 6 votes vote down vote up
public void evictionTest() {
    CacheConfiguration<Long, String> cacheConfiguration =
            CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(2L)).build();
    // .withEvictionAdvisor(new OddKeysEvictionAdvisor<Long, String>()).build();

    CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().withCache("cache", cacheConfiguration).build(true);

    Cache<Long, String> cache = cacheManager.getCache("cache", Long.class, String.class);

    // Work with the cache
    cache.put(42L, "The Answer!");
    cache.put(41L, "The wrong Answer!");
    cache.put(39L, "The other wrong Answer!");

    cacheManager.close();
}
 
Example #6
Source File: ThreadPoolsTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoDefaultThreadPoolFails() throws Exception {
  PooledExecutionServiceConfiguration executionServiceConfiguration = new PooledExecutionServiceConfiguration();
  executionServiceConfiguration.addPool("foo", 2, 4);
  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
      .using(executionServiceConfiguration)
      .build(true);

  try {
    cacheManager.createCache("testCache",
        CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, heap(10))
            .build());
    fail("expected IllegalStateException");
  } catch (IllegalStateException ise) {
    // expected
  }

  cacheManager.close();
}
 
Example #7
Source File: WriteBehindProviderFactoryTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testAddingWriteBehindConfigurationAtCacheLevel() {
  CacheManagerBuilder<CacheManager> cacheManagerBuilder = CacheManagerBuilder.newCacheManagerBuilder();
  WriteBehindConfiguration<?> writeBehindConfiguration = WriteBehindConfigurationBuilder.newBatchedWriteBehindConfiguration(Long.MAX_VALUE, SECONDS, 1)
      .concurrencyLevel(3)
      .queueSize(10)
      .build();
  Class<CacheLoaderWriter<?, ?>> klazz = (Class<CacheLoaderWriter<?, ?>>) (Class) (SampleLoaderWriter.class);
  CacheManager cacheManager = cacheManagerBuilder.build(true);
  final Cache<Long, String> cache = cacheManager.createCache("cache",
      CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, heap(100))
          .withService(writeBehindConfiguration)
          .withService(new DefaultCacheLoaderWriterConfiguration(klazz))
          .build());
  Collection<ServiceConfiguration<?, ?>> serviceConfiguration = cache.getRuntimeConfiguration()
      .getServiceConfigurations();
  assertThat(serviceConfiguration, IsCollectionContaining.<ServiceConfiguration<?, ?>>hasItem(instanceOf(WriteBehindConfiguration.class)));
  cacheManager.close();
}
 
Example #8
Source File: StatsUtilsTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Before
public void before() {
  CacheConfiguration<Long, String> cacheConfiguration =
    CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, heap(10))
      .withService(new StoreStatisticsConfiguration(true)) // explicitly enable statistics
      .build();

  cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
    .withCache("aCache", cacheConfiguration)
    .build(true);

  cache = cacheManager.getCache("aCache", Long.class, String.class);

  StatisticsManager.createPassThroughStatistic(cache, "test", tags(), properties("myproperty=myvalue"), StatisticType.COUNTER, () -> 0);

  cache.get(1L);
}
 
Example #9
Source File: UnSupportedCombinationsWithClusteredCacheTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testClusteredCacheWithSynchronousEventListeners() {
  CacheEventListenerConfigurationBuilder cacheEventListenerConfiguration = CacheEventListenerConfigurationBuilder
      .newEventListenerConfiguration(new TestEventListener(), EventType.CREATED, EventType.UPDATED)
      .unordered().synchronous();

  final CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder
      = CacheManagerBuilder.newCacheManagerBuilder()
      .with(ClusteringServiceConfigurationBuilder.cluster(URI.create("terracotta://localhost/my-application"))
          .autoCreate(c -> c));
  try (PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(true)) {
    CacheConfiguration<Long, String> config = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
        ResourcePoolsBuilder.newResourcePoolsBuilder()
            .with(ClusteredResourcePoolBuilder.clusteredDedicated("primary-server-resource", 8, MemoryUnit.MB)))
        .withService(cacheEventListenerConfiguration)
        .build();

    cacheManager.createCache("test", config);
    fail("IllegalStateException expected");
  } catch (IllegalStateException e){
    assertThat(e.getCause().getMessage(), is("Synchronous CacheEventListener is not supported with clustered tiers"));
  }
}
 
Example #10
Source File: EhCacheProvider3.java    From J2Cache with Apache License 2.0 6 votes vote down vote up
@Override
public EhCache3 buildCache(String region, long timeToLiveInSeconds, CacheExpiredListener listener) {
    EhCache3 ehcache = caches.computeIfAbsent(region, v -> {
        CacheConfiguration<String, Object> conf = CacheConfigurationBuilder.newCacheConfigurationBuilder(
                String.class, Object.class, ResourcePoolsBuilder.heap(defaultHeapSize))
                .withExpiry(Expirations.timeToLiveExpiration(Duration.of(timeToLiveInSeconds, TimeUnit.SECONDS)))
                .build();
        org.ehcache.Cache cache = manager.createCache(region, conf);
        log.info("Started Ehcache region [{}] with TTL: {}", region, timeToLiveInSeconds);
        return new EhCache3(region, cache, listener);
    });

    if (ehcache.ttl() != timeToLiveInSeconds)
        throw new IllegalArgumentException(String.format("Region [%s] TTL %d not match with %d", region, ehcache.ttl(), timeToLiveInSeconds));

    return ehcache;
}
 
Example #11
Source File: CacheManagerListenerTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Before
public void before() {
  CacheConfigurationBuilder<Long, String> cacheConfiguration =
    CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
      ResourcePoolsBuilder.newResourcePoolsBuilder()
        .heap(1, MB).disk(2, MB));

  cacheManagerListener = mock(CacheManagerListener.class);

  cacheManager = (EhcacheManager) CacheManagerBuilder.newCacheManagerBuilder()
    .with(new CacheManagerPersistenceConfiguration(folder.getRoot()))
    .withCache(CACHE, cacheConfiguration)
    .build();
  cacheManager.registerListener(cacheManagerListener);
  cacheManager.init();
}
 
Example #12
Source File: ConfigurationParser.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
private XmlConfiguration.Template parseTemplate(CacheTemplate template) {
  return new XmlConfiguration.Template() {
    @Override
    public <K, V> CacheConfigurationBuilder<K, V> builderFor(ClassLoader classLoader, Class<K> keyType, Class<V> valueType, ResourcePools resources) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
      checkTemplateTypeConsistency("key", classLoader, keyType, template);
      checkTemplateTypeConsistency("value", classLoader, valueType, template);

      if ((resources == null || resources.getResourceTypeSet().isEmpty()) && template.getHeap() == null && template.getResources().isEmpty()) {
        throw new IllegalStateException("Template defines no resources, and none were provided");
      }

      if (resources == null) {
        resources = resourceConfigurationParser.parseResourceConfiguration(template, newResourcePoolsBuilder());
      }

      return parseServiceConfigurations(newCacheConfigurationBuilder(keyType, valueType, resources), classLoader, template);
    }
  };
}
 
Example #13
Source File: BasicClusteredCacheOpsReplicationWithServersApiTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  CLUSTER.getClusterControl().startAllServers();

  final CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder
    = CacheManagerBuilder.newCacheManagerBuilder()
    .with(getConfigBuilder()
      .timeouts(TimeoutsBuilder.timeouts() // we need to give some time for the failover to occur
        .read(Duration.ofMinutes(1))
        .write(Duration.ofMinutes(1)))
      .autoCreate(server -> server.defaultServerResource("primary-server-resource")));
  CACHE_MANAGER = clusteredCacheManagerBuilder.build(true);
  CacheConfiguration<Long, String> config = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
    ResourcePoolsBuilder.newResourcePoolsBuilder().heap(100, EntryUnit.ENTRIES)
      .with(ClusteredResourcePoolBuilder.clusteredDedicated("primary-server-resource", 4, MemoryUnit.MB)))
    .build();

  CACHE1 = CACHE_MANAGER.createCache("clustered-cache", config);
  CACHE2 = CACHE_MANAGER.createCache("another-cache", config);
}
 
Example #14
Source File: CacheConfigurationCustomizerEnabledAppendTest.java    From camel-spring-boot with Apache License 2.0 6 votes vote down vote up
@Order(Ordered.HIGHEST_PRECEDENCE)
@Bean
public ComponentCustomizer<EhcacheComponent> customizer() {
    return new ComponentCustomizer<EhcacheComponent>() {
        @Override
        public void customize(EhcacheComponent component) {
            component.addCachesConfigurations(Collections.singletonMap(
                CACHE_CONFIG_ID,
                CacheConfigurationBuilder.newCacheConfigurationBuilder(
                    String.class,
                    String.class,
                    ResourcePoolsBuilder.newResourcePoolsBuilder()
                        .heap(2100, EntryUnit.ENTRIES)
                        .offheap(2, MemoryUnit.MB))
                    .build()
            ));
        }
    };
}
 
Example #15
Source File: EhcacheBulkMethodsITest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testPutAll_without_cache_writer() throws Exception {
  CacheConfigurationBuilder cacheConfigurationBuilder = CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class,
      heap(100));
  CacheConfiguration<String, String> cacheConfiguration = cacheConfigurationBuilder.build();

  CacheManagerBuilder<CacheManager> managerBuilder = CacheManagerBuilder.newCacheManagerBuilder();
  CacheManager cacheManager = managerBuilder.withCache("myCache", cacheConfiguration).build(true);

  Cache<String, String> myCache = cacheManager.getCache("myCache", String.class, String.class);

  HashMap<String, String> stringStringHashMap = new HashMap<>();
  for (int i = 0; i < 3; i++) {
    stringStringHashMap.put("key" + i, "value" + i);
  }

  // the call to putAll
  myCache.putAll(stringStringHashMap);

  for (int i = 0; i < 3; i++) {
    assertThat(myCache.get("key" + i), is("value" + i));
  }

}
 
Example #16
Source File: TransactionalOsgiTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
public static void testProgrammaticConfiguration() throws Exception {
  BitronixTransactionManager transactionManager = getTransactionManager();

  try (CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
    .withClassLoader(TestMethods.class.getClassLoader())
    .using(new LookupTransactionManagerProviderConfiguration(BitronixTransactionManagerLookup.class))
    .withCache("xaCache", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, heap(10))
      .withService(new XAStoreConfiguration("xaCache")).build()).build(true)) {

    Cache<Long, String> xaCache = cacheManager.getCache("xaCache", Long.class, String.class);

    transactionManager.begin();
    try {
      xaCache.put(1L, "one");
    } catch (Throwable t) {
      transactionManager.rollback();
    }
    transactionManager.commit();
  }
  transactionManager.shutdown();
}
 
Example #17
Source File: Tiering.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void threeTiersCacheManager() throws Exception {
  // tag::threeTiersCacheManager[]
  PersistentCacheManager persistentCacheManager = CacheManagerBuilder.newCacheManagerBuilder()
    .with(cluster(CLUSTER_URI).autoCreate(c -> c)) // <1>
    .withCache("threeTierCache",
      CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
        ResourcePoolsBuilder.newResourcePoolsBuilder()
          .heap(10, EntryUnit.ENTRIES) // <2>
          .offheap(1, MemoryUnit.MB) // <3>
          .with(ClusteredResourcePoolBuilder.clusteredDedicated("primary-server-resource", 2, MemoryUnit.MB)) // <4>
      )
    ).build(true);
  // end::threeTiersCacheManager[]

  persistentCacheManager.close();
}
 
Example #18
Source File: DefaultCacheLoaderWriterProviderTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testCacheConfigOverridesCacheManagerConfig() {
  final CacheConfiguration<Object, Object> cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(Object.class, Object.class, heap(10))
      .withService(new DefaultCacheLoaderWriterConfiguration(MyOtherLoader.class))
      .build();

  final Map<String, CacheConfiguration<?, ?>> caches = new HashMap<>();
  caches.put("foo", cacheConfiguration);
  final DefaultConfiguration configuration = new DefaultConfiguration(caches, null, new DefaultCacheLoaderWriterProviderConfiguration()
      .addLoaderFor("foo", MyLoader.class));
  final CacheManager manager = CacheManagerBuilder.newCacheManager(configuration);
  manager.init();
  final Object foo = manager.getCache("foo", Object.class, Object.class).get(new Object());
  assertThat(foo, is(MyOtherLoader.object));
}
 
Example #19
Source File: ThreadPools.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void diskStore() throws Exception {
  // tag::diskStore[]
  CacheManager cacheManager
      = CacheManagerBuilder.newCacheManagerBuilder()
      .using(PooledExecutionServiceConfigurationBuilder.newPooledExecutionServiceConfigurationBuilder() // <1>
          .defaultPool("dflt", 0, 10)
          .pool("defaultDiskPool", 1, 3)
          .pool("cache2Pool", 2, 2)
          .build())
      .with(new CacheManagerPersistenceConfiguration(new File(getStoragePath(), "myData")))
      .withDefaultDiskStoreThreadPool("defaultDiskPool") // <2>
      .withCache("cache1",
          CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
              ResourcePoolsBuilder.newResourcePoolsBuilder()
                  .heap(10, EntryUnit.ENTRIES)
                  .disk(10L, MemoryUnit.MB)))
      .withCache("cache2",
          CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
              ResourcePoolsBuilder.newResourcePoolsBuilder()
                  .heap(10, EntryUnit.ENTRIES)
                  .disk(10L, MemoryUnit.MB))
              .withDiskStoreThreadPool("cache2Pool", 2)) // <3>
      .build(true);

  Cache<Long, String> cache1 =
      cacheManager.getCache("cache1", Long.class, String.class);
  Cache<Long, String> cache2 =
      cacheManager.getCache("cache2", Long.class, String.class);

  cacheManager.close();
  // end::diskStore[]
}
 
Example #20
Source File: ThreadPoolsTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultThreadPoolSucceedsWithoutConfig() throws Exception {
  PooledExecutionServiceConfiguration executionServiceConfiguration = new PooledExecutionServiceConfiguration();
  executionServiceConfiguration.addDefaultPool("dflt", 2, 4);
  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
      .using(executionServiceConfiguration)
      .build(true);

  cacheManager.createCache("testCache",
      CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, heap(10))
          .build());

  cacheManager.close();
}
 
Example #21
Source File: ThreadPoolsTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoDefaultThreadPoolSucceedsWithExplicitConfig() throws Exception {
  PooledExecutionServiceConfiguration executionServiceConfiguration = new PooledExecutionServiceConfiguration();
  executionServiceConfiguration.addPool("foo", 2, 4);
  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
      .using(new CacheEventDispatcherFactoryConfiguration("foo"))
      .using(executionServiceConfiguration)
      .build(true);

  cacheManager.createCache("testCache",
      CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, heap(10))
          .build());

  cacheManager.close();
}
 
Example #22
Source File: ThreadPools.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void events() throws Exception {
  // tag::events[]
  CacheManager cacheManager
      = CacheManagerBuilder.newCacheManagerBuilder()
      .using(PooledExecutionServiceConfigurationBuilder.newPooledExecutionServiceConfigurationBuilder() // <1>
          .pool("defaultEventPool", 1, 3)
          .pool("cache2Pool", 2, 2)
          .build())
      .withDefaultEventListenersThreadPool("defaultEventPool") // <2>
      .withCache("cache1",
          CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
                                        ResourcePoolsBuilder.newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES))
              .withService(CacheEventListenerConfigurationBuilder
                  .newEventListenerConfiguration(new ListenerObject(), EventType.CREATED, EventType.UPDATED)))
      .withCache("cache2",
          CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
                                        ResourcePoolsBuilder.newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES))
              .withService(CacheEventListenerConfigurationBuilder
                  .newEventListenerConfiguration(new ListenerObject(), EventType.CREATED, EventType.UPDATED))
              .withEventListenersThreadPool("cache2Pool")) // <3>
      .build(true);

  Cache<Long, String> cache1 =
      cacheManager.getCache("cache1", Long.class, String.class);
  Cache<Long, String> cache2 =
      cacheManager.getCache("cache2", Long.class, String.class);

  cacheManager.close();
  // end::events[]
}
 
Example #23
Source File: ExpiryEventsTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testExpiredEventsOnHeapAndOffHeapByReference() throws Exception {

  CacheConfigurationBuilder<Long, String> configBuilder = byRefCacheConfigBuilder.withResourcePools(
      resourcePoolsBuilder.offheap(1, MemoryUnit.MB));
  Cache<Long, String> testCache = cacheManager.createCache("onHeapOffHeapCache",
      configBuilder.build());

  performActualTest(testCache);
}
 
Example #24
Source File: LoaderWriterErrorEhcacheTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Before
public void setUp() throws Exception {
  CacheLoaderWriterProvider cacheLoaderWriterProvider = mock(CacheLoaderWriterProvider.class);
  cacheLoaderWriter = mock(CacheLoaderWriter.class);
  when(cacheLoaderWriterProvider.createCacheLoaderWriter(anyString(), (CacheConfiguration<Number, CharSequence>) any())).thenReturn((CacheLoaderWriter) cacheLoaderWriter);
  cacheManager = newCacheManagerBuilder().using(cacheLoaderWriterProvider).build(true);
  testCache = cacheManager.createCache("testCache", CacheConfigurationBuilder
          .newCacheConfigurationBuilder(Number.class, CharSequence.class, heap(10))
          .withLoaderWriter(cacheLoaderWriter)
          .build());
}
 
Example #25
Source File: TestEhcache.java    From jframe with Apache License 2.0 5 votes vote down vote up
/**
 * -XX:MaxDirectMemorySize
 */
@Test
public void offHeadpManagedTest() {
    CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
            .withCache("tieredCache",
                    CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
                            ResourcePoolsBuilder.newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES).offheap(10,
                                    MemoryUnit.MB)))
            .build(true);

    cacheManager.close();
}
 
Example #26
Source File: DefaultCacheLoaderWriterProviderTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testCacheConfigUsage() {
  final CacheManager manager = CacheManagerBuilder.newCacheManagerBuilder()
      .withCache("foo",
          CacheConfigurationBuilder.newCacheConfigurationBuilder(Object.class, Object.class, heap(10))
              .withService(new DefaultCacheLoaderWriterConfiguration(MyLoader.class))
              .build()).build(true);
  final Object foo = manager.getCache("foo", Object.class, Object.class).get(new Object());
  assertThat(foo, is(MyLoader.object));
}
 
Example #27
Source File: TestEhcache.java    From jframe with Apache License 2.0 5 votes vote down vote up
@Test
public void diskManagedTest() {
    String path = "";
    PersistentCacheManager persistentCacheManager = CacheManagerBuilder.newCacheManagerBuilder()
            .with(CacheManagerBuilder.persistence(path + File.separator + "myData"))
            .withCache("persistent-cache",
                    CacheConfigurationBuilder
                            .newCacheConfigurationBuilder(Long.class,
                                    String.class, ResourcePoolsBuilder.newResourcePoolsBuilder()
                                            .heap(10, EntryUnit.ENTRIES).disk(10, MemoryUnit.MB, true)))
            .build(true);

    persistentCacheManager.close();
}
 
Example #28
Source File: DefaultManagementRegistryServiceTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void descriptorOffHeapTest() {
  CacheConfiguration<Long, String> cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, newResourcePoolsBuilder().heap(5, MB).offheap(10, MB))
      .build();

  ManagementRegistryService managementRegistry = new DefaultManagementRegistryService(new DefaultManagementRegistryConfiguration().setCacheManagerAlias("myCM"));

  try(CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
        .withCache("aCache", cacheConfiguration)
        .using(managementRegistry)
        .build(true)) {

    List<Capability> capabilities = new ArrayList<>(managementRegistry.getCapabilities());
    assertThat(capabilities).hasSize(4);
    assertThat(capabilities.get(0).getName()).isEqualTo("ActionsCapability");
    assertThat(capabilities.get(1).getName()).isEqualTo("SettingsCapability");
    assertThat(capabilities.get(2).getName()).isEqualTo("StatisticCollectorCapability");
    assertThat(capabilities.get(3).getName()).isEqualTo("StatisticsCapability");

    assertThat(capabilities.get(0).getDescriptors()).hasSize(4);

    Collection<? extends Descriptor> descriptors = capabilities.get(3).getDescriptors();
    Collection<Descriptor> allDescriptors = new ArrayList<>();
    allDescriptors.addAll(ONHEAP_DESCRIPTORS);
    allDescriptors.addAll(OFFHEAP_DESCRIPTORS);
    allDescriptors.addAll(CACHE_DESCRIPTORS);
    allDescriptors.add(new StatisticDescriptor("OnHeap:OccupiedByteSize" , "GAUGE"));

    assertThat(descriptors).containsOnlyElementsOf(allDescriptors);
  }
}
 
Example #29
Source File: ManagementTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void actionCall() throws Exception {
  // tag::actionCall[]
  CacheConfiguration<Long, String> cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(10))
      .build();

  CacheManager cacheManager = null;
  try {
    ManagementRegistryService managementRegistry = new DefaultManagementRegistryService();
    cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
        .withCache("aCache", cacheConfiguration)
        .using(managementRegistry)
        .build(true);

    Cache<Long, String> aCache = cacheManager.getCache("aCache", Long.class, String.class);
    aCache.put(0L, "zero"); // <1>

    Context context = StatsUtil.createContext(managementRegistry); // <2>

    managementRegistry.withCapability("ActionsCapability") // <3>
        .call("clear")
        .on(context)
        .build()
        .execute();

    Assert.assertThat(aCache.get(0L), Matchers.is(Matchers.nullValue())); // <4>
  }
  finally {
    if(cacheManager != null) cacheManager.close();
  }
  // end::actionCall[]
}
 
Example #30
Source File: CacheManagerDestroyRemovesPersistenceTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
private void initCacheManager(File file) {
  persistentCacheManager = CacheManagerBuilder.newCacheManagerBuilder()
      .with(new CacheManagerPersistenceConfiguration(file))
      .withCache(PERSISTENT_CACHE, CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
          newResourcePoolsBuilder()
              .heap(10, EntryUnit.ENTRIES)
              .disk(10L, MemoryUnit.MB, true))
          .build())
      .build(true);
}