Java源码示例:org.ehcache.event.CacheEvent

示例1
@Override
public void onEvent(CacheEvent event) {
    CacheListenerItem item = new CacheListenerItem(event.getKey(), event.getNewValue(), event.getOldValue());
    switch (event.getType()) {
        case CREATED:
            listener.onCreate(item);
            break;
        case EVICTED:
            listener.onEvict(item);
            break;
        case EXPIRED:
            listener.onExpire(item);
            break;
        case REMOVED:
            listener.onRemove(item);
            break;
        case UPDATED:
            listener.onUpdate(item);
            break;
        default:
            return;
    }
}
 
示例2
@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();
  }
}
 
示例3
@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();
}
 
示例4
void onEvent(CacheEvent<K, V> event) {
  ExecutorService executor;
  if (storeEventSource.isEventOrdering()) {
    executor = orderedExecutor;
  } else {
    executor = unOrderedExectuor;
  }
  if (!aSyncListenersList.isEmpty()) {
    executor.submit(new EventDispatchTask<>(event, aSyncListenersList));
  }
  if (!syncListenersList.isEmpty()) {
    Future<?> future = executor.submit(new EventDispatchTask<>(event, syncListenersList));
    try {
      future.get();
    } catch (Exception e) {
      LOGGER.error("Exception received as result from synchronous listeners", e);
    }
  }
}
 
示例5
/**
 * {@inheritDoc}
 */
@Override
public final void onEvent(CacheEvent<? extends K, ? extends V> event) {
  switch (event.getType()) {
    case CREATED:
      onCreation(event.getKey(), event.getNewValue());
      break;
    case UPDATED:
      onUpdate(event.getKey(), event.getOldValue(), event.getNewValue());
      break;
    case REMOVED:
      onRemoval(event.getKey(), event.getOldValue());
      break;
    case EXPIRED:
      onExpiry(event.getKey(), event.getOldValue());
      break;
    case EVICTED:
      onEviction(event.getKey(), event.getOldValue());
      break;
    default:
      throw new AssertionError("Unsupported event type " + event.getType());
  }
}
 
示例6
@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?");
  }
}
 
示例7
private static <V, K> Matcher<CacheEvent<? extends K, ? extends V>> event(EventType type, K key, V oldValue, V newValue) {
  return new TypeSafeMatcher<CacheEvent<? extends K, ? extends V>>() {
    @Override
    protected boolean matchesSafely(CacheEvent<? extends K, ? extends V> item) {
      return type.equals(item.getType()) && key.equals(item.getKey())
        && Objects.equals(oldValue, item.getOldValue())
        && Objects.equals(newValue, item.getNewValue());
    }

    @Override
    public void describeTo(Description description) {
      description.appendText(" on '").appendValue(key).appendText("' ").appendValue(type)
        .appendText(" [").appendValue(oldValue).appendText(" => ").appendValue(newValue).appendText("]");
    }
  };
}
 
示例8
@Override
@SuppressWarnings("unchecked")
public Cache<K, V> build(CacheManager manager) {
  checkNotNull(manager);
  checkNotNull(keyType);
  checkNotNull(valueType);
  checkNotNull(name);
  checkNotNull(expiryFactory);

  CacheConfigurationBuilder<K, V> builder = CacheConfigurationBuilder.newCacheConfigurationBuilder(
      keyType,
      valueType,
      ResourcePoolsBuilder.heap(cacheSize));

  builder.withExpiry(mapToEhCacheExpiry(expiryFactory.create()));

  Cache<K, V> cache = manager.createCache(name,  Eh107Configuration.fromEhcacheCacheConfiguration(builder));

  manager.enableStatistics(name, statisticsEnabled);
  manager.enableManagement(name, managementEnabled);

  if (persister != null) {
    CacheEventListener listener = (final CacheEvent cacheEvent) ->
        persister.accept((K) cacheEvent.getKey(), (V) cacheEvent.getOldValue());

    Eh107Configuration<K, V> configuration = cache.getConfiguration(Eh107Configuration.class);
    configuration.unwrap(CacheRuntimeConfiguration.class)
        .registerCacheEventListener(listener, EventOrdering.UNORDERED, EventFiring.ASYNCHRONOUS,
            EventType.EVICTED, EventType.REMOVED, EventType.EXPIRED);
  }

  return cache;
}
 
示例9
@Test
public void testCacheEntryEventUnwrap() {
  MutableConfiguration<String, String> configuration = new MutableConfiguration<>();
  configuration.setTypes(String.class, String.class);
  Cache<String, String> cache = cacheManager.createCache("cache", configuration);
  org.ehcache.event.CacheEvent<String, String> ehEvent = new EhEvent();
  Eh107CacheEntryEvent<String, String> cacheEntryEvent = new Eh107CacheEntryEvent.NormalEvent<>(cache, EventType.CREATED, ehEvent, false);
  assertThat(cacheEntryEvent.unwrap(org.ehcache.event.CacheEvent.class), is(instanceOf(CacheEvent.class)));
  assertThat(cacheEntryEvent.unwrap(cacheEntryEvent.getClass()), is(instanceOf(Eh107CacheEntryEvent.NormalEvent.class)));
}
 
示例10
EventDispatchTask(CacheEvent<K, V> cacheEvent, Iterable<EventListenerWrapper<K, V>> listener) {
  if (cacheEvent == null) {
    throw new NullPointerException("cache event cannot be null");
  }
  if (listener == null) {
    throw new NullPointerException("listener cannot be null");
  }
  this.cacheEvent = cacheEvent;
  this.listenerWrappers = listener;
}
 
示例11
@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++;
  }
}
 
示例12
@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);
}
 
示例13
@Test
public void testToString() throws Exception {
  @SuppressWarnings("unchecked")
  Cache<String, String> cache = mock(Cache.class);
  when(cache.toString()).thenReturn("cache");
  CacheEvent<String, String> event = CacheEvents.update("key", "old", "new", cache);
  assertThat(event.toString()).isEqualTo("UPDATED on cache key,oldValue,newValue='key','old','new'");
}
 
示例14
@Override
public void onEvent(CacheEvent<?, ?> cacheEvent) {
    LOG.info("Cache Key: {} | EventType: {} | Old value: {} | New value: {}", cacheEvent.getKey(),
            cacheEvent.getType(), cacheEvent.getOldValue(), cacheEvent.getNewValue());
}
 
示例15
@Override
public void onEvent(CacheEvent<?, ?> cacheEvent) {
  LOG.info("Key: {} | EventType: {} | Old value: {} | New value: {}",
           cacheEvent.getKey(), cacheEvent.getType(), cacheEvent.getOldValue(), cacheEvent.getNewValue());
}
 
示例16
@Override
public void onEvent(CacheEvent<? extends Number, ? extends String> event) {
  FIRED_EVENT = event;
}
 
示例17
@Override
public void onEvent(CacheEvent<? extends Number, ? extends String> event) {
  SECOND_LISTENER_FIRED_EVENT = event;
}
 
示例18
Eh107CacheEntryEvent(Cache<K, V> source, EventType eventType, CacheEvent<? extends K, ? extends V> ehEvent,
    boolean hasOldValue) {
  super(source, eventType);
  this.ehEvent = ehEvent;
  this.hasOldValue = hasOldValue;
}
 
示例19
public NormalEvent(Cache<K, V> source, EventType eventType, CacheEvent<? extends K, ? extends V> ehEvent, boolean hasOldValue) {
  super(source, eventType, ehEvent, hasOldValue);
}
 
示例20
public RemovingEvent(Cache<K, V> source, EventType eventType, CacheEvent<? extends K, ? extends V> ehEvent, boolean hasOldValue) {
  super(source, eventType, ehEvent, hasOldValue);
}
 
示例21
@Override
public void onEvent(CacheEvent<? extends String, ? extends String> event) {
  seen.add(event);
}
 
示例22
@Override
public void onEvent(CacheEvent<? extends Object, ? extends Object> event) {
  //noop
}
 
示例23
private static <K, V> CacheEvent<K, V> eventOfType(EventType type) {
  CacheEvent<K, V> event = mock(CacheEvent.class, type.name());
  when(event.getType()).thenReturn(type);
  when(event.getKey()).thenReturn((K)new Object());
  return event;
}
 
示例24
@Override
public void onEvent(CacheEvent<? extends K, ? extends V> event) {
  listener.onEvent(event);
}
 
示例25
public boolean matches(CacheEvent<K, V> event) {
  return (event.getType() == EventType.REMOVED);
}
 
示例26
public boolean matches(CacheEvent<K, V> event) {
  return (event.getType() == EventType.UPDATED);
}
 
示例27
public boolean matches(CacheEvent<K, V> event) {
  return (event.getType() == EventType.CREATED);
}
 
示例28
@Test
public void testNonExpiringEventSequence() throws TimeoutException {
  CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder =
    newCacheManagerBuilder()
      .with(cluster(CLUSTER_URI).autoCreate(s -> s.defaultServerResource("primary-server-resource")))
      .withCache(runningTest.getMethodName(), newCacheConfigurationBuilder(Long.class, String.class,
        newResourcePoolsBuilder().with(clusteredDedicated(16, MemoryUnit.MB))));

  try (PersistentCacheManager driver = clusteredCacheManagerBuilder.build(true)) {
    Cache<Long, String> driverCache = driver.getCache(runningTest.getMethodName(), Long.class, String.class);
    try (PersistentCacheManager observer = clusteredCacheManagerBuilder.build(true)) {
      Cache<Long, String> observerCache = observer.getCache(runningTest.getMethodName(), Long.class, String.class);

      List<CacheEvent<? extends Long, ? extends String>> driverEvents = new ArrayList<>();
      driverCache.getRuntimeConfiguration().registerCacheEventListener(driverEvents::add, EventOrdering.ORDERED, EventFiring.ASYNCHRONOUS, allOf(EventType.class));

      List<CacheEvent<? extends Long, ? extends String>> observerEvents = new ArrayList<>();
      observerCache.getRuntimeConfiguration().registerCacheEventListener(observerEvents::add, EventOrdering.ORDERED, EventFiring.ASYNCHRONOUS, allOf(EventType.class));


      driverCache.put(1L, "foo");
      driverCache.put(1L, "bar");
      driverCache.remove(1L);
      driverCache.putIfAbsent(1L, "baz");
      driverCache.replace(1L, "bat");
      driverCache.replace(1L, "bat", "bag");
      driverCache.remove(1L, "bag");

      @SuppressWarnings("unchecked")
      Matcher<Iterable<? extends CacheEvent<? extends Long, ? extends String>>> expectedSequence = contains(
        created(1L, "foo"),
        updated(1L, "foo", "bar"),
        removed(1L, "bar"),
        created(1L, "baz"),
        updated(1L, "baz", "bat"),
        updated(1L, "bat", "bag"),
        removed(1L, "bag"));

      within(Duration.ofSeconds(10)).runsCleanly(() -> {
        assertThat(driverEvents, expectedSequence);
        assertThat(observerEvents, expectedSequence);
      });
    }
  }
}
 
示例29
@Test
public void testExpiringEventSequence() throws TimeoutException {
  TestTimeSource timeSource = new TestTimeSource();

  CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder =
    newCacheManagerBuilder()
      .using(new TimeSourceConfiguration(timeSource))
      .with(cluster(CLUSTER_URI).autoCreate(s -> s.defaultServerResource("primary-server-resource")))
      .withCache(runningTest.getMethodName(), newCacheConfigurationBuilder(Long.class, String.class,
        newResourcePoolsBuilder().with(clusteredDedicated(16, MemoryUnit.MB)))
        .withExpiry(timeToLiveExpiration(Duration.ofMillis(1000))));

  try (PersistentCacheManager driver = clusteredCacheManagerBuilder.build(true)) {
    Cache<Long, String> driverCache = driver.getCache(runningTest.getMethodName(), Long.class, String.class);
    try (PersistentCacheManager observer = clusteredCacheManagerBuilder.build(true)) {
      Cache<Long, String> observerCache = observer.getCache(runningTest.getMethodName(), Long.class, String.class);

      List<CacheEvent<? extends Long, ? extends String>> driverEvents = new ArrayList<>();
      driverCache.getRuntimeConfiguration().registerCacheEventListener(driverEvents::add, EventOrdering.ORDERED, EventFiring.ASYNCHRONOUS, allOf(EventType.class));

      List<CacheEvent<? extends Long, ? extends String>> observerEvents = new ArrayList<>();
      observerCache.getRuntimeConfiguration().registerCacheEventListener(observerEvents::add, EventOrdering.ORDERED, EventFiring.ASYNCHRONOUS, allOf(EventType.class));


      driverCache.put(1L, "foo");
      timeSource.advanceTime(1100);
      driverCache.putIfAbsent(1L, "bar");
      timeSource.advanceTime(1100);
      driverCache.remove(1L);
      driverCache.put(1L, "baz");
      timeSource.advanceTime(1100);
      assertThat(driverCache.get(1L), nullValue());

      @SuppressWarnings("unchecked")
      Matcher<Iterable<? extends CacheEvent<? extends Long, ? extends String>>> expectedSequence = contains(
        created(1L, "foo"),
        expired(1L, "foo"),
        created(1L, "bar"),
        expired(1L, "bar"),
        created(1L, "baz"),
        expired(1L, "baz"));

      within(Duration.ofSeconds(10)).runsCleanly(() -> {
        assertThat(driverEvents, expectedSequence);
        assertThat(observerEvents, expectedSequence);
      });
    }
  }
}
 
示例30
private static <K, V> Matcher<CacheEvent<? extends K, ? extends V>> created(K key, V value) {
  return event(EventType.CREATED, key, null, value);
}