Search in sources :

Example 1 with CacheEventListener

use of net.sf.ehcache.event.CacheEventListener in project spring-framework by spring-projects.

the class EhCacheFactoryBean method afterPropertiesSet.

@Override
public void afterPropertiesSet() throws CacheException {
    // If no cache name given, use bean name as cache name.
    String cacheName = getName();
    if (cacheName == null) {
        cacheName = this.beanName;
        setName(cacheName);
    }
    // If no CacheManager given, fetch the default.
    if (this.cacheManager == null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Using default EhCache CacheManager for cache region '" + cacheName + "'");
        }
        this.cacheManager = CacheManager.getInstance();
    }
    synchronized (this.cacheManager) {
        // Fetch cache region: If none with the given name exists, create one on the fly.
        Ehcache rawCache;
        boolean cacheExists = this.cacheManager.cacheExists(cacheName);
        if (cacheExists) {
            if (logger.isDebugEnabled()) {
                logger.debug("Using existing EhCache cache region '" + cacheName + "'");
            }
            rawCache = this.cacheManager.getEhcache(cacheName);
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug("Creating new EhCache cache region '" + cacheName + "'");
            }
            rawCache = createCache();
            rawCache.setBootstrapCacheLoader(this.bootstrapCacheLoader);
        }
        if (this.cacheEventListeners != null) {
            for (CacheEventListener listener : this.cacheEventListeners) {
                rawCache.getCacheEventNotificationService().registerListener(listener);
            }
        }
        // Needs to happen after listener registration but before setStatisticsEnabled
        if (!cacheExists) {
            this.cacheManager.addCache(rawCache);
        }
        if (this.disabled) {
            rawCache.setDisabled(true);
        }
        Ehcache decoratedCache = decorateCache(rawCache);
        if (decoratedCache != rawCache) {
            this.cacheManager.replaceCacheWithDecoratedCache(rawCache, decoratedCache);
        }
        this.cache = decoratedCache;
    }
}
Also used : CacheEventListener(net.sf.ehcache.event.CacheEventListener) Ehcache(net.sf.ehcache.Ehcache)

Example 2 with CacheEventListener

use of net.sf.ehcache.event.CacheEventListener in project gocd by gocd.

the class StageSqlMapDaoIntegrationTest method shouldInvalidateStageHistoryCachesOnStageSave.

@Test
public void shouldInvalidateStageHistoryCachesOnStageSave() throws Exception {
    HgMaterial hg = new HgMaterial("url", null);
    String[] hg_revs = { "h1" };
    scheduleUtil.checkinInOrder(hg, hg_revs);
    String pipelineName = "p1";
    String stageName = "stage_name";
    ScheduleTestUtil.AddedPipeline p1 = scheduleUtil.saveConfigWith(pipelineName, stageName, scheduleUtil.m(hg));
    scheduleUtil.runAndPass(p1, "h1");
    Stage stage = stageDao.mostRecentStage(new StageConfigIdentifier(pipelineName, stageName));
    // PRIME CACHE
    stageDao.findStageHistoryPage(stage, 10);
    CacheEventListener listener = mock(CacheEventListener.class);
    goCache.addListener(listener);
    // NEW RUN OF STAGE, CACHE SHOULD BE INVALIDATED
    scheduleUtil.runAndPass(p1, "h1");
    stage = stageDao.mostRecentStage(new StageConfigIdentifier(pipelineName, stageName));
    // SHOULD QUERY AGAIN
    stageDao.findStageHistoryPage(stage, 10);
    ArgumentCaptor<Element> elementRemovedCaptor = ArgumentCaptor.forClass(Element.class);
    ArgumentCaptor<Element> elementAddedCaptor = ArgumentCaptor.forClass(Element.class);
    verify(listener, atLeastOnce()).notifyElementRemoved(any(), elementRemovedCaptor.capture());
    verify(listener, atLeastOnce()).notifyElementPut(any(), elementAddedCaptor.capture());
    List<Serializable> keysThatWereRemoved = new ArrayList<>();
    List<Serializable> keysThatWereAdded = new ArrayList<>();
    for (Element element : elementRemovedCaptor.getAllValues()) {
        keysThatWereRemoved.add(element.getKey());
    }
    for (Element element : elementAddedCaptor.getAllValues()) {
        keysThatWereAdded.add(element.getKey());
    }
    Assertions.assertThat(keysThatWereRemoved).contains(stageDao.cacheKeyForStageHistories(pipelineName, stageName), stageDao.cacheKeyForStageCount(pipelineName, stageName), stageDao.cacheKeyForStageOffset(stage));
    Assertions.assertThat(keysThatWereAdded).contains(stageDao.cacheKeyForStageHistories(pipelineName, stageName), stageDao.cacheKeyForStageCount(pipelineName, stageName), stageDao.cacheKeyForStageOffset(stage));
}
Also used : CacheEventListener(net.sf.ehcache.event.CacheEventListener) Serializable(java.io.Serializable) Element(net.sf.ehcache.Element) HgMaterial(com.thoughtworks.go.config.materials.mercurial.HgMaterial) ScheduleTestUtil(com.thoughtworks.go.server.service.ScheduleTestUtil) Test(org.junit.jupiter.api.Test)

Example 3 with CacheEventListener

use of net.sf.ehcache.event.CacheEventListener in project camel by apache.

the class CacheEndpoint method initializeCache.

/**
     * Returns {@link Cache} instance or create new one if not exists.
     * 
     * @return {@link Cache}
     */
public Ehcache initializeCache() {
    CacheManager cacheManager = getCacheManagerFactory().getInstance();
    Ehcache cache;
    if (cacheManager.cacheExists(config.getCacheName())) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Found an existing cache: {}", config.getCacheName());
            LOG.trace("Cache {} currently contains {} elements", config.getCacheName(), cacheManager.getEhcache(config.getCacheName()).getSize());
        }
        cache = cacheManager.getEhcache(config.getCacheName());
    } else {
        cache = new Cache(config.getCacheName(), config.getMaxElementsInMemory(), config.getMemoryStoreEvictionPolicy(), config.isOverflowToDisk(), config.getDiskStorePath(), config.isEternal(), config.getTimeToLiveSeconds(), config.getTimeToIdleSeconds(), config.isDiskPersistent(), config.getDiskExpiryThreadIntervalSeconds(), null);
        for (CacheEventListener listener : config.getEventListenerRegistry().getEventListeners()) {
            cache.getCacheEventNotificationService().registerListener(listener);
        }
        for (CacheLoaderWrapper loader : config.getCacheLoaderRegistry().getCacheLoaders()) {
            loader.init(cache);
            cache.registerCacheLoader(loader);
        }
        cacheManager.addCache(cache);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Added a new cache: " + cache.getName());
        }
    }
    return cache;
}
Also used : CacheEventListener(net.sf.ehcache.event.CacheEventListener) CacheManager(net.sf.ehcache.CacheManager) Ehcache(net.sf.ehcache.Ehcache) Cache(net.sf.ehcache.Cache)

Example 4 with CacheEventListener

use of net.sf.ehcache.event.CacheEventListener in project camel by apache.

the class CacheRegistryRefTest method testConfig.

@Test
public void testConfig() throws Exception {
    producerTemplate.send(new Processor() {

        public void process(Exchange exchange) throws Exception {
            exchange.setProperty(Exchange.CHARSET_NAME, "UTF-8");
            Message in = exchange.getIn();
            in.setHeader(CacheConstants.CACHE_OPERATION, CacheConstants.CACHE_OPERATION_ADD);
            in.setHeader(CacheConstants.CACHE_KEY, "greeting");
            in.setBody("Hello World");
        }
    });
    CacheManager cm = cacheEndpoint.getCacheManagerFactory().getInstance();
    Cache cache = cm.getCache(cacheEndpoint.getConfig().getCacheName());
    Set<CacheEventListener> ehcacheEventListners = cache.getCacheEventNotificationService().getCacheEventListeners();
    List<CacheLoader> cacheLoaders = cache.getRegisteredCacheLoaders();
    CacheEventListenerRegistry configuredEventRegistry = cacheEndpoint.getConfig().getEventListenerRegistry();
    CacheLoaderRegistry configuredLoaderRegistry = cacheEndpoint.getConfig().getCacheLoaderRegistry();
    //Test if CacheEventListenerRegistry was referenced correctly
    assertEquals("CacheEventListenerRegistry size", 1, configuredEventRegistry.size());
    //Expecting 1 loader to be configured via spring
    assertEquals("configuredLoaderRegistry size", 1, configuredLoaderRegistry.size());
    //Expecting 1 listener added by us: TestCacheEventListener
    assertEquals("Number of registered listeners", 1, ehcacheEventListners.size());
    assertEquals("Number of registered loaders", 1, cacheLoaders.size());
    //Is our TestCacheEventListener really invoked?
    int puts = 0;
    for (Object listener : ehcacheEventListners) {
        if (listener instanceof TestCacheEventListener) {
            puts = ((TestCacheEventListener) listener).getNumberOfPuts();
            break;
        }
    }
    assertEquals("TestCacheEventListener put invocations", 1, puts);
    //Is cache loader initialized by ehcache
    assertEquals("loader initialized", cacheLoaders.get(0).getStatus(), Status.STATUS_ALIVE);
}
Also used : CacheEventListener(net.sf.ehcache.event.CacheEventListener) Processor(org.apache.camel.Processor) Message(org.apache.camel.Message) CacheException(net.sf.ehcache.CacheException) Exchange(org.apache.camel.Exchange) CacheManager(net.sf.ehcache.CacheManager) CacheLoader(net.sf.ehcache.loader.CacheLoader) Cache(net.sf.ehcache.Cache) Test(org.junit.Test) BaseCacheTest(org.apache.camel.component.BaseCacheTest)

Example 5 with CacheEventListener

use of net.sf.ehcache.event.CacheEventListener in project BroadleafCommerce by BroadleafCommerce.

the class HydratedCacheEventListenerFactory method createCacheEventListener.

@Override
public CacheEventListener createCacheEventListener(Properties props) {
    try {
        if (props == null || props.isEmpty()) {
            manager = EhcacheHydratedCacheManagerImpl.getInstance();
        } else {
            String managerClass = props.getProperty("managerClass");
            Class<?> clazz = Class.forName(managerClass);
            Method method = clazz.getDeclaredMethod("getInstance");
            manager = (HydratedCacheManager) method.invoke(null);
        }
    } catch (Exception e) {
        throw new RuntimeException("Unable to create a CacheEventListener instance", e);
    }
    return (CacheEventListener) manager;
}
Also used : CacheEventListener(net.sf.ehcache.event.CacheEventListener) Method(java.lang.reflect.Method)

Aggregations

CacheEventListener (net.sf.ehcache.event.CacheEventListener)6 Cache (net.sf.ehcache.Cache)3 Ehcache (net.sf.ehcache.Ehcache)3 CacheException (net.sf.ehcache.CacheException)2 CacheManager (net.sf.ehcache.CacheManager)2 HgMaterial (com.thoughtworks.go.config.materials.mercurial.HgMaterial)1 ScheduleTestUtil (com.thoughtworks.go.server.service.ScheduleTestUtil)1 Serializable (java.io.Serializable)1 Method (java.lang.reflect.Method)1 Element (net.sf.ehcache.Element)1 CacheLoader (net.sf.ehcache.loader.CacheLoader)1 Exchange (org.apache.camel.Exchange)1 Message (org.apache.camel.Message)1 Processor (org.apache.camel.Processor)1 BaseCacheTest (org.apache.camel.component.BaseCacheTest)1 Test (org.junit.Test)1 Test (org.junit.jupiter.api.Test)1