1. 程式人生 > >springboot ehcache快取使用及自定義快取存取

springboot ehcache快取使用及自定義快取存取

新增依賴
首先在pom.xml新增必要依賴


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <dependency>
            <groupId>net.sf.ehcache</groupId
>
<artifactId>ehcache</artifactId> </dependency>

新增依賴時會提示net.sf.ehcache已經整合在springboot裡邊,但是不加程式又提示找不到net.sf.ehcache.CacheManager的class檔案。該問題需要朋友們解決一下。
開啟快取
在Spring Boot環境下,使用快取技術只需在專案中匯入相關快取技術的依賴包,並在配置類上使用@EnableCaching開啟快取即可。
在啟動類添加註解@EnableCaching

@SpringBootApplication
@EnableCaching public class MyTestApplication { private static Logger log=LoggerFactory.getLogger(MyTestApplication .class); public static void main(String[] args) { SpringApplication.run(MyTestApplication .class, args); log.info("服務啟動成功"); } }

新建資料庫表

CREATE TABLE `paraconfig`
( `paraId` int(11) NOT NULL AUTO_INCREMENT COMMENT '引數id', `paraName` varchar(20) NOT NULL COMMENT '引數名稱', `paraCode` varchar(50) NOT NULL COMMENT '引數值', `paraDesc` varchar(100) DEFAULT NULL COMMENT '引數描述', `status` enum('有效','無效') NOT NULL COMMENT '引數狀態', PRIMARY KEY (`paraId`), UNIQUE KEY `paraName` (`paraName`) USING BTREE, KEY `paraStatus` (`status`) USING BTREE ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8

新建實體類

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Paraconfig implements Serializable{
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue
    private Integer paraid;
    private String paraname;
    private String paracode;
    private String paradesc;
    private String status;
    public Integer getParaid() {
        return paraid;
    }
    public void setParaid(Integer paraid) {
        this.paraid = paraid;
    }
    public String getParaname() {
        return paraname;
    }
    public void setParaname(String paraname) {
        this.paraname = paraname;
    }
    public String getParacode() {
        return paracode;
    }
    public void setParacode(String paracode) {
        this.paracode = paracode;
    }
    public String getParadesc() {
        return paradesc;
    }
    public void setParadesc(String paradesc) {
        this.paradesc = paradesc;
    }
    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;
    }
    @Override
    public String toString() {
        return "Paraconfig [paraid=" + paraid + ", paraname=" + paraname + ", paracode=" + paracode + ", paradesc="
                + paradesc + ", status=" + status + "]";
    }

}

新建dao查詢資料庫介面

import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.xx.model.Paraconfig;
public interface IParaConfigDao extends JpaRepository<Paraconfig,Integer>{
    public Paraconfig findByParaid(Integer id);
    public Paraconfig findByParaname(String name);
    public List<Paraconfig> findByStatus(String status);
}

新建資料庫操作服務及實現

import java.util.List;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import com.xx.model.Paraconfig;
public interface IParaConfigService {
    @CacheEvict(value = "SystemCache")
    public int deletePara(int id);

    @CachePut(value = "SystemCache", key = "#para.paraid") 
    public Paraconfig addPara(Paraconfig para);

    @Cacheable(value = "SystemCache", key = "#id") 
    public Paraconfig findOne(int id);

    @Cacheable(value = "SystemCache", key = "#name") 
    public Paraconfig findByName(String name);

    @Cacheable(value = "SystemCache") 
    public List<Paraconfig> findAll();

    @Cacheable(value = "SystemCache") 
    public List<Paraconfig> findByStatus(String status);

    @CachePut(value = "SystemCache", key = "#para.paraid") 
    public Paraconfig updataPara(Paraconfig para);
}

import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xx.DatabaseSservice.paraConfig.IParaConfigService;
import com.xx.dao.IParaConfigDao;
import com.xx.model.Paraconfig;

@Service
public class ParaConfigServiceImpl implements IParaConfigService{
    private Logger log=LoggerFactory.getLogger(ParaConfigServiceImpl.class);
    @Autowired
    private IParaConfigDao dao;
    @Override
    public int deletePara(int id) {
        log.info("o==||======>刪除系統引數入參ID="+id);
        int result=0;
        try{
            dao.deleteById(id);
            result=0;
        }catch(Exception e){
            e.printStackTrace();
            result=-1;
            log.info("刪除系統引數異常");
        }
        return result;
    }
    @Override
    public Paraconfig addPara(Paraconfig para) {
        log.info("o==||=====>新增系統引數入參:"+para.toString());
        return doExecute("addPara",null,para);
    }
    @Override
    public Paraconfig findOne(int id) {
        log.info("o==||=====>id查詢系統引數入參:id="+id);
        return doExecute("findOne",String.valueOf(id),null);
    }
    @Override
    public Paraconfig findByName(String name) {
        log.info("o==||=====>name查詢系統引數入參:name="+name);
        return doExecute("findByName",name,null);
    }
    @Override
    public List<Paraconfig> findAll() {
        log.info("o==||=====>查詢All系統引數");
        return doExecutePage("findAll",null);
    }
    @Override
    public List<Paraconfig> findByStatus(String status) {
        log.info("o==||=====>status查詢系統引數:status="+status);
        return doExecutePage("findByStatus",status);
    }
    @Override
    public Paraconfig updataPara(Paraconfig para) {
        log.info("o==||=====>更新系統引數入參:"+para.toString());
        return doExecute("updataPara",null,para);
    }

    public Paraconfig doExecute(String type,String arg,Paraconfig req){
        Paraconfig resp=new Paraconfig();
        try{
            switch(type){
                case "addPara" : ;
                case "updataPara" : resp=dao.save(req);break;
                case "findOne" : resp=dao.findByParaid(Integer.valueOf(arg));break;
                case "findByName" : resp=dao.findByParaname(arg);break;
            }
        }catch(Exception e){
            e.printStackTrace();
            String Emsg = null;
            switch(type){
                case "addPara" : Emsg="新增系統引數異常";break;
                case "updataPara" : Emsg="更新系統引數異常";break;
                case "findOne" : Emsg="根據ID查詢系統引數異常";break;
                case "findByName" : Emsg="根據name查詢系統引數異常";break;
            }
            log.info(Emsg+e.getMessage());
        }finally{
            log.info("查詢系統引數返回:"+(resp==null?null:resp.toString()));
        }
        return resp;
    }

    public List<Paraconfig> doExecutePage(String type,String arg){
        List<Paraconfig> resp = null;
        try{
            switch(type){
                case "findAll" : resp=dao.findAll();break;
                case "findByStatus" : resp=dao.findByStatus(arg);break;
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            log.info("查詢系統引數返回:"+(resp==null?null:resp.toString()));
        }
        return resp;
    }
}

新建測試controller

@PostMapping("/testCachefindOne")
    public void testCachefindOne(){
        Paraconfig para=null;
        try{
            para=paraConfigService.findOne(1);
        }catch(Exception e){
            e.printStackTrace();
            log.info("異常:"+e.getMessage());
        }
    }

測試
使用postman請求。檢視控制執行資料庫操作日誌。
第一次請求快取沒有則有日誌列印,第二次請求快取有資料則不會列印日誌。
測試沒有問題說明快取自動儲存已經沒問題了,接下來就是怎麼取快取及新增自定義的快取了。
新增ehcache配置檔案

<?xml version="1.0" encoding="UTF-8"?>  
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"  
         updateCheck="false">
         <diskStore path="java.io.tmpdir/Tmp_EhCache" />  
    <defaultCache  
            eternal="false"  
            maxElementsInMemory="1000"  
            overflowToDisk="false"  
            diskPersistent="false"  
            timeToIdleSeconds="0"  
            timeToLiveSeconds="100"  
            memoryStoreEvictionPolicy="LRU" />  

    <cache  
            name="SystemCache"  
            eternal="false"  
            maxElementsInMemory="100"  
            overflowToDisk="false"  
            diskPersistent="false"  
            timeToIdleSeconds="0"  
            timeToLiveSeconds="30"  
            memoryStoreEvictionPolicy="LRU" />  
</ehcache>

配置檔案詳解

(1).diskStore: 為快取路徑,ehcache分為記憶體和磁碟兩級,此屬性定義磁碟的快取位置。引數解釋如下:    
user.home – 使用者主目錄
user.dir  – 使用者當前工作目錄
java.io.tmpdir – 預設臨時檔案路徑
(2).defaultCache:預設快取策略,當ehcache找不到定義的快取時,則使用這個快取策略。只能定義一個。
(3).cache:自定快取策略,為自定義的快取策略。引數解釋如下:
cache元素的屬性:
name:快取名稱
maxElementsInMemory:記憶體中最大快取物件數
maxElementsOnDisk:硬碟中最大快取物件數,若是0表示無窮大
eternal:true表示物件永不過期,此時會忽略timeToIdleSeconds和timeToLiveSeconds屬性,預設為false
overflowToDisk:true表示當記憶體快取的物件數目達到了maxElementsInMemory界限後,會把溢位的物件寫到硬碟快取中。注意:如果快取的物件要寫入到硬碟中的話,則該物件必須實現了Serializable接口才行。
diskSpoolBufferSizeMB:磁碟快取區大小,預設為30MB。每個Cache都應該有自己的一個快取區。
diskPersistent:是否快取虛擬機器重啟期資料
diskExpiryThreadIntervalSeconds:磁碟失效執行緒執行時間間隔,預設為120秒
timeToIdleSeconds: 設定允許物件處於空閒狀態的最長時間,以秒為單位。當物件自從最近一次被訪問後,如果處於空閒狀態的時間超過了timeToIdleSeconds屬性值,這個物件就會過期,EHCache將把它從快取中清空。只有當eternal屬性為false,該屬性才有效。如果該屬性值為0,則表示物件可以無限期地處於空閒狀態
timeToLiveSeconds:設定物件允許存在於快取中的最長時間,以秒為單位。當物件自從被存放到快取中後,如果處於快取中的時間超過了 timeToLiveSeconds屬性值,這個物件就會過期,EHCache將把它從快取中清除。只有當eternal屬性為false,該屬性才有效。如果該屬性值為0,則表示物件可以無限期地存在於快取中。timeToLiveSeconds必須大於timeToIdleSeconds屬性,才有意義
memoryStoreEvictionPolicy:當達到maxElementsInMemory限制時,Ehcache將會根據指定的策略去清理記憶體。可選策略有:LRU(最近最少使用,預設策略)、FIFO(先進先出)、LFU(最少訪問次數)。

將配置檔案放在src/main/resources下(或其他路徑,需要配置路徑)。
新建ApplicationContextUtils實現ApplicationContextAware介面

import org.springframework.beans.BeansException;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component  
@EnableAutoConfiguration  
public class ApplicationContextUtils implements ApplicationContextAware{
     public static ApplicationContext applicationContext=null;//可寫成單利模式,這裡為了方便  
     @Override  
     public void setApplicationContext(ApplicationContext arg0) throws BeansException {
         applicationContext=arg0;
         System.out.println("設定ApplicationContext成功!");
    }  
}

快取自定義存取

@PostMapping("/testCachefindOne")
    public void testCachefindOne(){
        Paraconfig para=null;
        try{
            para=paraConfigService.findOne(1);
            EhCacheCacheManager cacheCacheManager=ApplicationContextUtils.applicationContext.getBean(EhCacheCacheManager.class); 
            //獲取Cache  
            Cache cache=cacheCacheManager.getCache("SystemCache");  
            cache.put("Hello-key", "Hello-value");
            System.out.println("快取名:"+cache.getName());
            System.out.println("快取Hello-key:"+cache.get("Hello-key", String.class));
            System.out.println("快取SYSDATE:"+cache.get("SYSDATE",Paraconfig.class));
        }catch(Exception e){
            e.printStackTrace();
            log.info("異常:"+e.getMessage());
        }
    }

啟動測試
這裡寫圖片描述

小結:
[email protected]表示快取新新增的資料或者更新的資料到快取中,兩個引數value表示快取的名稱為SystemCache,key表示快取的key為#id 的資料,#id為方法引數 。
[email protected]表示從快取SystemCache中刪除key為id的資料
[email protected]表示新增資料到快取中,快取名稱為SystemCache,快取key為#para.paraid的資料。
注意: @CachePut總會執行SQL操作,其主要用在更新或插入資料時。
@Cacheable主要用在查詢資料庫時,快取有則不查資料庫。

相關推薦

springboot ehcache快取使用定義快取存取

新增依賴 首先在pom.xml新增必要依賴 <dependency> <groupId>org.springframework.boot</groupId>

.NET的三種快取(頁面快取,控制元件快取定義快取)

BLL.Area bll = new BLL.Area(); protected void Page_Load(object sender, EventArgs e) { if (Cache["tList"] != null) { Response.Write("已經有

MyBatis系統快取定義快取

1、 系統快取(一級快取) Mybatis對快取提供支援,在沒有開啟快取的情況下,mybatis會預設開啟一級快取(一級快取只是相對於同一個SQLSession而言) 所以在引數和SQL完全一樣的情況下,我們使用同一個SQLSession物

詳解SpringBoot——啟動原理定義starter

模塊 開始 print handler man comm toc ade ogg 一、引言 SpringBoot的一大優勢就是Starter,由於SpringBoot有很多開箱即用的Starter依賴,使得我們開發變得簡單,我們不需要過多的關註框架的配置。 在日常開發中,

.Net Core 跨平臺開發實戰-伺服器快取:本地快取、分散式快取定義快取

.Net Core 跨平臺開發實戰-伺服器快取:本地快取、分散式快取、自定義快取 1、概述   系統性能優化的第一步就是使用快取!什麼是快取?快取是一種效果,就是把資料結果存在某個介質中,下次直接重用。根據二八原則,80%的請求都集中在20%的資料上,快取就是把20%的資料存起來,直接複用。Web系統快取主要

(springboot)基於Redis實現Mybatis二級快取(定義快取)

Springboot + Mybatis + Redis Mybatis的二級快取是多個SqlSession共享的,作用於是mapper配置檔案中同一個namespace,不同的SqlSession兩次執行相同namespace下的sql語句且引數如果也一樣則最終執行的sq

springboot-cache定義快取載入資料字典表

專案需求:專案資料儲存在hbase中,每次查詢資料都需將一些資料進行轉換,對於大資料查詢操作頻繁連線資料庫獲取字典值,這會影響整個查詢速度。解決方案:1、根據不同業務模組劃分,專案中對於資料流處理(單獨spark服務),通過redis快取字典資料。2、前段需要用到字典資料,將

SpringBoot使用AOP實現定義介面快取

一、引入pom.xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data

springboot-cache3定義快取載入資料庫屬性配置

需求:由於專案中配置項太多,配置檔案維護很不方便,將配置項放在資料庫中維護,通過專案啟動時將資料庫配置載入到環境變數中,其他需要使用的業務直接使用引用的方式是@Value("${欄位}")專案結構:pom.xml引入依賴包<?xml version="1.0" enco

Springboot-讀取核心配置文件定義配置文件

定義 自定義配置文件 () 創建 ble get 兩個 ash dex 讀取核心配置文件 核心配置文件是指在resources根目錄下的application.properties或application.yml配置文件,讀取這兩個配置文件的方法有兩種,都比較簡單。 核

Springboot讀取配置文件定義配置文件

val request wire odin 自定義配置文件 方式 -s bin ssi 1.創建maven工程,在pom文件中添加依賴 1 <parent> 2 <groupId>org.springframework.boot

Springboot讀取配置檔案、pom檔案定義配置檔案

前言 很多人都知道讀取配置檔案,這是初級做法,上升一點難度是使用java bean的方式讀取自定義配置檔案,但是大家很少有知道讀取pom檔案資訊,接下來我都會講到。 正文 筆者還是基於Spring Boot ::        (v1.5.8.RE

【.NET Core專案實戰-統一認證平臺】第五章 閘道器篇-定義快取Redis

原文: 【.NET Core專案實戰-統一認證平臺】第五章 閘道器篇-自定義快取Redis 【.NET Core專案實戰-統一認證平臺】開篇及目錄索引 上篇文章我們介紹了2種閘道器配置資訊更新的方法和擴充套件Mysql儲存,本篇我們將介紹如何使用Redis來實現閘道器的所有快取功能,用到的文件及原始

fresco定義快取路徑

記得加許可權!記得加許可權!記得加許可權!  讀寫磁碟的許可權  //設定磁碟快取 DiskCacheConfig diskCacheConfig = DiskCacheConfig.newBuilder(this) .s

定義快取路徑

DiskCacheConfig diskCacheConfig = DiskCacheConfig.newBuilder(this)                 .setBaseDirectoryName("images_zz")                 .set

定義快取系統,使用讀寫鎖

package cn.itcast.heima2; import java.util.HashMap; import java.util.Map; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurre

shiro原始碼分析篇4:定義快取

這篇講解shiro如何管理session,如何與ehcache結合。我們自己如何寫個簡單的快取替換ehcache。 首先來看看配置 <!-- 快取管理器 使用Ehcache實現 --> <bean id="cacheManagerShiro" cla

SpringBoot通過AOP實現系統日誌記錄(三)-Mapper層日誌監控定義異常攔截

本文是SpringBoot通過AOP實現系統日誌記錄(三)-Mapper層日誌監控及異常攔截,若要實現Service層監控,請點選傳送門: SpringBoot通過AOP實現系統日誌記錄(二)-Service層日誌監控 由於公司業務上的需求,現在需要對整個系統做日誌效能監控,方便開發人員快速

laravel定義快取memcache(帶memcached,windows不支援)

1、首先弄清楚memcache和memcached的區別(自行搜尋) 2、安裝memcache服務端(參照https://www.cnblogs.com/winstonsias/p/10190745.html)及php擴充套件(參照https://www.cnblogs.com/winstonsias/p/

SpringBoot之@EnableAutoConfiguration原理定義擴充套件

spring Boot是一個偏執的開源框架,它可用於建立可執行的Spring應用程式,採用了習慣優於配置的方法。  此框架的神奇之處在於@EnableAutoConfiguration註釋,此註釋自動載入應用程式所需的所有Bean——這依賴於Spring Boot在類路徑