EhCache 缓存

EhCache 缓存

参考: 【SpringBoot】27、SpringBoot中整合Ehcache_Asurplus的博客-CSDN博客_springboot ehcache

什么是EhCache?

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

特性:

  • 快速、简单
  • 多种缓存策略
  • 缓存数据有两级:内存和磁盘,因此无需担心容量问题
  • 缓存数据会在虚拟机重启的过程中写入磁盘
  • 可以通过RMI、可插入API等方式进行分布式缓存
  • 具有缓存和缓存管理器的侦听接口
  • 支持多缓存管理器实例,以及一个实例的多个缓存区域
  • 提供Hibernate的缓存实现
与 Redis 相比
  1. EhCache 直接在jvm虚拟机中缓存,速度快,效率高;但是缓存共享麻烦,集群分布式应用不方便。
  2. Redis 是通过 Socket 访问到缓存服务,效率比 EhCache 低,比数据库要快很多,处理集群和分布式缓存方便,有成熟的方案。如果是单个应用或者对缓存访问要求很高的应用,用 EhCache 。如果是大型系统,存在缓存共享、分布式部署、缓存内容很大的,建议用 Redis。
  3. EhCache 也有缓存共享方案,不过是通过 RMI 或者 Jgroup 多播方式进行广播缓存通知更新,缓存共享复杂,维护不方便;简单的共享可以,但是涉及到缓存恢复,大数据缓存,则不合适

SpringBoot 集成使用

引入依赖

<!-- ehcache依赖 -->
<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>2.10.6</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

配置文件 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="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"/>

    <!--
        name = myCacheName,可以配置多个来解决不同业务处所需要的缓存策略的
        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="myCacheName"
           maxElementsInMemory="10000"
           eternal="false"
           timeToIdleSeconds="120"
           timeToLiveSeconds="120"
           maxElementsOnDisk="10000000"
           overflowToDisk="true"
           memoryStoreEvictionPolicy="LRU"/>

</ehcache>

项目配置文件 application.yml

spring:
  cache:
    type: ehcache
    ehcache:
      #默认是ehcache.xml ,需要修改文件名就要在这里指定EhCache配置文件的位置
      config: classpath:/ehcache.xml
server:
  port: 8001

启动类开启缓存

package com.ung.myencache;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

/**
 * @author: wenyi
 * @create: 2022/10/18
 * @Description:
 */
@SpringBootApplication
@EnableCaching//开启缓存
public class MyehcacheApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyehcacheApplication.class, args);
    }
}

创建EhcacheUtils

package com.ung.myencache.utils;

import lombok.extern.slf4j.Slf4j;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheException;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

/**
 * @author: wenyi
 * @create: 2022/10/18
 * @Description: Ehcache 缓存的工具类
 */
@Slf4j
public class EhcacheUtils {
    static CacheManager manager = null;

    static {
        try {
            manager = CacheManager.create(EhcacheUtils.class.getClassLoader().getResourceAsStream("ehcache.xml"));
        } catch (CacheException e) {
            e.printStackTrace();
            log.error("获取ehcache.xml失败", e);
        }
    }

    public static void put(String cacheName, String key, Object value) {
        Cache cache = checkCache(cacheName);
        Element e = new Element(key, value);
        cache.put(e);
    }


    public static Object get(String cacheName, String key) {
        Cache cache = checkCache(cacheName);
        Element element = cache.get(key);
        return element == null ? null : element.getObjectValue();
    }


    public static void remove(String cacheName, String key) {
        Cache cache = checkCache(cacheName);
        cache.remove(key);
    }

    public static void removeAll(String cacheName) {
        Cache cache = checkCache(cacheName);
        cache.removeAll();
    }

    private static Cache checkCache(String cacheName) {
        Cache cache = manager.getCache(cacheName);
        if (null == cache) {
            throw new IllegalArgumentException("name=[" + cacheName + "],不存在对应的缓存组,请查看ehcache.xml");
        }
        return cache;
    }
}
重要注解
  1. @CacheConfig

    在类上使用,用来描述该类中所有方法使用的缓存名称,当然也可以不使用该注解,直接在具体的缓存注解上配置名称

  2. @Cacheable

    加在查询方法上,表示将一个方法的返回值缓存起来,默认情况下,缓存的 key 就是方法的参数,缓存的 value 就是方法的返回值。

    多个key使用:连接

    @Cacheable(value = "myCacheName", key = "#name+':'+#phone")
    
  3. @CachePut

    加在更新方法上,当数据库中的数据更新后,缓存中的数据也要跟着更新,使用该注解,可以将方法的返回值自动更新到已经存在的 key 上

  4. @CacheEvict

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

在service里使用

package com.ung.myencache.service.impl;

import com.ung.myencache.entity.User;
import com.ung.myencache.service.UserService;
import com.ung.myencache.utils.EhcacheUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @author: wenyi
 * @create: 2022/10/18
 * @Description:
 */
@Service
//类的所有方法都是要这个缓存名称
//@CacheConfig(cacheNames = "myCacheName")
public class UserServiceImpl implements UserService {

    public static Map<Integer, User> map = new ConcurrentHashMap<>();

    static {
        map.put(1, new User(1, "name1"));
        map.put(2, new User(2, "name2"));
        map.put(3, new User(3, "name3"));
        map.put(4, new User(4, "name4"));
        map.put(5, new User(5, "name5"));
    }

    /**
     * @Cacheable 注解使用在查询方法上,将方法返回值缓存
     * <p> value = "myCacheName" 指定 cacheNames
     * 缓存默认key是方法入参,value是返回值
     */
    @Cacheable(value = "myCacheName", key = "#id")
    @Override
    public User getById(Integer id) {
        System.out.println("getById 执行了!!!");
        return map.get(id);
    }

    @Cacheable(value = "myCacheName")
    public List<User> list(String name) {
        System.out.println("list 执行了!!!");
        List<User> collect = map.values().stream().collect(Collectors.toList());
        return collect;
    }

    @Override
    public List<User> myList() {
        //手动缓存,不使用注解
        List<User> collect = (List<User>) EhcacheUtils.get("myCacheName", "list");
        if (collect == null) {
            collect = map.values().stream().collect(Collectors.toList());
            EhcacheUtils.put("myCacheName", "list", collect);
        }
        return collect;
    }

    @Override
    public List<User> updateMyList(User user) {
        map.put(user.getId(), user);
        List<User> collect = map.values().stream().collect(Collectors.toList());
        EhcacheUtils.put("myCacheName", "list", collect);
        return collect;
    }

    /**
     * @CacheEvict 删除方法 相关的缓存数据也要自动清除
     */
    @CacheEvict(value = "myCacheName", key = "#id")
    @Override
    public boolean deleteUser(Integer id) {
        System.out.println("deleteUser 执行了!!!");
        map.remove(id);
        return true;
    }

    @CachePut(value = "myCacheName", key = "#user.id")
    @Override
    public User addUser(User user) {
        System.out.println("addUser 执行了!!!");
        map.put(user.getId(), user);
        return user;
    }

    @CachePut(value = "myCacheName", key = "#user.id")
    @Override
    public User updateUser(User user) {
        System.out.println("updateUser 执行了!!!");
        map.put(user.getId(), user);
        return user;
    }
}

SpringBoot 中使用 Ehcache 比较简单,只需要简单配置,说白了还是 Spring Cache 的用法,合理使用缓存机制,可以很好地提高项目的响应速度。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值