欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解SpringBoot+Ehcache使用示例

 更新時(shí)間:2025年09月30日 11:19:15   作者:咖啡Beans  
本文介紹了SpringBoot中配置Ehcache、自定義get/set方式,并實(shí)際使用緩存的過程,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

摘要

本文介紹了SpringBoot中配置Ehcache、自定義get/set方式,并實(shí)際使用緩存的過程。

概念

Ehcache是一種Java緩存框架,支持多種緩存策略,如:

  • 最近最少使用LRU:當(dāng)緩存達(dá)到最大容量時(shí),會將最近最少使用的元素淘汰。
  • 最少最近使用LFU:根據(jù)元素被訪問的頻率來淘汰元素,最少被訪問的元素會被優(yōu)先淘汰。
  • 先進(jìn)先出FIFO:按元素進(jìn)入緩存的時(shí)間順序淘汰元素,先進(jìn)入的元素會被優(yōu)先淘汰。

內(nèi)存與磁盤持久化存儲:

Ehcache支持將數(shù)據(jù)存儲在內(nèi)存中,以實(shí)現(xiàn)快速訪問。當(dāng)內(nèi)存不足時(shí),Ehcache可以將數(shù)據(jù)交換到磁盤,確保緩存數(shù)據(jù)不會因?yàn)閮?nèi)存限制而丟失。磁盤存儲路徑可以通過配置靈活指定,即使在系統(tǒng)重啟后也能恢復(fù)緩存數(shù)據(jù)。提供多種持久化策略,包括本地臨時(shí)交換localTempSwap和自定義持久化實(shí)現(xiàn)。

配置靈活性:

可通過配置ehcache.xml文件,放在啟動(dòng)類資源目錄里,可自定義緩存策略,LRU,diskExpiryThreadIntervalSeconds。

編碼示例

引入依賴:

pom.xml指定ehcache坐標(biāo)并排除slf4j

<!-- Ehcache 坐標(biāo) -->
<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文件:

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
    <diskStore path="java.io.tmpdir/ehcache"/> <!-- 定義磁盤存儲路徑,將緩存數(shù)據(jù)存儲在臨時(shí)目錄下 -->
    <!-- 
        參數(shù)說明:
        maxElementsInMemory 內(nèi)存中最多存儲的元素?cái)?shù)量 
        eternal             是否為永生緩存,false表示元素有生存和閑置時(shí)間 
        timeToIdleSeconds   元素閑置 120 秒后失效 
        timeToLiveSeconds   元素存活 120 秒后失效 
        maxElementsOnDisk   磁盤上最多存儲的元素?cái)?shù)量 
        diskExpiryThreadIntervalSeconds 磁盤清理線程運(yùn)行間隔 
        memoryStoreEvictionPolic 內(nèi)存存儲的淘汰策略,采用 LRU(最近最少使用) 
    -->
    <!-- defaultCache:echcache 的默認(rèn)緩存策略-->
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            maxElementsOnDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </defaultCache>
    <!-- 自定義緩存策略 這里的name是用于緩存名指定時(shí)  需要對應(yīng)緩存名添加-->
    <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: classpath:ehcache.xml

自定義緩存get/set方式:

利用CacheManager處理緩存:

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;

    /**
     * 根據(jù)名稱獲取緩存數(shù)據(jù)
     * @param cacheName cache名稱
     * @param keyName cache中對應(yīng)key名稱
     * @return cache數(shù)據(jù)
     */
    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<>();
    }

    /**
     * 往緩存中存放數(shù)據(jù) 名字區(qū)分
     * @param cacheName     cache名稱
     * @param keyName       cache中對應(yīng)key名稱
     * @param dataList      存放數(shù)據(jù)
     */
    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);
    }

}

啟動(dòng)類加注解:

@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("獲取緩存數(shù)據(jù):" + cacheData.toString());
    }

}

測試結(jié)果:

總結(jié)

以上我們了解了SpringBoot中配置Ehcache、自定義get/set方式,并實(shí)際使用緩存的過程。

到此這篇關(guān)于詳解SpringBoot+Ehcache使用示例的文章就介紹到這了,更多相關(guān)SpringBoot+Ehcache使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論