使用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。

- MultiCache 類
操作 List 型的 Cache 數(shù)據(jù)(看做是 SingleCache 的批處理),由 ParameterValueKeyProvider 和 CacheKeyMethod 來標(biāo)識組裝 key。

-
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
