Memcached結(jié)合Spring

使用simple-spring-memcached
在POM中添加:

<dependencies>
   <dependency>
     <groupId>com.google.code.simple-spring-memcached</groupId>
     <artifactId>xmemcached-provider</artifactId>
     <version>3.6.1</version>
   </dependency> 
</dependencies>

在Spring配置文件中添加:

<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

  <import resource="simplesm-context.xml" />
  <aop:aspectj-autoproxy />
  /*simplesm-context.xml封裝在simple-spring-memcached-*.jar文件當(dāng)中,主要用來加載組件核心的Advice,供程序調(diào)度使用。
  而由于simple-spring-memcached主要是基于AOP的代理,所以加入<aop:aspectj-autoproxy />讓代理機(jī)制起到作用。*/

  <bean name="defaultMemcachedClient" class="com.google.code.ssm.CacheFactory">
      <property name="cacheClientFactory">
            <bean class="com.google.code.ssm.providers.xmemcached.MemcacheClientFactoryImpl" />
      </property>
      <property name="addressProvider">
            <bean class="com.google.code.ssm.config.DefaultAddressProvider">
                 <property name="address" value="127.0.0.1:11211" />
            </bean>
      </property>
      <property name="configuration">
            <bean class="com.google.code.ssm.providers.CacheConfiguration">
                  <property name="consistentHashing" value="true" />
            </bean>
      </property>
   </bean>
</beans>

接下來就可以使用注解讀寫緩存了:

public class UserDaoImpl implements IUserDao {  
    private static final String NAMESPACE="user";  
    private Map<String,User> users=new HashMap<String,User>();  
    @Override  
    public void saveUser(User user) {  
        users.put(user.getUserId(), user);  
    }  
    /** 
     * 當(dāng)執(zhí)行g(shù)etById查詢方法時,系統(tǒng)首先會從緩存中獲取userId對應(yīng)的實(shí)體 
     * 如果實(shí)體還沒有被緩存,則執(zhí)行查詢方法并將查詢結(jié)果放入緩存中 
     */  
    @Override  
    @ReadThroughSingleCache(namespace = NAMESPACE, expiration = 3600)  //3600秒=1小時
    public User getById(@ParameterValueKeyProvider String userId) {  
        System.out.println(userId);  
        return users.get(userId);  
    }  
    /** 
     * 當(dāng)執(zhí)行updateUser方法時,系統(tǒng)會更新緩存中userId對應(yīng)的實(shí)體 
     * 將實(shí)體內(nèi)容更新成@*DataUpdateContent標(biāo)簽所描述的實(shí)體 
     */  
    @UpdateSingleCache(namespace = NAMESPACE, expiration = 3600)  
    @Override  
    public void updateUser(@ParameterValueKeyProvider @ParameterDataUpdateContent User user) {  
        users.put(user.getUserId(), user);  
    }  
    /** 
     * 當(dāng)執(zhí)行deleteUser方法時,系統(tǒng)會刪除緩存中userId對應(yīng)的實(shí)體 
     */  
    @InvalidateSingleCache(namespace = NAMESPACE)  
    @Override  
    public void deleteUser(@ParameterValueKeyProvider String userId) {  
        users.remove(userId);  
    }  
}  
  • 注意這里的User(實(shí)體及實(shí)體的每個成員變量)必須是可序列化的,需實(shí)現(xiàn)Serializable接口。

  • @ParameterValueKeyProvider: 標(biāo)記將方法的參數(shù)做為計算緩存key.如果被其注解的對象有標(biāo)記@CacheKeyMethod的getCacheKey()方法,這根據(jù)getCacheKey()方法生成緩存key。否則調(diào)用toString()生成

  • 多個方法參數(shù)都作為cacheKey時,@ParameterValueKeyProvider必須指明其order值,之間用 '/' 號分隔。上面例子中生成的Key為user:{userId}(namespace:參數(shù)1|參數(shù)2),namespace可以設(shè)置成模塊名加方法名等方法以避免Key重復(fù)。例如:
    @ReadThroughSingleCache(namespace = "goodscenter:EventGoodsDo", expiration = 60)
    public EventGoodsDo queryEventGoodsDo
    (@ParameterValueKeyProvider(order = 0) long goodsId, @ParameterValueKeyProvider(order = 1) long eventId)
    {
    return getRemoteServiceBean().queryEventGoodsDo(goodsId, eventId);
    }

  • SingleCache 類
    操作單個 POJO 的 Cache 數(shù)據(jù),由 ParameterValueKeyProvider 和 CacheKeyMethod 來標(biāo)識組裝 key。

SingleCache
  • MultiCache 類
    操作 List 型的 Cache 數(shù)據(jù)(看做是 SingleCache 的批處理),由 ParameterValueKeyProvider 和 CacheKeyMethod 來標(biāo)識組裝 key。
MultiCache
  • AssignCache 類
    操作所有類型的 Cache 數(shù)據(jù)。適用于無參方法或者需要自定義 Key 的場景。指定 key 操作 Cache 數(shù)據(jù),由 annotation 中的 assignedKey 指定 key。


    AssignCache
  • @ReadThroughSingleCache,@ReadThroughMultiCache,@ReadThroughAssignCache
    當(dāng)遇到查詢方法聲明這些切入點(diǎn)時,組件首先會從緩存中讀取數(shù)據(jù),取到數(shù)據(jù)則跳過查詢方法,直接返回。取不到數(shù)據(jù)在執(zhí)行查詢方法,并將查詢結(jié)果放入緩存,以便下一次獲取。

  • @InvalidateSingleCache,@InvalidateMultiCache,@InvalidateAssignCache
    當(dāng)遇到刪除方法聲明這些切入點(diǎn)時,組件會刪除緩存中的對應(yīng)實(shí)體。

  • @UpdateSingleCache,@UpdateMultiCache,@UpdateAssignCache
    當(dāng)遇到更新方法聲明這些切入點(diǎn)是,組件會更新緩存中對應(yīng)的實(shí)體,以便下次從緩存中讀取出的數(shù)據(jù)狀態(tài)是最新的

  • 使用UpdateCache 更新Cache中的數(shù)據(jù)key生成規(guī)則:@ParameterDataUpdateContent:參數(shù)中的數(shù)據(jù),作為更新緩存的數(shù)據(jù)
    @ReturnDataUpdateContent:方法調(diào)用后返回的數(shù)據(jù),作為更新緩存的數(shù)據(jù),這上述兩個注解,必須與Update
    系列的注解一起使用
    //@ParameterDataUpdateContent
    @UpdateSingleCache(namespace = "Alpha", expiration = 30)
    public void overrideDateString(final int trash, @ParameterValueKeyProvider final String key,
    @ParameterDataUpdateContent final String overrideData) {
    }

      //@ReturnDataUpdateContent
      @UpdateSingleCache(namespace = "Bravo", expiration = 300)  
      @ReturnDataUpdateContent  
      public String updateTimestampValue(@ParameterValueKeyProvider final Long key) {  
          try {  
              Thread.sleep(100);  
          } catch (InterruptedException ex) {  
          }  
          final Long now = new Date().getTime();  
          final String result = now.toString() + "-U-" + key.toString();  
          return result;  
      }  
    

和Spring Cache結(jié)合
于Ehcache一樣,Memcached也可以和Spring Cache結(jié)合使用
在POM中添加:

<dependency>
  <groupId>com.google.code.simple-spring-memcached</groupId>
  <artifactId>spring-cache</artifactId>
  <version>3.6.1</version>
</dependency>
<dependency>
  <groupId>com.google.code.simple-spring-memcached</groupId>
  <artifactId>xmemcached-provider</artifactId>
  <version>3.6.1</version>
</dependency>   

在Spring配置文件中添加:

<?xml version="1.0" encoding="UTF-8"?>
<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-3.1.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.1.xsd
           http://www.springframework.org/schema/cache 
           http://www.springframework.org/schema/cache/spring-cache-3.1.xsd">

  <cache:annotation-driven />

  <bean name="cacheManager" class="com.google.code.ssm.spring.SSMCacheManager">
    <property name="caches">
      <set>
        <bean class="com.google.code.ssm.spring.SSMCache">
      <constructor-arg name="cache" index="0" ref="defaultCache" />
          <!-- 5 minutes -->
      <constructor-arg name="expiration" index="1" value="300" />
          <!-- @CacheEvict(..., "allEntries" = true) won't work because allowClear is false, 
           so we won't flush accidentally all entries from memcached instance -->
      <constructor-arg name="allowClear" index="2" value="false" />
    </bean>
      </set>
    </property>
  </bean>

  <bean name="defaultCache" class="com.google.code.ssm.CacheFactory" depends-on="cacheBase">
    <property name="cacheName" value="default" />
    <property name="cacheClientFactory">
      <bean name="cacheClientFactory" class="com.google.code.ssm.providers.xmemcached.MemcacheClientFactoryImpl" />
    </property>
    <property name="addressProvider">
      <bean class="com.google.code.ssm.config.DefaultAddressProvider">
        <property name="address" value="127.0.0.1:11211" />
      </bean>
    </property>
    <property name="configuration">
      <bean class="com.google.code.ssm.providers.CacheConfiguration">
        <property name="consistentHashing" value="true" />
        <!-- spring can produce keys that contain unacceptable characters -->
        <property name="useBinaryProtocol" value="true" />
      </bean>
    </property>
  </bean>
</beans>

然后就可以使用Spring Cache的注解了。


參考:
https://github.com/ragnor/simple-spring-memcached/wiki/Getting-Started
http://greemranqq.iteye.com/blog/2168710
http://www.myexception.cn/software-architecture-design/414190.html
http://blog.csdn.net/javaman_chen/article/details/7682290

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,694評論 19 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,285評論 6 342
  • 轉(zhuǎn)自:http://blog.csdn.net/jackfrued/article/details/4493116...
    王帥199207閱讀 2,774評論 0 19
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法,類相關(guān)的語法,內(nèi)部類的語法,繼承相關(guān)的語法,異常的語法,線程的語...
    子非魚_t_閱讀 34,834評論 18 399
  • 十點(diǎn)半看朋友圈發(fā)現(xiàn)才60幾個贊,不行啊,必須今晚搞定100個贊,所以我就翻看朋友圈,有朋友發(fā)圈我就給她點(diǎn)贊,然后...
    向往精靈閱讀 236評論 0 0

友情鏈接更多精彩內(nèi)容