1、EhCache介紹
在查詢數(shù)據(jù)的時候,數(shù)據(jù)大多來自于數(shù)據(jù)庫,我們會基于SQL語句與數(shù)據(jù)庫交互,數(shù)據(jù)庫一般會基于本地磁盤IO將數(shù)據(jù)讀取到內(nèi)存,返回給Java服務(wù)端,我們再將數(shù)據(jù)響應(yīng)給前端,做數(shù)據(jù)展示。
但是MySQL這種關(guān)系型數(shù)據(jù)庫查詢數(shù)據(jù)相對比較慢,因為有磁盤IO,或者是全盤掃描的風(fēng)險,在針對一些熱點數(shù)據(jù)時,會對MySQL造成比較大的壓力,此時我們可以采用緩存的方式來解決。
而緩存又分為很多種,相對服務(wù)端角度來說,可以采用Redis和JVM這兩種方式。
Redis不必多說,直接基于基于內(nèi)存讀寫,并發(fā)讀寫的并發(fā)能力特別強,所以很多時間,在分布式或者微服務(wù)的項目中,為了保證數(shù)據(jù)一致性,我們會采用Redis來實現(xiàn)緩存。
但是在一些單體項目,我們可以采用JVM級別的緩存,比如直接采用框架自帶的,例如Hibernate的緩存,MyBatis的緩存,或者是Guava提供的Cache,以及今兒要玩的EhCache。
還有一種情況可以采用JVM緩存,在分布式環(huán)境下,如果并發(fā)特別大,Redis也扛不住,這是我們可以將數(shù)據(jù)平均的分散在各個節(jié)點的JVM緩存中,并且設(shè)置一個較短的生存時間,這樣就可以減緩Redis的壓力,從而解決熱點數(shù)據(jù)Redis扛不住的問題
同時EhCache也是Hibernate框架默認使用的緩存組件實現(xiàn)二級緩存。類似MyBatis,就直接用的HashMap。
2、引入EhCache
官網(wǎng):http://www.ehcache.org
通過后綴就可以看出EhCache是開源的組件。
EhCache除了開源,還有可以幾乎0成本和Spring整合的有點,畢竟現(xiàn)在Java項目大多都是基于Spring方式構(gòu)建的,這也可以讓我們在使用EhCache的時候更加方便。
這里還是單獨的使用EhCache來感受一下,其實使用方式和HashMap的put和get的方式類似,不過EhCache提供了更加豐富的功能。
EhCache有2.x和3.x兩個常用的大版本,兩個版本API差異巨大,這里咱們以3.x為講解的內(nèi)容應(yīng)用
官方入門文檔:
Ehcache 3.10 Documentation
<!-- ehcache依賴 -->
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>3.8.1</version>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.6</version>
</dependency>
3、復(fù)制配置文件
- 復(fù)制xml文件
文章來源:http://www.zghlxwxcb.cn/news/detail-789282.html
<!-- Ehcache2.x的變化(取自https://github.com/springside/springside4/wiki/Ehcache) -->
<!-- 1)最好在ehcache.xml中聲明不進行updateCheck -->
<!-- 2)為了配合BigMemory和Size Limit,原來的屬性最好改名 -->
<!-- maxElementsInMemory->maxEntriesLocalHeap -->
<!-- maxElementsOnDisk->maxEntriesLocalDisk -->
<ehcache>
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="60"
timeToLiveSeconds="60"
overflowToDisk="false"/>
<cache name="myCache"
maxElementsOnDisk="20000"
maxElementsInMemory="2000"
eternal="true"
overflowToDisk="true"
diskPersistent="true"/>
<cache name="myCache2"
maxElementsOnDisk="20000"
maxElementsInMemory="2000"
eternal="true"
overflowToDisk="true"
diskPersistent="true"/>
</ehcache>
<!--
<diskStore>==========當內(nèi)存緩存中對象數(shù)量超過maxElementsInMemory時,將緩存對象寫到磁盤緩存中(需對象實現(xiàn)序列化接口)
<diskStore path="">==用來配置磁盤緩存使用的物理路徑,Ehcache磁盤緩存使用的文件后綴名是*.data和*.index
name=================緩存名稱,cache的唯一標識(ehcache會把這個cache放到HashMap里)
maxElementsOnDisk====磁盤緩存中最多可以存放的元素數(shù)量,0表示無窮大
maxElementsInMemory==內(nèi)存緩存中最多可以存放的元素數(shù)量,若放入Cache中的元素超過這個數(shù)值,則有以下兩種情況
1)若overflowToDisk=true,則會將Cache中多出的元素放入磁盤文件中
2)若overflowToDisk=false,則根據(jù)memoryStoreEvictionPolicy策略替換Cache中原有的元素
eternal==============緩存中對象是否永久有效,即是否永駐內(nèi)存,true時將忽略timeToIdleSeconds和timeToLiveSeconds
timeToIdleSeconds====緩存數(shù)據(jù)在失效前的允許閑置時間(單位:秒),僅當eternal=false時使用,默認值是0表示可閑置時間無窮大,此為可選屬性
即訪問這個cache中元素的最大間隔時間,若超過這個時間沒有訪問此Cache中的某個元素,那么此元素將被從Cache中清除
timeToLiveSeconds====緩存數(shù)據(jù)在失效前的允許存活時間(單位:秒),僅當eternal=false時使用,默認值是0表示可存活時間無窮大
即Cache中的某元素從創(chuàng)建到清楚的生存時間,也就是說從創(chuàng)建開始計時,當超過這個時間時,此元素將從Cache中清除
overflowToDisk=======內(nèi)存不足時,是否啟用磁盤緩存(即內(nèi)存中對象數(shù)量達到maxElementsInMemory時,Ehcache會將對象寫到磁盤中)
會根據(jù)標簽中path值查找對應(yīng)的屬性值,寫入磁盤的文件會放在path文件夾下,文件的名稱是cache的名稱,后綴名是data
diskPersistent=======是否持久化磁盤緩存,當這個屬性的值為true時,系統(tǒng)在初始化時會在磁盤中查找文件名為cache名稱,后綴名為index的文件
這個文件中存放了已經(jīng)持久化在磁盤中的cache的index,找到后會把cache加載到內(nèi)存
要想把cache真正持久化到磁盤,寫程序時注意執(zhí)行net.sf.ehcache.Cache.put(Element element)后要調(diào)用flush()方法
diskExpiryThreadIntervalSeconds==磁盤緩存的清理線程運行間隔,默認是120秒
diskSpoolBufferSizeMB============設(shè)置DiskStore(磁盤緩存)的緩存區(qū)大小,默認是30MB
memoryStoreEvictionPolicy========內(nèi)存存儲與釋放策略,即達到maxElementsInMemory限制時,Ehcache會根據(jù)指定策略清理內(nèi)存
共有三種策略,分別為LRU(最近最少使用)、LFU(最常用的)、FIFO(先進先出)
-->
- 修改springmvc.xml文件
文章來源地址http://www.zghlxwxcb.cn/news/detail-789282.html
4、通過注解使用ehcache
- 服務(wù)接口
package com.shenmazong.zg2.service;
import java.util.HashMap;
/**
* @author 軍哥
* @version 1.0
* @description: 緩存接口
* @date 2023/10/15 19:24
*/
public interface EhCacheService {
public HashMap<String, Object> createCache(String key, String value);
public HashMap<String, Object> getCache(String key);
public void delCache(String key);
}
- 服務(wù)接口實現(xiàn)
package com.shenmazong.zg2.service.impl;
import com.shenmazong.zg2.service.EhCacheService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.util.HashMap;
/**
* @author 軍哥
* @version 1.0
* @description: TODO
* @date 2023/10/15 19:26
*/
@Service
@Slf4j
public class EhCacheServiceImpl implements EhCacheService {
@Override
@Cacheable(value = "myCache", key = "'EhCacheServiceImpl'+#key")
public HashMap<String, Object> createCache(String key, String value) {
log.info("createCache:"+key+"~~~~~");
HashMap<String, Object> map = new HashMap<>();
map.put("name", "馮剛剛");
map.put("age", "18歲");
map.put(key, value);
return map;
}
@Override
@Cacheable(value = "myCache", key = "'EhCacheServiceImpl'+#key")
public HashMap<String, Object> getCache(String key) {
return null;
}
@Override
@CacheEvict(value = "myCache", key = "'EhCacheServiceImpl'+#key")
public void delCache(String key) {
log.info("delCache:"+key+"~~~~~");
return;
}
}
- 緩存控制層
package com.shenmazong.zg2.controller;
import com.shenmazong.zg2.service.EhCacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author 軍哥
* @version 1.0
* @description: 緩存控制類
* @date 2023/10/15 19:46
*/
@RestController
@RequestMapping(value = "/cache")
public class EhCacheController {
@Autowired
EhCacheService ehCacheService;
@PostMapping(value = "/create")
public Object create() {
return ehCacheService.createCache("name", "張飛");
}
@PostMapping(value = "/get")
public Object get() {
return ehCacheService.getCache("name");
}
@PostMapping(value = "/delete")
public Object delete() {
ehCacheService.delCache("name");
return "OK";
}
}
- 刪除所有緩存
@Override
@CacheEvict(value = "myCache", allEntries = true)
public void delCacheAll() {
}
5、通過注解使用ehcache
package com.shenmazong.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@Slf4j
@RequestMapping(value = "/eh")
public class EhController {
@Autowired
EhCacheCacheManager cacheManager;
/**
* 放入緩存
* @param code
* @return
*/
@GetMapping(value = "/put")
@ResponseBody
public Object put(@RequestParam("code") String code) {
cacheManager.getCache("myCache").put("userCode", code);
return "OK";
}
/**
* 從緩存中取數(shù)據(jù)
* @return
*/
@GetMapping(value = "/get")
@ResponseBody
public Object get() {
String userCode = cacheManager.getCache("myCache").get("userCode", String.class);
if(userCode != null) {
System.out.println(userCode);
return userCode;
}
return "NO DATA";
}
/**
* 從緩存中刪除數(shù)據(jù)
* @return
*/
@GetMapping(value = "/del")
@ResponseBody
public Object del() {
cacheManager.getCache("myCache").evict("userCode");
return "OK";
}
/**
* 刪除所有緩存
* @return
*/
@GetMapping(value = "/delAll")
public Object delAll() {
cacheManager.getCache("myCache").clear();
return "OK";
}
}
到了這里,關(guān)于如何在Spring Boot中使用EhCache緩存的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!