SpringBootLean 是对springboot学习与研究项目,是依据实际项目的形式对进行配置与处理,欢迎star与fork。

[oschina 地址]

http://git.oschina.net/cmlbeliever/SpringBootLearning

[github 地址]

https://github.com/cmlbeliever/SpringBootLearning

近期研究了下server端缓存处理。并整合到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.

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

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

SpringBoot 整合Ehcache3的更多相关文章

  1. spring-boot整合mybatis(1)

    sprig-boot是一个微服务架构,加快了spring工程快速开发,以及简便了配置.接下来开始spring-boot与mybatis的整合. 1.创建一个maven工程命名为spring-boot- ...

  2. SpringBoot整合Mybatis之项目结构、数据源

    已经有好些日子没有总结了,不是变懒了,而是我一直在奋力学习springboot的路上,现在也算是完成了第一阶段的学习,今天给各位总结总结. 之前在网上找过不少关于springboot的教程,都是一些比 ...

  3. springboot整合mq接收消息队列

    继上篇springboot整合mq发送消息队列 本篇主要在上篇基础上进行activiemq消息队列的接收springboot整合mq发送消息队列 第一步:新建marven项目,配置pom文件 < ...

  4. springboot整合mybaits注解开发

    springboot整合mybaits注解开发时,返回json或者map对象时,如果一个字段的value为空,需要更改springboot的配置文件 mybatis: configuration: c ...

  5. SpringBoot整合Redis、ApachSolr和SpringSession

    SpringBoot整合Redis.ApachSolr和SpringSession 一.简介 SpringBoot自从问世以来,以其方便的配置受到了广大开发者的青睐.它提供了各种starter简化很多 ...

  6. SpringBoot整合ElasticSearch实现多版本的兼容

    前言 在上一篇学习SpringBoot中,整合了Mybatis.Druid和PageHelper并实现了多数据源的操作.本篇主要是介绍和使用目前最火的搜索引擎ElastiSearch,并和Spring ...

  7. SpringBoot整合Kafka和Storm

    前言 本篇文章主要介绍的是SpringBoot整合kafka和storm以及在这过程遇到的一些问题和解决方案. kafka和storm的相关知识 如果你对kafka和storm熟悉的话,这一段可以直接 ...

  8. SpringBoot整合SpringCloud搭建分布式应用

    什么是SpringCloud? SpringCloud是一个分布式的整体解决方案.SpringCloud为开发者提供了在分布式系统中快速构建的工具,使用SpringCloud可以快速的启动服务或构建应 ...

  9. SpringBoot整合RabbitMQ-整合演示

    本系列是学习SpringBoot整合RabbitMQ的练手,包含服务安装,RabbitMQ整合SpringBoot2.x,消息可靠性投递实现等三篇博客. 学习路径:https://www.imooc. ...

随机推荐

  1. OpenCASCADE BRepMesh - 2D Delaunay Triangulation

    OpenCASCADE BRepMesh - 2D Delaunay Triangulation eryar@163.com Abstract. OpenCASCADE package BRepMes ...

  2. Scrum Meeting Alpha - 3

    Scrum Meeting Alpha - 3 NewTeam 2017/10/27 地点:新主楼F座二楼 任务反馈 团队成员 完成任务 计划任务 安万贺 找到了几个开源项目,参考了API的包装方式, ...

  3. 29.使用register_chrdev_region()系列来注册字符设备

    1.之前注册字符设备用的如下函数注册字符设备驱动: register_chrdev(unsigned int major, const char *name,const struct file_ope ...

  4. C#中一些默认的预定义属性

    C#中一些默认的预定义属性,见下表: 预定义的属性 有效目标 说明 AttributeUsage Class 指定另一个属性类的有效使用方式 CLSCompliant 全部 指出程序元素是否与CLS兼 ...

  5. 微信JS-SDK 选取手机照片并进行上传

    项目中遇到需要选取照片上传的需求,因为网页运行在微信的浏览器里面,所以用微信的 js-sdk 提供的选取照片功能,来进行项目开发.实际开发中需要用到微信web开发者工具,详细参考链接:https:// ...

  6. Function Programming - 纯函数(Pure Function)

    纯函数的定义,非常重要!! Pure function 意指相同的输入,永远会得到相同的输出,而且没有任何显著的副作用. 老样子,我们还是从最简单的栗子开始: var minimum = 21; va ...

  7. MYSQL无法使用索引的场景

    设计优化–无法使用索引的场景 •通过索引扫描的记录数超过30%,变成全表扫描 •联合索引中,第一个索引列使用范围查询--只能用到部分索引 •联合索引中,第一个查询条件不是最左索引列 •模糊查询条件列最 ...

  8. JSONP原理解析

    前言 我工作以来接触的第一个项目就是前后端分离的,前端静态文件有自己独立域名,通过接口来获取数据进行渲染等操作. 跨域的方法不需要多言,随便一搜,就有很多,但最常用不外乎jsonp和CORS.json ...

  9. css选择器的优先级问题

    当我们写页面的时候,不知道你会不会产生这样的问题,为什么我给他添加的这条样式分明已经选择到我要给的元素了,但是他的样式并没有生效,那是为什么呢? 定义的属性有冲突时,浏览器会选择用那一套样式呢,下面来 ...

  10. Python基础学习-'module' object has no attribute 'urlopen'解决方法

    import numpy as npimport urlliburl = "http://archive.ics.uci.edu/ml/machine-learning-databases/ ...