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>

但是我加了這個依賴啓動會報錯 所以就註釋掉了。

然後在resource下面創建EhCache.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>


<defaultCache maxElementsInMemory="10000" eternal="false"
	timeToIdleSeconds="120" timeToLiveSeconds="120"
	maxElementsOnDisk="10000000" diskExpiryThreadIntervalSeconds="120"
	memoryStoreEvictionPolicy="LRU">
	<persistence strategy="localTempSwap" />
</defaultCache>


<cache name="userCache" eternal="false" timeToIdleSeconds="2400"
	timeToLiveSeconds="2400" maxEntriesLocalHeap="10000"
	maxEntriesLocalDisk="10000000" diskExpiryThreadIntervalSeconds="120"
	overflowToDisk="false" memoryStoreEvictionPolicy="LRU">
</cache>

name:緩存名稱。
maxElementsInMemory:緩存最大個數。
eternal:對象是否永久有效,一但設置了,timeout將不起作用。
timeToIdleSeconds:設置對象在失效前的允許閒置時間(單位:秒)。僅當eternal=false對象不是永久有效時使用,可選屬性,默認值是0,也就是可閒置時間無窮大。
timeToLiveSeconds:設置對象在失效前允許存活時間(單位:秒)。最大時間介於創建時間和失效時間之間。僅當eternal=false對象不是永久有效時使用,默認是0.,也就是對象存活時間無窮大。
overflowToDisk:當內存中對象數量達到maxElementsInMemory時,Ehcache將會對象寫到磁盤中。 diskSpoolBufferSizeMB:這個參數設置DiskStore(磁盤緩存)的緩存區大小。默認是30MB。每個Cache都應該有自己的一個緩衝區。
maxElementsOnDisk:硬盤最大緩存個數。
diskPersistent:是否緩存虛擬機重啓期數據 Whether the diskstore persists between restarts of the Virtual Machine. The default value is false.
diskExpiryThreadIntervalSeconds:磁盤失效線程運行時間間隔,默認是120秒。
memoryStoreEvictionPolicy:當達到maxElementsInMemory限制時,Ehcache將會根據指定的策略去清理內存。默認策略是LRU(最近最少使用)。你可以設置爲FIFO(先進先出)或是LFU(較少使用)。  

Ehcache 的三種清空策略

1 FIFO,first in first out,這個是大家最熟的,先進先出。

2 LFU, Less Frequently Used,就是上面例子中使用的策略,直白一點就是講一直以來

最少被使用的。如上面所講,緩存的元素有一個 hit 屬性,hit 值最小的將會被清出緩存。

3 LRU,Least Recently Used,最近最少使用的,緩存的元素有一個時間戳,當緩存容量

滿了,而又需要騰出地方來緩存新的元素的時候,那麼現有緩存元素中時間戳離當前時

間最遠的元素將被清出緩存

 

clearOnFlush:內存數量最大時是否清除。

 

在service層中使用

@Service
@CacheConfig(cacheNames = { "userCache" })
public class User1Service {

	private static final String CACHE_KEY = "'person'";// 這裏一定要加單引號,否則會被當做一個正常的字符串來識別

	private static final String CACHE_NAME = "userCache";// 對應ehcache.xml中cache的name

	@Autowired
	private User1Mapper mapper1;
	
	@Autowired
	private CacheManager manager;

	@Cacheable(value = CACHE_NAME, key = "'person_'+#id")
	public UserDemo findOne(Integer id) {

		System.out.println(id);
		return mapper1.findOne(id);
	}

	@CachePut(value = CACHE_NAME, key = CACHE_KEY)
	public UserDemo saveOne(UserDemo user) {
		return mapper1.save(user);
	}
	
	@CacheEvict(value=CACHE_NAME,key="'person_'+#id")
        public void deleteOne(String username) {
            mapper1.delete(username);
        }
	
	public void clear() {
		manager.getCache("userCache").clear();
	}
}

@CacheConfig: 指定緩存配置的名稱,這裏可以配置多個,多個用逗號分開
private static final String CACHE_KEY = "'person'";這個地方要特別注意,一定要寫單引號,否則表達式會把它當做一個正常的字符串來解析的
@Cacheable:類或者方法上,類代表所有的方法都使用它,方法上針對特定的方法,作用就是先查詢緩存是否有值,有的話就直接返回緩存結果
@CachePut:標註在方法上, Spring在每次執行前都會檢查Cache中是否存在相同key的緩存元素,如果存在就不再執行該方法,而是直接從緩存中獲取結果進行返回,否則纔會執行並將返回結果存入指定的緩存中
@CacheEvict:標註在方法或類上,做值的清除
上面三個註解有幾個公有的參數:

value():值必須填寫,是指定屬於ehcache.xml中cache的name,可以是多個
key:自定義策略和默認策略
自定義策略:使用方法參數時我們可以直接使用“#參數名”或者“#p參數index”

condition:指定緩存的條件
 

這裏的clear方法是清空緩存。getCache方法的參數就是xml配置中cache的name。

調用findOne方法傳一個id,獲取到一條數據,然後在數據庫中把該條數據刪除 ,再調用方法依然可以獲取到,便是從內存中讀取的。如果在獲取過一次數據後調用clear方法,清空緩存數據,再調用findOne方法便讀不到數據了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章