Spring Boot整合EhCache

本文讲解Spring Boot与EhCache的整合。

1 EhCache简介

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

2 Spring Boot整合EhCache步骤

2.1 创建项目,导入依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.yiidian</groupId>
    <artifactId>ch03_10_springboot_ehcache</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!-- 导入springboot父工程. 注意:任何的SpringBoot工程都必须有的!!! -->
    <!-- 父工程的作用:锁定起步的依赖的版本号,并没有真正到依赖 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.11.RELEASE</version>
    </parent>

    <dependencies>
        <!--web起步依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--springboot 集成 junit 起步依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>2.1.6.RELEASE</version>
            <scope>test</scope>
        </dependency>

        <!-- 缓存坐标 -->
        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-cache -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
            <version>2.1.11.RELEASE</version>
        </dependency>
        <!-- Ehcache支持 -->
        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache</artifactId>
            <version>2.10.6</version>
        </dependency>

    </dependencies>

</project>

2.2 配置ehcache.xml

在resources目录下建立ehcache.xml,内容如下:

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">

    <diskStore path="java.io.tmpdir"/>

    <!-- defaultCache: 默认配置 -->
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            maxElementsOnDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </defaultCache>

    <!-- 缓存名称为customer的配置 -->
    <cache name="customer"
           maxElementsInMemory="10000"
           eternal="false"
           timeToIdleSeconds="120"
           timeToLiveSeconds="120"
           maxElementsOnDisk="10000000"
           diskExpiryThreadIntervalSeconds="120"
           memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </cache>

</ehcache>

参数说明:

  • name 缓存名称
  • maxElementsInMemory 缓存最大个数
  • eternal 对象是否永久有效,一但设置了,timeout将不起作用
  • timeToIdleSeconds 设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大
  • timeToLiveSeconds 设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大
  • overflowToDisk 当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中
  • diskSpoolBufferSizeMB 这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区
  • maxElementsOnDisk 硬盘最大缓存个数
  • diskPersistent 是否缓存虚拟机重启期数据
  • diskExpiryThreadIntervalSeconds 磁盘失效线程运行时间间隔,默认是120秒。
  • memoryStoreEvictionPolicy 当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)
  • clearOnFlush 内存数量最大时是否清除

2.3 编写application.yml

#配置EhCache的配置
spring:
  cache:
    ehcache:
      config: ehcache.xml # 读取ehcache.xml配置

2.4 编写引导类

package com.yiidian;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;

/**
 * Spring Boot引导类
 * 一点教程网 - www.yiidian.com
 */
@SpringBootApplication
@EnableCaching // 开启缓存
public class MyBootApplication {

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

}

引导类中需要添加@EnableCaching注解,开启缓存功能

2.5 编写Service类

package com.yiidian.service;

import com.yiidian.domain.Customer;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * 业务层
 *一点教程网 - www.yiidian.com
 */
@Service
public class CustomerService {

    @Cacheable(value = "customer",key = "#id")
    public Customer findById(Integer id){
        System.out.println("执行了UserService获取User");
        Customer customer = new Customer();
        customer.setId(1);
        customer.setName("小明");
        customer.setGender("男");
        customer.setTelephone("13244445555");
        return customer;
    }

}

@Cacheable的属性:

  • value:对应ehcache.xml的缓存配置名称(name属性值)
  • key:给缓存值起个key,便于Spring内部检索不同的缓存数据。#id这个语法代表把方法形参作为key。

2.6 编写测试类

package com.yiidian.test;

import com.yiidian.MyBootApplication;
import com.yiidian.service.CustomerService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 *  SpringBoot整合EhCache
 * 一点教程网 - www.yiidian.com
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = MyBootApplication.class)
public class EhCacheDemo {
    @Autowired
    private CustomerService customerService;

    @Test
    public void test1(){
        //查询第一次
        System.out.println(customerService.findById(1));
        //查询第二次
        System.out.println(customerService.findById(1));
    }
}

2.7 运行测试

从结果可以看出,第一次调用Service的时候,到Service内部获取数据。但是第二次调用Service时已经不需要从Service获取数据,证明第一次查询的时候已经把Customer对象缓存到EhCache中。

3 EhCache常用注解

  • @Cacheable: 主要针对方法配置,能够根据方法的请求参数对其进行缓存
  • @CacheConfig: 统一配置本类的缓存注解的属性
  • @CachePut:保证方法被调用,又希望结果被缓存。与@Cacheable区别在于是否每次都调用方法,常用于更新
  • @CacheEvict :清空缓存

@Cacheable/@CachePut/@CacheEvict 主要的参数:

  • value:缓存的名称,在 spring 配置文件中定义,必须指定至少一个
    例如:
    @Cacheable(value=”mycache”) 或者
    @Cacheable(value={”cache1”,”cache2”}
  • key:缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写,
    如果不指定,则缺省按照方法的所有参数进行组合
    例如:
    @Cacheable(value=”testcache”,key=”#id”)
  • condition:缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false,
    只有为 true 才进行缓存/清除缓存
    例如:@Cacheable(value=”testcache”,condition=”#userName.length()>2”)
  • unless 否定缓存。当条件结果为TRUE时,就不会缓存。
    @Cacheable(value=”testcache”,unless=”#userName.length()>2”)
  • allEntries
    (@CacheEvict ): 是否清空所有缓存内容,缺省为 false,如果指定为 true,
    则方法调用后将立即清空所有缓存
    例如:
    @CachEvict(value=”testcache”,allEntries=true)
  • beforeInvocation
    (@CacheEvict): 是否在方法执行前就清空,缺省为 false,如果指定为 true,
    则在方法还没有执行的时候就清空缓存,缺省情况下,如果方法
    执行抛出异常,则不会清空缓存
    例如:
    @CachEvict(value=”testcache”,beforeInvocation=true)

3.1 @Cacheable

@Cacheable注解会先查询是否已经有缓存,有会使用缓存,没有则会执行方法并缓存。

@Cacheable(value = "customer" ,key = "targetClass + methodName +#p0")
public List<Customer> queryAll(Customer cust) {
   return customerDao.findAllByUid(cust);
}

3.2 @CacheConfig

当我们需要缓存的地方越来越多,你可以使用@CacheConfig(cacheNames = {"myCache"})注解来统一指定value的值,这时可省略value,如果你在你的方法依旧写上了value,那么依然以方法的value值为准。

使用方法如下:

@CacheConfig(cacheNames = {"myCache"})
public class UserServiceImpl implements UserService {
    @Override
    @Cacheable(key = "targetClass + methodName +#p0")//此处没写value
    public List<BotRelation> findUsers(int num) {
        return userDao.findUsers(num);
    }
    .....
}

3.3 @CachePut

@CachePut注解的作用 主要针对方法配置,能够根据方法的请求参数对其结果进行缓存,和 @Cacheable 不同的是,它每次都会触发真实方法的调用 。简单来说就是用户更新缓存数据。但需要注意的是该注解的value 和 key 必须与要更新的缓存相同,也就是与@Cacheable 相同。示例:

@CachePut(value = "customer", key = "targetClass + #p0")
public Customer updata(Customer cust) {
    Customer customer = customerDao.findAllById(cust.getId());
    customer.updata(cust);
    return customer ;
}

@Cacheable(value = "customer", key = "targetClass +#p0")//清空缓存
public Customer save(Customer cust) {
    customerDao.save(cust);
    return cust;
}

3.4 @CacheEvict

@CachEvict 的作用 主要针对方法配置,能够根据一定的条件对缓存进行清空 。

@Cacheable(value = "customer",key = "#p0.id")
public Customer save(Customer cust) {
    customerDao.save(cust);
    return job;
}

//清除一条缓存,key为要清空的数据
@CacheEvict(value="customer",key="#id")
public void delect(int id) {
    customerDao.deleteAllById(id);
}

//方法调用后清空所有缓存
@CacheEvict(value="customerCache",allEntries=true)
public void delectAll() {
    customerDao.deleteAll();
}

//方法调用前清空所有缓存
@CacheEvict(value="customerCache",beforeInvocation=true)
public void delectAll() {
    customerDao.deleteAll();
}

欢迎关注我的公众号::一点教程。获得独家整理的学习资源和日常干货推送。
如果您对我的系列教程感兴趣,也可以关注我的网站:yiidian.com

原文地址:https://www.cnblogs.com/yiidian/p/12297759.html

时间: 2024-08-13 15:31:17

Spring Boot整合EhCache的相关文章

spring boot 整合 quartz 集群环境 实现 动态定时任务配置【原】

最近做了一个spring boot 整合 quartz  实现 动态定时任务配置,在集群环境下运行的 任务.能够对定时任务,动态的进行增删改查,界面效果图如下: 1. 在项目中引入jar 2. 将需要的表导入数据库 官网上有不同数据库的脚本,找到对应的,导入即可 3. java 代码 将quartz 的相关配置文件,配置为暴露bean,方便后期引用. 有一处关键的地方,就是注入spring 上下文,也可以算是一个坑.如果,不注入spring 上下文,那么新添加的定时任务job,是新new 的一个

spring boot 整合spring Data JPA+Spring Security+Thymeleaf框架(上)

最近上班太忙所以耽搁了给大家分享实战springboot 框架的使用. 下面是spring boot 整合多个框架的使用. 首先是准备工作要做好. 第一  导入框架所需的包,我们用的事maven 进行对包的管理. 以上的举例是本人的H5DS的真实的后台管理项目,这个项目正在盛情融资中,各位多多捧点人场.关注一下软件发展的动态,说不定以后就是您的生活不可或缺的软件哟. 点击打开链接.闲话少说.现在切入正题. 第二,写点配置文件 第三,spring data -设计一个简单的po关系,这里需要下载一

spring boot整合jsp的那些坑(spring boot 学习笔记之三)

Spring Boot 整合 Jsp 步骤: 1.新建一个spring boot项目 2.修改pom文件 <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-web</artifactId>        </dependency>        <depend

Spring boot整合jsp

这几天在集中学习Spring boot+Shiro框架,因为之前view层用jsp比较多,所以想在spring boot中配置jsp,但是spring boot官方不推荐使用jsp,因为jsp相对于一些模板引擎,性能都比较低,官方推荐使用thymeleaf,但是Spring boot整合jsp的过程已经完成,在这里记录一下. 这篇博文是在LZ上篇文章spring boot+mybatis整合基础上写的,开发工具仍然是Intellij idea.这篇文章的重点是Intellij idea的设置,否

企业分布式微服务云SpringCloud SpringBoot mybatis (十三)Spring Boot整合MyBatis

Spring中整合MyBatis就不多说了,最近大量使用Spring Boot,因此整理一下Spring Boot中整合MyBatis的步骤.搜了一下Spring Boot整合MyBatis的文章,方法都比较老,比较繁琐.查了一下文档,实际已经支持较为简单的整合与使用.下面就来详细介绍如何在Spring Boot中整合MyBatis,并通过注解方式实现映射. 整合MyBatis 新建Spring Boot项目,或以Chapter1为基础来操作 pom.xml中引入依赖 这里用到spring-bo

Spring Kafka和Spring Boot整合实现消息发送与消费简单案例

本文主要分享下Spring Boot和Spring Kafka如何配置整合,实现发送和接收来自Spring Kafka的消息. 先前我已经分享了Kafka的基本介绍与集群环境搭建方法.关于Kafka的介绍请阅读Apache Kafka简介与安装(一),关于Kafka安装请阅读Apache Kafka安装,关于Kafka集群环境搭建请阅读Apache Kafka集群环境搭建 .这里关于服务器环境搭建不在赘述. Spring Kafka整合Spring Boot创建生产者客户端案例 创建一个kafk

spring boot 整合kafka 报错 Exception thrown when sending a message with key=&#39;null&#39; and payload=JSON to topic proccess_trading_end: TimeoutException: Failed to update metadata after 60000 ms.

org.springframework.kafka.support.LoggingProducerListener- Exception thrown when sending a message with key='null' and payload='{"dataDts":["20180329","20180328","20180327","20180326","20180323"]

activeMQ入门+spring boot整合activeMQ

最近想要学习MOM(消息中间件:Message Oriented Middleware),就从比较基础的activeMQ学起,rabbitMQ.zeroMQ.rocketMQ.Kafka等后续再去学习. 上面说activeMQ是一种消息中间件,可是为什么要使用activeMQ? 在没有使用JMS的时候,很多应用会出现同步通信(客户端发起请求后需要等待服务端返回结果才能继续执行).客户端服务端耦合.单一点对点(P2P)通信的问题,JMS可以通过面向消息中间件的方式很好的解决了上面的问题. JMS规

Spring Boot 整合JDBC 实现后端项目开发

一.前言 前后端分离开发是将项目开发工作前后端交互工作拆分,使前端开发人员能够专注于页面开发或APP 开发,后端开发人员专注与接口开发.业务逻辑开发. 此处开发后端项目,给前端或者APP 端提供接口.不涉及复杂的业务逻辑,通过简单的增删改查来演示后端开发项目. 环境介绍: 开发工具:IDEA JDK: 1.7 及以上 Spring Boot: 2.0 及以上 Maven: 3.0 及以上 二.新建Spring Boot 项目 通过功能菜单File - New - Project 新建Spring