org.ehcache.event.EventType Java Examples

The following examples show how to use org.ehcache.event.EventType. 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: OnHeapStoreEvictionTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testEvictionCandidateLimits() throws Exception {
  TestTimeSource timeSource = new TestTimeSource();
  StoreConfigurationImpl<String, String> configuration = new StoreConfigurationImpl<>(
    String.class, String.class, noAdvice(),
    getClass().getClassLoader(), ExpiryPolicyBuilder.noExpiration(), heap(1).build(), 1, null, null);
  TestStoreEventDispatcher<String, String> eventDispatcher = new TestStoreEventDispatcher<>();
  final String firstKey = "daFirst";
  eventDispatcher.addEventListener(event -> {
    if (event.getType().equals(EventType.EVICTED)) {
      assertThat(event.getKey(), is(firstKey));
    }
  });
  OnHeapStore<String, String> store = new OnHeapStore<>(configuration, timeSource,
    new IdentityCopier<>(), new IdentityCopier<>(), new NoopSizeOfEngine(), eventDispatcher, new DefaultStatisticsService());
  timeSource.advanceTime(10000L);
  store.put(firstKey, "daValue");
  timeSource.advanceTime(10000L);
  store.put("other", "otherValue");
}
 
Example #2
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 #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: DefaultCacheEventListenerConfigurationParserTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void unparseServiceConfiguration() {
  DefaultCacheEventListenerConfiguration listenerConfig =
    new DefaultCacheEventListenerConfiguration(EnumSet.of(CREATED, REMOVED), TestCacheEventListener.class);
  listenerConfig.setEventFiringMode(SYNCHRONOUS);
  listenerConfig.setEventOrderingMode(UNORDERED);

  CacheConfiguration<?, ?> cacheConfig = newCacheConfigurationBuilder(Object.class, Object.class, heap(10)).withService(listenerConfig).build();
  CacheType cacheType = new CacheType();
  cacheType = new DefaultCacheEventListenerConfigurationParser().unparseServiceConfiguration(cacheConfig, cacheType);

  List<ListenersType.Listener> listeners = cacheType.getListeners().getListener();
  assertThat(listeners).hasSize(1);
  ListenersType.Listener listener = listeners.get(0);
  assertThat(listener.getEventFiringMode()).isEqualTo(EventFiringType.SYNCHRONOUS);
  assertThat(listener.getEventOrderingMode()).isEqualTo(EventOrderingType.UNORDERED);
  assertThat(listener.getEventsToFireOn()).contains(org.ehcache.xml.model.EventType.CREATED, org.ehcache.xml.model.EventType.REMOVED);
}
 
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: EventNotificationTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Override
public void onEvent(final CacheEvent<? extends Object, ? extends Object> event) {
  Logger logger = LoggerFactory.getLogger(EventNotificationTest.class + "-" + "EventNotificationTest");
  logger.info(event.getType().toString());
  if(event.getType() == EventType.EVICTED){
    evicted.getAndIncrement();
  }
  if(event.getType() == EventType.CREATED){
    created.getAndIncrement();
  }
  if(event.getType() == EventType.UPDATED){
    updated.getAndIncrement();
  }
  if(event.getType() == EventType.REMOVED){
    removed.getAndIncrement();
  }
  if(event.getType() == EventType.EXPIRED){
    expired.getAndIncrement();
  }
  latch.countDown();
}
 
Example #7
Source File: EventNotificationTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Override
public void onEvent(CacheEvent<? extends Object, ? extends Object> event) {
  Logger logger = LoggerFactory.getLogger(Ehcache.class + "-" + "EventNotificationTest");
  logger.info(event.getType().toString());
  eventTypeHashMap.put(event.getType(), eventCounter.get());
  eventCounter.getAndIncrement();
  if(event.getType() == EventType.EVICTED){
    evicted.getAndIncrement();
  }
  if(event.getType() == EventType.CREATED){
    created.getAndIncrement();
  }
  if(event.getType() == EventType.UPDATED){
    updated.getAndIncrement();
  }
  if(event.getType() == EventType.REMOVED){
    removed.getAndIncrement();
  }
  if(event.getType() == EventType.EXPIRED){
    expired.getAndIncrement();
  }
}
 
Example #8
Source File: CacheEventDispatcherImplTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testShutdownDisableStoreEventsAndShutsDownOrderedExecutor() {
  eventService.registerCacheEventListener(listener,
      EventOrdering.UNORDERED, EventFiring.SYNCHRONOUS, EnumSet.of(EventType.CREATED));
  CacheEventListener<Number, String> otherLsnr = mock(CacheEventListener.class);
  eventService.registerCacheEventListener(otherLsnr,
      EventOrdering.ORDERED, EventFiring.SYNCHRONOUS, EnumSet.of(EventType.REMOVED));

  eventService.shutdown();

  InOrder inOrder = inOrder(storeEventDispatcher, orderedExecutor);
  inOrder.verify(storeEventDispatcher).removeEventListener(any(StoreEventListener.class));
  inOrder.verify(storeEventDispatcher).setEventOrdering(false);
  inOrder.verify(orderedExecutor).shutdown();
  inOrder.verifyNoMoreInteractions();
}
 
Example #9
Source File: DefaultCacheStatisticsTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Before
public void before() {
  CacheEventListenerConfigurationBuilder cacheEventListenerConfiguration = CacheEventListenerConfigurationBuilder
    .newEventListenerConfiguration((CacheEventListener<Long, String>) expirations::add, EventType.EXPIRED)
    .unordered()
    .synchronous();

  CacheConfiguration<Long, String> cacheConfiguration =
    CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, heap(10))
      .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(TIME_TO_EXPIRATION)))
      .withService(cacheEventListenerConfiguration)
      .withService(new StoreStatisticsConfiguration(enableStoreStatistics))
      .build();

  cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
    .withCache("aCache", cacheConfiguration)
    .using(new TimeSourceConfiguration(timeSource))
    .build(true);

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

  cacheStatistics = new DefaultCacheStatistics(cache);
}
 
Example #10
Source File: EventNotificationTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testEventOrderForUpdateThatTriggersEviction () {
  CacheConfiguration<Long, SerializableObject> cacheConfiguration = newCacheConfigurationBuilder(Long.class, SerializableObject.class,
      newResourcePoolsBuilder()
          .heap(1L, EntryUnit.ENTRIES).offheap(1l, MemoryUnit.MB).build()).build();

  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().withCache("cache", cacheConfiguration)
      .build(true);
  Cache<Long, SerializableObject> cache = cacheManager.getCache("cache", Long.class, SerializableObject.class);
  cache.getRuntimeConfiguration().registerCacheEventListener(listener1, EventOrdering.ORDERED, EventFiring.SYNCHRONOUS, EnumSet
      .of(EventType.EVICTED, EventType.CREATED, EventType.UPDATED, EventType.REMOVED));
  SerializableObject object1 = new SerializableObject(0xAAE60);     // 700 KB
  SerializableObject object2 = new SerializableObject(0xDBBA0);     // 900 KB

  cache.put(1L, object1);
  cache.put(1L, object2);
  assertThat(listener1.eventTypeHashMap.get(EventType.EVICTED), lessThan(listener1.eventTypeHashMap.get(EventType.CREATED)));

  cacheManager.close();
}
 
Example #11
Source File: EhCacheIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testEhCacheEventConsumer() throws Exception {
    CamelContext camelctx = new DefaultCamelContext(new JndiBeanRepository());
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("ehcache://wfccache?cacheManager=#cacheManager&eventTypes=CREATED")
            .to("mock:result");
        }
    });

    MockEndpoint mockEndpoint = camelctx.getEndpoint("mock:result", MockEndpoint.class);
    mockEndpoint.expectedHeaderReceived(EhcacheConstants.KEY, "foo");
    mockEndpoint.expectedHeaderReceived(EhcacheConstants.EVENT_TYPE, EventType.CREATED);
    mockEndpoint.expectedMessageCount(1);

    camelctx.start();
    try {
        Cache<Object, Object> cache = cacheManager.getCache("wfccache", Object.class, Object.class);
        cache.put("foo", "bar");

        mockEndpoint.assertIsSatisfied();
    } finally {
        camelctx.close();
    }
}
 
Example #12
Source File: AbstractOffHeapStoreTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testExpiryEventFiredOnExpiredCachedEntry() throws StoreAccessException {
  offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofMillis(10L)));

  final List<String> expiredKeys = new ArrayList<>();
  offHeapStore.getStoreEventSource().addEventListener(event -> {
    if (event.getType() == EventType.EXPIRED) {
      expiredKeys.add(event.getKey());
    }
  });

  offHeapStore.put("key1", "value1");
  offHeapStore.put("key2", "value2");

  offHeapStore.get("key1");   // Bring the entry to the caching tier

  timeSource.advanceTime(11);   // Expire the elements

  offHeapStore.get("key1");
  offHeapStore.get("key2");
  assertThat(expiredKeys, containsInAnyOrder("key1", "key2"));
  assertThat(getExpirationStatistic(offHeapStore).count(StoreOperationOutcomes.ExpirationOutcome.SUCCESS), is(2L));
}
 
Example #13
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 #14
Source File: UserManagedCacheBuilderTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvalidListenerConfig() {
  try {
    UserManagedCacheBuilder.newUserManagedCacheBuilder(String.class, String.class)
      .withEventListeners(CacheEventListenerConfigurationBuilder
          .newEventListenerConfiguration(DefaultCacheEventListenerProviderTest.ListenerObject.class,
              EventType.CREATED,
              EventType.UPDATED)
              .synchronous()
              .unordered()
              .build())
      .build();
    fail();
  } catch (IllegalArgumentException e) {
    assertThat(e.getMessage(), equalTo("Listeners will not work unless Executors or EventDispatcher is configured."));
  }
}
 
Example #15
Source File: CacheEventDispatcherImplTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testAsyncEventFiring() throws Exception {
  eventService = new CacheEventDispatcherImpl<>(Executors.newCachedThreadPool(), orderedExecutor);
  eventService.setStoreEventSource(storeEventDispatcher);
  final CountDownLatch signal = new CountDownLatch(1);
  final CountDownLatch signal2 = new CountDownLatch(1);
  doAnswer(invocation -> {
    if (!signal.await(2, TimeUnit.SECONDS)) {
      return null;
    } else {
      signal2.countDown();
      return null;
    }
  }).when(listener).onEvent(any(CacheEvent.class));
  eventService.registerCacheEventListener(listener, EventOrdering.UNORDERED, EventFiring.ASYNCHRONOUS, EnumSet.of(EventType.CREATED));
  final CacheEvent<Number, String> create = eventOfType(EventType.CREATED);

  eventService.onEvent(create);

  signal.countDown();
  if (!signal2.await(2, TimeUnit.SECONDS)) {
    fail("event handler never triggered latch - are we synchronous?");
  }
}
 
Example #16
Source File: EventListenerWrapper.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
public EventListenerWrapper(CacheEventListener<? super K, ? super V> listener, final EventFiring firing, final EventOrdering ordering,
                     final EnumSet<EventType> forEvents) {
  if (listener == null) {
    throw new NullPointerException("listener cannot be null");
  }
  if (firing == null) {
    throw new NullPointerException("firing cannot be null");
  }
  if (ordering == null) {
    throw new NullPointerException("ordering cannot be null");
  }
  if (forEvents == null) {
    throw new NullPointerException("forEvents cannot be null");
  }
  if (forEvents.isEmpty()) {
    throw new IllegalArgumentException("forEvents cannot be empty");
  }
  this.listener = listener;
  this.firing = firing;
  this.ordering = ordering;
  this.forEvents = forEvents;
}
 
Example #17
Source File: Matchers.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
public static <K, V> Matcher<StoreEvent<K, V>> eventOfType(final EventType type) {
  return new TypeSafeMatcher<StoreEvent<K, V>>() {
    @Override
    protected boolean matchesSafely(StoreEvent<K, V> item) {
      return item.getType().equals(type);
    }

    @Override
    public void describeTo(Description description) {
      description.appendText("event of type '").appendValue(type).appendText("'");
    }
  };
}
 
Example #18
Source File: AbstractOffHeapStoreTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testIteratorDoesNotSkipOrExpiresEntries() throws Exception {
  offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(10L)));

  offHeapStore.put("key1", "value1");
  offHeapStore.put("key2", "value2");

  timeSource.advanceTime(11L);

  offHeapStore.put("key3", "value3");
  offHeapStore.put("key4", "value4");

  final List<String> expiredKeys = new ArrayList<>();
  offHeapStore.getStoreEventSource().addEventListener(event -> {
    if (event.getType() == EventType.EXPIRED) {
      expiredKeys.add(event.getKey());
    }
  });

  List<String> iteratedKeys = new ArrayList<>();
  Store.Iterator<Cache.Entry<String, Store.ValueHolder<String>>> iterator = offHeapStore.iterator();
  while(iterator.hasNext()) {
    iteratedKeys.add(iterator.next().getKey());
  }

  assertThat(iteratedKeys, containsInAnyOrder("key1", "key2", "key3", "key4"));
  assertThat(expiredKeys.isEmpty(), is(true));
}
 
Example #19
Source File: CacheEventDispatcherImplTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testCheckEventType() {
  eventService.registerCacheEventListener(listener, EventOrdering.UNORDERED, EventFiring.SYNCHRONOUS, EnumSet.of(EventType.EVICTED));
  CacheEvent<Number, String> create = eventOfType(EventType.CREATED);
  eventService.onEvent(create);
  verify(listener, Mockito.never()).onEvent(any(CacheEvent.class));

  CacheEvent<Number, String> evict = eventOfType(EventType.EVICTED);
  eventService.onEvent(evict);
  verify(listener).onEvent(evict);
}
 
Example #20
Source File: ByteAccountingTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testEviction() throws StoreAccessException {
  OnHeapStoreForTests<String, String> store = newStore(1);
  @SuppressWarnings("unchecked")
  StoreEventListener<String, String> listener = mock(StoreEventListener.class);
  store.getStoreEventSource().addEventListener(listener);

  store.put(KEY, VALUE);
  assertThat(store.getCurrentUsageInBytes(), is(SIZE_OF_KEY_VALUE_PAIR));

  String key1 = "key1";
  char[] chars = new char[250];
  Arrays.fill(chars, (char) 0xffff);
  String value1 = new String(chars);

  long requiredSize = getSize(key1, value1);

  store.put(key1, value1);
  Matcher<StoreEvent<String, String>> matcher = eventType(EventType.EVICTED);
  verify(listener, times(1)).onEvent(argThat(matcher));
  if (store.get(key1) != null) {
    assertThat(store.getCurrentUsageInBytes(), is(requiredSize));
  } else {
    assertThat(store.getCurrentUsageInBytes(), is(SIZE_OF_KEY_VALUE_PAIR));
  }

}
 
Example #21
Source File: TestStoreEventDispatcher.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Override
public void updated(K key, Supplier<V> previousValue, V newValue) {
  if (accepted(EventType.UPDATED, key, previousValue.get(), newValue)) {
    StoreEvent<K, V> event = StoreEvents.updateEvent(key, previousValue.get(), newValue);
    for (StoreEventListener<K, V> listener : listeners) {
      listener.onEvent(event);
    }
  }
}
 
Example #22
Source File: AbstractOffHeapStoreTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
public static <K, V> Matcher<StoreEvent<K, V>> eventType(final EventType type) {
  return new TypeSafeMatcher<StoreEvent<K, V>>() {
    @Override
    protected boolean matchesSafely(StoreEvent<K, V> item) {
      return item.getType().equals(type);
    }

    @Override
    public void describeTo(Description description) {
      description.appendText("store event of type '").appendValue(type).appendText("'");
    }
  };
}
 
Example #23
Source File: CacheEventDispatcherImplTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeregisterNotLastListenerDoesNotStopStoreEvents() {
  eventService.registerCacheEventListener(listener, EventOrdering.UNORDERED, EventFiring.SYNCHRONOUS, EnumSet.of(EventType.EVICTED));
  eventService.registerCacheEventListener(mock(CacheEventListener.class), EventOrdering.UNORDERED, EventFiring.SYNCHRONOUS, EnumSet.of(EventType.EVICTED));
  eventService.deregisterCacheEventListener(listener);
  verify(storeEventDispatcher, never()).removeEventListener(any(StoreEventListener.class));
}
 
Example #24
Source File: GettingStarted.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void configuringEventProcessing() {
  CacheEventListenerConfigurationBuilder cacheEventListenerConfiguration = CacheEventListenerConfigurationBuilder
      .newEventListenerConfiguration(ListenerObject.class, EventType.EVICTED).ordered().synchronous();
  // tag::configuringEventProcessingQueues[]
  CacheConfiguration<Long, String> cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
                                                                                        ResourcePoolsBuilder.heap(5L))
      .withDispatcherConcurrency(10) // <1>
      .withEventListenersThreadPool("listeners-pool")
      .build();
  // end::configuringEventProcessingQueues[]
  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().withCache("cache", cacheConfiguration)
      .build(true);
  cacheManager.close();
}
 
Example #25
Source File: GettingStarted.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void registerListenerAtRuntime() {
  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
      .withCache("cache", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
          ResourcePoolsBuilder.heap(10L)))
      .build(true);

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

  // tag::registerListenerAtRuntime[]
  ListenerObject listener = new ListenerObject(); // <1>
  cache.getRuntimeConfiguration().registerCacheEventListener(listener, EventOrdering.ORDERED,
      EventFiring.ASYNCHRONOUS, EnumSet.of(EventType.CREATED, EventType.REMOVED)); // <2>

  cache.put(1L, "one");
  cache.put(2L, "two");
  cache.remove(1L);
  cache.remove(2L);

  cache.getRuntimeConfiguration().deregisterCacheEventListener(listener); // <3>

  cache.put(1L, "one again");
  cache.remove(1L);
  // end::registerListenerAtRuntime[]

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

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

  cacheManager.close();
  // end::events[]
}
 
Example #27
Source File: ListenerObject.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Override
public void onEvent(CacheEvent<? extends Object, ? extends Object> event) {
  Logger logger = LoggerFactory.getLogger(Ehcache.class + "-" + "GettingStarted");
  logger.info(event.getType().toString());
  if(event.getType() == EventType.EVICTED){
    evicted++;
  }
}
 
Example #28
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 #29
Source File: EventsFailureBehaviorTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testEventsFailover() throws Exception {
  AccountingCacheEventListener<Long, byte[]> accountingCacheEventListener1 = new AccountingCacheEventListener<>();
  Cache<Long, byte[]> cache1 = createCache(cacheManager1, accountingCacheEventListener1, ExpiryPolicyBuilder.noExpiration());
  AccountingCacheEventListener<Long, byte[]> accountingCacheEventListener2 = new AccountingCacheEventListener<>();
  Cache<Long, byte[]> cache2 = createCache(cacheManager2, accountingCacheEventListener2, ExpiryPolicyBuilder.noExpiration());


  byte[] value = new byte[10 * 1024];

  range(0, KEYS).forEach(k -> {
    cache1.put(k, value);
  });
  assertThat(() -> accountingCacheEventListener1.events.get(EventType.CREATED), within(TIMEOUT).matches(hasSize(greaterThan(0))));
  assertThat(() -> accountingCacheEventListener1.events.get(EventType.EVICTED), within(TIMEOUT).matches(hasSize(greaterThan(0))));
  assertThat(() -> accountingCacheEventListener2.events.get(EventType.CREATED), within(TIMEOUT).matches(hasSize(greaterThan(0))));
  assertThat(() -> accountingCacheEventListener2.events.get(EventType.EVICTED), within(TIMEOUT).matches(hasSize(greaterThan(0))));

  // failover passive -> active
  failover(cache1, cache2);

  range(0, KEYS).forEach(k -> {
    cache1.put(k, value);
  });
  assertThat(() -> accountingCacheEventListener1.events.get(EventType.UPDATED), within(TIMEOUT).matches(hasSize(greaterThan(0))));
  assertThat(() -> accountingCacheEventListener2.events.get(EventType.UPDATED), within(TIMEOUT).matches(hasSize(greaterThan(0))));

  range(0, KEYS).forEach(cache1::remove);
  assertThat(() -> accountingCacheEventListener1.events.get(EventType.REMOVED), within(TIMEOUT).matches(hasSize(greaterThan(0))));
  assertThat(() -> accountingCacheEventListener2.events.get(EventType.REMOVED), within(TIMEOUT).matches(hasSize(greaterThan(0))));

  range(KEYS, KEYS * 2).forEach(k -> {
    cache1.put(k, value);
  });
  assertThat(() -> accountingCacheEventListener1.events.get(EventType.CREATED), within(TIMEOUT).matches(hasSize(greaterThan(0))));
  assertThat(() -> accountingCacheEventListener1.events.get(EventType.EVICTED), within(TIMEOUT).matches(hasSize(greaterThan(0))));
  assertThat(() -> accountingCacheEventListener2.events.get(EventType.CREATED), within(TIMEOUT).matches(hasSize(greaterThan(0))));
  assertThat(() -> accountingCacheEventListener2.events.get(EventType.EVICTED), within(TIMEOUT).matches(hasSize(greaterThan(0))));
}
 
Example #30
Source File: EhCacheManager.java    From nuls with MIT License 5 votes vote down vote up
/**
     * 创建一个缓存容器
     * Create a cache container.
     *
     * @param title    容器标识,cache name
     * @param params   初始化参数,init parameters
     */
    public void createCache(String title, CacheMapParams params) {
        AssertUtil.canNotEmpty(params.getHeapMb());
        AssertUtil.canNotEmpty(params.getKeyType());
        AssertUtil.canNotEmpty(params.getValueType());
        CacheConfigurationBuilder builder = CacheConfigurationBuilder.newCacheConfigurationBuilder(params.getKeyType(), params.getValueType(),
                ResourcePoolsBuilder.newResourcePoolsBuilder().heap(params.getHeapMb(), MemoryUnit.MB)
        );
        if (params.getListener() != null) {
            Set<EventType> types = new HashSet<>();
            types.add(EventType.CREATED);
            types.add(EventType.UPDATED);
            types.add(EventType.EVICTED);
            types.add(EventType.EXPIRED);
            types.add(EventType.REMOVED);
            CacheEventListenerConfigurationBuilder cacheEventListenerConfiguration = CacheEventListenerConfigurationBuilder
                    .newEventListenerConfiguration(new EhcacheListener(params.getListener()), types)
                    .unordered().asynchronous();
            builder = builder.add(cacheEventListenerConfiguration);
        }
        builder = builder.withSizeOfMaxObjectGraph(MAX_SIZE_OF_CACHE_OBJ_GRAPH);
//        builder = builder.withValueSerializer(new CacheObjectSerializer(params.getValueType())).withKeySerializer(new CacheObjectSerializer(params.getKeyType()));
        if (params.getTimeToLiveSeconds() > 0) {
            builder = builder.withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(params.getTimeToLiveSeconds())));
        }
        if (params.getTimeToIdleSeconds() > 0) {
            builder = builder.withExpiry(ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofSeconds(params.getTimeToIdleSeconds())));
        }
        if (null != params.getValueCopier()) {
            builder = builder.withValueCopier( params.getValueCopier());
        }
        cacheManager.createCache(title, builder.build());
        KEY_TYPE_MAP.put(title, params.getKeyType());
        VALUE_TYPE_MAP.put(title, params.getValueType());
    }