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);
    }
}
相关推荐
果果软件32 分钟前
2026 后台管理系统选型:若依、JeecgBoot、芋道、NocoBase 和 GewuMind Boot 怎么选?
java·人工智能·后端·ai·开源
码云社区4 小时前
Java家政服务系统源码:人员技能、服务范围与多商家业务落地
java·开发语言·家政服务·家政小程序·家政系统
摇滚侠5 小时前
《On Java 中文版 基础卷》阅读笔记 接口 18
java·笔记·python
CoderYanger5 小时前
Java EE 进阶:9.MyBatis 操作数据库(进阶)(第八弹):MyBatis Generator
java·数据库·spring boot·spring·java-ee·tomcat·mybatis
jaysee-sjc8 小时前
【黑马点评】Day02:优惠券秒杀与分布式锁
java·分布式·nginx·spring·node.js·tomcat·maven
五彩小白8 小时前
Redis的过期删除和内存淘汰机制
数据库·redis·缓存
学长毕设9 小时前
基于SpringBoot 博物馆文物租赁及修复管理系统-附源码
大数据·数据库·spring boot
秋天的怀念_David9 小时前
算法一千零一夜 · 第三十五夜 · 恢复风暴
java·程序人生·算法
考虑考虑9 小时前
JDK27中的加密对象的 PEM 编码
java·后端·java ee
行者-全栈开发9 小时前
SpringBoot + GraalVM 原生编译实战:启动时间从8秒到0.5秒的极致优化
java·spring boot·后端