org.ehcache.config.builders.ResourcePoolsBuilder Java Examples

The following examples show how to use org.ehcache.config.builders.ResourcePoolsBuilder. 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: ConfigurationDerivation.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void updateService() {
  Configuration configuration = ConfigurationBuilder.newConfigurationBuilder()
    .withCache("cache", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(10))
      .withService(new ClusteredStoreConfiguration(Consistency.STRONG)))
    .build();

  //tag::updateService[]
  Configuration changedConsistency = configuration.derive()
    .updateCache("cache", cache -> cache.updateServices(
      ClusteredStoreConfiguration.class,
      existing -> Consistency.EVENTUAL)
    )
    .build();
  //end::updateService[]

  Assert.assertThat(ServiceUtils.findSingletonAmongst(ClusteredStoreConfiguration.class,
    configuration.getCacheConfigurations().get("cache").getServiceConfigurations()).getConsistency(), Is.is(Consistency.STRONG));

  Assert.assertThat(ServiceUtils.findSingletonAmongst(ClusteredStoreConfiguration.class,
    changedConsistency.getCacheConfigurations().get("cache").getServiceConfigurations()).getConsistency(), Is.is(Consistency.EVENTUAL));
}
 
Example #3
Source File: Tiering.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void diskSegments() throws Exception {
  // tag::diskSegments[]
  String storagePath = getStoragePath();
  PersistentCacheManager persistentCacheManager = CacheManagerBuilder.newCacheManagerBuilder()
    .with(CacheManagerBuilder.persistence(new File(storagePath, "myData")))
    .withCache("less-segments",
      CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
        ResourcePoolsBuilder.newResourcePoolsBuilder().disk(10, MemoryUnit.MB))
      .withService(new OffHeapDiskStoreConfiguration(2)) // <1>
    )
    .build(true);

  persistentCacheManager.close();
  // end::diskSegments[]
}
 
Example #4
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 #5
Source File: UserManagedCaches.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void userManagedListenerCache() throws Exception {
  // tag::userManagedListenerCache[]

  UserManagedCache<Long, String> cache = UserManagedCacheBuilder.newUserManagedCacheBuilder(Long.class, String.class)
      .withEventExecutors(Executors.newSingleThreadExecutor(), Executors.newFixedThreadPool(5)) // <1>
      .withEventListeners(CacheEventListenerConfigurationBuilder
          .newEventListenerConfiguration(ListenerObject.class, EventType.CREATED, EventType.UPDATED)
          .asynchronous()
          .unordered()) // <2>
      .withResourcePools(ResourcePoolsBuilder.newResourcePoolsBuilder()
          .heap(3, EntryUnit.ENTRIES))
      .build(true);

  cache.put(1L, "Put it");
  cache.put(1L, "Update it");

  cache.close();
  // end::userManagedListenerCache[]
}
 
Example #6
Source File: UserManagedCaches.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void userManagedDiskCache() throws Exception {
  // tag::persistentUserManagedCache[]
  LocalPersistenceService persistenceService = new DefaultLocalPersistenceService(new DefaultPersistenceConfiguration(new File(getStoragePath(), "myUserData"))); // <1>

  PersistentUserManagedCache<Long, String> cache = UserManagedCacheBuilder.newUserManagedCacheBuilder(Long.class, String.class)
      .with(new UserManagedPersistenceContext<>("cache-name", persistenceService)) // <2>
      .withResourcePools(ResourcePoolsBuilder.newResourcePoolsBuilder()
          .heap(10L, EntryUnit.ENTRIES)
          .disk(10L, MemoryUnit.MB, true)) // <3>
      .build(true);

  // Work with the cache
  cache.put(42L, "The Answer!");
  assertThat(cache.get(42L), is("The Answer!"));

  cache.close(); // <4>
  cache.destroy(); // <5>

  persistenceService.stop(); // <6>
  // end::persistentUserManagedCache[]
}
 
Example #7
Source File: TokenProviderUtility.java    From Insights with Apache License 2.0 6 votes vote down vote up
/**
 * used to initilize cache
 */
@PostConstruct
public void initilizeTokenCache() {
	log.debug("Inside initilizeTokenCache of tokenProviderUtility ==== ");
	if (TokenProviderUtility.cacheManager == null) {
		TokenProviderUtility.cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
				.withCache("tokenCache",
						CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class,
								ResourcePoolsBuilder.newResourcePoolsBuilder().heap(30, EntryUnit.ENTRIES)
										.offheap(10, MemoryUnit.MB)))
				.build();

		TokenProviderUtility.cacheManager.init();
		if (TokenProviderUtility.tokenCache == null) {
			TokenProviderUtility.tokenCache = cacheManager.createCache("pipeline",
					CacheConfigurationBuilder
							.newCacheConfigurationBuilder(String.class, String.class,
									ResourcePoolsBuilder.heap(TraceabilityConstants.PIPELINE_CACHE_HEAP_SIZE_BYTES))
							.withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(
									Duration.ofSeconds(TraceabilityConstants.PIPELINE_CACHE_EXPIRY_IN_SEC))));
		}
	}
}
 
Example #8
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 #9
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 #10
Source File: CacheConfiguration.java    From TeamDojo with Apache License 2.0 6 votes vote down vote up
public CacheConfiguration(JHipsterProperties jHipsterProperties) {
    BeanClassLoaderAwareJCacheRegionFactory.setBeanClassLoader(this.getClass().getClassLoader());
    JHipsterProperties.Cache.Ehcache ehcache =
        jHipsterProperties.getCache().getEhcache();

    jcacheConfiguration = Eh107Configuration.fromEhcacheCacheConfiguration(
        CacheConfigurationBuilder.newCacheConfigurationBuilder(Object.class, Object.class,
            ResourcePoolsBuilder.heap(ehcache.getMaxEntries()))
            .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(ehcache.getTimeToLiveSeconds())))
            .build());
}
 
Example #11
Source File: EhcacheRuntimeConfigurationTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateResources() throws Exception {
  CacheConfiguration<Long, String> cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
      ResourcePoolsBuilder.newResourcePoolsBuilder()
          .heap(10L, EntryUnit.ENTRIES).disk(10, MemoryUnit.MB).build()).build();

  try (CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
      .with(new CacheManagerPersistenceConfiguration(diskPath.newFolder("myData")))
      .withCache("cache", cacheConfiguration).build(true)) {

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

    ResourcePoolsBuilder poolsBuilder = ResourcePoolsBuilder.newResourcePoolsBuilder();
    poolsBuilder = poolsBuilder.heap(20L, EntryUnit.ENTRIES);
    ResourcePools pools = poolsBuilder.build();
    cache.getRuntimeConfiguration().updateResourcePools(pools);
    assertThat(cache.getRuntimeConfiguration().getResourcePools()
      .getPoolForResource(ResourceType.Core.HEAP).getSize(), is(20L));
    pools = poolsBuilder.build();
    cache.getRuntimeConfiguration().updateResourcePools(pools);
    assertThat(cache.getRuntimeConfiguration().getResourcePools()
      .getPoolForResource(ResourceType.Core.HEAP).getSize(), is(20L));
  }
}
 
Example #12
Source File: UnSupportedCombinationsWithClusteredCacheTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testClusteredCacheWithXA() throws Exception {
  TransactionManagerServices.getConfiguration().setJournal("null");

  BitronixTransactionManager transactionManager =
      TransactionManagerServices.getTransactionManager();

  try {
    CacheManagerBuilder.newCacheManagerBuilder()
        .using(new LookupTransactionManagerProviderConfiguration(BitronixTransactionManagerLookup.class))
        .with(ClusteringServiceConfigurationBuilder.cluster(URI.create("terracotta://localhost/my-application")).autoCreate(c -> c))
        .withCache("xaCache", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
            ResourcePoolsBuilder.newResourcePoolsBuilder()
                .with(ClusteredResourcePoolBuilder.clusteredDedicated("primary-server-resource", 8, MemoryUnit.MB))
            )
                .withService(new XAStoreConfiguration("xaCache"))
                .build()
        )
        .build(true).close();
    fail("Expected StateTransitionException");
  } catch (StateTransitionException e) {
    assertThat(e.getCause().getCause().getMessage(), is("Unsupported resource type : interface org.ehcache.clustered.client.config.DedicatedClusteredResourcePool"));
  }

  transactionManager.shutdown();
}
 
Example #13
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 #14
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 #15
Source File: TestEhcache.java    From elastic-rabbitmq with MIT License 6 votes vote down vote up
@Test
public void testTem() {
    CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
    .withCache("preConfigured",
       CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(10)))
    .build();

    cacheManager.init();

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

    Cache<Long, String> myCache = cacheManager.createCache("myCache",
            CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(10)));

    myCache.put(1L, "da one!");
    myCache.putIfAbsent(0L, "ee");
    String value = myCache.get(1L);

    System.out.println("Value is " + value);
    cacheManager.removeCache("preConfigured");
    cacheManager.close();
}
 
Example #16
Source File: TestJCache.java    From jframe with Apache License 2.0 6 votes vote down vote up
@Test
public void configEhcache2Jsr107() {
    CachingProvider provider = Caching.getCachingProvider();
    CacheManager cacheManager = provider.getCacheManager();

    CacheConfiguration<Long, String> cacheConfiguration = CacheConfigurationBuilder
            .newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(10)).build();

    Cache<Long, String> cache = cacheManager.createCache("myCache",
            Eh107Configuration.fromEhcacheCacheConfiguration(cacheConfiguration));

    Eh107Configuration<Long, String> configuration = cache.getConfiguration(Eh107Configuration.class);
    configuration.unwrap(CacheConfiguration.class);

    configuration.unwrap(CacheRuntimeConfiguration.class);

    try {
        cache.getConfiguration(CompleteConfiguration.class);
        throw new AssertionError("IllegalArgumentException expected");
    } catch (IllegalArgumentException iaex) {
        // Expected
    }
}
 
Example #17
Source File: BasicClusteredCacheOpsReplicationTest.java    From ehcache3 with Apache License 2.0 6 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("/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")));
  cacheManager = 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", 1, MemoryUnit.MB)))
      .withService(ClusteredStoreConfigurationBuilder.withConsistency(cacheConsistency))
      .build();

  cacheOne = cacheManager.createCache(testName.getMethodName() + "-1", config);
  cacheTwo = cacheManager.createCache(testName.getMethodName() + "-2", config);
}
 
Example #18
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 #19
Source File: ConfigurationDerivation.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void updateCache() {
  Configuration configuration = ConfigurationBuilder.newConfigurationBuilder()
    .withCache("cache", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(10)))
    .build();

  //tag::updateCache[]
  Configuration withOffHeap = configuration.derive()
    .updateCache("cache", cache -> cache.updateResourcePools(
      resources -> ResourcePoolsBuilder.newResourcePoolsBuilder(resources)
        .offheap(100, MemoryUnit.MB)
        .build()))
    .build();
  //end::updateCache[]

  Assert.assertThat(configuration.getCacheConfigurations().get("cache").getResourcePools().getResourceTypeSet(), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP));
  Assert.assertThat(withOffHeap.getCacheConfigurations().get("cache").getResourcePools().getResourceTypeSet(), IsIterableContainingInAnyOrder.containsInAnyOrder(ResourceType.Core.HEAP, ResourceType.Core.OFFHEAP));
}
 
Example #20
Source File: DiskBackedDuplicateDetectionStrategy.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
public DiskBackedDuplicateDetectionStrategy(final ApplicationDirectories directories,
                                            final int maxHeapGb,
                                            final int maxDiskGb)
{
  String randomDirectory = UUID.randomUUID().toString();

  cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
      .with(CacheManagerBuilder.persistence(directories.getTemporaryDirectory().getPath() + "/" + randomDirectory))
      .withCache(CACHE_NAME, newCacheConfigurationBuilder(String.class, String.class,
          ResourcePoolsBuilder.newResourcePoolsBuilder()
              .heap(maxHeapGb, GB)
              .disk(maxDiskGb, GB))
      )
      .build(true);

  map = cacheManager.getCache(CACHE_NAME, String.class, String.class);
}
 
Example #21
Source File: NonXACacheTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testNonXA() throws Exception {

  /*
   * Ensure the XA provider classes are loadable through the ServiceLoader mechanism.
   */
  assertThat(stream(spliterator(ClassLoading.servicesOfType(ServiceFactory.class).iterator(), Long.MAX_VALUE, 0), false).map(s -> s.getServiceType()).collect(toList()),
    hasItems(XAStore.Provider.class, TransactionManagerProvider.class));

  CacheConfiguration<String, String> cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(
      String.class,
      String.class,
      ResourcePoolsBuilder.newResourcePoolsBuilder()
          .heap(10, EntryUnit.ENTRIES)
          .offheap(1, MemoryUnit.MB)
          .build())
      .build();


  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().build(true);

  cacheManager.createCache("cache-1", cacheConfiguration);
  cacheManager.createCache("cache-2", cacheConfiguration);

  cacheManager.close();
}
 
Example #22
Source File: ClusteredResourcePoolUpdationTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUp() throws Exception {
  UnitTestConnectionService.add(CLUSTER_URI,
    new UnitTestConnectionService.PassthroughServerBuilder()
      .resource("primary-server-resource", 8, MemoryUnit.MB)
      .resource("secondary-server-resource", 8, MemoryUnit.MB)
      .build());

  cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
    .with(ClusteringServiceConfigurationBuilder.cluster(CLUSTER_URI).autoCreate(server -> server
      .defaultServerResource("primary-server-resource")
      .resourcePool("resource-pool-a", 2, MemoryUnit.MB, "secondary-server-resource")
      .resourcePool("resource-pool-b", 4, MemoryUnit.MB)))
    .withCache("dedicated-cache", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
      ResourcePoolsBuilder.newResourcePoolsBuilder()
        .with(ClusteredResourcePoolBuilder.clusteredDedicated("primary-server-resource", 4, MemoryUnit.MB))))
    .withCache("shared-cache", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
      ResourcePoolsBuilder.newResourcePoolsBuilder()
        .with(ClusteredResourcePoolBuilder.clusteredShared("resource-pool-a"))))
    .build();
  cacheManager.init();

  dedicatedCache = cacheManager.getCache("dedicated-cache", Long.class, String.class);
  sharedCache = cacheManager.getCache("shared-cache", Long.class, String.class);
}
 
Example #23
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 #24
Source File: EhCache107ConfigurationIntegrationDocTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testUsingEhcacheConfiguration() throws Exception {
  // tag::ehcacheBasedConfigurationExample[]
  CacheConfiguration<Long, String> cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
      ResourcePoolsBuilder.heap(10)).build(); // <1>

  Cache<Long, String> cache = cacheManager.createCache("myCache",
      Eh107Configuration.fromEhcacheCacheConfiguration(cacheConfiguration)); // <2>

  Eh107Configuration<Long, String> configuration = cache.getConfiguration(Eh107Configuration.class);
  configuration.unwrap(CacheConfiguration.class); // <3>

  configuration.unwrap(CacheRuntimeConfiguration.class); // <4>

  try {
    cache.getConfiguration(CompleteConfiguration.class); // <5>
    throw new AssertionError("IllegalArgumentException expected");
  } catch (IllegalArgumentException iaex) {
    // Expected
  }
  // end::ehcacheBasedConfigurationExample[]
}
 
Example #25
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 #26
Source File: ConfigurationDerivation.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void withServiceCreation() {
  Configuration configuration = ConfigurationBuilder.newConfigurationBuilder()
    .withCache("cache", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(10)))
    .build();

  //tag::withServiceCreation[]
  Configuration withBoundedThreads = configuration.derive()
    .withService(new PooledExecutionServiceConfiguration()
      .addDefaultPool("default", 1, 16))
    .build();
  //end::withServiceCreation[]

  Assert.assertThat(configuration.getServiceCreationConfigurations(), IsNot.not(IsCollectionContaining.hasItem(IsInstanceOf.instanceOf(PooledExecutionServiceConfiguration.class))));
  PooledExecutionServiceConfiguration serviceCreationConfiguration = ServiceUtils.findSingletonAmongst(PooledExecutionServiceConfiguration.class, withBoundedThreads.getServiceCreationConfigurations());
  Assert.assertThat(serviceCreationConfiguration.getDefaultPoolAlias(), Is.is("default"));
  Assert.assertThat(serviceCreationConfiguration.getPoolConfigurations().keySet(), IsIterableContainingInAnyOrder.containsInAnyOrder("default"));
  PooledExecutionServiceConfiguration.PoolConfiguration pool = serviceCreationConfiguration.getPoolConfigurations().get("default");
  Assert.assertThat(pool.minSize(), Is.is(1));
  Assert.assertThat(pool.maxSize(), Is.is(16));
}
 
Example #27
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 #28
Source File: JCacheCacheFactory.java    From cache2k-benchmark with Apache License 2.0 6 votes vote down vote up
@Override
protected <K, V> BenchmarkCache<K, V> createSpecialized(
  final Class<K> _keyType, final Class<V> _valueType, final int _maxElements) {
  MyBenchmarkCacheAdapter c = new MyBenchmarkCacheAdapter();
  String _cacheName = constructCacheName(_maxElements);
  CacheManager mgr = resolveCacheManager();
  if (mgr.getClass().getName().toString().contains("Eh107")) {
     CacheConfiguration<K, V> _eh107Configuration =
       CacheConfigurationBuilder.newCacheConfigurationBuilder(_keyType, _valueType,
        ResourcePoolsBuilder.heap(_maxElements)).build();
      c.cache = mgr.createCache(_cacheName,
        Eh107Configuration.fromEhcacheCacheConfiguration(_eh107Configuration));
  } else if (mgr.getClass().getName().toString().contains("cache2k")) {
    c.cache = mgr.createCache(_cacheName,
      ExtendedMutableConfiguration.of(
        Cache2kBuilder.of(_keyType, _valueType)
          .entryCapacity(_maxElements)));
  } else {
    c.cache = mgr.getCache(_cacheName);
  }
  if (c.cache == null) {
    throw new NullPointerException("No cache returned for name: " + _cacheName);
  }
  return c;
}
 
Example #29
Source File: DefaultClusteringServiceTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreate() throws Exception {
  CacheConfigurationBuilder<Long, String> configBuilder =
      CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
          ResourcePoolsBuilder.newResourcePoolsBuilder()
              .with(ClusteredResourcePoolBuilder.clusteredShared("primary")));
  ClusteringServiceConfiguration configuration =
      ClusteringServiceConfigurationBuilder.cluster(URI.create(CLUSTER_URI_BASE + "my-application"))
          .autoCreate(c -> c)
          .build();
  DefaultClusteringService service = new DefaultClusteringService(configuration);

  PersistableResourceService.PersistenceSpaceIdentifier<?> spaceIdentifier = service.getPersistenceSpaceIdentifier("cacheAlias", configBuilder
      .build());
  assertThat(spaceIdentifier, instanceOf(ClusteredCacheIdentifier.class));
  assertThat(((ClusteredCacheIdentifier) spaceIdentifier).getId(), is("cacheAlias"));
}
 
Example #30
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();
}