SpringBoot整合EhCache

一、引入依赖

<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

二、开启缓存

//启动类添加该注解
@EnableCaching// 标注启动了缓存

三、配置文件: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">

    <!--
        磁盘存储:将缓存中暂时不使用的对象,转移到硬盘,类似于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="E:\ehcache" />

    <!--
        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="smsCode"
           maxElementsInMemory="10000"
           eternal="false"
           timeToIdleSeconds="120"
           timeToLiveSeconds="120"
           maxElementsOnDisk="10000000"
           overflowToDisk="true"
           memoryStoreEvictionPolicy="LRU" />

    <cache name="myCache"
           maxElementsInMemory="10000"
           eternal="false"
           timeToIdleSeconds="120"
           timeToLiveSeconds="120"
           maxElementsOnDisk="10000000"
           overflowToDisk="true"
           memoryStoreEvictionPolicy="LRU" />

</ehcache>

四、yml配置

spring:
  cache:
    type: ehcache
    ehcache:
      config: classpath:/ehcache.xml

五、开始使用

5.1 封装工具类

package com.zxh.projectzxh.utils.sms;

import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @description: 验证码工具类
 * @author: zxh
 * @create: 2022-11-11 15:54
 **/
@Repository
@CacheConfig
public class CodeUtils {
    private String [] patch = {"000000","00000","0000","000","00","0",""};

    public String generator(String tele){
        int hash = tele.hashCode();
        int encryption = 20206666;
        long result = hash ^ encryption;
        long nowTime = System.currentTimeMillis();
        result = result ^ nowTime;
        long code = result % 1000000;
        code = code < 0 ? -code : code;
        String codeStr = code + "";
        int len = codeStr.length();
        return patch[len] + codeStr;
    }

    /**
     * 获取缓存信息
     * @param tele
     * @return
     */
    @Cacheable(value = "smsCode", key = "#tele")
    public String getCode(String tele){
        return new String();
    }

    /**
     * 获取缓存信息
     * @param id
     * @return
     */
    @Cacheable(value = "myCache", key = "#id")
    public Map<String, Object> getCache(String id){
        return new HashMap<>();
    }

    /**
     * 添加修改缓存信息
     * @param id
     * @return
     */
    @CachePut(value = "myCache", key = "#id")
    public Map<String, Object> putCache(String id){
        Map<String, Object> map = new HashMap<>();
        String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        map.put("name", "李四");
        map.put("date", format);
        return map;
    }

    /**
     * 删除缓存信息
     * allEntries:非必需,默认为false。当为true时,会移除所有数据
     * @param id
     */
    @CacheEvict(value = "myCache", key = "#id")
    public void deleteCache(String id){
        return;
    }
}

5.2 测试

@RequestMapping("/get")
    public String get(String tele) {
        String code = codeUtils.getCode(tele);
        return code;
    }

    @RequestMapping("/putCache")
    public Map<String, Object> putCache(String id) {
        Map<String, Object> map = codeUtils.putCache(id);
        System.out.println("=====添加缓存====" + map);
        return map;

    }

    @RequestMapping("/getCode")
    public Map<String, Object> getCode(String id) {
        Map<String, Object> map1 = codeUtils.getCache(id);
        System.out.println("======获取缓存=====" + map1);
        return map1;
    }

    @RequestMapping("/deleteCache")
    public void deleteCache(@RequestParam String id) {
        codeUtils.deleteCache(id);
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值