实践应用:Spring Boot项目集成Ehcache缓存

在这里插入图片描述

概 述

在如今高并发的互联网应用中,缓存的地位举足轻重,对提升程序性能帮助不小。而3.x开始的 Spring也引入了对 Cache的支持,那对于如今发展得如火如荼的 Spring Boot来说自然也是支持缓存特性的。当然 Spring Boot默认使用的是 SimpleCacheConfiguration,即使用ConcurrentMapCacheManager 来实现的缓存。但本文将讲述如何将 Ehcache缓存应用到Spring Boot应用中。

Ehcache」 是一个基于Java实现的开源缓存管理库,提供了用内存磁盘文件存储、以及分布式存储等多种灵活的管理方案。使用方式和原理都有点类似于 Spring事务管理,配合各项注解可以很容易的上手。

简介

EhCache 是一个纯 Java 的进程内缓存框架,具有快速、精干等特点,是 Hibernate 中默认CacheProviderEhcache 是一种广泛使用的开源 Java 分布式缓存。主要面向通用缓存,Java EE 和轻量级容器。它具有内存和磁盘存储,缓存加载器,缓存扩展,缓存异常处理程序,一个 gzip 缓存 servlet 过滤器,支持 REST 和 SOAP api 等特点。

特性

  • 快速、简单
  • 多种缓存策略
  • 缓存数据有两级:内存和磁盘,因此无需担心容量问题
  • 缓存数据会在虚拟机重启的过程中写入磁盘
  • 可以通过RMI、可插入API等方式进行分布式缓存
  • 具有缓存和缓存管理器的侦听接口
  • 支持多缓存管理器实例,以及一个实例的多个缓存区域
  • 提供Hibernate的缓存实现

与 Redis 相比

  • EhCache 直接在jvm虚拟机中缓存,速度快,效率高;但是缓存共享麻烦,集群分布式应用不方便。
  • Redis 是通过 Socket 访问到缓存服务,效率比 EhCache 低,比数据库要快很多,处理集群和分布式缓存方便,有成熟的方案。如果是单个应用或者对缓存访问要求很高的应用,用 EhCache 。如果是大型系统,存在缓存共享、分布式部署、缓存内容很大的,建议用 Redis。
  • EhCache 也有缓存共享方案,不过是通过 RMI 或者 Jgroup 多播方式进行广播缓存通知更新,缓存共享复杂,维护不方便;简单的共享可以,但是涉及到缓存恢复,大数据缓存,则不合适。

下文就上手来摸一摸它,结合对数据库的操作,我们让 Ehcache作为本地缓存来看一下效果!

准备工作

准备好数据库和数据表并插入相应的数据(MySQL)

比如我这里准备了一张部门表,包含几条记录:

CREATE TABLE `dept` (
  `dept_no` bigint(20) NOT NULL AUTO_INCREMENT,
  `dept_name` varchar(60) DEFAULT NULL,
  `dept_source` varchar(60) DEFAULT NULL,
  PRIMARY KEY (`dept_no`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COMMENT='部门表';

-- ----------------------------
-- Records of dept
-- ----------------------------
INSERT INTO `dept` VALUES ('1', '开发部', 'db01');
INSERT INTO `dept` VALUES ('2', '人事部', 'db01');
INSERT INTO `dept` VALUES ('3', '财务部', 'db01');
INSERT INTO `dept` VALUES ('4', '市场部', 'db01');
INSERT INTO `dept` VALUES ('5', '运维部', 'db01');

我们将通过模拟数据库的存取操作来看看 Ehcache缓存加入后的效果。

搭建工程(SpringBoot+MyBatis+MySQL+Ehcache)

pom.xml 中添加如下依赖:

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>

        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.17</version>
        </dependency>
        <!-- ehcache依赖 -->
        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache</artifactId>
            <version>2.10.6</version>
        </dependency>
        <!-- Spring boot Cache-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>

        <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>

建立 Ehcache配置文件

创建Ehcache的配置文件 ehcache.xml并置于项目 classpath下:

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    <!--
        磁盘存储:将缓存中暂时不使用的对象,转移到硬盘,类似于Windows系统的虚拟内存
        path:指定在硬盘上存储对象的路径
        path可以配置的目录有:
        user.home(用户的家目录)
        user.dir(用户当前的工作目录)
        java.io.tmpdir(默认的临时目录)
        ehcache.disk.store.dir(ehcache的配置目录)
        绝对路径(如:d:\\ehcache)
        查看路径方法:String tmpDir = System.getProperty("java.io.tmpdir");
     -->
    <diskStore path="java.io.tmpdir" />

    <!--
        defaultCache:默认的缓存配置信息,如果不加特殊说明,则所有对象按照此配置项处理
        maxElementsInMemory:设置了缓存的上限,最多存储多少个记录对象
        eternal:代表对象是否永不过期 (指定true则下面两项配置需为0无限期)
        timeToIdleSeconds:最大的发呆时间 /秒
        timeToLiveSeconds:最大的存活时间 /秒
        overflowToDisk:是否允许对象被写入到磁盘
        说明:下列配置自缓存建立起600(10分钟)有效 。
        在有效的600(10分钟)内,如果连续120(2分钟)未访问缓存,则缓存失效。
        就算有访问,也只会存活600秒。
     -->
    <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="600"
                  timeToLiveSeconds="600" overflowToDisk="true" />

    <!--
        maxElementsInMemory,内存缓存中最多可以存放的元素数量,若放入Cache中的元素超过这个数值,则有以下两种情况
                            1)若overflowToDisk=true,则会将Cache中多出的元素放入磁盘文件中
                            2)若overflowToDisk=false,则根据memoryStoreEvictionPolicy策略替换Cache中原有的元素
        eternal,            缓存中对象是否永久有效
        timeToIdleSeconds,  缓存数据在失效前的允许闲置时间(单位:),仅当eternal=false时使用,默认值是0表示可闲置时间无穷大,若超过这个时间没有访问此Cache中的某个元素,那么此元素将被从Cache中清除
        timeToLiveSeconds,  缓存数据的总的存活时间(单位:秒),仅当eternal=false时使用,从创建开始计时,失效结束
        maxElementsOnDisk,  磁盘缓存中最多可以存放的元素数量,0表示无穷大
        overflowToDisk,     内存不足时,是否启用磁盘缓存
        diskExpiryThreadIntervalSeconds,    磁盘缓存的清理线程运行间隔,默认是120秒
        memoryStoreEvictionPolicy,  内存存储与释放策略,即达到maxElementsInMemory限制时,Ehcache会根据指定策略清理内存  共有三种策略,分别为LRU(最近最少使用)LFU(最常用的)FIFO(先进先出)
    -->
    <cache name="dept"
           maxElementsInMemory="10000"
           eternal="false"
           timeToIdleSeconds="120"
           timeToLiveSeconds="120"
           maxElementsOnDisk="10000000"
           overflowToDisk="true"
           memoryStoreEvictionPolicy="LRU" />

</ehcache>

<cache name="user"></cache>,我们是可以配置多个来解决我们不同业务处所需要的缓存策略的

配置 application.yml

默认情况下,EhCache 的配置文件名是固定的,ehcache.xml,如果需要更改文件名,需要在 application.yml 文件中指定配置文件位置,如

server:
  port: 10100   #  配置启动端口号


spring: #springboot的配置
  datasource: #定义数据源
    #127.0.0.1为本机测试的ip,3306是mysql的端口号。serverTimezone是定义时区,照抄就好,mysql高版本需要定义这些东西
    #useSSL也是某些高版本mysql需要问有没有用SSL连接
    url: jdbc:mysql://127.0.0.1:3306/db01?serverTimezone=GMT%2B8&useSSL=FALSE
    username: root  #数据库用户名,root为管理员
    password: 123456 #该数据库用户的密码
    # 使用druid数据源
    type: com.alibaba.druid.pool.DruidDataSource
  cache:
    type: ehcache
    ehcache:
      config: classpath:/ehcache.xml
#mybatis配置
mybatis:
  mapper-locations: classpath:mapper/*.xml
  configuration:
    map-underscore-to-camel-case: true

指定了 EhCache 的配置文件位置

编写操作数据库和Ehcache缓存的业务代码

编写entity

@Data
@NoArgsConstructor
public class Dept implements Serializable {
    private static final long serialVersionUID = 1L;
    private Long deptNo;
    private String deptName;
    private String deptSource;
}

编写mapper

@Repository
@Mapper
public interface DeptMapper {
    List<Dept> selectAll();
    int insert(Dept record);
    List<Dept> selectDept(Long deptNo);
}

编写service

service接口

public interface DeptService {
    List<Dept> selectAll();
    int insert(Dept record);
    List<Dept> selectDept(Long deptNo);

}

service实现类

@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    DeptMapper deptMapper;

    @Override
    public List<Dept> selectAll() {
        return deptMapper.selectAll();
    }

    @Override
    public int insert(Dept dept) {
        return deptMapper.insert(dept);
    }

    @Override
    @Cacheable(value = "dept", key = "#deptNo")
    public List<Dept> selectDept(Long deptNo) {
        List<Dept> list=deptMapper.selectDept(deptNo);
        System.out.println("从数据库读取,而非读取缓存!");
        return list;
    }
}

看得很明白了,我们在 selectDept接口上添加了注解: @Cacheable。这是 Ehcache的使用注解之一,除此之外常用的还有 @CachePut@CacheEvit,分别简单介绍一下:

Ehcache缓存的注解

@CacheConfig

这个注解在上使用,用来描述该类中所有方法使用的缓存名称,当然也可以不使用该注解,直接在具体的缓存注解上配置名称,示例代码如下:

@Service
@CacheConfig(cacheNames = "user")
public class DeptServiceImpl implements DeptService {

}

@Cacheable

这个注解一般加在查询方法上,表示将一个方法的返回值缓存起来,默认情况下,缓存的 key 就是方法的参数,缓存的 value 就是方法的返回值。示例代码如下:

	@Override
    @Cacheable(value = "dept", key = "#deptNo")
    //配置在 selectDept方法上表示其返回值将被加入缓存。同时在查询时,会先从缓存中获取,若不存在才再发起对数据库的访问
    public List<Dept> selectDept(Long deptNo) {
        List<Dept> list=deptMapper.selectDept(deptNo);
        System.out.println("从数据库读取,而非读取缓存!");
        return list;
    }

如果在类上没有加入 @CacheConfig,我们则需要使用 value 来指定缓存名称
这里如果需要多个 key 时,需要使用 “:” 来连接,如:

@Cacheable(value = "user", key = "#name+':'+#phone")

@CachePut

这个注解一般加在更新方法上,当数据库中的数据更新后,缓存中的数据也要跟着更新,使用该注解,可以将方法的返回值自动更新到已经存在的 key 上,示例代码如下:

@Override
@CachePut(value = "user", key = "#id")
public User updateUserById(User user) {
    return userMapper.updateUserById(user);
}

配置于方法上时,能够根据参数定义条件来进行缓存,其与 @Cacheable不同的是使用 @CachePut标注的方法在执行前不会去检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中,所以主要用于数据新增和修改操作上

@CacheEvict

这个注解一般加在删除方法上,当数据库中的数据删除后,相关的缓存数据也要自动清除,该注解在使用的时候也可以配置按照某种条件删除( condition 属性)或者或者配置清除所有缓存( allEntries 属性),示例代码如下:

@Override
@CacheEvict(value = "user", key = "#id")
//配置于方法上时,表示从缓存中移除相应数据。
public void deleteUserById(Long id) {
    userMapper.deleteUserById(id);
}

@Cacheable/@CachePut/@CacheEvicat 主要的参数

在这里插入图片描述

编写controller

@RestController
@RequestMapping("/userInfo")
public class DeptInfoController {

    @Resource
    private DeptService deptService;



    /**
     * 查询全部信息
     * @return List<Dept> 部门实体集合
     */
    @RequestMapping("/getList")
    public List<Dept> getList(){
        return  deptService.selectAll();
    }


    /**
     * 新增用户信息
     */
    @RequestMapping("/saveInfo")
    public Object saveInfo(@RequestBody Dept dept ){
        return  deptService.insert(dept);
    }

    /**
     * 根据ID获取部门信息
     * @param dept
     * @return Dept 部门实体
     */

    @RequestMapping("/selectDept")
    public  List<Dept> selectDept(@RequestBody Dept dept){
        System.out.println("-------------------------------------------");
        System.out.println("call /selectDept");
        //System.out.println(cacheManager.toString());
        return  deptService.selectDept(dept.getDeptNo());
    }

}

编写DeptMapper.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="com.dhx.mapper.DeptMapper">
  <resultMap id="BaseResultMap" type="com.dhx.po.Dept">
    <id column="dept_no" jdbcType="BIGINT" property="deptNo" />
    <result column="dept_name" jdbcType="VARCHAR" property="deptName" />
    <result column="dept_source" jdbcType="VARCHAR" property="deptSource" />
  </resultMap>


  <select id="selectAll" resultMap="BaseResultMap">
    select dept_no, dept_name, dept_source
    from dept
  </select>


  <insert id="insert" parameterType="com.dhx.po.Dept">
    insert into dept (dept_no, dept_name, dept_source)
    values (#{deptNo,jdbcType=BIGINT}, #{deptName,jdbcType=VARCHAR}, #{deptSource,jdbcType=VARCHAR}
      )
  </insert>

  
  <select id="selectDept" parameterType="java.lang.Long" resultMap="BaseResultMap">
    select dept_no, dept_name, dept_source
    from dept
    where dept_no = #{deptNo,jdbcType=BIGINT}
  </select>

</mapper>

改造 SpringBoot应用主类

主要是在启动类上通过 @EnableCaching注解来显式地开启 Ehcache缓存

@SpringBootApplication
@MapperScan("com.dhx.mapper")
@EnableCaching
public class SpringbootEhcacheApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootEhcacheApplication.class, args);
    }

}

最终完工的整个工程的结构如下:
在这里插入图片描述

实际实验

通过多次向接口 http://localhost:10100/userInfo/selectDept POST数据来观察效果:
在这里插入图片描述
在这里插入图片描述

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值