org.ehcache.PersistentCacheManager Java Examples

The following examples show how to use org.ehcache.PersistentCacheManager. 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: 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: 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 #4
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 #5
Source File: StatefulSerializerWithStateRepositoryTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testStatefulSerializerWithDiskStateRepository() 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.init();

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

  assertThat(myCache.get(42L).getName(), is("John"));
}
 
Example #6
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 #7
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(CacheManagerBuilder.persistence(new File(getStoragePath(), "myData")))
    .withCache("threeTieredCache",
      CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
        ResourcePoolsBuilder.newResourcePoolsBuilder()
          .heap(10, EntryUnit.ENTRIES)
          .offheap(1, MemoryUnit.MB)
          .disk(20, MemoryUnit.MB, true)
      )
    ).build(true);
  // end::threeTiersCacheManager[]

  persistentCacheManager.close();
}
 
Example #8
Source File: GettingStarted.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(CacheManagerBuilder.persistence(new File(getStoragePath(), "myData"))) // <1>
      .withCache("threeTieredCache",
          CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
              ResourcePoolsBuilder.newResourcePoolsBuilder()
                  .heap(10, EntryUnit.ENTRIES) // <2>
                  .offheap(1, MemoryUnit.MB) // <3>
                  .disk(20, MemoryUnit.MB, true) // <4>
              )
      ).build(true);

  Cache<Long, String> threeTieredCache = persistentCacheManager.getCache("threeTieredCache", Long.class, String.class);
  threeTieredCache.put(1L, "stillAvailableAfterRestart"); // <5>

  persistentCacheManager.close();
  // end::threeTiersCacheManager[]
}
 
Example #9
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 #10
Source File: AutoCreateOnReconnectTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void cacheManagerCanReconnect() throws Exception {
  URI connectionURI = CLUSTER.getConnectionURI();

  try (PersistentCacheManager cacheManager = newCacheManagerBuilder()
    .with(cluster(connectionURI.resolve("/crud-cm"))
      .autoCreateOnReconnect(server -> server.defaultServerResource("primary-server-resource")))
    .build(true)) {

    Cache<Long, String> cache = cacheManager.createCache("clustered-cache",
      newCacheConfigurationBuilder(Long.class, String.class, newResourcePoolsBuilder()
        .with(clusteredDedicated("primary-server-resource", 1, MemoryUnit.MB)))
        .build());

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

    CLUSTER.getClusterControl().terminateAllServers();
    CLUSTER.getClusterControl().startAllServers();

    assertThat(() -> {
      cache.put(1L, "two");
      return cache.get(1L);
    }, within(Duration.ofSeconds(30)).is("two"));
  }
}
 
Example #11
Source File: ResourcePoolAllocationFailureTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testTooLowResourceException() throws InterruptedException {

  DedicatedClusteredResourcePool resourcePool = ClusteredResourcePoolBuilder.clusteredDedicated(10, MemoryUnit.KB);
  CacheManagerBuilder<PersistentCacheManager> cacheManagerBuilder = getPersistentCacheManagerCacheManagerBuilder(resourcePool);

  try {
    cacheManagerBuilder.build(true);
    fail("InvalidServerStoreConfigurationException expected");
  } catch (Exception e) {
    Throwable cause = getCause(e, PerpetualCachePersistenceException.class);
    assertThat(cause, notNullValue());
    assertThat(cause.getMessage(), startsWith("Unable to create"));
  }
  resourcePool = ClusteredResourcePoolBuilder.clusteredDedicated(100, MemoryUnit.KB);
  cacheManagerBuilder = getPersistentCacheManagerCacheManagerBuilder(resourcePool);
  PersistentCacheManager persistentCacheManager = cacheManagerBuilder.build(true);

  assertThat(persistentCacheManager, notNullValue());
  persistentCacheManager.close();

}
 
Example #12
Source File: TerminatedServerTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore("There are no timeout on the create cache right now. It waits until the server comes back")
public void testTerminationBeforeCacheCreate() throws Exception {
  CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder =
      CacheManagerBuilder.newCacheManagerBuilder()
          .with(ClusteringServiceConfigurationBuilder.cluster(CLUSTER.get().getConnectionURI().resolve("/").resolve(testName.getMethodName()))
                  .autoCreate(server -> server.defaultServerResource("primary-server-resource")));
  PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(false);
  cacheManager.init();

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

  assertExceptionOccurred(IllegalStateException.class,
    new TimeLimitedTask<Cache<Long, String>>(ofSeconds(10)) {
      @Override
      Cache<Long, String> runTask() throws Exception {
        return cacheManager.createCache("simple-cache",
            CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
                ResourcePoolsBuilder.newResourcePoolsBuilder()
                    .with(ClusteredResourcePoolBuilder.clusteredDedicated(4, MemoryUnit.MB))));
      }
    })
    .withRootCauseInstanceOf(TimeoutException.class);
}
 
Example #13
Source File: BasicClusteredCacheTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testClusteredCacheSingleClient() throws Exception {

  final CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder =
      newCacheManagerBuilder()
          .with(cluster(CLUSTER_URI).autoCreate(c -> c))
          .withCache("clustered-cache", newCacheConfigurationBuilder(Long.class, String.class,
              ResourcePoolsBuilder.newResourcePoolsBuilder()
                  .with(clusteredDedicated("primary-server-resource", 2, MemoryUnit.MB))));
  try (PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(true)) {

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

    cache.put(1L, "value");
    assertThat(cache.get(1L), is("value"));
  }
}
 
Example #14
Source File: BasicClusteredCacheTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testClusteredCacheTwoClients() throws Exception {
  final CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder =
      newCacheManagerBuilder()
          .with(cluster(CLUSTER_URI).autoCreate(c -> c))
          .withCache("clustered-cache", newCacheConfigurationBuilder(Long.class, String.class,
              ResourcePoolsBuilder.newResourcePoolsBuilder().heap(100, EntryUnit.ENTRIES)
                  .with(clusteredDedicated("primary-server-resource", 2, MemoryUnit.MB)))
              .withService(new ClusteredStoreConfiguration(Consistency.STRONG)));

  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(cache2.get(1L), is("value1"));
      assertThat(cache1.get(1L), is("value1"));
      cache1.put(1L, "value2");
      assertThat(cache2.get(1L), is("value2"));
      assertThat(cache1.get(1L), is("value2"));
    }
  }
}
 
Example #15
Source File: BasicClusteredCacheTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testTieredClusteredCache() throws Exception {
  final CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder =
      newCacheManagerBuilder()
          .with(cluster(CLUSTER_URI).autoCreate(c -> c))
          .withCache("clustered-cache", newCacheConfigurationBuilder(Long.class, String.class,
                  heap(2)
                  .with(clusteredDedicated("primary-server-resource", 2, MemoryUnit.MB))));
  try (PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(true)) {

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

    cache.put(1L, "value");
    assertThat(cache.get(1L), is("value"));
  }
}
 
Example #16
Source File: BasicCacheOpsMultiThreadedTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
private Callable<?> content() {
  return () -> {
    try (PersistentCacheManager cacheManager = createCacheManager(CLUSTER.getConnectionURI())) {
      Cache<String, Boolean> synCache = cacheManager.getCache(SYN_CACHE_NAME, String.class, Boolean.class);
      Cache<Long, String> customValueCache = cacheManager.getCache(CLUSTERED_CACHE_NAME, Long.class, String.class);
      parallelPuts(customValueCache);
      String firstClientStartKey = "first_client_start", firstClientEndKey = "first_client_end";
      if (synCache.putIfAbsent(firstClientStartKey, true) == null) {
        customValueCache.put(1L, "value");
        assertThat(customValueCache.get(1L), is("value"));
        synCache.put(firstClientEndKey, true);
      } else {
        assertThat(() -> synCache.get(firstClientEndKey), within(Duration.ofSeconds(30)).matches(notNullValue()));
        assertThat(customValueCache.get(1L), is("value"));
      }
      return null;
    }
  };
}
 
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: 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 #19
Source File: GettingStarted.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void clusteredCacheManagerWithDynamicallyAddedCacheExample() throws Exception {
  // tag::clusteredCacheManagerWithDynamicallyAddedCacheExample[]
  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 {
    CacheConfiguration<Long, String> config = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
            ResourcePoolsBuilder.newResourcePoolsBuilder()
                    .with(ClusteredResourcePoolBuilder.clusteredDedicated("primary-server-resource", 2, MemoryUnit.MB))).build();

    Cache<Long, String> cache = cacheManager.createCache("clustered-cache", config);

  } finally {
    cacheManager.close();
  }
  // end::clusteredCacheManagerWithDynamicallyAddedCacheExample[]
}
 
Example #20
Source File: ClusteredCacheDestroyTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testDestroyUnknownCacheAlias() throws Exception {
  clusteredCacheManagerBuilder.build(true).close();

  try (PersistentCacheManager cacheManager = newCacheManagerBuilder().with(cluster(CLUSTER_URI).expecting(c -> c)).build(true)) {

    cacheManager.destroyCache(CLUSTERED_CACHE);

    try {
      cacheManager.createCache(CLUSTERED_CACHE, newCacheConfigurationBuilder(Long.class, String.class, newResourcePoolsBuilder()
        .with(clustered())));
      fail("Expected exception as clustered store no longer exists");
    } catch (IllegalStateException e) {
      assertThat(e.getMessage(), containsString(CLUSTERED_CACHE));
    }
  }
}
 
Example #21
Source File: OversizedCacheOpsPassiveTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
private void doPuts(CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder,
                    CountDownLatch syncLatch) {
  try (PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(true)) {
    CacheConfiguration<Long, String> config = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
      ResourcePoolsBuilder.newResourcePoolsBuilder()
        .with(ClusteredResourcePoolBuilder.clusteredDedicated("primary-server-resource", CACHE_SIZE_IN_MB, MemoryUnit.MB)))
      .build();

    syncLatch.countDown();
    Cache<Long, String> cache = cacheManager.createCache("clustered-cache", config);
    for (long i = 0; i < MAX_PUTS; i++) {
      if (i % 1000 == 0) {
        // a small pause
        try {
          Thread.sleep(10);
        } catch (InterruptedException e) {
          throw new AssertionError(e);
        }
      }
      cache.put(i, LARGE_VALUE);
    }
  }
}
 
Example #22
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 #23
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 #24
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 #25
Source File: CacheManagerDestroyTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testDestroyCacheManagerDoesNotAffectsExistingCacheWithExistingClientsConnected() throws CachePersistenceException {

  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);
  try (PersistentCacheManager persistentCacheManager2 = cacheManagerBuilder.build(true)) {

    persistentCacheManager1.close();
    try {
      persistentCacheManager1.destroy();
      fail("StateTransitionException expected");
    } catch (StateTransitionException e) {
      assertThat(e.getMessage(), is("Couldn't acquire cluster-wide maintenance lease"));
    }

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

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

    assertThat(cache.get(1L), is("One"));
  }
}
 
Example #26
Source File: CacheManagerDestroyTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testCloseCacheManagerMultipleClients() {
  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);
  try (PersistentCacheManager persistentCacheManager2 = cacheManagerBuilder.build(true)) {

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

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

    persistentCacheManager1.close();
    assertThat(persistentCacheManager1.getStatus(), is(Status.UNINITIALIZED));

    Cache<Long, String> cache2 = persistentCacheManager2.getCache("test", Long.class, String.class);

    assertThat(cache2.get(1L), is("One"));
  }
}
 
Example #27
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 #28
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 #29
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 #30
Source File: ClusteredCacheDestroyTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testDestroyCacheWithCacheManagerStopped() throws CachePersistenceException {
  PersistentCacheManager persistentCacheManager = clusteredCacheManagerBuilder.build(true);
  persistentCacheManager.close();
  persistentCacheManager.destroyCache(CLUSTERED_CACHE);
  assertThat(persistentCacheManager.getStatus(), is(Status.UNINITIALIZED));
}