SpringBoot 缓存(EhCache 2.x 篇)

SpringBoot 缓存

在 Spring Boot中,通过@EnableCaching注解自动化配置合适的缓存管理器(CacheManager),Spring Boot根据下面的顺序去侦测缓存提供者:
* Generic
* JCache (JSR-107)
* EhCache 2.x
* Hazelcast
* Infinispan
* Redis
* Guava
* Simple

关于 Spring Boot 的缓存机制:
高速缓存抽象不提供实际存储,并且依赖于由org.springframework.cache.Cacheorg.springframework.cache.CacheManager接口实现的抽象。 Spring Boot根据实现自动配置合适的CacheManager,只要缓存支持通过@EnableCaching注释启用即可。

Spring Boot 配置 EhCache 2.x

官方文档上对于注解缓存的介绍资料非常之少,往往需要我们自己去了解相应的缓存提供者。我这里主要介绍的是 EhCache .

引入依赖

pom.xml文件中引入以下依赖

      <!--开启 cache 缓存-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- ehcache 缓存 -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>

引入配置文件 ehcache.xml

resource文件夹下创建文件ehcache.xml,并进行配置:

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<defaultCache
eternal="false"
maxElementsInMemory="1000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="0"
timeToLiveSeconds="600"
memoryStoreEvictionPolicy="LRU" /> <!-- 这里的 users 缓存空间是为了下面的 demo 做准备 -->
<cache
name="users"
eternal="false"
maxElementsInMemory="100"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="0"
timeToLiveSeconds="300"
memoryStoreEvictionPolicy="LRU" />
</ehcache>

 ehcache.xml 文件配置详解:

  • diskStore:为缓存路径,ehcache分为内存和磁盘两级,此属性定义磁盘的缓存位置。
  • defaultCache:默认缓存策略,当ehcache找不到定义的缓存时,则使用这个缓存策略。只能定义一个。
  • name:缓存名称。
  • maxElementsInMemory:缓存最大数目
  • maxElementsOnDisk:硬盘最大缓存个数。
  • eternal:对象是否永久有效,一但设置了,timeout将不起作用。
  • overflowToDisk:是否保存到磁盘,当系统当机时
  • timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
  • timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
  • diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
  • diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
  • memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
  • clearOnFlush:内存数量最大时是否清除。
  • memoryStoreEvictionPolicy:可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。

FIFO,first in first out,先进先出。
LFU, Less Frequently Used,一直以来最少被使用的。如上面所讲,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。
LRU,Least Recently Used,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。

在主类加上启动注解

在 Spring Boot 主类加上开启缓存的注解@EnableCaching

demo : SpringBoot + EhCache

搭建 Spring Boot 工程

我搭建了一个普通的 SpringBoot 工程,配置了 Druid+MySQL。
并在数据库中创建了 users 表,各字段如下:

字段名 属性
id bigint
uuid varchar
name varchar
age int

用户实体类

User.java

public class User {

    private long id;
private String uuid;
private String name;
private Integer age; //省略 get、set 及 toString 方法
}

用户数据库操作接口

UserDao.java

@Mapper
public interface UserDao{ void delete(String uuid); User update(User user); User findByUuid(String uuid); int save(@Param("user") User user);
}

用户操作Mapper文件

UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="qg.fangrui.boot.dao.UserDao">
<!--目的:为Dao接口方法提供SQL语句--> <!--映射实体对象-->
<resultMap id="UserResultMap" type="qg.fangrui.boot.model.User">
<id property="id" column="id" />
<result property="uuid" column="uuid" />
<result property="name" column="name" />
<result property="age" column="age" />
</resultMap> <insert id="save">
INSERT INTO users(name, age, uuid)
VALUES (#{user.name}, #{user.age}, #{user.uuid})
</insert> <select id="findByUuid" resultType="User">
SELECT * FROM users WHERE uuid = #{uuid}
</select> <delete id="delete">
DELETE FROM users WHERE uuid = #{uuid}
</delete> </mapper>

用户操作 service 层

一般情况下,我们在Sercive层进行对缓存的操作。先介绍 Ehcache 在 Spring 中的注解:在支持 Spring Cache 的环境下,
* @Cacheable : Spring在每次执行前都会检查Cache中是否存在相同key的缓存元素,如果存在就不再执行该方法,而是直接从缓存中获取结果进行返回,否则才会执行并将返回结果存入指定的缓存中。
* @CacheEvict : 清除缓存。
* @CachePut : @CachePut也可以声明一个方法支持缓存功能。使用@CachePut标注的方法在执行前不会去检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中。
* 这三个方法中都有两个主要的属性:value 指的是 ehcache.xml 中的缓存策略空间;key 指的是缓存的标识,同时可以用 # 来引用参数。

UserService.java

@Service
public class UserService { //这里的单引号不能少,否则会报错,被识别是一个对象
private static final String CACHE_KEY = "'user'";
private static final String DEMO_CACHE_NAME = "users"; @Autowired
private UserDao userDao; //删除用户数据
@CacheEvict(value = DEMO_CACHE_NAME,key = "'user_'+#uuid")//这是清除缓存
public void delete(String uuid){
userDao.delete(uuid);
} //更新用户数据
@CachePut(value = DEMO_CACHE_NAME,key = "'user_'+#user.getUuid()")
public User update(User user) throws CacheException{
User user1 = userDao.findByUuid(user.getUuid());
if (null == user1){
throw new CacheException("Not Find");
}
user1.setAge(user.getAge());
user1.setName(user.getName());
return user1;
} //查找用户数据
@Cacheable(value=DEMO_CACHE_NAME,key="'user_'+#uuid")
public User findByUuid(String uuid){
//若找不到缓存将打印出提示语句
System.err.println("没有走缓存!"+uuid);
return userDao.findByUuid(uuid);
} //保存用户数据
@CacheEvict(value=DEMO_CACHE_NAME,key=CACHE_KEY)
public int save(User user){
return userDao.save(user);
}
}

Controller 类

最后我们创建一个 Controller 来访问我们的缓存。因为我的 SpringBoot 处于 Debug 模式,会将所有的数据库操作打印出来,这样子缓存作用就可一目了然了。
EhcacheController.java

@RestController
public class EhcacheController { private static final Logger logger = LoggerFactory.getLogger(EhcacheController.class); @Autowired
private UserService userService; @RequestMapping("/encache")
public String EhcacheTest(){
logger.debug("进行Encache缓存测试");
System.out.println("====生成第一个用户====");
User user1 = new User();
//生成第一个用户的唯一标识符 UUID
String u1_uuid = UUID.randomUUID().toString();
//去掉 UUID 的 - 符号
String uuid1 = u1_uuid.substring(0,8)+u1_uuid.substring(9,13)+u1_uuid.substring(14,18)+u1_uuid.substring(19,23)+u1_uuid.substring(24);
user1.setName("张三");
user1.setAge(18);
user1.setUuid(uuid1);
if (userService.save(user1) == 0){
throw new JdbcException("用户对象插入数据库失败");
} //第一次查询
System.out.println(userService.findByUuid(user1.getUuid()));
//通过缓存查询
System.out.println(userService.findByUuid(user1.getUuid())); System.out.println("====修改数据====");
User user2 = new User();
user2.setName("李四-update");
user2.setAge(22);
user2.setId(user1.getId());
user2.setUuid(user1.getUuid());
try {
System.out.println(userService.update(user2));
} catch (CacheException e){
e.printStackTrace();
} System.out.println(userService.findByUuid(user2.getUuid()));
return "success";
}
}

测试

启动 SpringBoot 工程,访问 http://localhost:8080/encache ,并查看控制台打印信息:

由控制台,我们可以清楚到看到,第一次查询用户信息时,工程将用户信息存入缓存中;在第二次查询时,无需访问数据库直接从缓存中获取用户信息。

个人参考项目:

个人参考项目:https://github.com/FunriLy/springboot-study/tree/master/%E6%A1%88%E4%BE%8B9

spring boot学习(十三)SpringBoot缓存(EhCache 2.x 篇)的更多相关文章

  1. spring boot 学习(五)SpringBoot+MyBatis(XML)+Druid

    SpringBoot+MyBatis(xml)+Druid 前言 springboot集成了springJDBC与JPA,但是没有集成mybatis,所以想要使用mybatis就要自己去集成. 主要是 ...

  2. spring boot 学习(十)SpringBoot配置发送Email

    SpringBoot配置发送Email 引入依赖 在 pom.xml 文件中引入邮件配置: <dependency> <groupId>org.springframework. ...

  3. spring boot学习(4) SpringBoot 之Spring Data Jpa 支持(1)

    第一节:Spring Data Jpa 简介 Spring-Data-Jpa JPA(Java Persistence API)定义了一系列对象持久化的标准,目前实现这一规范的产品有Hibernate ...

  4. spring boot学习(2) SpringBoot 项目属性配置

    第一节:项目内置属性 application.properties配置整个项目的,相当于以前的web.xml: 注意到上一节的访问HelloWorld时,项目路径也没有加:直接是http://loca ...

  5. spring boot学习(3) SpringBoot 之MVC 支持

    第一节:@RequestMapping 配置url 映射   第二节:@Controller 处理http 请求 转发到一个页面,以前是转发到jsp页面,现在使用freemarker: 在pom.xm ...

  6. spring boot学习(7) SpringBoot 之表单验证

    第一节:SpringBoot 之表单验证@Valid 是spring-data-jpa的功能:   下面是添加学生的信息例子,要求姓名不能为空,年龄大于18岁.   贴下代码吧: Student实体: ...

  7. spring boot学习(6) SpringBoot 之事务管理

    两个操作要么同时成功,要么同时失败: 事务的一致性: 以前学ssh ssm都有事务管理service层通过applicationContext.xml配置,所有service方法都加上事务操作: 用来 ...

  8. Spring boot 学习八 Springboot的filter

    一:  传统的javaEE增加Filter是在web.xml中配置,如以下代码: <filter> <filter-name>TestFilter</filter-nam ...

  9. spring boot学习(8) SpringBoot 之切面AOP

    在方法执行的前后,切入代码:经典的service层切入事务: @Aspect注解是切面注解类 @Pointcut切点定义 @Before是方法执行前调用 @After是方法执行后调用 @AfterRe ...

随机推荐

  1. 20145105 《Java程序设计》第9周学习总结

    20145105 <Java程序设计>第9周学习总结 教材学习内容总结 第十六章 整合数据库 一.JDBC入门 (一)JDBC简介 厂商在操作JDBC驱动程序时,依操作方式可将驱动程序分为 ...

  2. Android实践项目汇报总结(上)修改

    微博客户端的设计与实现(上) 第一章 绪论 1.1课题背景 微博可以说是时下最受人们所喜爱的一种社交方式,它是一种通过关注机制分享简短实时信息的广播式的社交网络平台.通过微博我们可以了解最新的时事新闻 ...

  3. C++ vector 删除一个指定元素 和 find 一个指定元素以及遍历删除、 map遍历删除元素和删除find到的元素

    vector: 1.delete element 转载:http://www.cnblogs.com/xudong-bupt/p/3522457.html #include <vector> ...

  4. 如何高效判断java数组是否包含某个值

    在java中,我们如何判断一个未排序数组中是否包含一个特定的值?这在java中是一个频繁非常实用的操作.那么什么样的方法才是最高效的方式?当然 ,这个问题在Stack Overflow也是得票率非常高 ...

  5. linux下如何查看当前机器提供了哪些服务

    答:使用netstat工具 在命令行下输入netstat -atun即可列出当前机器提供的服务 netstat各选项解析: -a 列出所有服务 -t 列出tcp相关 -u 列出udp相关 -n 以数字 ...

  6. linux下kermit工具的使用

    1.环境: ubuntu16.04 2.背景: 想更换下位机内核 3.使用kermit进行串口传输 举例:传输文件到下位机 2.1首先进入下位机的uboot 2.2 使用uboot自带的命令从串口接收 ...

  7. spring注解注入properties配置文件

    早期,如果需要通过spring读取properties文件中的配置信息,都需要在XML文件中配置文件读取方式. 基于XML的读取方式: <bean class="org.springf ...

  8. Spring Boot详细学习地址转载

    阿里中间件牛人,学习榜样,源码分析: https://fangjian0423.github.io/ 基础.详细.全面的教程: https://gitee.com/roncoocom/spring-b ...

  9. POJ 2117 Electricity(割点求连通分量)

    http://poj.org/problem?id=2117 题意:求删除图中任意一个顶点后的最大连通分量数. 思路: 求出每个割点对应的连通分量数,注意这道题目中图可能是不连通的. 这道题目我wa了 ...

  10. POJ 1953 World Cup Noise(递推)

    https://vjudge.net/problem/POJ-1953 题意:输入一个n,这n位数只由0和1组成,并且不能两个1相邻.计算共有多少种排列方法. 思路:递推题. 首先a[1]=2,a[2 ...