原文地址:http://www.cnblogs.com/rollenholt/p/4202631.html
快取
是實際工作中非常常用的一種提高效能的方法, 我們會在許多場景下來使用快取。
本文通過一個簡單的例子進行展開,通過對比我們原來的自定義快取和 spring 的基於註釋的 cache 配置方法,展現了 spring cache 的強大之處,然後介紹了其基本的原理,擴充套件點和使用場景的限制。通過閱讀本文,你應該可以短時間內掌握 spring 帶來的強大快取技術,在很少的配置下即可給既有程式碼提供快取能力。
概述
Spring 3.1 引入了激動人心的基於註釋(annotation)的快取(cache)技術,它本質上不是一個具體的快取實現方案(例如EHCache 或者 OSCache),而是一個對快取使用的抽象,通過在既有程式碼中新增少量它定義的各種 annotation,即能夠達到快取方法的返回物件的效果。
Spring 的快取技術還具備相當的靈活性,不僅能夠使用 SpEL(Spring Expression Language)來定義快取的 key 和各種 condition,還提供開箱即用的快取臨時儲存方案,也支援和主流的專業快取例如 EHCache 整合。
其特點總結如下:
- 通過少量的配置 annotation 註釋即可使得既有程式碼支援快取
- 支援開箱即用 Out-Of-The-Box,即不用安裝和部署額外第三方元件即可使用快取
- 支援 Spring Express Language,能使用物件的任何屬性或者方法來定義快取的 key 和 condition
- 支援 AspectJ,並通過其實現任何方法的快取支援
- 支援自定義 key 和自定義快取管理者,具有相當的靈活性和擴充套件性
本文將針對上述特點對 Spring cache 進行詳細的介紹,主要通過一個簡單的例子和原理介紹展開,然後我們將一起看一個比較實際的快取例子,最後會介紹 spring cache 的使用限制和注意事項。好吧,讓我們開始吧
我們以前如何自己實現快取的呢
這裡先展示一個完全自定義的快取實現,即不用任何第三方的元件來實現某種物件的記憶體快取。
場景如下:
對一個賬號查詢方法做快取,以賬號名稱為 key,賬號物件為 value,當以相同的賬號名稱查詢賬號的時候,直接從快取中返回結果,否則更新快取。賬號查詢服務還支援 reload 快取(即清空快取)
首先定義一個實體類:賬號類,具備基本的 id 和 name 屬性,且具備 getter 和 setter 方法
public class Account {
private int id;
private String name;
public Account(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
然後定義一個快取管理器,這個管理器負責實現快取邏輯,支援物件的增加、修改和刪除,支援值物件的泛型。如下:
import com.google.common.collect.Maps;
import java.util.Map;
/**
* @author wenchao.ren
* 2015/1/5.
*/
public class CacheContext<T> {
private Map<String, T> cache = Maps.newConcurrentMap();
public T get(String key){
return cache.get(key);
}
public void addOrUpdateCache(String key,T value) {
cache.put(key, value);
}
// 根據 key 來刪除快取中的一條記錄
public void evictCache(String key) {
if(cache.containsKey(key)) {
cache.remove(key);
}
}
// 清空快取中的所有記錄
public void evictCache() {
cache.clear();
}
}
好,現在我們有了實體類和一個快取管理器,還需要一個提供賬號查詢的服務類,此服務類使用快取管理器來支援賬號查詢快取,如下:
import com.google.common.base.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* @author wenchao.ren
* 2015/1/5.
*/
@Service
public class AccountService1 {
private final Logger logger = LoggerFactory.getLogger(AccountService1.class);
@Resource
private CacheContext<Account> accountCacheContext;
public Account getAccountByName(String accountName) {
Account result = accountCacheContext.get(accountName);
if (result != null) {
logger.info("get from cache... {}", accountName);
return result;
}
Optional<Account> accountOptional = getFromDB(accountName);
if (!accountOptional.isPresent()) {
throw new IllegalStateException(String.format("can not find account by account name : [%s]", accountName));
}
Account account = accountOptional.get();
accountCacheContext.addOrUpdateCache(accountName, account);
return account;
}
public void reload() {
accountCacheContext.evictCache();
}
private Optional<Account> getFromDB(String accountName) {
logger.info("real querying db... {}", accountName);
//Todo query data from database
return Optional.fromNullable(new Account(accountName));
}
}
現在我們開始寫一個測試類,用於測試剛才的快取是否有效
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import static org.junit.Assert.*;
public class AccountService1Test {
private AccountService1 accountService1;
private final Logger logger = LoggerFactory.getLogger(AccountService1Test.class);
@Before
public void setUp() throws Exception {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext1.xml");
accountService1 = context.getBean("accountService1", AccountService1.class);
}
@Test
public void testInject(){
assertNotNull(accountService1);
}
@Test
public void testGetAccountByName() throws Exception {
accountService1.getAccountByName("accountName");
accountService1.getAccountByName("accountName");
accountService1.reload();
logger.info("after reload ....");
accountService1.getAccountByName("accountName");
accountService1.getAccountByName("accountName");
}
}
按照分析,執行結果應該是:首先從資料庫查詢,然後直接返回快取中的結果,重置快取後,應該先從資料庫查詢,然後返回快取中的結果. 檢視程式執行的日誌如下:
00:53:17.166 [main] INFO c.r.s.cache.example1.AccountService - real querying db... accountName
00:53:17.168 [main] INFO c.r.s.cache.example1.AccountService - get from cache... accountName
00:53:17.168 [main] INFO c.r.s.c.example1.AccountServiceTest - after reload ....
00:53:17.168 [main] INFO c.r.s.cache.example1.AccountService - real querying db... accountName
00:53:17.169 [main] INFO c.r.s.cache.example1.AccountService - get from cache... accountName
可以看出我們的快取起效了,但是這種自定義的快取方案有如下劣勢:
- 快取程式碼和業務程式碼耦合度太高,如上面的例子,AccountService 中的 getAccountByName()方法中有了太多快取的邏輯,不便於維護和變更
- 不靈活,這種快取方案不支援按照某種條件的快取,比如只有某種型別的賬號才需要快取,這種需求會導致程式碼的變更
- 快取的儲存這塊寫的比較死,不能靈活的切換為使用第三方的快取模組
如果你的程式碼中有上述程式碼的影子,那麼你可以考慮按照下面的介紹來優化一下你的程式碼結構了,也可以說是簡化,你會發現,你的程式碼會變得優雅的多!
Spring cache是如何做的呢
我們對AccountService1 進行修改,建立AccountService2:
import com.google.common.base.Optional;
import com.rollenholt.spring.cache.example1.Account;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
/**
* @author wenchao.ren
* 2015/1/5.
*/
@Service
public class AccountService2 {
private final Logger logger = LoggerFactory.getLogger(AccountService2.class);
// 使用了一個快取名叫 accountCache
@Cacheable(value="accountCache")
public Account getAccountByName(String accountName) {
// 方法內部實現不考慮快取邏輯,直接實現業務
logger.info("real querying account... {}", accountName);
Optional<Account> accountOptional = getFromDB(accountName);
if (!accountOptional.isPresent()) {
throw new IllegalStateException(String.format("can not find account by account name : [%s]", accountName));
}
return accountOptional.get();
}
private Optional<Account> getFromDB(String accountName) {
logger.info("real querying db... {}", accountName);
//Todo query data from database
return Optional.fromNullable(new Account(accountName));
}
}
我們注意到在上面的程式碼中有一行:
@Cacheable(value="accountCache")
這個註釋的意思是,當呼叫這個方法的時候,會從一個名叫 accountCache 的快取中查詢,如果沒有,則執行實際的方法(即查詢資料庫),並將執行的結果存入快取中,否則返回快取中的物件。這裡的快取中的 key 就是引數 accountName,value 就是 Account 物件。“accountCache”快取是在 spring*.xml 中定義的名稱。我們還需要一個 spring 的配置檔案來支援基於註釋的快取
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd">
<context:component-scan base-package="com.rollenholt.spring.cache"/>
<context:annotation-config/>
<cache:annotation-driven/>
<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
<property name="caches">
<set>
<bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean">
<property name="name" value="default"/>
</bean>
<bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean">
<property name="name" value="accountCache"/>
</bean>
</set>
</property>
</bean>
</beans>
注意這個 spring 配置檔案有一個關鍵的支援快取的配置項:
<cache:annotation-driven />
這個配置項預設使用了一個名字叫 cacheManager 的快取管理器,這個快取管理器有一個 spring 的預設實現,即 org.springframework.cache.support.SimpleCacheManager
,這個快取管理器實現了我們剛剛自定義的快取管理器的邏輯,它需要配置一個屬性 caches,即此快取管理器管理的快取集合,除了預設的名字叫 default 的快取,我們還自定義了一個名字叫 accountCache 的快取,使用了預設的記憶體儲存方案 ConcurrentMapCacheFactoryBea
n,它是基於 java.util.concurrent.ConcurrentHashMap
的一個記憶體快取實現方案。
然後我們編寫測試程式:
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import static org.junit.Assert.*;
public class AccountService2Test {
private AccountService2 accountService2;
private final Logger logger = LoggerFactory.getLogger(AccountService2Test.class);
@Before
public void setUp() throws Exception {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext2.xml");
accountService2 = context.getBean("accountService2", AccountService2.class);
}
@Test
public void testInject(){
assertNotNull(accountService2);
}
@Test
public void testGetAccountByName() throws Exception {
logger.info("first query...");
accountService2.getAccountByName("accountName");
logger.info("second query...");
accountService2.getAccountByName("accountName");
}
}
上面的測試程式碼主要進行了兩次查詢,第一次應該會查詢資料庫,第二次應該返回快取,不再查資料庫,我們執行一下,看看結果
01:10:32.435 [main] INFO c.r.s.c.example2.AccountService2Test - first query...
01:10:32.456 [main] INFO c.r.s.cache.example2.AccountService2 - real querying account... accountName
01:10:32.457 [main] INFO c.r.s.cache.example2.AccountService2 - real querying db... accountName
01:10:32.458 [main] INFO c.r.s.c.example2.AccountService2Test - second query...
可以看出我們設定的基於註釋的快取起作用了,而在 AccountService.java 的程式碼中,我們沒有看到任何的快取邏輯程式碼,只有一行註釋:@Cacheable(value="accountCache"),就實現了基本的快取方案,是不是很強大?
如何清空快取
好,到目前為止,我們的 spring cache 快取程式已經執行成功了,但是還不完美,因為還缺少一個重要的快取管理邏輯:清空快取.
當賬號資料發生變更,那麼必須要清空某個快取,另外還需要定期的清空所有快取,以保證快取資料的可靠性。
為了加入清空快取的邏輯,我們只要對 AccountService2.java 進行修改,從業務邏輯的角度上看,它有兩個需要清空快取的地方
- 當外部呼叫更新了賬號,則我們需要更新此賬號對應的快取
- 當外部呼叫說明重新載入,則我們需要清空所有快取
我們在AccountService2的基礎上進行修改,修改為AccountService3,程式碼如下:
import com.google.common.base.Optional;
import com.rollenholt.spring.cache.example1.Account;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
/**
* @author wenchao.ren
* 2015/1/5.
*/
@Service
public class AccountService3 {
private final Logger logger = LoggerFactory.getLogger(AccountService3.class);
// 使用了一個快取名叫 accountCache
@Cacheable(value="accountCache")
public Account getAccountByName(String accountName) {
// 方法內部實現不考慮快取邏輯,直接實現業務
logger.info("real querying account... {}", accountName);
Optional<Account> accountOptional = getFromDB(accountName);
if (!accountOptional.isPresent()) {
throw new IllegalStateException(String.format("can not find account by account name : [%s]", accountName));
}
return accountOptional.get();
}
@CacheEvict(value="accountCache",key="#account.getName()")
public void updateAccount(Account account) {
updateDB(account);
}
@CacheEvict(value="accountCache",allEntries=true)
public void reload() {
}
private void updateDB(Account account) {
logger.info("real update db...{}", account.getName());
}
private Optional<Account> getFromDB(String accountName) {
logger.info("real querying db... {}", accountName);
//Todo query data from database
return Optional.fromNullable(new Account(accountName));
}
}
我們的測試程式碼如下:
import com.rollenholt.spring.cache.example1.Account;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AccountService3Test {
private AccountService3 accountService3;
private final Logger logger = LoggerFactory.getLogger(AccountService3Test.class);
@Before
public void setUp() throws Exception {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext2.xml");
accountService3 = context.getBean("accountService3", AccountService3.class);
}
@Test
public void testGetAccountByName() throws Exception {
logger.info("first query.....");
accountService3.getAccountByName("accountName");
logger.info("second query....");
accountService3.getAccountByName("accountName");
}
@Test
public void testUpdateAccount() throws Exception {
Account account1 = accountService3.getAccountByName("accountName1");
logger.info(account1.toString());
Account account2 = accountService3.getAccountByName("accountName2");
logger.info(account2.toString());
account2.setId(121212);
accountService3.updateAccount(account2);
// account1會走快取
account1 = accountService3.getAccountByName("accountName1");
logger.info(account1.toString());
// account2會查詢db
account2 = accountService3.getAccountByName("accountName2");
logger.info(account2.toString());
}
@Test
public void testReload() throws Exception {
accountService3.reload();
// 這2行查詢資料庫
accountService3.getAccountByName("somebody1");
accountService3.getAccountByName("somebody2");
// 這兩行走快取
accountService3.getAccountByName("somebody1");
accountService3.getAccountByName("somebody2");
}
}
在這個測試程式碼中我們重點關注testUpdateAccount()
方法,在測試程式碼中我們已經註釋了在update完account2以後,再次查詢的時候,account1會走快取,而account2不會走快取,而去查詢db,觀察程式執行日誌,執行日誌為:
01:37:34.549 [main] INFO c.r.s.cache.example3.AccountService3 - real querying account... accountName1
01:37:34.551 [main] INFO c.r.s.cache.example3.AccountService3 - real querying db... accountName1
01:37:34.552 [main] INFO c.r.s.c.example3.AccountService3Test - Account{id=0, name='accountName1'}
01:37:34.553 [main] INFO c.r.s.cache.example3.AccountService3 - real querying account... accountName2
01:37:34.553 [main] INFO c.r.s.cache.example3.AccountService3 - real querying db... accountName2
01:37:34.555 [main] INFO c.r.s.c.example3.AccountService3Test - Account{id=0, name='accountName2'}
01:37:34.555 [main] INFO c.r.s.cache.example3.AccountService3 - real update db...accountName2
01:37:34.595 [main] INFO c.r.s.c.example3.AccountService3Test - Account{id=0, name='accountName1'}
01:37:34.596 [main] INFO c.r.s.cache.example3.AccountService3 - real querying account... accountName2
01:37:34.596 [main] INFO c.r.s.cache.example3.AccountService3 - real querying db... accountName2
01:37:34.596 [main] INFO c.r.s.c.example3.AccountService3Test - Account{id=0, name='accountName2'}
我們會發現實際執行情況和我們預估的結果是一致的。
如何按照條件操作快取
前面介紹的快取方法,沒有任何條件,即所有對 accountService 物件的 getAccountByName 方法的呼叫都會起動快取效果,不管引數是什麼值。
如果有一個需求,就是隻有賬號名稱的長度小於等於 4 的情況下,才做快取,大於 4 的不使用快取
雖然這個需求比較坑爹,但是拋開需求的合理性,我們怎麼實現這個功能呢?
通過檢視CacheEvict
註解的定義,我們會發現:
/**
* Annotation indicating that a method (or all methods on a class) trigger(s)
* a cache invalidate operation.
*
* @author Costin Leau
* @author Stephane Nicoll
* @since 3.1
* @see CacheConfig
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface CacheEvict {
/**
* Qualifier value for the specified cached operation.
* <p>May be used to determine the target cache (or caches), matching the qualifier
* value (or the bean name(s)) of (a) specific bean definition.
*/
String[] value() default {};
/**
* Spring Expression Language (SpEL) attribute for computing the key dynamically.
* <p>Default is "", meaning all method parameters are considered as a key, unless
* a custom {@link #keyGenerator()} has been set.
*/
String key() default "";
/**
* The bean name of the custom {@link org.springframework.cache.interceptor.KeyGenerator} to use.
* <p>Mutually exclusive with the {@link #key()} attribute.
*/
String keyGenerator() default "";
/**
* The bean name of the custom {@link org.springframework.cache.CacheManager} to use to
* create a default {@link org.springframework.cache.interceptor.CacheResolver} if none
* is set already.
* <p>Mutually exclusive with the {@link #cacheResolver()} attribute.
* @see org.springframework.cache.interceptor.SimpleCacheResolver
*/
String cacheManager() default "";
/**
* The bean name of the custom {@link org.springframework.cache.interceptor.CacheResolver} to use.
*/
String cacheResolver() default "";
/**
* Spring Expression Language (SpEL) attribute used for conditioning the method caching.
* <p>Default is "", meaning the method is always cached.
*/
String condition() default "";
/**
* Whether or not all the entries inside the cache(s) are removed or not. By
* default, only the value under the associated key is removed.
* <p>Note that setting this parameter to {@code true} and specifying a {@link #key()}
* is not allowed.
*/
boolean allEntries() default false;
/**
* Whether the eviction should occur after the method is successfully invoked (default)
* or before. The latter causes the eviction to occur irrespective of the method outcome (whether
* it threw an exception or not) while the former does not.
*/
boolean beforeInvocation() default false;
}
定義中有一個condition
描述:
Spring Expression Language (SpEL) attribute used for conditioning the method caching.Default is "", meaning the method is always cached.
我們可以利用這個方法來完成這個功能,下面只給出示例程式碼:
@Cacheable(value="accountCache",condition="#accountName.length() <= 4")// 快取名叫 accountCache
public Account getAccountByName(String accountName) {
// 方法內部實現不考慮快取邏輯,直接實現業務
return getFromDB(accountName);
}
注意其中的 condition=”#accountName.length() <=4”
,這裡使用了 SpEL 表示式訪問了引數 accountName 物件的 length() 方法,條件表示式返回一個布林值,true/false,當條件為 true,則進行快取操作,否則直接呼叫方法執行的返回結果。
如果有多個引數,如何進行 key 的組合
我們看看CacheEvict
註解的key()
方法的描述:
Spring Expression Language (SpEL) attribute for computing the key dynamically. Default is "", meaning all method parameters are considered as a key, unless a custom {@link #keyGenerator()} has been set.
假設我們希望根據物件相關屬性的組合來進行快取,比如有這麼一個場景:
要求根據賬號名、密碼和是否傳送日誌查詢賬號資訊
很明顯,這裡我們需要根據賬號名、密碼對賬號物件進行快取,而第三個引數“是否傳送日誌”對快取沒有任何影響。所以,我們可以利用 SpEL 表示式對快取 key 進行設計
我們為Account類增加一個password 屬性, 然後修改AccountService程式碼:
@Cacheable(value="accountCache",key="#accountName.concat(#password)")
public Account getAccount(String accountName,String password,boolean sendLog) {
// 方法內部實現不考慮快取邏輯,直接實現業務
return getFromDB(accountName,password);
}
注意上面的 key 屬性,其中引用了方法的兩個引數 accountName 和 password,而 sendLog 屬性沒有考慮,因為其對快取沒有影響。
accountService.getAccount("accountName", "123456", true);// 查詢資料庫
accountService.getAccount("accountName", "123456", true);// 走快取
accountService.getAccount("accountName", "123456", false);// 走快取
accountService.getAccount("accountName", "654321", true);// 查詢資料庫
accountService.getAccount("accountName", "654321", true);// 走快取
如何做到:既要保證方法被呼叫,又希望結果被快取
根據前面的例子,我們知道,如果使用了 @Cacheable 註釋,則當重複使用相同引數呼叫方法的時候,方法本身不會被呼叫執行,即方法本身被略過了,取而代之的是方法的結果直接從快取中找到並返回了。
現實中並不總是如此,有些情況下我們希望方法一定會被呼叫,因為其除了返回一個結果,還做了其他事情,例如記錄日誌,呼叫介面等,這個時候,我們可以用 @CachePut
註釋,這個註釋可以確保方法被執行,同時方法的返回值也被記錄到快取中。
@Cacheable(value="accountCache")
public Account getAccountByName(String accountName) {
// 方法內部實現不考慮快取邏輯,直接實現業務
return getFromDB(accountName);
}
// 更新 accountCache 快取
@CachePut(value="accountCache",key="#account.getName()")
public Account updateAccount(Account account) {
return updateDB(account);
}
private Account updateDB(Account account) {
logger.info("real updating db..."+account.getName());
return account;
}
我們的測試程式碼如下
Account account = accountService.getAccountByName("someone");
account.setPassword("123");
accountService.updateAccount(account);
account.setPassword("321");
accountService.updateAccount(account);
account = accountService.getAccountByName("someone");
logger.info(account.getPassword());
如上面的程式碼所示,我們首先用 getAccountByName 方法查詢一個人 someone 的賬號,這個時候會查詢資料庫一次,但是也記錄到快取中了。然後我們修改了密碼,呼叫了 updateAccount 方法,這個時候會執行資料庫的更新操作且記錄到快取,我們再次修改密碼並呼叫 updateAccount 方法,然後通過 getAccountByName 方法查詢,這個時候,由於快取中已經有資料,所以不會查詢資料庫,而是直接返回最新的資料,所以列印的密碼應該是“321”
@Cacheable、@CachePut、@CacheEvict 註釋介紹
- @Cacheable 主要針對方法配置,能夠根據方法的請求引數對其結果進行快取
- @CachePut 主要針對方法配置,能夠根據方法的請求引數對其結果進行快取,和 @Cacheable 不同的是,它每次都會觸發真實方法的呼叫
-@CachEvict 主要針對方法配置,能夠根據一定的條件對快取進行清空
基本原理
一句話介紹就是Spring AOP的動態代理技術。 如果讀者對Spring AOP不熟悉的話,可以去看看官方文件
擴充套件性
直到現在,我們已經學會了如何使用開箱即用的 spring cache,這基本能夠滿足一般應用對快取的需求。
但現實總是很複雜,當你的使用者量上去或者效能跟不上,總需要進行擴充套件,這個時候你或許對其提供的記憶體快取不滿意了,因為其不支援高可用性,也不具備持久化資料能力,這個時候,你就需要自定義你的快取方案了。
還好,spring 也想到了這一點。我們先不考慮如何持久化快取,畢竟這種第三方的實現方案很多。
我們要考慮的是,怎麼利用 spring 提供的擴充套件點實現我們自己的快取,且在不改原來已有程式碼的情況下進行擴充套件。
首先,我們需要提供一個 CacheManager
介面的實現,這個介面告訴 spring 有哪些 cache 例項,spring 會根據 cache 的名字查詢 cache 的例項。另外還需要自己實現 Cache 介面,Cache 介面負責實際的快取邏輯,例如增加鍵值對、儲存、查詢和清空等。
利用 Cache 介面,我們可以對接任何第三方的快取系統,例如 EHCache
、OSCache
,甚至一些記憶體資料庫例如 memcache
或者 redis
等。下面我舉一個簡單的例子說明如何做。
import java.util.Collection;
import org.springframework.cache.support.AbstractCacheManager;
public class MyCacheManager extends AbstractCacheManager {
private Collection<? extends MyCache> caches;
/**
* Specify the collection of Cache instances to use for this CacheManager.
*/
public void setCaches(Collection<? extends MyCache> caches) {
this.caches = caches;
}
@Override
protected Collection<? extends MyCache> loadCaches() {
return this.caches;
}
}
上面的自定義的 CacheManager 實際繼承了 spring 內建的 AbstractCacheManager,實際上僅僅管理 MyCache 類的例項。
下面是MyCache的定義:
import java.util.HashMap;
import java.util.Map;
import org.springframework.cache.Cache;
import org.springframework.cache.support.SimpleValueWrapper;
public class MyCache implements Cache {
private String name;
private Map<String,Account> store = new HashMap<String,Account>();;
public MyCache() {
}
public MyCache(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public Object getNativeCache() {
return store;
}
@Override
public ValueWrapper get(Object key) {
ValueWrapper result = null;
Account thevalue = store.get(key);
if(thevalue!=null) {
thevalue.setPassword("from mycache:"+name);
result = new SimpleValueWrapper(thevalue);
}
return result;
}
@Override
public void put(Object key, Object value) {
Account thevalue = (Account)value;
store.put((String)key, thevalue);
}
@Override
public void evict(Object key) {
}
@Override
public void clear() {
}
}
上面的自定義快取只實現了很簡單的邏輯,但這是我們自己做的,也很令人激動是不是,主要看 get 和 put 方法,其中的 get 方法留了一個後門,即所有的從快取查詢返回的物件都將其 password 欄位設定為一個特殊的值,這樣我們等下就能演示“我們的快取確實在起作用!”了。
這還不夠,spring 還不知道我們寫了這些東西,需要通過 spring*.xml 配置檔案告訴它
<cache:annotation-driven />
<bean id="cacheManager" class="com.rollenholt.spring.cache.MyCacheManager">
<property name="caches">
<set>
<bean
class="com.rollenholt.spring.cache.MyCache"
p:name="accountCache" />
</set>
</property>
</bean>
接下來我們來編寫測試程式碼:
Account account = accountService.getAccountByName("someone");
logger.info("passwd={}", account.getPassword());
account = accountService.getAccountByName("someone");
logger.info("passwd={}", account.getPassword());
上面的測試程式碼主要是先呼叫 getAccountByName 進行一次查詢,這會呼叫資料庫查詢,然後快取到 mycache 中,然後我列印密碼,應該是空的;下面我再次查詢 someone 的賬號,這個時候會從 mycache 中返回快取的例項,記得上面的後門麼?我們修改了密碼,所以這個時候列印的密碼應該是一個特殊的值
注意和限制
基於 proxy 的 spring aop 帶來的內部呼叫問題
上面介紹過 spring cache 的原理,即它是基於動態生成的 proxy 代理機制來對方法的呼叫進行切面,這裡關鍵點是物件的引用問題.
如果物件的方法是內部呼叫(即 this 引用)而不是外部引用,則會導致 proxy 失效,那麼我們的切面就失效,也就是說上面定義的各種註釋包括 @Cacheable、@CachePut 和 @CacheEvict 都會失效,我們來演示一下。
public Account getAccountByName2(String accountName) {
return this.getAccountByName(accountName);
}
@Cacheable(value="accountCache")// 使用了一個快取名叫 accountCache
public Account getAccountByName(String accountName) {
// 方法內部實現不考慮快取邏輯,直接實現業務
return getFromDB(accountName);
}
上面我們定義了一個新的方法 getAccountByName2,其自身呼叫了 getAccountByName 方法,這個時候,發生的是內部呼叫(this),所以沒有走 proxy,導致 spring cache 失效
要避免這個問題,就是要避免對快取方法的內部呼叫,或者避免使用基於 proxy 的 AOP 模式,可以使用基於 aspectJ 的 AOP 模式來解決這個問題。
@CacheEvict 的可靠性問題
我們看到,@CacheEvict
註釋有一個屬性 beforeInvocation
,預設為 false,即預設情況下,都是在實際的方法執行完成後,才對快取進行清空操作。期間如果執行方法出現異常,則會導致快取清空不被執行。我們演示一下
// 清空 accountCache 快取
@CacheEvict(value="accountCache",allEntries=true)
public void reload() {
throw new RuntimeException();
}
我們的測試程式碼如下:
accountService.getAccountByName("someone");
accountService.getAccountByName("someone");
try {
accountService.reload();
} catch (Exception e) {
//...
}
accountService.getAccountByName("someone");
注意上面的程式碼,我們在 reload 的時候丟擲了執行期異常,這會導致清空快取失敗。上面的測試程式碼先查詢了兩次,然後 reload,然後再查詢一次,結果應該是隻有第一次查詢走了資料庫,其他兩次查詢都從快取,第三次也走快取因為 reload 失敗了。
那麼我們如何避免這個問題呢?我們可以用 @CacheEvict 註釋提供的 beforeInvocation 屬性,將其設定為 true,這樣,在方法執行前我們的快取就被清空了。可以確保快取被清空。
非 public 方法問題
和內部呼叫問題類似,非 public 方法如果想實現基於註釋的快取,必須採用基於 AspectJ 的 AOP 機制
Dummy CacheManager 的配置和作用
有的時候,我們在程式碼遷移、除錯或者部署的時候,恰好沒有 cache 容器,比如 memcache 還不具備條件,h2db 還沒有裝好等,如果這個時候你想除錯程式碼,豈不是要瘋掉?這裡有一個辦法,在不具備快取條件的時候,在不改程式碼的情況下,禁用快取。
方法就是修改 spring*.xml 配置檔案,設定一個找不到快取就不做任何操作的標誌位,如下
<cache:annotation-driven />
<bean id="simpleCacheManager" class="org.springframework.cache.support.SimpleCacheManager">
<property name="caches">
<set>
<bean
class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"
p:name="default" />
</set>
</property>
</bean>
<bean id="cacheManager" class="org.springframework.cache.support.CompositeCacheManager">
<property name="cacheManagers">
<list>
<ref bean="simpleCacheManager" />
</list>
</property>
<property name="fallbackToNoOpCache" value="true" />
</bean>
注意以前的 cacheManager 變為了 simpleCacheManager,且沒有配置 accountCache 例項,後面的 cacheManager 的例項是一個 CompositeCacheManager,他利用了前面的 simpleCacheManager 進行查詢,如果查詢不到,則根據標誌位 fallbackToNoOpCache 來判斷是否不做任何快取操作。
使用 guava cache
<bean id="cacheManager" class="org.springframework.cache.guava.GuavaCacheManager">
<property name="cacheSpecification" value="concurrencyLevel=4,expireAfterAccess=100s,expireAfterWrite=100s" />
<property name="cacheNames">
<list>
<value>dictTableCache</value>
</list>
</property>
</bean>