SpringBoot+Ehcache使用示例

摘要

本文介绍了SpringBoot中配置Ehcache、自定义get/set方式,并实际使用缓存的过程。

概念

Ehcache是一种Java缓存框架,支持多种缓存策略,如:

  • 最近最少使用LRU:当缓存达到最大容量时,会将最近最少使用的元素淘汰。
  • 最少最近使用LFU:根据元素被访问的频率来淘汰元素,最少被访问的元素会被优先淘汰。
  • 先进先出FIFO:按元素进入缓存的时间顺序淘汰元素,先进入的元素会被优先淘汰。

内存与磁盘持久化存储:

Ehcache支持将数据存储在内存中,以实现快速访问。当内存不足时,Ehcache可以将数据交换到磁盘,确保缓存数据不会因为内存限制而丢失。磁盘存储路径可以通过配置灵活指定,即使在系统重启后也能恢复缓存数据。提供多种持久化策略,包括本地临时交换localTempSwap和自定义持久化实现。

配置灵活性:

可通过配置ehcache.xml文件,放在启动类资源目录里,可自定义缓存策略,LRU,diskExpiryThreadIntervalSeconds。

编码示例

引入依赖:

pom.xml指定ehcache坐标并排除slf4j

xml 复制代码
<!-- Ehcache 坐标 -->
<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>2.10.9.2</version>
    <scope>compile</scope>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

配置ehcache.xml文件:

xml 复制代码
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
    <diskStore path="java.io.tmpdir/ehcache"/> <!-- 定义磁盘存储路径,将缓存数据存储在临时目录下 -->
    <!-- 
        参数说明:
        maxElementsInMemory 内存中最多存储的元素数量 
        eternal             是否为永生缓存,false表示元素有生存和闲置时间 
        timeToIdleSeconds   元素闲置 120 秒后失效 
        timeToLiveSeconds   元素存活 120 秒后失效 
        maxElementsOnDisk   磁盘上最多存储的元素数量 
        diskExpiryThreadIntervalSeconds 磁盘清理线程运行间隔 
        memoryStoreEvictionPolic 内存存储的淘汰策略,采用 LRU(最近最少使用) 
    -->
    <!-- defaultCache:echcache 的默认缓存策略-->
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            maxElementsOnDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </defaultCache>
    <!-- 自定义缓存策略 这里的name是用于缓存名指定时  需要对应缓存名添加-->
    <cache name="cacheName"
           maxElementsInMemory="10000"
           eternal="false"
           timeToIdleSeconds="0"
           timeToLiveSeconds="0"
           maxElementsOnDisk="10000000"
           diskExpiryThreadIntervalSeconds="120"
           memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </cache>
</ehcache>

配置文件:

application.yml指定spring的缓存文件路径

yaml 复制代码
spring:
  cache:
    type: ehcache
    ehcache:
      config: classpath:ehcache.xml

自定义缓存get/set方式:

利用CacheManager处理缓存:

typescript 复制代码
package org.coffeebeans.ehcache;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <li>ClassName: EhCacheService </li>
 * <li>Author: OakWang </li>
 */
@Service
public class EhCacheService {

    @Autowired
    private CacheManager cacheManager;

    /**
     * 根据名称获取缓存数据
     * @param cacheName cache名称
     * @param keyName cache中对应key名称
     * @return cache数据
     */
    public List<?> getCacheData(String cacheName, String keyName){
       Cache cache = cacheManager.getCache(cacheName);
       if (!Objects.isNull(cache)) {
          Element element = cache.get(keyName);
          if (!Objects.isNull(element)) {
             return (List<?>) element.getObjectValue();
          }
       }
       return new ArrayList<>();
    }

    /**
     * 往缓存中存放数据 名字区分
     * @param cacheName     cache名称
     * @param keyName       cache中对应key名称
     * @param dataList      存放数据
     */
    public void putCacheData(String cacheName, String keyName, List<?> dataList){
       Cache cache = cacheManager.getCache(cacheName);
       if (Objects.isNull(cache)){
          cache = new Cache(cacheName,1000,true,false,0,0);
       }
       Element newElement = new Element(keyName, dataList);
       cache.put(newElement);
    }

}

启动类加注解:

@EnableCaching开启程序缓存

java 复制代码
package org.coffeebeans;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

/**
 * <li>ClassName: EhCacheApplication </li>
 * <li>Author: OakWang </li>
 */
@Slf4j
@SpringBootApplication
@EnableCaching//开启程序缓存
public class EhCacheApplication {

    public static void main(String[] args) {
       SpringApplication springApplication = new SpringApplication(EhCacheApplication.class);
       springApplication.run(args);
       log.info("EhCacheApplication start success!");
    }

}

编辑测试类:

kotlin 复制代码
package org.coffeebeans.ehcache;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Collections;
import java.util.List;

/**
 * <li>ClassName: TestEhCache </li>
 * <li>Author: OakWang </li>
 */
@Service
public class TestEhCache {

    @Autowired
    private EhCacheService ehCacheService;

    public void testEhCache() {
       ehCacheService.putCacheData("cacheName", "keyName", Collections.singletonList("value"));
       List<?> cacheData = ehCacheService.getCacheData("cacheName", "keyName");
       System.out.println("获取缓存数据:" + cacheData.toString());
    }

}

测试结果:

总结

以上我们了解了SpringBoot中配置Ehcache、自定义get/set方式,并实际使用缓存的过程。

关注公众号:咖啡Beans

在这里,我们专注于软件技术的交流与成长,分享开发心得与笔记,涵盖编程、AI、资讯、面试等多个领域。无论是前沿科技的探索,还是实用技巧的总结,我们都致力于为大家呈现有价值的内容。期待与你共同进步,开启技术之旅。

相关推荐
自由的疯2 小时前
Java 使用Jackson进行深拷贝:优化与最佳实践
java·后端·架构
毕设源码-郭学长2 小时前
【开题答辩全过程】以 springboot+美食电子商城的设计与实现为例,包含答辩的问题和答案
java·eclipse·美食
王嘉俊9252 小时前
Kafka 和 RabbitMQ 使用:消息队列的强大工具
java·分布式·中间件·kafka·消息队列·rabbitmq·springboot
渣哥2 小时前
事务没生效还以为成功了?Spring 事务失效的雷区你中招了吗?
java
教游泳的程序员3 小时前
【JDBC】系列文章第一章,怎么在idea中连接数据库,并操作插入数据?
java·ide·mysql·intellij-idea
懒羊羊不懒@3 小时前
C语言指针进阶(进阶)
java·开发语言·面试
nlog3n3 小时前
分布式秒杀系统设计方案
java·分布式
间彧3 小时前
JWT(JSON Web Token)详解
java
前路不黑暗@3 小时前
Java:代码块
java·开发语言·经验分享·笔记·python·学习·学习方法