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);
    }
}
相关推荐
Seven9710 小时前
一致性Hash算法:如何实现分布式系统中的高效数据分片?
java
摇滚侠10 小时前
IDEA 生成 try catch 快捷键
java·ide·intellij-idea
阿旭超级学得完11 小时前
C++11包装器(function和bind)
java·开发语言·c++·算法·哈希算法·散列表
掉鱼的猫12 小时前
Spring AI 2.0 GA 倒计时:先别急,来看看 Java AI 框架的另一条路
java·openai·agent
Refrain_zc12 小时前
Android 应用内 APK 安装全方案:从静默安装到普通安装的详解
java
正儿八经的少年12 小时前
Spring Boot 两种激活配置方式的作用与区别
java·spring boot·后端
云烟成雨TD12 小时前
Spring AI Alibaba 1.x 系列【52】Interrupts 中断机制:节点执行前后静态中断
java·人工智能·spring
疯狂成瘾者13 小时前
Spring Boot 项目中的 SMTP 邮件验证码服务技术解析
java·spring boot·后端
y = xⁿ13 小时前
Java并发八股学习日记
java·开发语言·学习