這兩日對Cache研究了一點,讀了一些源代碼,自己也寫了點code,借此假期也算是休閑加學習了。
什么時候用Cache?
在系統中,如果要考慮系統的性能,我們最好都使用Cache,在各個層次上都用上Cache,這樣的話可以盡最大程度的減少數據庫的壓力。估計現在的系統都在分層,vo,po,do(domain object);我們可以把這些東西能緩存的都緩存起來,當然要根據具體系統具體分析(Cache多長時間,Cache多少東西)。
Tip:公司的系統中,由于用一臺數據庫,數據庫的壓力一直都是一個很大的問題,timeout,too many connection,等問題應接不暇。
怎么用Cache?
估計每個公司都有自己的Cache framework,簡單的就是幾個類,麻煩的可以做個小的framework去包裝已有的opensource的cache provider。很多opensource的cache provider(例如:oscahe,ehcache)都對性能進行了優化,所以肯定性能比Map好很多,但是肯定不能拿過來就用,那樣的話每次調用的時候太過于麻煩,寫很多的類,很多的方法。所以說包裝是很重要的,建議包裝成一個Bus一樣的東西(CacheBus,叫做CacheManager比較好),這樣的話就可以在各個層次都向上面寫和讀了。
Tip: Cache就是key value,我們只要能寫好key-value怎么寫都可以的。這樣也讓系統變得簡單實用(更能體現OO)
Cache Provider
Oh,這方面太多東西了,oscache(貌似停止開發了),ehcache(被terracotta收購了,前途不錯),treecache(jbosstreecache大而全),memecached(很火了很久),nosql相關的東西(couchdb,mongodb)。Oh...不能忘記Map
其實用什么都可以,關鍵是用好,一般的解決方案很簡單,既然你要在系統中用Cache并且想風風火火的用一下,那就來個二級Cache,第一級用本地Cache(速度快,但是東西不能太多),第二級,用memcached (能存放大的東東,便宜)。第一級Cache上3分鐘(自己要調試確定時間),自動收割到第二級Cache中。
什么在第一級Cache中永遠存活? 小的,永遠都要用的,例如用戶信息,Site信息,一些template等。
特別強調一下
nosql 這方面mongodb和couchdb做的很好,在document相關的東西,可以緩存到這里面,例如:系統要在半天后發一封郵件,這封郵件所有的數據現在內存中都有,比較大的東東。到時候再去太復雜,太浪費內存了。怎么辦呢? 放在一級緩存肯定不合適,放在二級緩存,要存活半天呀,太浪費時間了,存在數據庫里面,增加壓力,也不是很好,NOSQL的mongodb和couchdb就可以解決這個問題,這個schemaless的數據庫,可以讓你輕松的存任何的東西(性能不錯)。(自己要優化一下代碼)
舉例:
Annotation
@Documented
@java.lang.annotation.Target(value={java.lang.annotation.ElementType.TYPE})
@java.lang.annotation.Retention(value=java.lang.annotation.RetentionPolicy.RUNTIME)
public @interface CacheIt {
//Provide the cacheProvider which will be use to cache the object which is just used to replace the xml configuration.
public String cacheProvider();
//Used to define how long the cache need to be provide
public long cacheDuration();
//The level of the cache, define, level1, level2 (If there is level2 defination in the annotation, the cache will be kick to level2 after the timeout in the level1)
public int cacheLevel();
}
一個VO的configuration
@CacheIt(cacheProvider="com.javaeye.wmwm.cache.impl.HashMapCacheProvider", cacheDuration=10000, cacheLevel=1)
public class TestVo {
@Identifier
public String key;
public String test;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getTest() {
return test;
}
之后寫一個CacheManager
public class CommonCacheManager implements CacheManager {
/**
* Cache the object into the cache.
* <p> the provider is defined in the annotation in the related Vo/PO/DO
* <p> the key is annotated by the <code>Identifier</code>.
* @param object represents the input objects which needs to be cached.
*/
public void cache(Object object) {
Cache cache = CachePool.getInstance().loadCache(object.getClass());
Object key = new CacheKeyFinder().find(object);
cache.put(key, object);
}
public Object load(Class<?> clazz, Object key) {
Cache cache = CachePool.getInstance().loadCache(clazz);
return cache.get(key);
}
}