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);
    }
}
相关推荐
itzixiao2 小时前
L1-051 打折(5分)[java][python]
java·python·算法
それども2 小时前
Spring Bean 注入的优先级顺序
java·数据库·sql·spring
ID_180079054732 小时前
Python 实现京东商品详情 API 数据准确性校验(极简可直接用)
java·前端·python
贾斯汀玛尔斯2 小时前
每天学一个算法--Aho–Corasick 自动机
java·linux·算法
LF男男2 小时前
Action- C# 内置的委托类型
java·开发语言·c#
weixin_704266052 小时前
Spring Cloud Gateway
spring boot
练习时长一年2 小时前
@NotEmpty注解引发的报错
java·服务器·前端
西海天际蔚蓝2 小时前
用AI写的一个包含web和小程序的个人简历
java
郝学胜-神的一滴2 小时前
[力扣 227] 双栈妙解表达式计算:从思维逻辑到C++实战,吃透反向波兰式底层原理
java·前端·数据结构·c++·算法