springcache

在springcache之前

在沒有使springcache之前我們使用緩存的方式是這樣的:

 Map<StoreKey, List<SpecialHall>> keyListHashMap = Maps.newHashMap();
        DateTime dt = new DateTime().withHourOfDay(2).plusDays(1);
        DateTime now = DateTime.now();
        int toTwo = (int) (dt.getMillis() - now.getMillis()) / 1000;
        List<SpecialHall> resList = Lists.newArrayList();
        for (Integer cinemaId : cinemaIds) {
            StoreKey storeKey = new StoreKey(CacheConstants.GDATA_STRING, String.format(CacheConstants.GATEWAY_SPECIALS_BY_CINEMAID, cinemaId));
            keyListHashMap.put(storeKey, resList);
            returnTocMap.put(cinemaId, transToTSpecialHallToApp(resList));
        }
        redisStoreClient.multiSet(keyListHashMap, toTwo);

這段代碼我剛開始看的時候也覺得沒問題,還覺得寫的挺好的(因為是我寫的偷笑),等我看到了springcache之后我覺得這段代碼就不是那么的優(yōu)雅了,總體來說就是代碼的處理邏輯和緩存耦合在一起,降低了代碼的可讀性,不利于后期人員的維護;還有就是緩存切換的話成本很大,需要改動的地方比較多,風險成本比較高。

在springcache之后
springcache是什么?

首先,要明白springcache是一種解決緩存的方案,而不是一種具體的緩存方式(類似的Redis,memcache,ehcache等等)。

springcache的相關(guān)配置

pom配置:
這里需要注意spring應該是3.1+

<dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache</artifactId>
            <version>2.8.3</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>4.1.1.RELEASE</version>
        </dependency>

springcache相關(guān)xml配置

 <!-- ehcache -->
    <cache:annotation-driven cache-manager="ehcacheManager"/>
    <!-- 聲明cacheManager -->
    <bean id="ehcacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
        <property name="cacheManager" ref="ehcacheManagerFactory" />
    </bean>
    <!-- cacheManager工廠類,指定ehcache.xml的位置 -->
    <bean id="ehcacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
        <property name="configLocation" value="classpath:ehcache.xml" />
    </bean>

還需要配置具體的緩存:

<?xml version="1.0" encoding="UTF-8"?>
<ehcache updateCheck="false">
    <diskStore path="/Users/yuxi/work/myoschina/tmpdir"/>
    <!--
    name:緩存名稱。
    maxElementsInMemory:緩存最大個數(shù)。
    eternal:對象是否永久有效,一但設置了,timeout將不起作用。
    timeToIdleSeconds:設置對象在失效前的允許閑置時間(單位:秒)。
    僅當eternal=false對象不是永久有效時使用,可選屬性,默認值是0,也就是可閑置時間無窮大。
    timeToLiveSeconds:設置對象在失效前允許存活時間(單位:秒)。最大時間介于創(chuàng)建時間和失效時間之間。
    僅當eternal=false對象不是永久有效時使用,默認是0.,也就是對象存活時間無窮大。
    overflowToDisk:當內(nèi)存中對象數(shù)量達到maxElementsInMemory時,Ehcache將會對象寫到磁盤中。
    diskSpoolBufferSizeMB:這個參數(shù)設置DiskStore(磁盤緩存)的緩存區(qū)大小。默認是30MB。每個Cache都應該有自己的一個緩沖區(qū)。
    maxElementsOnDisk:硬盤最大緩存?zhèn)€數(shù)。
    diskPersistent:是否緩存虛擬機重啟期數(shù)據(jù) Whether the disk store persists between restarts
    of the Virtual Machine. The default value is false.
    diskExpiryThreadIntervalSeconds:磁盤失效線程運行時間間隔,默認是120秒。
    memoryStoreEvictionPolicy:當達到maxElementsInMemory限制時,Ehcache將會根據(jù)指定的策略去清理內(nèi)存。
    默認策略是LRU(最近最少使用)。你可以設置為FIFO(先進先出)或是LFU(較少使用)。
    clearOnFlush:內(nèi)存數(shù)量最大時是否清除。
    -->
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="60"
            timeToLiveSeconds="60"
            overflowToDisk="true"
            maxElementsOnDisk="10000000"
            diskPersistent="true"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU"
    />
    <cache name="dbCache" maxElementsInMemory="10000" eternal="false"
           timeToLiveSeconds="1800" overflowToDisk="false" diskPersistent="true"/>
</ehcache>
springcache的相關(guān)代碼實現(xiàn)
package com.yuxi.cache;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * Created by yuxi on 2017/9/28.
 */
@Service("cacheService")
public class CacheService {

    @Cacheable(value = "dbCache", key = "'info_' + #id")
    public Info getInfo(Integer id) {
        System.out.println("from cache");
        return getDb(id);
    }

    private Info getDb(Integer id) {
        System.out.println("from db" + id);
        return new Info(id);
    }


    @CachePut(value = "dbCache", key = "'info_' + #id")
    public Info getInfo2(Integer id) {
        System.out.println("from cache put");
        return getDb(id);
    }


    @CacheEvict(value = "dbCache", key = "'info_' + #id")
    public boolean delete(Integer id) {
        System.out.println("delete");
        return true;
    }
}

相關(guān)測試類

package com.yuxi.main;

import com.yuxi.cache.CacheService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Created by yuxi on 2017/8/5.
 */
public class KnightMain {
    public static void main(String[] args) {
        // spring 應用上下文
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("knight.xml");
   
        CacheService cacheService = (CacheService) applicationContext.getBean("cacheService");
        cacheService.getInfo(1);
        cacheService.getInfo(1);
        cacheService.getInfo(1);
        cacheService.getInfo(1);
        cacheService.getInfo(1);

        cacheService.getInfo2(1);
        cacheService.getInfo2(1);
        cacheService.getInfo2(1);
        cacheService.delete(1);
    }
}

相關(guān)的測試結(jié)果為:

from cache
from db1
from cache put
from db1
from cache put
from db1
from cache put
from db1
delete
springcache的相關(guān)注解說明:

三圖勝過萬言,圖片來自郭老師的wiki,不要問我郭老師是誰?他是一個傳說。

郭老師的wiki
郭老師的wiki
郭老師的wiki

相關(guān)代碼可以參考:springcache

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容

  • 一、MemCache簡介 session MemCache是一個自由、源碼開放、高性能、分布式的分布式內(nèi)存對象緩存...
    李偉銘MIng閱讀 3,873評論 2 13
  • 實現(xiàn)目標 在客戶端請求訪問到業(yè)務層之前使用緩存攔截,使得大部分的流量轉(zhuǎn)向到緩存而不是數(shù)據(jù)庫,降低數(shù)據(jù)庫壓力。提高用...
    哥別打臉閱讀 962評論 0 1
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,282評論 25 708
  • 1、memcache的概念? Memcache是一個高性能的分布式的內(nèi)存對象緩存系統(tǒng),通過在內(nèi)存里維護一個統(tǒng)一的巨...
    桖辶殤閱讀 2,271評論 2 12
  • 張愛玲的小說《半生緣》我讀過兩次,另外還看過些林心如和蔣勤勤演的電視劇版。 因為喜歡這部小說,所以才會去看電視劇,...
    悠然小蝦閱讀 2,735評論 0 3