1. 程式人生 > 程式設計 >Springboot使用cache快取過程程式碼例項

Springboot使用cache快取過程程式碼例項

1.pom.xml

<!-- Ehcache 座標 -->
<dependency>
  <groupId>net.sf.ehcache</groupId>
  <artifactId>ehcache</artifactId>
</dependency>

2.ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
 
  <diskStore path="java.io.tmpdir"/>
 
  <!--defaultCache:echcache的預設快取策略 -->
  <defaultCache
      maxElementsInMemory="10000"
      eternal="false"
      timeToIdleSeconds="120"
      timeToLiveSeconds="120"
      maxElementsOnDisk="10000000"
      diskExpiryThreadIntervalSeconds="120"
      memoryStoreEvictionPolicy="LRU">
    <persistence strategy="localTempSwap"/>
  </defaultCache>
  <!--
    maxElementsInMemory設定成1,overflowToDisk設定成true,只要有一個快取元素,就直接存到硬碟上去
    eternal設定成true,代表物件永久有效
    maxElementsOnDisk設定成0 表示硬碟中最大快取物件數無限大
    diskPersistent設定成true表示快取虛擬機器重啟期資料
  -->
  <cache name="usercache"
      maxElementsInMemory="1"
      eternal="true"
      overflowToDisk="true"
      maxElementsOnDisk="0"
      diskPersistent="true">
<!--    <persistence strategy="localTempSwap"/>--> <!--不能和diskPersistent 同時存在-->
  </cache>

diskStore是物理檔案的儲存路徑,

cache標籤中的name是多cache時區分的唯一標識, 和程式中初始化方法getCache("***")引數一致。<br>快取引數和本地資料持久化儲存需自行配置

3.application.yml

spring:
 cache:
  ehcache:
   config: classpath:/ehcache.xml

4.啟動類新增

@EnableCaching

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
 
@EnableCaching
@SpringBootApplication
public class DemoApplication {
 
  public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class,args);
  }
 
}

5.springcloud 中使用cache

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.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
 
import java.io.IOException;
 
 
/**
 * @Author: Peacock__
 * @Date: 2019/6/14 17:30
 */
@Component
public class CacheService {
 
  @Autowired
  private CacheManager cacheManager;
  /**
   * 從快取中獲取資料
   * @return
   * @throws IOException
   */
  public String getCache() throws IOException {
   String res = "";
 
    Cache cache = cacheManager.getCache("usercache");
    if(cache != null){
      Element element = cache.get("name");
      if(element != null){
        Object objectValue = element.getObjectValue();
        res = (String) objectValue;
      }
    }
    return res;
  }
 
  /**
   * 資料存入快取
   * @param data
   * @throws IOException
   */
  public void putCache(String data) throws IOException {
    //若cacheManager被關閉,則重新建立
    if(cacheManager == null || cacheManager.getStatus().intValue() != 1){
      cacheManager = new CacheManager(new ClassPathResource("ehcache.xml").getInputStream());
    }
    Cache cache = cacheManager.getCache("usercache");
    //處理成要快取的資料
 
    //存入快取(注意:需要保證存入快取的資料都是可序列化的)
    cache.put(new Element("name",data));
    /**
     * ehcache和其它快取類似,需要flush或shutdown後才會持久化到磁碟。
     * 會生成.data 的資料檔案和 .index 的索引檔案,方便重啟恢復。
     * ehcache恢復資料是根據.index索引檔案來進行資料恢復的。
     * 當程式再次啟動的時候,ehcache的一個方法會將.data檔案和.index檔案的修改時間進行比較,如果不符合直接將.index檔案刪除。
     */
    //將所有快取項從記憶體重新整理到磁碟儲存,並從DiskStore重新整理到磁碟。
//    cache.flush();
    //更新.index檔案
//    cacheManager.shutdown();
  }
}

6.controller層

import java.io.IOException;
 
@RestController
public class AppController{
 
 
  @Autowired
  private CacheService cacheService;
 
  @RequestMapping("/setName")
  public String setName() {
 
    try {
      cacheService.putCache( "heshan");
    } catch (IOException e) {
      e.printStackTrace();
    }
    return "yes";
  }
  @RequestMapping("/getName")
  public String getName() {
 
    String res = null;
    try {
      res = cacheService.getCache( );
    } catch (IOException e) {
      e.printStackTrace();
    }
    return res;
  }
}

結果:

Springboot使用cache快取過程程式碼例項Springboot使用cache快取過程程式碼例項

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。