SpringBoot 整合Ehcache3

SpringBootLean 是对springboot学习与研究项目,是根据实际项目的形式对进行配置与处理,欢迎star与fork。
[oschina 地址]
http://git.oschina.net/cmlbeliever/SpringBootLearning
[github 地址]
https://github.com/cmlbeliever/SpringBootLearning

最近研究了下服务器端缓存处理,并整合到SpringBoot中,已提交到branch-ehcache3分支。

网上使用的大部分是ehcache2的版本,groupId为net.sf.ehcache,升级到3以后groupId改成了org.ehcache,所以代码改变还是比较大的,根据官网上的博客地址
http://www.ehcache.org/blog/2016/05/18/ehcache3_jsr107_spring.html
按照官网的博客进行整合即可,总结步骤如下:

1、导入pom依赖

<dependency>
            <groupId>org.ehcache</groupId>
            <artifactId>ehcache</artifactId>
            <version>3.2.0</version>
        </dependency>

        <dependency>
            <groupId>javax.cache</groupId>
            <artifactId>cache-api</artifactId>
            <version>1.0.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-core -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>1.1.9</version>
        </dependency>

2、导入ehcache配置文件

<config xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
    xmlns='http://www.ehcache.org/v3' xmlns:jsr107='http://www.ehcache.org/v3/jsr107'>

    <service>
        <jsr107:defaults>
            <jsr107:cache name="people" template="heap-cache" />
        </jsr107:defaults>
    </service>

    <cache-template name="heap-cache">
        <listeners>
            <listener>
                <class>com.cml.springboot.framework.cache3.EventLogger</class>
                <event-firing-mode>ASYNCHRONOUS</event-firing-mode>
                <event-ordering-mode>UNORDERED</event-ordering-mode>
                <events-to-fire-on>CREATED</events-to-fire-on>
                <events-to-fire-on>UPDATED</events-to-fire-on>
                <events-to-fire-on>EXPIRED</events-to-fire-on>
                <events-to-fire-on>REMOVED</events-to-fire-on>
                <events-to-fire-on>EVICTED</events-to-fire-on>
            </listener>
        </listeners>
        <resources>
            <heap unit="entries">2000</heap>
            <offheap unit="MB">100</offheap>
        </resources>
    </cache-template>
</config>

3、添加log监听类

package com.cml.springboot.framework.cache3;

import org.ehcache.event.CacheEvent;
import org.ehcache.event.CacheEventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author GGIB
 */
public class EventLogger implements CacheEventListener<Object, Object> {

    private static final Logger LOGGER = LoggerFactory.getLogger(EventLogger.class);

    @Override
    public void onEvent(CacheEvent<? extends Object, ? extends Object> event) {

        LOGGER.info("Event: " + event.getType() + " Key: " + event.getKey() + " old value: " + event.getOldValue()
                + " new value: " + event.getNewValue());

    }

}

4、添加cache配置类,这里添加cacheName为people

package com.cml.springboot.framework.cache3;

import java.util.concurrent.TimeUnit;

import javax.cache.CacheManager;
import javax.cache.configuration.MutableConfiguration;
import javax.cache.expiry.Duration;
import javax.cache.expiry.TouchedExpiryPolicy;
import org.ehcache.spi.loaderwriter.CacheLoaderWriter;
import org.springframework.boot.autoconfigure.cache.JCacheManagerCustomizer;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.condition.ProducesRequestCondition;

@Component
public class Ehcache3Config implements JCacheManagerCustomizer {

    private static final String NAME_CACHE = "people";

    @Override
    public void customize(CacheManager cacheManager) {
        cacheManager.createCache(NAME_CACHE,
                new MutableConfiguration<>()
                        .setExpiryPolicyFactory(TouchedExpiryPolicy.factoryOf(new Duration(TimeUnit.SECONDS, 10)))
                        .setStoreByValue(true).setStatisticsEnabled(true));
    }

}

按照上述步骤配置即可,然后添加单元测试,可以从log上看出缓存是否使用到了。

单元测试类 com.cml.springboot.cache.Ehcache3Test
测试结果:

====================================================
2017-01-28 16:30:05.732  INFO 41240 --- [           main] o.s.t.web.servlet.TestDispatcherServlet  : FrameworkServlet '': initialization completed in 1120 ms
2017-01-28 16:30:06.213  INFO 41240 --- [           main] o.s.s.c.ThreadPoolTaskScheduler          : Initializing ExecutorService  'taskScheduler'
2017-01-28 16:30:06.562  INFO 41240 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 0
2017-01-28 16:30:06.563  INFO 41240 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : Adding {logging-channel-adapter:_org.springframework.integration.errorLogger} as a subscriber to the 'errorChannel' channel
2017-01-28 16:30:06.563  INFO 41240 --- [           main] o.s.i.channel.PublishSubscribeChannel    : Channel 'application:-1.errorChannel' has 1 subscriber(s).
2017-01-28 16:30:06.563  INFO 41240 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : started _org.springframework.integration.errorLogger
2017-01-28 16:30:06.579  INFO 41240 --- [           main] com.cml.springboot.cache3.Ehcache3Test   : Started Ehcache3Test in 7.565 seconds (JVM running for 8.36)
2017-01-28 16:30:06.886  INFO 41240 --- [           main] c.c.s.s.service.impl.UserServiceImpl     : ====================read user from db=========
2017-01-28 16:30:06.938  INFO 41240 --- [           main] c.c.s.sample.controller.CacheController  : read data token=C78CE23552BC46328959C8C0AE391886,user:User [username=null, password=null, token=C78CE23552BC46328959C8C0AE391886, newToken=null, userId=1, birthday=1987-02-27T00:00:00.000+08:00, nickName=小明22]
2017-01-28 16:30:06.938  INFO 41240 --- [hcache [null]-0] c.c.s.framework.cache3.EventLogger       : Event: CREATED Key: C78CE23552BC46328959C8C0AE391886 old value: null new value: User [username=null, password=null, token=C78CE23552BC46328959C8C0AE391886, newToken=null, userId=1, birthday=1987-02-27T00:00:00.000+08:00, nickName=小明22]
==============================
{"code":1,"user":{"token":"C78CE23552BC46328959C8C0AE391886","userId":1,"birthday":"19870227000000","nickName":"小明22"}}
=====================read data second==========================
2017-01-28 16:30:07.022  INFO 41240 --- [           main] c.c.s.sample.controller.CacheController  : read data token=C78CE23552BC46328959C8C0AE391886,user:User [username=null, password=null, token=C78CE23552BC46328959C8C0AE391886, newToken=null, userId=1, birthday=1987-02-27T00:00:00.000+08:00, nickName=小明22]
==============================
{"code":1,"user":{"token":"C78CE23552BC46328959C8C0AE391886","userId":1,"birthday":"19870227000000","nickName":"小明22"}}
2017-01-28 16:30:07.031  INFO 41240 --- [       Thread-2] o.s.w.c.s.GenericWebApplicationContext   : Closing org.springframework.web.context.support.GenericWebApplicationContext@17f62e33: startup date [Sat Jan 28 16:29:59 CST 2017]; root of context hierarchy
2017-01-28 16:30:07.035  INFO 41240 --- [       Thread-2] o.s.c.support.DefaultLifecycleProcessor  : Stopping beans in phase 0
2017-01-28 16:30:07.036  INFO 41240 --- [       Thread-2] o.s.i.endpoint.EventDrivenConsumer       : Removing {logging-channel-adapter:_org.springframework.integration.errorLogger} as a subscriber to the 'errorChannel' channel
2017-01-28 16:30:07.036  INFO 41240 --- [       Thread-2] o.s.i.channel.PublishSubscribeChannel    : Channel 'application:-1.errorChannel' has 0 subscriber(s).
2017-01-28 16:30:07.037  INFO 41240 --- [       Thread-2] o.s.i.endpoint.EventDrivenConsumer       : stopped _org.springframework.integration.errorLogger
2017-01-28 16:30:07.038  INFO 41240 --- [       Thread-2] o.s.s.c.ThreadPoolTaskScheduler          : Shutting down ExecutorService 'taskScheduler'
2017-01-28 16:30:07.061  INFO 41240 --- [       Thread-2] org.ehcache.core.EhcacheManager          : Cache 'people' removed from EhcacheManager.

注:工程上分支branch-ehcache为ehcache2版本的配置。

步骤4只配置了内存缓存,至于文件缓存以及配置需要年后再研究,欢迎补充!

posted @ 2017-01-28 16:34  小小架构师  阅读(583)  评论(0编辑  收藏  举报