springboot配置可持久化本地缓存ehcache

1、添加maven依赖

<dependency>

<groupId>org.ehcache</groupId>

<artifactId>ehcache</artifactId>

<version>3.10.8</version>

</dependency>

2、编写配置类

java 复制代码
  package com.figo.test.utils;

import org.ehcache.config.CacheConfiguration;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.config.builders.ExpiryPolicyBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.config.units.MemoryUnit;
import org.ehcache.core.EhcacheManager;
import org.ehcache.impl.config.persistence.CacheManagerPersistenceConfiguration;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.File;
import java.io.Serializable;
import java.time.Duration;

@Configuration
@EnableCaching
public class EhcacheConfig {

    public static final String USER_CACHE = "userCache";

    @Bean
    public EhcacheManager ehcacheManager() {
        // 持久化目录
        File persistenceDir = new File("D:\\test\\cache\\ehcache-invoice");

        // 先删除损坏的缓存文件(第一次必须加,防止旧文件冲突)
        deleteCorruptCacheFiles(persistenceDir);

        return (EhcacheManager) CacheManagerBuilder.newCacheManagerBuilder()
                .with(new CacheManagerPersistenceConfiguration(persistenceDir))
                .withCache(USER_CACHE, userCacheConfig())
                .build(true);
    }

    // 【关键】使用 Serializable 而不是 Object!!!
    private CacheConfiguration<String, Serializable> userCacheConfig() {
        return CacheConfigurationBuilder.newCacheConfigurationBuilder(
                        String.class,            // Key
                        Serializable.class,    // Value 必须可序列化
                        ResourcePoolsBuilder
                                .heap(100)
                                .disk(10, MemoryUnit.MB, true)
                )
                .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofHours(24)))
                .build();
    }

    // 清理缓存目录(防止旧缓存报错)
    private void deleteCorruptCacheFiles(File dir) {
        try {
            if (dir.exists()) {
                for (File file : dir.listFiles()) {
                    file.delete();
                }
            }
        } catch (Exception e) {}
    }
}

3、编写工具类

java 复制代码
package com.figo.test.utils;

import org.ehcache.Cache;
import org.ehcache.core.EhcacheManager;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.Serializable;

@Component
public class EhCacheUtils {

    @Resource
    private EhcacheManager ehcacheManager;

    private Cache<String, Serializable> cache;

    @PostConstruct
    public void init() {
        cache = ehcacheManager.getCache(EhcacheConfig.USER_CACHE, String.class, Serializable.class);
    }

    // 存入缓存(必须传 可序列化对象)
    public void put(String key, Serializable value) {
        cache.put(key, value);
    }

    public Serializable get(String key) {
        return cache.get(key);
    }

    public void remove(String key) {
        cache.remove(key);
    }

    public void clear() {
        cache.clear();
    }
}

4、单元测试

java 复制代码
package com.chinapay.invoice.utils;

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.cache.support.SimpleValueWrapper;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class EhCacheUtilsTest {
    @Autowired
    EhCacheUtils ehCacheUtils;
    @Test
    public void testCache() {
//        ehCacheUtils.put("key1","hello,world,hello,china!"); 经测试确实持久化了,注释后,重新运行都能拿到数据
        String value=(String)ehCacheUtils.get("key1");
        System.out.println(value);
    }
}
相关推荐
mldong4 小时前
一个 App,十三套后端:手机审批端 uni-jeeflow-app 开源了
java·架构
tqs_123455 小时前
MySQL RR隔离级别死锁|Gap间隙锁、临键锁,订单并发范围查询死锁根因方案
java
逆境不可逃5 小时前
Pi Agent 学习笔记:多个工具怎样并行执行
java
weixin_BYSJ19876 小时前
【计算机毕设】基于SpringBoot与Vue的文物保护档案管理系统08621
vue.js·spring boot·spring cloud·微服务·架构·django·课程设计
Flynt6 小时前
Java 27 升级实测:默认值动得比新特性多,有个老参数会让 JVM 直接起不来
java·jvm·后端
Bs_MoneyMagnet6 小时前
基于springboot+vue的个人健康管理系统的设计与实现 源码+文档
java·vue.js·spring boot·后端·vue3·springboot3·计算机毕业设计
星云API技术支持6 小时前
企业微信二次开发:群权限设置、成员管理与群资料维护的接口组合实践
java·前端·企业微信
wdfk_prog7 小时前
ROS教程:01 搭建 ROS1 Noetic Docker 开发环境
运维·缓存·docker·容器·ros
niucloud-admin7 小时前
JAVA V6 多商户商城 开发文档——job 计划任务开发
java·python·github
wdfk_prog8 小时前
ros教程02:创建 catkin Workspace、Package 与第一个 ROS1 C++ Node
运维·缓存·docker·容器·ros