springboot 整合 ehcache

Spring Boot中整合Ehcache

添加Ehcache依赖:

<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId> --根据需要选择版本。
    <version>2.10.6</version>
</dependency>

配置Ehcache
Spring Boot项目的application.properties文件中添加以下配置:

# Ehcache配置
ehcache.diskStorePath=target/ehcache
ehcache.maxBytesLocalHeap=100M
ehcache.maxBytesLocalDisk=500M
ehcache.eternal=false
ehcache.timeToIdleSeconds=120
ehcache.timeToLiveSeconds=120
ehcache.overflowToDisk=true

创建EhcacheManagerBean
Spring Boot项目中创建一个名为EhcacheManagerBean的类,并实现以下内容:

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.config.CacheConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;

@Configuration
public class EhcacheConfiguration {

    @Bean
    @Lazy(false)
    public CacheManager cacheManager() {
        CacheManager cacheManager = new CacheManager();
        Cache configurationCache = new Cache(new CacheConfiguration("configurationCache", 10000));
        configurationCache.setDiskStorePath("target/ehcache");
        cacheManager.addCache(configurationCache);
        return cacheManager;
    }
}

创建“configurationCache”的Ehcache缓存,并设置缓存配置。

使用Ehcache缓存注解
要在Spring Boot中使用Ehcache缓存注解,添加@EnableCaching注解,并在需要缓存的方法上添加@Cacheable、@CachePut或@CacheEvict注解。例如:

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
@EnableCaching
public class MyService {
    @Cacheable(value = "configurationCache")
    public String getConfigurationValue(String key) {
        // 从数据库或其他源获取配置值并返回缓存中相应的值。
    }
}
posted @   Ai喝咖啡Demo  阅读(215)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· 字符编码:从基础到乱码解决
· Open-Sora 2.0 重磅开源!
点击右上角即可分享
微信分享提示