SpringBoot整合Ehcache

SpringBoot整合Ehcache

【一】简介

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

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

【二】添加maven依赖

  • 项目在github的地址:
https://github.com/fengsri/springboot-ehcache.git
  • 创建springboot的项目
  • 基本依赖
		<!--web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--lombok简化操作-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!--测试-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        
		<!--连接mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
            <version>8.0.15</version>
        </dependency>

        <!--mybatis框架-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>
  • Ehcache依赖
		<!-- 缓存支持,超级重要 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.ehcache/ehcache -->
        <dependency>
            <groupId>org.ehcache</groupId>
            <artifactId>ehcache</artifactId>
            <version>3.8.1</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/javax.cache/cache-api -->
        <dependency>
            <groupId>javax.cache</groupId>
            <artifactId>cache-api</artifactId>
            <version>1.1.1</version>
        </dependency>

【三】基本架构

在这里插入图片描述

  • yml配置
#数据库配置
spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/db3?autoReconnect=true&characterEncoding=utf8&useUnicode=true&serverTimezone=UTC&zeroDateTimeBehavior=CONVERT_TO_NULL&useSSL=false
    password: 123456
    username: root
    driver-class-name: com.mysql.cj.jdbc.Driver

#mybatis配置
mybatis:
  type-aliases-package: com.feng.ehcache.model
  #mapper-locations: classpath:mapper/*.xml;
  • User

@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class User implements Serializable {

    private static final long serialVersionUID = -5371156879549631125L;
    /**
     * 用户id
     */
    private Integer id;

    /**
     * 用户名称
     */
    private String username;

    /**
     * 用户密码
     */
    private String password;

    /**
     * 用户性别
     */
    private Integer gander;

    /**
     * 用户年龄
     */
    private Integer age;

}

  • UserDao

@Mapper
public interface UserDao {

    @Select("select * from user where id=#{id}")
    User getById(@Param("id") Integer id);

}

  • UserService
@Service
@Slf4j
public class UserService {

    @Autowired
    private UserDao userDao;


    /**
     * 通过id查询用户,进行缓存
     * @param id
     * @return
     */
    
    public User getById(Integer id){
        User user = userDao.getById(id);
        return user;
    }

}
  • UserController
@RestController
@Slf4j
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("{id}")
    public User getById(@PathVariable("id")Integer id){
        System.out.println(System.currentTimeMillis());
        User user = userService.getById(id);
        System.out.println(System.currentTimeMillis());
        return user;
    }

}

【四】进行本地缓存配置

  • 添加启动支持
    在启动类上添加 @EnableCaching 进行支持缓存
@SpringBootApplication
@MapperScan("com.feng.ehcache.dao")
@EnableCaching
public class EhcacheApplication {

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

}

  • 添加ehcache.xml文件
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://www.ehcache.org/v3"
        xmlns:jsr107="http://www.ehcache.org/v3/jsr107"
        xsi:schemaLocation="
            http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.0.xsd
            http://www.ehcache.org/v3/jsr107 http://www.ehcache.org/schema/ehcache-107-ext-3.0.xsd">
    <service>
        <jsr107:defaults enable-statistics="true"/>
    </service>

    <!-- user 为该缓存名称 对应@Cacheable的属性cacheNames-->
    <cache alias="user">
        <!-- 指定缓存 key 类型,对应@Cacheable的属性key -->
        <key-type>java.lang.Integer</key-type>
        <!-- 配置value类型 -->
        <value-type>com.feng.ehcache.model.User</value-type>
        <expiry>
            <!-- 缓存 ttl -->
            <ttl unit="minutes">1</ttl>
        </expiry>
        <listeners>
            <listener>
                <!-- 配置Listener -->
                <class>com.feng.ehcache.listener.CacheEventLogger</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>
</config>

  • 添加yml配置
spring:
  cache:
    jcache:
      config: classpath:ehcache.xml
  • 添加缓存注解
    在userService中添加缓存注解
	@Cacheable(cacheNames = "user", key = "#id")
    public User getById(Integer id){
        User user = userDao.getById(id);
        return user;
    }

  • 访问效果
    第一次访问:
    在这里插入图片描述
    第二次访问:
    在这里插入图片描述
    这个地方还是使用的本地进行测试,如果使用的远程访问数据就可以减少查询数据库,并且不用进行远程的网络数据传输,速度是会提高很多

【五】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,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。

【六】链接

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值