Java Code Examples for org.ehcache.Cache#clear()

The following examples show how to use org.ehcache.Cache#clear() . 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: TranslateEhcacheManager.java    From sagacity-sqltoy with Apache License 2.0 6 votes vote down vote up
@Override
public void clear(String cacheName, String cacheKey) {
	synchronized (cacheName) {
		if (cacheManager == null) {
			return;
		}
		Cache<String, HashMap> cache = cacheManager.getCache(cacheName, String.class, HashMap.class);
		// 缓存没有配置,自动创建缓存不建议使用
		if (cache != null) {
			if (StringUtil.isBlank(cacheKey)) {
				cache.clear();
			} else {
				cache.remove(cacheKey);
			}
		}
	}
}
 
Example 2
Source File: XACacheTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testAtomicsWithoutLoaderWriter() throws Exception {
  CacheConfigurationBuilder<Long, String> cacheConfigurationBuilder = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
      newResourcePoolsBuilder()
                  .heap(10, EntryUnit.ENTRIES)
                  .offheap(10, MemoryUnit.MB)
              )
      .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(1)));

  cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
      .withCache("txCache1", cacheConfigurationBuilder.withService(new XAStoreConfiguration("txCache1")).build())
      .using(new DefaultTimeSourceService(new TimeSourceConfiguration(testTimeSource)))
      .using(new LookupTransactionManagerProviderConfiguration(BitronixTransactionManagerLookup.class))
      .build(true);

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

  putIfAbsentAssertions(transactionManager, txCache1);
  txCache1.clear();
  remove2ArgsAssertions(transactionManager, txCache1);
  txCache1.clear();
  replace2ArgsAssertions(transactionManager, txCache1);
  txCache1.clear();
  replace3ArgsAssertions(transactionManager, txCache1);
  txCache1.clear();
}
 
Example 3
Source File: SimpleEhcacheTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testClear() throws Exception {
  Cache<Number, CharSequence> testCache = cacheManager.createCache("testCache", newCacheConfigurationBuilder(Number.class, CharSequence.class, heap(10)));

  testCache.put(1, "one");
  testCache.put(2, "two");

  testCache.clear();

  assertThat(testCache.get(1), is(nullValue()));
  assertThat(testCache.get(2), is(nullValue()));
}
 
Example 4
Source File: XACacheTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testAtomicsWithLoaderWriter() throws Exception {
  SampleLoaderWriter<Long, String> loaderWriter = new SampleLoaderWriter<>();

  CacheConfigurationBuilder<Long, String> cacheConfigurationBuilder = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
      newResourcePoolsBuilder()
                  .heap(10, EntryUnit.ENTRIES)
                  .offheap(10, MemoryUnit.MB))
      .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(1)))
      .withLoaderWriter(loaderWriter);

  cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
      .withCache("txCache1", cacheConfigurationBuilder.withService(new XAStoreConfiguration("txCache1")).build())
      .using(new DefaultTimeSourceService(new TimeSourceConfiguration(testTimeSource)))
      .using(new LookupTransactionManagerProviderConfiguration(BitronixTransactionManagerLookup.class))
      .build(true);

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

  putIfAbsentAssertions(transactionManager, txCache1);
  txCache1.clear();
  loaderWriter.clear();
  remove2ArgsAssertions(transactionManager, txCache1);
  txCache1.clear();
  loaderWriter.clear();
  replace2ArgsAssertions(transactionManager, txCache1);
  txCache1.clear();
  loaderWriter.clear();
  replace3ArgsAssertions(transactionManager, txCache1);
  txCache1.clear();
  loaderWriter.clear();
}
 
Example 5
Source File: Tiering.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void updateResourcesAtRuntime() throws InterruptedException {
  ListenerObject listener = new ListenerObject();
  CacheEventListenerConfigurationBuilder cacheEventListenerConfiguration = CacheEventListenerConfigurationBuilder
    .newEventListenerConfiguration(listener, EventType.EVICTED).unordered().synchronous();

  CacheConfiguration<Long, String> cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
    ResourcePoolsBuilder.newResourcePoolsBuilder().heap(10L, EntryUnit.ENTRIES))
    .withService(cacheEventListenerConfiguration)
    .build();

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

  Cache<Long, String> cache = cacheManager.getCache("cache", Long.class, String.class);
  for(long i = 0; i < 20; i++ ){
    cache.put(i, "Hello World");
  }
  assertThat(listener.evicted(), is(10));

  cache.clear();
  listener.resetEvictionCount();

  // tag::updateResourcesAtRuntime[]
  ResourcePools pools = ResourcePoolsBuilder.newResourcePoolsBuilder().heap(20L, EntryUnit.ENTRIES).build(); // <1>
  cache.getRuntimeConfiguration().updateResourcePools(pools); // <2>
  assertThat(cache.getRuntimeConfiguration().getResourcePools()
    .getPoolForResource(ResourceType.Core.HEAP).getSize(), is(20L));
  // end::updateResourcesAtRuntime[]

  for(long i = 0; i < 20; i++ ){
    cache.put(i, "Hello World");
  }
  assertThat(listener.evicted(), is(0));

  cacheManager.close();
}
 
Example 6
Source File: BasicClusteredWriteBehindPassthroughTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testBasicClusteredWriteBehind() {
  try (PersistentCacheManager cacheManager = createCacheManager()) {
    Cache<Long, String> cache = cacheManager.getCache(CACHE_NAME, Long.class, String.class);

    put(cache, String.valueOf(0));
    put(cache, String.valueOf(1));

    assertValue(cache, String.valueOf(1));

    verifyRecords(cache);
    cache.clear();
  }
}
 
Example 7
Source File: BasicClusteredWriteBehindPassthroughTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testWriteBehindMultipleClients() {
  try (PersistentCacheManager cacheManager1 = createCacheManager();
       PersistentCacheManager cacheManager2 = createCacheManager()) {
    Cache<Long, String> client1 = cacheManager1.getCache(CACHE_NAME, Long.class, String.class);
    Cache<Long, String> client2 = cacheManager2.getCache(CACHE_NAME, Long.class, String.class);

    put(client1, "The one from client1");
    put(client2, "The one one from client2");
    assertValue(client1, "The one one from client2");
    remove(client1);
    put(client2, "The one from client2");
    put(client1, "The one one from client1");
    assertValue(client2, "The one one from client1");
    remove(client2);
    assertValue(client1, null);
    put(client1, "The one from client1");
    put(client1, "The one one from client1");
    remove(client2);
    put(client2, "The one from client2");
    put(client2, "The one one from client2");
    remove(client1);
    assertValue(client2, null);

    verifyRecords(client1);
    client1.clear();
  }
}
 
Example 8
Source File: BasicClusteredWriteBehindPassthroughTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testClusteredWriteBehindCAS() {
  try (PersistentCacheManager cacheManager = createCacheManager()) {
    Cache<Long, String> cache = cacheManager.getCache(CACHE_NAME, Long.class, String.class);
    putIfAbsent(cache, "First value", true);
    assertValue(cache, "First value");
    putIfAbsent(cache, "Second value", false);
    assertValue(cache, "First value");
    put(cache, "First value again");
    assertValue(cache, "First value again");
    replace(cache, "Replaced First value", true);
    assertValue(cache, "Replaced First value");
    replace(cache, "Replaced First value", "Replaced First value again", true);
    assertValue(cache, "Replaced First value again");
    replace(cache, "Replaced First", "Tried Replacing First value again", false);
    assertValue(cache, "Replaced First value again");
    condRemove(cache, "Replaced First value again", true);
    assertValue(cache, null);
    replace(cache, "Trying to replace value", false);
    assertValue(cache, null);
    put(cache, "new value", true);
    assertValue(cache, "new value");
    condRemove(cache, "new value", false);

    verifyRecords(cache);
    cache.clear();
  }
}
 
Example 9
Source File: BasicClusteredWriteBehindPassthroughTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testClusteredWriteBehindLoading() {
  try (CacheManager cacheManager = createCacheManager()) {
    Cache<Long, String> cache = cacheManager.getCache(CACHE_NAME, Long.class, String.class);

    put(cache, "Some value");
    tryFlushingUpdatesToSOR(cache);
    cache.clear();

    assertThat(cache.get(KEY), notNullValue());

    cache.clear();
  }
}
 
Example 10
Source File: BasicClusteredCacheOpsTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void basicCacheCRUD() throws Exception {
  final CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder
      = CacheManagerBuilder.newCacheManagerBuilder()
      .with(ClusteringServiceConfigurationBuilder.cluster(CLUSTER.getConnectionURI().resolve("/crud-cm"))
          .autoCreate(server -> server.defaultServerResource("primary-server-resource")));
  final 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", 1, MemoryUnit.MB))).build();

    Cache<Long, String> cache = cacheManager.createCache("clustered-cache", config);
    cache.put(1L, "The one");
    assertThat(cache.containsKey(2L), is(false));
    cache.put(2L, "The two");
    assertThat(cache.containsKey(2L), is(true));
    cache.put(1L, "Another one");
    cache.put(3L, "The three");
    assertThat(cache.get(1L), equalTo("Another one"));
    assertThat(cache.get(2L), equalTo("The two"));
    assertThat(cache.get(3L), equalTo("The three"));
    cache.remove(1L);
    assertThat(cache.get(1L), is(nullValue()));

    cache.clear();
    assertThat(cache.get(1L), is(nullValue()));
    assertThat(cache.get(2L), is(nullValue()));
    assertThat(cache.get(3L), is(nullValue()));
  } finally {
    cacheManager.close();
  }
}
 
Example 11
Source File: ClusteredIterationTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testIterationWithConcurrentClearedCacheException() {
  try (CacheManager cacheManager = createTestCacheManager()) {
    Cache<Long, byte[]> cache = cacheManager.getCache(testName.getMethodName(), Long.class, byte[].class);

    byte[] data = new byte[10 * 1024];
    Set<Long> initialKeySet = new HashSet<>();
    range(0, 20).forEach(k -> {
      cache.put(k, data);
      initialKeySet.add(k);
    });

    Iterator<Cache.Entry<Long, byte[]>> iterator = cache.iterator();

    cache.clear();

    HashSet<Long> foundKeys = new HashSet<>();
    try {
      while (true) {
        assertThat(foundKeys.add(iterator.next().getKey()), is(true));
      }
    } catch (NoSuchElementException e) {
      //expected
    }
    foundKeys.forEach(k -> assertThat(k, isIn(initialKeySet)));
  }
}
 
Example 12
Source File: TranslateEhcacheManager.java    From sagacity-sqltoy with Apache License 2.0 4 votes vote down vote up
@Override
public void put(TranslateConfigModel cacheConfig, String cacheName, String cacheKey,
		HashMap<String, Object[]> cacheValue) {
	if (cacheManager == null) {
		return;
	}
	synchronized (cacheName) {
		Cache<String, HashMap> cache = cacheManager.getCache(cacheName, String.class, HashMap.class);
		// 缓存没有配置,自动创建缓存(不建议使用)
		if (cache == null) {
			ResourcePoolsBuilder resBuilder = ResourcePoolsBuilder.newResourcePoolsBuilder();
			// 堆内内存大小(20000条)
			resBuilder = resBuilder.heap((cacheConfig.getHeap() < 1) ? 1000 : cacheConfig.getHeap(),
					EntryUnit.ENTRIES);
			if (cacheConfig.getOffHeap() > 0) {
				resBuilder = resBuilder.offheap(cacheConfig.getOffHeap(), MemoryUnit.MB);
			}
			if (cacheConfig.getDiskSize() > 0) {
				resBuilder = resBuilder.disk(cacheConfig.getDiskSize(), MemoryUnit.MB, true);
			}
			cache = cacheManager.createCache(cacheName,
					CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, HashMap.class, resBuilder)
							.withExpiry(cacheConfig.getKeepAlive() > 0
									? ExpiryPolicyBuilder
											.timeToLiveExpiration(Duration.ofSeconds(cacheConfig.getKeepAlive()))
									: ExpiryPolicyBuilder.noExpiration())
							.build());
		}
		// 清除缓存(一般不会执行,即缓存值被设置为null表示清除缓存)
		if (cacheValue == null) {
			if (StringUtil.isBlank(cacheKey)) {
				cache.clear();
			} else {
				cache.remove(cacheKey);
			}
		}
		// 更新缓存
		else {
			cache.put(StringUtil.isBlank(cacheKey) ? cacheName : cacheKey, cacheValue);
		}
	}
}
 
Example 13
Source File: DefaultCollectorServiceTest.java    From ehcache3 with Apache License 2.0 4 votes vote down vote up
@Test
public void test_collector() throws Exception {
  final Queue<Object> messages = new ConcurrentLinkedQueue<>();
  final List<String> notifs = new ArrayList<>(7);
  final CountDownLatch num = new CountDownLatch(6);

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

  ManagementRegistryService managementRegistry = new DefaultManagementRegistryService(new DefaultManagementRegistryConfiguration()
      .setCacheManagerAlias("my-cm-1"));

  CollectorService collectorService = new DefaultCollectorService(new CollectorService.Collector() {
    @Override
    public void onNotification(ContextualNotification notification) {
      onEvent(notification);
    }

    @Override
    public void onStatistics(Collection<ContextualStatistics> statistics) {
      onEvent(statistics);
    }

    void onEvent(Object event) {
      messages.offer(event);
      if (event instanceof ContextualNotification) {
        notifs.add(((ContextualNotification) event).getType());
      }
      num.countDown();
    }
  });

  // ehcache cache manager
  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
      .using(managementRegistry)
      .using(collectorService)
      .build(false);

  cacheManager.init();

  cacheManager.close();
  cacheManager.init();

  managementRegistry.withCapability("StatisticCollectorCapability")
      .call("startStatisticCollector",
        new Parameter(1L, long.class.getName()),
        new Parameter(TimeUnit.SECONDS, TimeUnit.class.getName()))
      .on(Context.create("cacheManagerName", "my-cm-1"))
      .build()
      .execute()
      .getSingleResult();

  Cache<String, String> cache = cacheManager.createCache("my-cache", cacheConfiguration);
  cache.put("key", "val");
  cache.clear();

  num.await(10, TimeUnit.SECONDS);
  cacheManager.removeCache("my-cache");
  cacheManager.close();

  assertThat(notifs, equalTo(Arrays.asList("CACHE_MANAGER_AVAILABLE", "CACHE_MANAGER_CLOSED", "CACHE_MANAGER_AVAILABLE", "CACHE_ADDED", "CACHE_CLEARED", "CACHE_REMOVED", "CACHE_MANAGER_CLOSED")));
  assertThat(messages.size(), equalTo(8));
}
 
Example 14
Source File: EHCache3Manager.java    From javalite with Apache License 2.0 4 votes vote down vote up
private void purgeGroup(String group) {
    final Cache<String, Object> cache = cacheManager.getCache(group, String.class, Object.class);
    if (cache != null) {
        cache.clear();
    }
}
 
Example 15
Source File: BasicClusteredLoaderWriterTest.java    From ehcache3 with Apache License 2.0 3 votes vote down vote up
@Test
public void testBulkOps() {
  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);

    Map<Long, String> mappings = new HashMap<>();

    for (int i = 1; i <= 5; i++) {
      mappings.put((long) i, "" + i);
    }

    cache.putAll(mappings);

    assertThat(loaderWriter.storeMap.keySet(), containsInAnyOrder(mappings.keySet().toArray()));

    cache.clear();

    Map<Long, String> loadedData = cache.getAll(mappings.keySet());

    assertThat(mappings.keySet(), containsInAnyOrder(loadedData.keySet().toArray()));

    cache.removeAll(mappings.keySet());

    assertThat(loaderWriter.storeMap.isEmpty(), is(true));
  }
}