开发者

详解SpringBoot+Ehcache使用示例

目录
  • 摘要
  • 概念
    • 内存与磁盘持久化存储:
    • 配置灵活性:
  • 编码示例
    • 引入依赖:
    • 配置ehcache.XML文件:
    • 配置文件:
    • 自定义缓存get/set方式:
    • 启动类加注解:
    • 编辑测试类:
    • 测试结果:
  • 总结

    摘要

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

    概念

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

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

    内存与磁盘持久化存储:

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

    配置灵活性:

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

    编码示例

    引入依赖:

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

    <!-- 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>n编程et.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文件:

    <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"
                timeToIdle编程客栈Seconds="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的缓存文件路径

    spring:
      cache:
        type: ehcache
        ehcache:
          config: clapythonsspath:ehcache.xml
    

    自定义缓存get/set方式:

    利用CacheManager处理缓存:

    package org.coffeebeans.ehcache;
    
    import net.sf.ehcacphphe.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开启程序缓存

    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!");
        }
    
    }
    

    编辑测试类:

    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使用示例

    总结

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

    到此这篇关于详解SpringBoot+Ehcache使用示例的文章就介绍到这了,更多相关SpringBoot+Ehcache使用内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!

    0

    上一篇:

    下一篇:

    精彩评论

    暂无评论...
    验证码 换一张
    取 消

    最新开发

    开发排行榜