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);
    }
}
相关推荐
好家伙VCC6 分钟前
区块链双向支付通道实战:从签名到结算
java·后端·区块链·asp.net
ss27315 分钟前
【入门OJ题解】分苹果问题(Python/Java/C 实现)
java·c语言·python
weikecms27 分钟前
美团霸王餐报名API接口
java·开发语言
真实的菜31 分钟前
【无标题】Redis 从入门到精通(七):缓存设计与最佳实践 —— 穿透、击穿、雪崩与一致性终极指南
数据库·redis·缓存
李白的天不白32 分钟前
配置mysql密码
java
念何架构之路32 分钟前
存储技术Redis
数据库·redis·缓存
何中应33 分钟前
Nexus如何上传JAR包
java·maven·jar
我登哥MVP40 分钟前
Spring Boot 从“会用”到“精通”:参数解析原理
java·spring boot·后端·spring·servlet·maven·intellij-idea
Wenzar_43 分钟前
VITS+Whisper微调:低延迟TTS实战
java·人工智能·whisper
创可贴治愈心灵1 小时前
AI浪潮下C#就业前景剖析:深耕C#为主,按需选修Java与Python
java·人工智能·c#