概述
上一節(jié)我們講了SpringBoot整合Redis緩存嘹叫,這節(jié)我們來講Ehcache蓬痒。EhCache 是一個純Java的輕量級進程內(nèi)緩存框架秽澳,具有快速闯睹、簡單等特點,是Hibernate中默認(rèn)的緩存提供方肝集。
相對于Redis這類可分布式的緩存中間件,Ehcache是屬于進程內(nèi)緩存,和Guava Cache瞻坝、Caffeine等緩存框架一樣都屬于堆內(nèi)存緩存,適合單點使用蛛壳,不太適合分布式場景杏瞻。
EhCache有哪些特點
- 快速,簡單衙荐,并且提供多種緩存策略捞挥;
- 緩存數(shù)據(jù)有兩級:內(nèi)存和磁盤,無需擔(dān)心容量問題忧吟;
- 緩存數(shù)據(jù)會在虛擬機重啟的過程中寫入磁盤砌函;
- 可以通過RMI、可插入API等方式進行分布式緩存溜族;
- 具有緩存和緩存管理器的偵聽接口讹俊;
- 支持多緩存管理器實例,以及一個實例的多個緩存區(qū)域煌抒;
- 提供Hibernate的緩存實現(xiàn)仍劈;
開始在SpringBoot項目中使用Ehcache
※在上一節(jié)Redis的基礎(chǔ)上,把redis相關(guān)的內(nèi)容刪除
- 在pom.xml中加入ecache依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
- 在資源根目錄下創(chuàng)建ehcache.xml文件,內(nèi)容如下
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
<!-- 操作系統(tǒng)緩存的臨時目錄,內(nèi)存滿后寫入該目錄 -->
<diskStore path="java.io.tmpdir"/>
<!-- 默認(rèn)緩存
maxElementsInMemory:內(nèi)存中最多可以存放的元素數(shù)量
overflowToDisk=true:將Cache中多出的元素放入磁盤文件中
overflowToDisk=false:根據(jù)memoryStoreEvictionPolicy策略替換Cache中原有的元素
eternal:緩存中對象是否永久有效
imeToIdleSeconds:當(dāng)eternal=false時使用,緩存數(shù)據(jù)有效期(單位:秒),時間段內(nèi)沒有訪問該元素,將被清除
timeToLiveSeconds:緩存數(shù)據(jù)的存活時間
maxElementsOnDisk:磁盤緩存中最多可以存放的元素數(shù)量
diskExpiryThreadIntervalSeconds:磁盤緩存的清理線程運行間隔
memoryStoreEvictionPolicy:緩存釋放策略,LRU會優(yōu)先清理最少使用的緩存
localTempSwap:持久化策略寡壮,當(dāng)堆內(nèi)存或者非堆內(nèi)存里面的元素已經(jīng)滿了的時候贩疙,將其中的元素臨時的存放在磁盤上讹弯,重啟后就會消失
-->
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="3600"
timeToLiveSeconds="3600"
maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LFU">
<persistence strategy="localTempSwap"/>
</defaultCache>
<cache name="users"
maxEntriesLocalHeap="200"
timeToLiveSeconds="600">
</cache>
</ehcache>
- 在yml文件中,加入ehcache配置信息
# Spring配置
spring:
cache:
ehcache:
config: classpath:ehcache.xml
在啟動類上加入@EnableCaching開啟緩存
Service層,和上節(jié)一樣,代碼如下:
package com.zhlab.demo.service;
import com.zhlab.demo.dao.SysAdminUserRepository;
import com.zhlab.demo.model.SysAdminUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
/**
* @ClassName SysAdminUserService
* @Description //SysAdminUserService
* @Author singleZhang
* @Email 405780096@qq.com
* @Date 2020/10/31 0031 上午 9:45
**/
@CacheConfig(cacheNames = "users")
@Service
public class SysAdminUserService {
@Autowired
SysAdminUserRepository sysAdminUserRepository;
@Cacheable(key="'user_'+#userId")
public SysAdminUser findUser(Long userId){
return sysAdminUserRepository.findById(userId).orElse(null);
}
@CachePut(key="'user_'+#result.adminUserId")
public SysAdminUser save(SysAdminUser user){
return sysAdminUserRepository.save(user);
}
@CacheEvict(key="'user_'+#userId")
public void deleteUser(Long userId) {
sysAdminUserRepository.findById(userId).ifPresent(sysAdminUserRepository::delete);
}
}
- 在接口層,我們來測試一下緩存是否實現(xiàn)了,注釋部分就是需要測試的位置
package com.zhlab.demo.controller;
import com.zhlab.demo.model.SysAdminUser;
import com.zhlab.demo.service.SysAdminUserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.web.bind.annotation.*;
/**
* @ClassName UserController
* @Description //用戶接口層
* @Author singleZhang
* @Email 405780096@qq.com
* @Date 2020/10/31 0031 上午 9:43
**/
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
SysAdminUserService sysAdminUserService;
@Autowired
private CacheManager cacheManager;
@ApiOperation(value = "方法名:用戶信息", notes = "獲取用戶信息")
@GetMapping("/{userId}")
public SysAdminUser findUser(@PathVariable Long userId){
// 查看一下CacheManager是否已經(jīng)是EhCacheCacheManager
System.out.println("CacheManager type : " + cacheManager.getClass());
// 查詢用戶信息的時候,有無sql檢索
SysAdminUser userInfo =sysAdminUserService.findUser(userId);
return userInfo;
}
}
- 啟動項目,打開http://localhost:8080/swagger-ui.html
接口調(diào)試
第一次執(zhí)行后,查看控制臺輸出的信息:
- CacheManager已經(jīng)是EhCacheCacheManager
-
有sql查詢信息
第一次查詢結(jié)果
繼續(xù)查詢一次或者多查幾次,后邊幾次都沒有出現(xiàn)sql查詢信息,返回的結(jié)果來自緩存
繼續(xù)查詢接口
返回結(jié)果
總結(jié)
EhCache的使用也是比較簡單的,使用也比較廣泛这溅,通過上邊的例子和之前的Redis操作,大家應(yīng)該已經(jīng)熟悉了緩存操作這個環(huán)節(jié),以后在項目中應(yīng)用起來應(yīng)該是得心應(yīng)手了组民。