Spring緩存 cache:
jar包
org.springframework:spring-context-support:4.1.7.RELEASE
com.googlecode.ehcache-spring-annotations:ehcache-spring-annotations:1.2.0
net.sf.ehcache:ehcache:2.10.1
配置文件:application-ecache.xml內配置緩存相關設置:
<span style="font-size:10px;"><?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
<!-- 1)最好在ehcache.xml中聲明不進行updateCheck -->
<!-- 2)爲了配合BigMemory和Size Limit,原來的屬性最好改名 -->
<!-- maxElementsInMemory->maxEntriesLocalHeap -->
<!-- maxElementsOnDisk->maxEntriesLocalDisk -->
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="0"
timeToLiveSeconds="0"
overflowToDisk="false"/>
<cache name="cache"
maxElementsOnDisk="20000"
maxElementsInMemory="2000"
eternal="true"
overflowToDisk="false"
diskPersistent="true"/>
</ehcache></span>
不懂可百度。
調用方式-註解
我是在數據層調用的,創建緩存的時候注意到緩存的value和key,要注意value必須是在xml配置中 cache name屬性中存在的。
我目前只瞭解一些普通用法,花式用法... ...沒去了解o(︶︿︶)o
底層sql弄好,那些就不講了,然後數據層調用相應方法。例如sql文件或者寫sql的類 的名字爲mapper(.xml/.java),裏面有個sql語句是select和update,調用這兩個方法的類叫做Dao,實體類叫做Domain。
調用註解:
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;
import Mapper;
import Domain;
@Repository("dao")
public class Dao{
@Resource
private Mapper mapper;
/**
* 查詢所有字段配置
*/
@Cacheable(value = "<span style="font-family: Arial, Helvetica, sans-serif;"><span style="font-size:10px;">cache</span></span>", key = "'key1'")
public Domain select() {
return mapper.select();
}
/**
* 修改字段顯示配置
*/
@CacheEvict(value = "<span style="font-size: 10px; font-family: Arial, Helvetica, sans-serif;">cache</span>", key = "'key1'")
public int update(Domain domain) {
return mapper.update(domain);
}
}
@cacheable(value="cache", key="key2"):
調用這個select方法時(該註解位於方法名上方)會從一個名叫cache的緩存中查詢,如果沒有,則會執行實際方法(數據庫操作---查詢,如果sql語句是查詢的話o(︶︿︶)o )並將執行的結果存入緩存中,否則返回緩存中的對象,其中key是方法參數,value是返回值類型,兩個參數是可選一個作爲key,這個value和key不是強制的,不信可以試試看。不加key的時候,cacheEvict的key就要注意下啦,它會是調用的相應的get... ...我也說不清楚,往下看看吧
<span style="white-space:pre"> </span>public Domain select(String name);
domain 爲cache的value name爲cache的key 這樣比較容易理解
@cacheEvict(value="cache", key="key1")
調用這個update方法後,會清空緩存,其中key指緩存中的key,可以試用SpEL表達式來獲取name值來作爲key---#domain.getName() 這個方法不予解釋o(︶︿︶)o
如果在cacheable時,有表名key,那就直接放key的名字。
屬性:value key就不再加進來了
allEntries:是否需要清空緩存中所有的元素(該緩存名中的)
一般不加,boolean值,默認爲false,就是不清空,也可以騷氣一點加上,然後還是等於false。當等於true的時候,就是清空所有,此時的key已經可有可無了。
beforelocation:是否在調用方法前清除(該緩存名中的)
一般不加,它的作用... ... 覺得目前我用不上啊,知道下就好了。boolean值,默認爲false。
爲true時會調用方法之前清除這個緩存,不會因爲執行失敗而不執行,爲false時,則會受到方法執行成功與否的影響。成功了調用,沒成功,就呵呵噠了。
@cachePut(value="cache"):
確保方法爲執行同時方法的返回值也被記錄到緩存中,實現緩存與數據庫同步更新。
@CachePut(value = "cache", key = "'key1'")
public Domain update(Domain domain) {
... ...
}
以上三個註解有一個共同的屬性 condition:
緩存條件可以爲空,使用SpEL編寫,返回值爲boolean,爲true時才執行