org.ehcache.config.builders.CacheManagerBuilder Java Examples

The following examples show how to use org.ehcache.config.builders.CacheManagerBuilder. 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: BasicClusteredCacheOpsReplicationMultiThreadedTest.java    From ehcache3 with Apache License 2.0 7 votes vote down vote up
@Before
public void startServers() throws Exception {
  CLUSTER.getClusterControl().startAllServers();
  final CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder
      = CacheManagerBuilder.newCacheManagerBuilder()
      .with(ClusteringServiceConfigurationBuilder.cluster(CLUSTER.getConnectionURI().resolve("/crud-cm-replication"))
          .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")));
  cacheManager1 = clusteredCacheManagerBuilder.build(true);
  cacheManager2 = clusteredCacheManagerBuilder.build(true);
  CacheConfiguration<Long, BlobValue> config = CacheConfigurationBuilder
      .newCacheConfigurationBuilder(Long.class, BlobValue.class,
          ResourcePoolsBuilder.newResourcePoolsBuilder().heap(500, EntryUnit.ENTRIES)
              .with(ClusteredResourcePoolBuilder.clusteredDedicated("primary-server-resource", 4, MemoryUnit.MB)))
      .withService(ClusteredStoreConfigurationBuilder.withConsistency(cacheConsistency))
      .build();

  cache1 = cacheManager1.createCache(testName.getMethodName(), config);
  cache2 = cacheManager2.createCache(testName.getMethodName(), config);

  caches = Arrays.asList(cache1, cache2);
}
 
Example #2
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 #3
Source File: IntegrationConfigurationTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testCacheEventListener() throws Exception {
  Configuration configuration = new XmlConfiguration(this.getClass().getResource("/configs/ehcache-cacheEventListener.xml"));
  assertThat(configuration.getCacheConfigurations().containsKey("bar"), is(true));
  final CacheManager cacheManager = CacheManagerBuilder.newCacheManager(configuration);
  cacheManager.init();
  final Cache<Number, String> cache = cacheManager.getCache("bar", Number.class, String.class);
  cache.put(10, "dog");
  assertThat(TestCacheEventListener.FIRED_EVENT.getType(), is(EventType.CREATED));
  cache.put(10, "cat");
  assertThat(TestCacheEventListener.FIRED_EVENT.getType(), is(EventType.UPDATED));
  cache.remove(10);
  assertThat(TestCacheEventListener.FIRED_EVENT.getType(), is(EventType.REMOVED));
  cache.put(10, "dog");
  resetValues();
  assertThat(configuration.getCacheConfigurations().containsKey("template1"), is(true));
  final Cache<Number, String> templateCache = cacheManager.getCache("template1", Number.class, String.class);
  templateCache.put(10,"cat");
  assertThat(TestCacheEventListener.FIRED_EVENT, nullValue());
  templateCache.put(10, "dog");
  assertThat(TestCacheEventListener.FIRED_EVENT.getType(), is(EventType.UPDATED));
}
 
Example #4
Source File: BasicClusteredLoaderWriterTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testBasicClusteredCacheLoaderWriter() {

  TestCacheLoaderWriter loaderWriter = new TestCacheLoaderWriter();
  CacheConfiguration<Long, String> cacheConfiguration = getCacheConfiguration(loaderWriter);

  try (CacheManager cacheManager = CacheManagerBuilder
          .newCacheManagerBuilder()
          .with(cluster(CLUSTER_URI).autoCreate(c -> c))
          .withCache("cache-1", cacheConfiguration)
          .build(true)) {

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

    cache.put(1L, "1");

    assertThat(cache.get(1L), is("1"));

    assertThat(loaderWriter.storeMap.get(1L), is("1"));
  }
}
 
Example #5
Source File: CommonCachedLatencyReportController.java    From maestro-java with Apache License 2.0 6 votes vote down vote up
protected CommonCachedLatencyReportController() {
    if (cacheManager == null) {
        synchronized (this) {
            if (cacheManager == null) {
                CacheConfigurationBuilder<File, LatencyDistribution> config = CacheConfigurationBuilder
                        .newCacheConfigurationBuilder(File.class, LatencyDistribution.class, ResourcePoolsBuilder.heap(30))
                        .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMinutes(30)));

                cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
                        .withCache("latDistribution",config)
                        .build();

                cacheManager.init();

                latencyDistributionCache = cacheManager.getCache("latDistribution", File.class,
                        LatencyDistribution.class);
            }
        }
    }
}
 
Example #6
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 #7
Source File: CacheProvider.java    From mangooio with Apache License 2.0 6 votes vote down vote up
@Inject
@SuppressFBWarnings(value = "FII_USE_FUNCTION_IDENTITY", justification = "Required by cache creation function")
public CacheProvider(Config config) {
    Objects.requireNonNull(config, Required.CONFIG.toString());
    
    if (config.isCacheCluserEnable()) {
        CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder = CacheManagerBuilder.newCacheManagerBuilder() 
                .with(ClusteringServiceConfigurationBuilder.cluster(URI.create(config.getCacheClusterUrl())) 
                .autoCreate(b -> b));

        this.cacheManager = clusteredCacheManagerBuilder.build(true);
    } else {
        this.cacheManager = CacheManagerBuilder.newCacheManagerBuilder().build();
        this.cacheManager.init();
    }

    initApplicationCache();
    initAuthenticationCache();
    initRequestCache();
    initResponseCache();
    initServerEventCache();
    initWebSocketCache();
}
 
Example #8
Source File: CacheCalculationTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Before
public void before() throws Exception {
  CacheConfiguration<Integer, String> cacheConfiguration =
    CacheConfigurationBuilder.newCacheConfigurationBuilder(Integer.class, String.class, resources).build();

  StatisticsService statisticsService = new DefaultStatisticsService();

  cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
    .withCache("cache", cacheConfiguration)
    .using(new DefaultPersistenceConfiguration(diskPath.newFolder()))
    .using(statisticsService)
    .build(true);

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

  cacheStatistics = statisticsService.getCacheStatistics("cache");
}
 
Example #9
Source File: GettingStarted.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testCacheEventListener() {
  // tag::cacheEventListener[]
  CacheEventListenerConfigurationBuilder cacheEventListenerConfiguration = CacheEventListenerConfigurationBuilder
      .newEventListenerConfiguration(new ListenerObject(), EventType.CREATED, EventType.UPDATED) // <1>
      .unordered().asynchronous(); // <2>

  final CacheManager manager = CacheManagerBuilder.newCacheManagerBuilder()
      .withCache("foo",
          CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class, ResourcePoolsBuilder.heap(10))
              .withService(cacheEventListenerConfiguration) // <3>
      ).build(true);

  final Cache<String, String> cache = manager.getCache("foo", String.class, String.class);
  cache.put("Hello", "World"); // <4>
  cache.put("Hello", "Everyone"); // <5>
  cache.remove("Hello"); // <6>
  // end::cacheEventListener[]

  manager.close();
}
 
Example #10
Source File: GettingStarted.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void cacheEvictionAdvisor() throws Exception {
  // tag::cacheEvictionAdvisor[]
  CacheConfiguration<Long, String> cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
                                                                                      ResourcePoolsBuilder.heap(2L)) // <1>
      .withEvictionAdvisor(new OddKeysEvictionAdvisor<>()) // <2>
      .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();
  // end::cacheEvictionAdvisor[]
}
 
Example #11
Source File: BasicClusteredCacheExpiryTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetExpiredTwoClients() {

  TestTimeSource timeSource = new TestTimeSource();
  TimeSourceConfiguration timeSourceConfiguration = new TimeSourceConfiguration(timeSource);

  final CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder =
      commonClusteredCacheManagerBuilder.using(timeSourceConfiguration);

  try (PersistentCacheManager cacheManager1 = clusteredCacheManagerBuilder.build(true)) {
    try (PersistentCacheManager cacheManager2 = clusteredCacheManagerBuilder.build(true)) {

      final Cache<Long, String> cache1 = cacheManager1.getCache("clustered-cache", Long.class, String.class);
      final Cache<Long, String> cache2 = cacheManager2.getCache("clustered-cache", Long.class, String.class);

      assertThat(cache2.get(1L), nullValue());
      cache1.put(1L, "value1");
      assertThat(cache1.get(1L), is("value1"));
      timeSource.advanceTime(1L);

      assertThat(cache2.get(1L), nullValue());
      assertThat(cache1.get(1L), nullValue());
    }
  }
}
 
Example #12
Source File: PersistentCacheTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("try")
public void testPersistentCachesColliding() throws Exception {
  File folder = temporaryFolder.newFolder(testName.getMethodName());
  try (PersistentCacheManager cm = CacheManagerBuilder.newCacheManagerBuilder()
    .with(new CacheManagerPersistenceConfiguration(folder)).build(true)) {
    CacheManagerBuilder.newCacheManagerBuilder()
      .with(new CacheManagerPersistenceConfiguration(folder))
      .build(true)
      .close();
    Assert.fail("Expected StateTransitionException");
  } catch (StateTransitionException e) {
    assertThat(e.getCause().getMessage(), containsString("Persistence directory already locked by this process"));
    assertThat(e.getCause().getCause(), instanceOf(OverlappingFileLockException.class));
  }
}
 
Example #13
Source File: GettingStarted.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void explicitConsistencyConfiguration() throws Exception {
  CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder
          = CacheManagerBuilder.newCacheManagerBuilder()
          .with(ClusteringServiceConfigurationBuilder.cluster(URI.create("terracotta://localhost/my-application"))
                  .autoCreateOnReconnect(server -> server.defaultServerResource("primary-server-resource")
                    .resourcePool("resource-pool-a", 8, MemoryUnit.MB)));
  PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(false);
  cacheManager.init();

  try {
    // tag::clusteredCacheConsistency[]
    CacheConfiguration<Long, String> config = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
            ResourcePoolsBuilder.newResourcePoolsBuilder()
                    .with(ClusteredResourcePoolBuilder.clusteredDedicated("primary-server-resource", 2, MemoryUnit.MB)))
        .withService(ClusteredStoreConfigurationBuilder.withConsistency(Consistency.STRONG)) // <1>
        .build();

    Cache<Long, String> cache = cacheManager.createCache("clustered-cache", config);
    cache.put(42L, "All you need to know!"); // <2>

    // end::clusteredCacheConsistency[]
  } finally {
    cacheManager.close();
  }
}
 
Example #14
Source File: DefaultSharedManagementServiceTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Before
public void init() {
  CacheConfiguration<Long, String> cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, heap(10))
      .build();

  service = new DefaultSharedManagementService();

  cacheManager1 = CacheManagerBuilder.newCacheManagerBuilder()
      .withCache("aCache1", cacheConfiguration)
      .using(service)
      .using(config1 = new DefaultManagementRegistryConfiguration().setCacheManagerAlias("myCM1"))
      .build(true);

  cacheManager2 = CacheManagerBuilder.newCacheManagerBuilder()
      .withCache("aCache2", cacheConfiguration)
      .withCache("aCache3", cacheConfiguration)
      .using(service)
      .using(config2 = new DefaultManagementRegistryConfiguration().setCacheManagerAlias("myCM2"))
      .build(true);

  // this serie of calls make sure the registry still works after a full init / close / init loop
  cacheManager1.close();
  cacheManager1.init();
  cacheManager2.close();
  cacheManager2.init();
}
 
Example #15
Source File: DefaultCacheEventListenerProviderTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testCacheConfigUsage() {
  Set<EventType> eventTypeSet = new HashSet<>();
  eventTypeSet.add(EventType.CREATED);
  eventTypeSet.add(EventType.UPDATED);

  CacheEventListenerConfigurationBuilder listenerBuilder = CacheEventListenerConfigurationBuilder
      .newEventListenerConfiguration(ListenerObject.class, eventTypeSet).unordered().asynchronous();
  final CacheManager manager = CacheManagerBuilder.newCacheManagerBuilder()
      .withCache("foo",
          CacheConfigurationBuilder.newCacheConfigurationBuilder(Object.class, Object.class, heap(10))
              .withService(listenerBuilder)
              .build()).build(true);
  final Collection<?> bar = manager.getCache("foo", Object.class, Object.class).getRuntimeConfiguration().getServiceConfigurations();
  assertThat(bar.iterator().next().getClass().toString(), is(ListenerObject.object.toString()));
}
 
Example #16
Source File: BasicClusteredCacheExpiryTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testContainsKeyExpiredTwoClients() {

  TestTimeSource timeSource = new TestTimeSource();
  TimeSourceConfiguration timeSourceConfiguration = new TimeSourceConfiguration(timeSource);

  final CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder =
      commonClusteredCacheManagerBuilder.using(timeSourceConfiguration);

  try (PersistentCacheManager cacheManager1 = clusteredCacheManagerBuilder.build(true)) {
    try (PersistentCacheManager cacheManager2 = clusteredCacheManagerBuilder.build(true)) {

      final Cache<Long, String> cache1 = cacheManager1.getCache("clustered-cache", Long.class, String.class);
      final Cache<Long, String> cache2 = cacheManager2.getCache("clustered-cache", Long.class, String.class);

      assertThat(cache2.get(1L), nullValue());
      cache1.put(1L, "value1");
      assertThat(cache1.containsKey(1L), is(true));
      timeSource.advanceTime(1L);

      assertThat(cache1.containsKey(1L), is(false));
      assertThat(cache2.containsKey(1L), is(false));
    }
  }
}
 
Example #17
Source File: ClusteredCacheExpirationTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetNoExpirationPropagatedToHigherTiers() throws CachePersistenceException {
  CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder = cacheManagerBuilder(ExpiryPolicyBuilder.noExpiration());

  try(PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(true)) {

    Map<String, TierStatistics> tierStatistics = statisticsService.getCacheStatistics(CLUSTERED_CACHE).getTierStatistics();
    TierStatistics onheap = tierStatistics.get("OnHeap");
    TierStatistics offheap = tierStatistics.get("OffHeap");

    Cache<Long, String> cache = cacheManager.getCache(CLUSTERED_CACHE, Long.class, String.class);
    for (long i = 0; i < 30; i++) {
      cache.put(i, "value"); // store on the cluster
      cache.get(i); // push it up on heap and offheap tier
    }

    assertThat(onheap.getMappings()).isEqualTo(10);
    assertThat(offheap.getMappings()).isEqualTo(20);
  }
}
 
Example #18
Source File: TerminatedServerTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testTerminationBeforeCacheManagerRetrieve() throws Exception {
  // Close all servers
  CLUSTER.get().getClusterControl().terminateAllServers();

  // Try to retrieve an entity (that doesn't exist but I don't care... the server is not running anyway
  CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder =
      CacheManagerBuilder.newCacheManagerBuilder()
          .with(ClusteringServiceConfigurationBuilder.cluster(CLUSTER.get().getConnectionURI().resolve("/").resolve(testName.getMethodName()))
                  .timeouts(TimeoutsBuilder.timeouts().connection(Duration.ofSeconds(1))) // Need a connection timeout shorter than the TimeLimitedTask timeout
                  .expecting(server -> server.defaultServerResource("primary-server-resource")));
  PersistentCacheManager cacheManagerExisting = clusteredCacheManagerBuilder.build(false);

  // Base test time limit on observed TRANSPORT_HANDSHAKE_SYNACK_TIMEOUT; might not have been set in time to be effective
  long synackTimeout = TimeUnit.MILLISECONDS.toSeconds(ClientMessageTransport.TRANSPORT_HANDSHAKE_SYNACK_TIMEOUT);

  assertExceptionOccurred(StateTransitionException.class,
    new TimeLimitedTask<Void>(ofSeconds(3 + synackTimeout)) {
      @Override
      Void runTask() {
        cacheManagerExisting.init();
        return null;
      }
    })
    .withRootCauseInstanceOf(TimeoutException.class);
}
 
Example #19
Source File: OverSizeMappingTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testOverSizedObjectPutFailsWithOnHeapAsAuthority() {
  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
      .withDefaultSizeOfMaxObjectSize(500, MemoryUnit.B).build(true);

  CacheConfiguration<String, String> cacheConfiguration = CacheConfigurationBuilder
      .newCacheConfigurationBuilder(String.class, String.class,
          newResourcePoolsBuilder()
              .heap(100, MemoryUnit.KB).build())
      .build();

  Cache<String, String> cache = cacheManager.createCache("cache",
      cacheConfiguration);

  cache.put("key1", getOverSizedObject());
  assertThat(cache.get("key1"), nullValue());

  cache.put("key1", "value1");
  cache.replace("key1", getOverSizedObject());
  assertThat(cache.get("key1"), nullValue());

}
 
Example #20
Source File: TerminatedServerTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testTerminationBeforeCacheRemove() 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.removeCache("simple-cache");
}
 
Example #21
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 #22
Source File: WriteBehindTestBase.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
PersistentCacheManager createCacheManager(URI clusterUri) {
  CacheConfiguration<Long, String> cacheConfiguration =
    newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.newResourcePoolsBuilder()
                                                                               .heap(10, EntryUnit.ENTRIES)
                                                                               .offheap(1, MemoryUnit.MB)
                                                                               .with(ClusteredResourcePoolBuilder.clusteredDedicated("primary-server-resource", 2, MemoryUnit.MB)))
      .withLoaderWriter(loaderWriter)
      .withService(WriteBehindConfigurationBuilder.newUnBatchedWriteBehindConfiguration())
      .withResilienceStrategy(new ThrowingResilienceStrategy<>())
      .withService(new ClusteredStoreConfiguration(Consistency.STRONG))
      .build();

  return CacheManagerBuilder
    .newCacheManagerBuilder()
    .with(cluster(clusterUri.resolve("/cm-wb")).timeouts(TimeoutsBuilder.timeouts().read(Duration.ofMinutes(1)).write(Duration.ofMinutes(1))).autoCreate(c -> c))
    .withCache(testName.getMethodName(), cacheConfiguration)
    .build(true);
}
 
Example #23
Source File: BasicClusteredCacheTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testLargeValues() throws Exception {
  DefaultStatisticsService statisticsService = new DefaultStatisticsService();
  CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder =
          newCacheManagerBuilder()
                  .using(statisticsService)
                  .with(cluster(CLUSTER_URI).autoCreate(c -> c))
                  .withCache("small-cache", newCacheConfigurationBuilder(Long.class, BigInteger.class,
                          ResourcePoolsBuilder.newResourcePoolsBuilder()
                                  .with(clusteredDedicated("secondary-server-resource", 4, MemoryUnit.MB))));

  // The idea here is to add big things in the cache, and cause eviction of them to see if something crashes

  try(PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(true)) {

    Cache<Long, BigInteger> cache = cacheManager.getCache("small-cache", Long.class, BigInteger.class);

    Random random = new Random();
    for (long i = 0; i < 100; i++) {
      BigInteger value = new BigInteger(30 * 1024 * 128 * (1 + random.nextInt(10)), random);
      cache.put(i, value);
    }
  }
}
 
Example #24
Source File: StatefulSerializerWithStateRepositoryTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testStatefulSerializerWithDiskStateRepositoryDifferentPersistenceServices() throws Exception {
  CacheManagerBuilder<PersistentCacheManager> cmBuilder = newCacheManagerBuilder().with(persistence(temporaryFolder.newFolder()
      .getAbsolutePath()))
      .withCache("myCache", newCacheConfigurationBuilder(Long.class, Person.class, heap(10).disk(50, MemoryUnit.MB, true))
          .withValueSerializer(CompactJavaSerializer.asTypedSerializer()));
  PersistentCacheManager cacheManager = cmBuilder.build(true);

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

  myCache.put(42L, new Person("John", 42));
  myCache.put(35L, new Person("Marie", 35));

  cacheManager.close();

  cacheManager = cmBuilder.build(true);

  myCache = cacheManager.getCache("myCache", Long.class, Person.class);

  assertThat(myCache.get(42L).getName(), is("John"));
}
 
Example #25
Source File: IntegrationConfigurationTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testCacheEventListenerWithMultipleListener() throws Exception {
  Configuration configuration = new XmlConfiguration(this.getClass().getResource("/configs/ehcache-multipleCacheEventListener.xml"));
  assertThat(configuration.getCacheConfigurations().containsKey("bar"), is(true));
  final CacheManager cacheManager = CacheManagerBuilder.newCacheManager(configuration);
  cacheManager.init();
  final Cache<Number, String> cache = cacheManager.getCache("bar", Number.class, String.class);
  resetValues();
  cache.put(10, "dog");
  assertThat(TestCacheEventListener.FIRED_EVENT.getType(), is(EventType.CREATED));
  assertThat(TestSecondCacheEventListener.SECOND_LISTENER_FIRED_EVENT, is(nullValue()));
  resetValues();
  cache.put(10, "cat");
  assertThat(TestCacheEventListener.FIRED_EVENT.getType(), is(EventType.UPDATED));
  assertThat(TestSecondCacheEventListener.SECOND_LISTENER_FIRED_EVENT.getType(), is(EventType.UPDATED));
  resetValues();
  cache.remove(10);
  assertThat(TestCacheEventListener.FIRED_EVENT.getType(), is(EventType.REMOVED));
  assertThat(TestSecondCacheEventListener.SECOND_LISTENER_FIRED_EVENT.getType(), is(EventType.REMOVED));
}
 
Example #26
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 #27
Source File: GettingStarted.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testXmlToString() throws IOException {
  // tag::xmlTranslation[]
  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
    .with(CacheManagerBuilder.persistence(tmpDir.newFile("myData")))
    .withCache("threeTieredCache",
      CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
        ResourcePoolsBuilder.newResourcePoolsBuilder()
          .heap(10, EntryUnit.ENTRIES)
          .offheap(1, MemoryUnit.MB)
          .disk(20, MemoryUnit.MB, true))
        .withExpiry(ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofSeconds(20)))
    ).build(false);

  Configuration configuration = cacheManager.getRuntimeConfiguration();
  XmlConfiguration xmlConfiguration = new XmlConfiguration(configuration);  // <1>
  String xml = xmlConfiguration.toString(); // <2>
  // end::xmlTranslation[]
}
 
Example #28
Source File: IntegrationConfigurationTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testThreadPools() throws Exception {
  Configuration configuration = new XmlConfiguration(this.getClass().getResource("/configs/thread-pools.xml"));
  final CacheManager cacheManager = CacheManagerBuilder.newCacheManager(configuration);
  cacheManager.init();
  try {
    Cache<String, String> cache = cacheManager.createCache("testThreadPools", newCacheConfigurationBuilder(String.class, String.class, heap(10))
            .withService(new DefaultCacheLoaderWriterConfiguration(ThreadRememberingLoaderWriter.class))
            .withService(newUnBatchedWriteBehindConfiguration().useThreadPool("small"))
            .build());

    cache.put("foo", "bar");

    ThreadRememberingLoaderWriter.USED.acquireUninterruptibly();

    assertThat(ThreadRememberingLoaderWriter.LAST_SEEN_THREAD.getName(), containsString("[small]"));
  } finally {
    cacheManager.close();
  }
}
 
Example #29
Source File: StoreStatisticsTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void test2TiersStoreStatsAvailableInContextManager() throws Exception {
  try(CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
      .withCache("threeTieredCache",
          CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
              newResourcePoolsBuilder()
                  .heap(1, MemoryUnit.MB)
                  .offheap(2, MemoryUnit.MB)
              )
      ).build(true)) {

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

    assertNull(cache.get(0L));

    long onHeapMisses = StoreStatisticsTest.<CachingTierOperationOutcomes.GetOrComputeIfAbsentOutcome>findStat(cache, "getOrComputeIfAbsent", "OnHeap")
      .count(CachingTierOperationOutcomes.GetOrComputeIfAbsentOutcome.MISS);
    assertThat(onHeapMisses, equalTo(1L));
    long offheapMisses = StoreStatisticsTest.<AuthoritativeTierOperationOutcomes.GetAndFaultOutcome>findStat(cache, "getAndFault", "OffHeap")
      .count(AuthoritativeTierOperationOutcomes.GetAndFaultOutcome.MISS);
    assertThat(offheapMisses, equalTo(1L));
  }
}
 
Example #30
Source File: CacheManagerDestroyTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testCloseCacheManagerSingleClient() {
  CacheManagerBuilder<PersistentCacheManager> cacheManagerBuilder = clusteredCacheManagerBuilder
      .withCache("test", newCacheConfigurationBuilder(Long.class, String.class,
          ResourcePoolsBuilder.newResourcePoolsBuilder()
              .with(ClusteredResourcePoolBuilder.clusteredDedicated("primary-server-resource", 2, MemoryUnit.MB))));

  PersistentCacheManager persistentCacheManager1 = cacheManagerBuilder.build(true);

  persistentCacheManager1.close();

  persistentCacheManager1.init();

  Cache<Long, String> cache = persistentCacheManager1.getCache("test", Long.class, String.class);
  cache.put(1L, "One");

  assertThat(cache.get(1L), is("One"));

  persistentCacheManager1.close();
}