主要是基于這幾種方式http://www.cnblogs.com/EasonJim/p/7624822.html去實作與Spring內建,而個人建議使用Xmemcached去內建好一些,因為現在官方還在更新,具體參考:https://github.com/killme2008/xmemcached/wiki/Xmemcached%20%E4%B8%AD%E6%96%87%E7%94%A8%E6%88%B7%E6%8C%87%E5%8D%97
以下方式據說第一種會報錯,沒測試過。
既然已經使用Spring做內建,那麼依賴肯定要使用Maven。
Memcached已經過時了,如果是新項目就不應該側重選擇它,轉投Redis。
Memcached Client for Java
<!-- https://mvnrepository.com/artifact/com.whalin/Memcached-Java-Client -->
<dependency>
<groupId>com.whalin</groupId>
<artifactId>Memcached-Java-Client</artifactId>
<version>3.0.2</version>
</dependency>
memcached.properties配置檔案:配置伺服器位址,連接配接數,逾時時間等
#######################Memcached配置#######################
#伺服器位址
memcached.server1=127.0.0.1
memcached.port1=11211
#memcached.server=127.0.0.1:11211
#初始化時對每個伺服器建立的連接配接數目
memcached.initConn=20
#每個伺服器建立最小的連接配接數
memcached.minConn=10
#每個伺服器建立最大的連接配接數
memcached.maxConn=50
#自查線程周期進行工作,其每次休眠時間
memcached.maintSleep=3000
#Socket的參數,如果是true在寫資料時不緩沖,立即發送出去
memcached.nagle=false
#Socket阻塞讀取資料的逾時時間
memcached.socketTO=3000
##pool.setServers(servers);
##pool.setWeights(weights);
##pool.setHashingAlg(SockIOPool.CONSISTENT_HASH);
##pool.setInitConn(5);
##pool.setMinConn(5);
##pool.setMaxConn(250);
##pool.setMaxIdle(1000 * 60 * 60 * 6);
##pool.setMaintSleep(30);
##pool.setNagle(false);
##pool.setSocketTO(3000);
##pool.setSocketConnectTO(0);
配置Bean
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
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/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
<!-- properties config -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="order" value="1"/>
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="locations">
<list>
<!--<value>classpath:/com/springmvc/config/memcached.properties</value>-->
<value>/WEB-INF/config/memcached.properties</value>
</list>
</property>
</bean>
<!-- Memcached配置 -->
<bean id="memcachedPool" class="com.danga.MemCached.SockIOPool" factory-method="getInstance" init-method="initialize" destroy-method="shutDown">
<property name="servers">
<!-- ${memcached.server} -->
<list>
<value>${memcached.server1}:${memcached.port1}</value>
</list>
</property>
<property name="initConn">
<value>${memcached.initConn}</value>
</property>
<property name="minConn">
<value>${memcached.minConn}</value>
</property>
<property name="maxConn">
<value>${memcached.maxConn}</value>
</property>
<property name="maintSleep">
<value>${memcached.maintSleep}</value>
</property>
<property name="nagle">
<value>${memcached.nagle}</value>
</property>
<property name="socketTO">
<value>${memcached.socketTO}</value>
</property>
</bean>
</beans>
将app-context-memcached.xml配置到app-context.xml中
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
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/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
<import resource="app-context-memcached.xml" /><!--memcached 緩存配置 -->
<!-- <import resource="app-context-xmemcached.xml" /> -->
<!-- <import resource="app-context-spymemcached.xml" /> -->
<!-- @Component and @Resource -->
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
<!-- 對com包中的所有類進行掃描,以完成Bean建立和自動依賴注入的功能 -->
<context:component-scan base-package="com.springmvc.imooc" />
<!-- 定時器 -->
<!-- <task:annotation-driven /> -->
<!-- mvc -->
<mvc:annotation-driven />
<!-- Aspect -->
<!-- <aop:aspectj-autoproxy /> -->
</beans>
Memcached工具類:
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import com.danga.MemCached.MemCachedClient;
public final class MemcachedUtils {
/**
* cachedClient.
*/
private static MemCachedClient cachedClient;
static {
if (cachedClient == null) {
cachedClient = new MemCachedClient("memcachedPool");
}
}
/**
* 構造函數.
*/
private MemcachedUtils() {
}
/**
* 向緩存添加新的鍵值對。如果鍵已經存在,則之前的值将被替換.
* @param key 鍵
* @param value 值
* @return boolean
*/
public static boolean set(String key, Object value) {
return setExp(key, value, null);
}
/**
* 向緩存添加新的鍵值對。如果鍵已經存在,則之前的值将被替換.
* @param key 鍵
* @param value 值
* @param expire 過期時間 New Date(1000*10):十秒後過期
* @return boolean
*/
public static boolean set(String key, Object value, Date expire) {
return setExp(key, value, expire);
}
/**
* 向緩存添加新的鍵值對。如果鍵已經存在,則之前的值将被替換.
* @param key 鍵
* @param value 值
* @param expire 過期時間 New Date(1000*10):十秒後過期
* @return boolean
*/
private static boolean setExp(String key, Object value, Date expire) {
boolean flag = false;
try {
flag = cachedClient.set(key, value, expire);
} catch (Exception e) {
MemcachedLog.writeLog("Memcached set方法報錯,key值:" + key + "\r\n" + exceptionWrite(e));
}
return flag;
}
/**
* 僅當緩存中不存在鍵時,add 指令才會向緩存中添加一個鍵值對.
* @param key 鍵
* @param value 值
* @return boolean
*/
public static boolean add(String key, Object value) {
return addExp(key, value, null);
}
/**
* 僅當緩存中不存在鍵時,add 指令才會向緩存中添加一個鍵值對.
* @param key 鍵
* @param value 值
* @param expire 過期時間 New Date(1000*10):十秒後過期
* @return boolean
*/
public static boolean add(String key, Object value, Date expire) {
return addExp(key, value, expire);
}
/**
* 僅當緩存中不存在鍵時,add 指令才會向緩存中添加一個鍵值對.
* @param key 鍵
* @param value 值
* @param expire 過期時間 New Date(1000*10):十秒後過期
* @return boolean
*/
private static boolean addExp(String key, Object value, Date expire) {
boolean flag = false;
try {
flag = cachedClient.add(key, value, expire);
} catch (Exception e) {
MemcachedLog.writeLog("Memcached add方法報錯,key值:" + key + "\r\n" + exceptionWrite(e));
}
return flag;
}
/**
* 僅當鍵已經存在時,replace 指令才會替換緩存中的鍵.
* @param key 鍵
* @param value 值
* @return boolean
*/
public static boolean replace(String key, Object value) {
return replaceExp(key, value, null);
}
/**
* 僅當鍵已經存在時,replace 指令才會替換緩存中的鍵.
* @param key 鍵
* @param value 值
* @param expire 過期時間 New Date(1000*10):十秒後過期
* @return boolean
*/
public static boolean replace(String key, Object value, Date expire) {
return replaceExp(key, value, expire);
}
/**
* 僅當鍵已經存在時,replace 指令才會替換緩存中的鍵.
* @param key 鍵
* @param value 值
* @param expire 過期時間 New Date(1000*10):十秒後過期
* @return boolean
*/
private static boolean replaceExp(String key, Object value, Date expire) {
boolean flag = false;
try {
flag = cachedClient.replace(key, value, expire);
} catch (Exception e) {
MemcachedLog.writeLog("Memcached replace方法報錯,key值:" + key + "\r\n" + exceptionWrite(e));
}
return flag;
}
/**
* get 指令用于檢索與之前添加的鍵值對相關的值.
* @param key 鍵
* @return boolean
*/
public static Object get(String key) {
Object obj = null;
try {
obj = cachedClient.get(key);
} catch (Exception e) {
MemcachedLog.writeLog("Memcached get方法報錯,key值:" + key + "\r\n" + exceptionWrite(e));
}
return obj;
}
/**
* 删除 memcached 中的任何現有值.
* @param key 鍵
* @return boolean
*/
public static boolean delete(String key) {
return deleteExp(key, null);
}
/**
* 删除 memcached 中的任何現有值.
* @param key 鍵
* @param expire 過期時間 New Date(1000*10):十秒後過期
* @return boolean
*/
public static boolean delete(String key, Date expire) {
return deleteExp(key, expire);
}
/**
* 删除 memcached 中的任何現有值.
* @param key 鍵
* @param expire 過期時間 New Date(1000*10):十秒後過期
* @return boolean
*/
@SuppressWarnings("deprecation")
private static boolean deleteExp(String key, Date expire) {
boolean flag = false;
try {
flag = cachedClient.delete(key, expire);
} catch (Exception e) {
MemcachedLog.writeLog("Memcached delete方法報錯,key值:" + key + "\r\n" + exceptionWrite(e));
}
return flag;
}
/**
* 清理緩存中的所有鍵/值對.
* @return boolean
*/
public static boolean flashAll() {
boolean flag = false;
try {
flag = cachedClient.flushAll();
} catch (Exception e) {
MemcachedLog.writeLog("Memcached flashAll方法報錯\r\n" + exceptionWrite(e));
}
return flag;
}
/**
* 傳回異常棧資訊,String類型.
* @param e Exception
* @return boolean
*/
private static String exceptionWrite(Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
pw.flush();
return sw.toString();
}
}
測試:
System.out.println(MemcachedUtils.set("aa", "bb", new Date(1000 * 60)));
Object obj = MemcachedUtils.get("aa");
System.out.println("***************************");
System.out.println(obj.toString());
SpyMemcached
<!-- https://mvnrepository.com/artifact/net.spy/spymemcached -->
<dependency>
<groupId>net.spy</groupId>
<artifactId>spymemcached</artifactId>
<version>2.12.3</version>
</dependency>
spymemcached.properties配置檔案:
#連接配接池大小即用戶端個數
memcached.connectionPoolSize=1
memcached.failureMode=true
#server1
memcached.servers=127.0.0.1:11211
memcached.protocol=BINARY
memcached.opTimeout=1000
memcached.timeoutExceptionThreshold=1998
memcached.locatorType=CONSISTENT
memcached.failureMode=Redistribute
memcached.useNagleAlgorithm=false
app-context-spymemcached.xml配置bean:
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
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/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
<!-- properties config -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="order" value="1"/>
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="locations">
<list>
<value>classpath:/com/springmvc/config/spymemcached.properties</value>
</list>
</property>
</bean>
<!-- Memcached配置 -->
<!--
枚舉類型要想注入到類中,一定要先使用org.springframework.beans.factory.config.FieldRetrievingFactoryBean類将枚舉類型進行轉換
将DefaultHashAlgorithm.KETAMA_HASH轉換為KETAMA_HASH這個bean,
然後在要注入的bean中使用<property name="hashAlg" ref="KETAMA_HASH" />引用即可。
-->
<bean id="KETAMA_HASH" class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean">
<property name="staticField" value="net.spy.memcached.DefaultHashAlgorithm.KETAMA_HASH" />
</bean>
<bean id="memcachedClient" class="net.spy.memcached.spring.MemcachedClientFactoryBean">
<!-- 一個字元串,包括由空格或逗号分隔的主機或IP位址與端口号 -->
<property name="servers" value="${memcached.servers}" />
<!-- 指定要使用的協定(BINARY,TEXT),預設是TEXT -->
<property name="protocol" value="${memcached.protocol}" />
<!-- 設定預設的轉碼器(預設以net.spy.memcached.transcoders.SerializingTranscoder) -->
<property name="transcoder">
<bean class="net.spy.memcached.transcoders.SerializingTranscoder">
<property name="compressionThreshold" value="1024" />
</bean>
</property>
<!-- 以毫秒為機關設定預設的操作逾時時間 -->
<property name="opTimeout" value="${memcached.opTimeout}" />
<property name="timeoutExceptionThreshold" value="${memcached.timeoutExceptionThreshold}" />
<!-- 設定雜湊演算法 -->
<property name="hashAlg" ref="KETAMA_HASH" />
<!-- 設定定位器類型(ARRAY_MOD,CONSISTENT),預設是ARRAY_MOD -->
<property name="locatorType" value="${memcached.locatorType}" />
<!-- 設定故障模式(取消,重新配置設定,重試),預設是重新配置設定 -->
<property name="failureMode" value="${memcached.failureMode}" />
<!-- 想使用Nagle算法,設定為true -->
<property name="useNagleAlgorithm" value="${memcached.useNagleAlgorithm}" />
</bean>
<bean id="memcachedManager" class="com.springmvc.imooc.util.SpyMemcachedManager">
<property name="memcachedClient" ref="memcachedClient" />
</bean>
</beans>
SpyMemcachedManager工具類:
import java.io.IOException;
import java.io.OutputStream;
import java.net.SocketAddress;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Future;
import net.spy.memcached.ConnectionObserver;
import net.spy.memcached.MemcachedClient;
import net.spy.memcached.transcoders.Transcoder;
public class SpyMemcachedManager {
/**
* memcached客戶單執行個體.
*/
private MemcachedClient memcachedClient;
/**
*
* TODO 添加方法注釋.
*
* @param obs obs
*/
public void addObserver(ConnectionObserver obs) {
memcachedClient.addObserver(obs);
}
/**
*
* TODO 添加方法注釋.
*
* @param obs obs
*/
public void removeObserver(ConnectionObserver obs) {
memcachedClient.removeObserver(obs);
}
/**
*
* 加入緩存.
*
* @param key key
* @param value value
* @param expire 過期時間
* @return boolean
*/
public boolean set(String key, Object value, int expire) {
Future<Boolean> f = memcachedClient.set(key, expire, value);
return getBooleanValue(f);
}
/**
*
*從緩存中擷取.
*
* @param key key
* @return Object
*/
public Object get(String key) {
return memcachedClient.get(key);
}
/**
*
*從緩存中擷取.
*
* @param key key
* @return Object
*/
public Object asyncGet(String key) {
Object obj = null;
Future<Object> f = memcachedClient.asyncGet(key);
try {
obj = f.get(SpyMemcachedConstants.DEFAULT_TIMEOUT, SpyMemcachedConstants.DEFAULT_TIMEUNIT);
} catch (Exception e) {
f.cancel(false);
}
return obj;
}
/**
*
* 加入緩存.
*
* @param key key
* @param value value
* @param expire 過期時間
* @return boolean
*/
public boolean add(String key, Object value, int expire) {
Future<Boolean> f = memcachedClient.add(key, expire, value);
return getBooleanValue(f);
}
/**
*
* 替換.
*
* @param key key
* @param value value
* @param expire 過期時間
* @return boolean
*/
public boolean replace(String key, Object value, int expire) {
Future<Boolean> f = memcachedClient.replace(key, expire, value);
return getBooleanValue(f);
}
/**
*
* 從緩存中删除.
*
* @param key key
* @return boolean
*/
public boolean delete(String key) {
Future<Boolean> f = memcachedClient.delete(key);
return getBooleanValue(f);
}
/***
*
* flush.
*
* @return boolean
*/
public boolean flush() {
Future<Boolean> f = memcachedClient.flush();
return getBooleanValue(f);
}
/**
*
* 從緩存中擷取.
*
* @param keys keys
* @return Map<String, Object>
*/
public Map<String, Object> getMulti(Collection<String> keys) {
return memcachedClient.getBulk(keys);
}
/**
*
* 從緩存中擷取.
*
* @param keys keys
* @return Map<String, Object>
*/
public Map<String, Object> getMulti(String[] keys) {
return memcachedClient.getBulk(keys);
}
/**
*
* 從緩存中擷取.
*
* @param keys keys
* @return Map<String, Object>
*/
public Map<String, Object> asyncGetMulti(Collection<String> keys) {
Map<String, Object> map = null;
Future<Map<String, Object>> f = memcachedClient.asyncGetBulk(keys);
try {
map = f.get(SpyMemcachedConstants.DEFAULT_TIMEOUT, SpyMemcachedConstants.DEFAULT_TIMEUNIT);
} catch (Exception e) {
f.cancel(false);
}
return map;
}
/**
*
* 從緩存中擷取.
*
* @param keys keys
* @return Map<String, Object>
*/
public Map<String, Object> asyncGetMulti(String[] keys) {
Map<String, Object> map = null;
Future<Map<String, Object>> f = memcachedClient.asyncGetBulk(keys);
try {
map = f.get(SpyMemcachedConstants.DEFAULT_TIMEOUT, SpyMemcachedConstants.DEFAULT_TIMEUNIT);
} catch (Exception e) {
f.cancel(false);
}
return map;
}
// ---- Basic Operation End ----//
// ---- increment & decrement Start ----//
public long increment(String key, int by, long defaultValue, int expire) {
return memcachedClient.incr(key, by, defaultValue, expire);
}
public long increment(String key, int by) {
return memcachedClient.incr(key, by);
}
public long decrement(String key, int by, long defaultValue, int expire) {
return memcachedClient.decr(key, by, defaultValue, expire);
}
public long decrement(String key, int by) {
return memcachedClient.decr(key, by);
}
public long asyncIncrement(String key, int by) {
Future<Long> f = memcachedClient.asyncIncr(key, by);
return getLongValue(f);
}
public long asyncDecrement(String key, int by) {
Future<Long> f = memcachedClient.asyncDecr(key, by);
return getLongValue(f);
}
// ---- increment & decrement End ----//
public void printStats() throws IOException {
printStats(null);
}
public void printStats(OutputStream stream) throws IOException {
Map<SocketAddress, Map<String, String>> statMap = memcachedClient.getStats();
if (stream == null) {
stream = System.out;
}
StringBuffer buf = new StringBuffer();
Set<SocketAddress> addrSet = statMap.keySet();
Iterator<SocketAddress> iter = addrSet.iterator();
while (iter.hasNext()) {
SocketAddress addr = iter.next();
buf.append(addr.toString() + "/n");
Map<String, String> stat = statMap.get(addr);
Set<String> keys = stat.keySet();
Iterator<String> keyIter = keys.iterator();
while (keyIter.hasNext()) {
String key = keyIter.next();
String value = stat.get(key);
buf.append(" key=" + key + ";value=" + value + "/n");
}
buf.append("/n");
}
stream.write(buf.toString().getBytes());
stream.flush();
}
public Transcoder getTranscoder() {
return memcachedClient.getTranscoder();
}
private long getLongValue(Future<Long> f) {
try {
Long l = f.get(SpyMemcachedConstants.DEFAULT_TIMEOUT, SpyMemcachedConstants.DEFAULT_TIMEUNIT);
return l.longValue();
} catch (Exception e) {
f.cancel(false);
}
return -1;
}
private boolean getBooleanValue(Future<Boolean> f) {
try {
Boolean bool = f.get(SpyMemcachedConstants.DEFAULT_TIMEOUT, SpyMemcachedConstants.DEFAULT_TIMEUNIT);
return bool.booleanValue();
} catch (Exception e) {
f.cancel(false);
return false;
}
}
public MemcachedClient getMemcachedClient() {
return memcachedClient;
}
public void setMemcachedClient(MemcachedClient memcachedClient) {
this.memcachedClient = memcachedClient;
}
}
public class SpyMemcached extends BaseTest {
private ApplicationContext app;
private SpyMemcachedManager memcachedManager;
@Before
public void init() {
app = new ClassPathXmlApplicationContext("com/springmvc/config/app-context.xml");
memcachedManager = (SpyMemcachedManager) app.getBean("memcachedManager");
}
@Test
public void test() {
try {
System.out.println("set:"+memcachedManager.set("SpyMemcached", "test", 9000));
System.out.println("get:"+memcachedManager.get("SpyMemcached"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
Xmemcached
<!-- https://mvnrepository.com/artifact/com.googlecode.xmemcached/xmemcached -->
<dependency>
<groupId>com.googlecode.xmemcached</groupId>
<artifactId>xmemcached</artifactId>
<version>2.3.2</version>
</dependency>
xmemcached.properties配置檔案:
#連接配接池大小即用戶端個數
memcached.connectionPoolSize=1
memcached.failureMode=true
#server1
memcached.server1.host=127.0.0.1
memcached.server1.port=11211
memcached.server1.weight=1
app-context-xmemcached.xml配置檔案:
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
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/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
<!-- properties config -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="order" value="1"/>
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="locations">
<list>
<value>classpath:/com/springmvc/config/xmemcached.properties</value>
</list>
</property>
</bean>
<!-- Memcached配置 -->
<!-- p:connectionPoolSize="${memcached.connectionPoolSize}" p:failureMode="${memcached.failureMode}" -->
<bean id="memcachedClientBuilder" class="net.rubyeye.xmemcached.XMemcachedClientBuilder">
<constructor-arg>
<list>
<bean class="java.net.InetSocketAddress">
<constructor-arg>
<value>${memcached.server1.host}</value>
</constructor-arg>
<constructor-arg>
<value>${memcached.server1.port}</value>
</constructor-arg>
</bean>
</list>
</constructor-arg>
<constructor-arg>
<list>
<value>${memcached.server1.weight}</value>
</list>
</constructor-arg>
<property name="commandFactory" >
<bean class="net.rubyeye.xmemcached.command.TextCommandFactory" />
</property>
<property name="sessionLocator" >
<bean class="net.rubyeye.xmemcached.impl.KetamaMemcachedSessionLocator" />
</property>
<property name="transcoder" >
<bean class="net.rubyeye.xmemcached.transcoders.SerializingTranscoder" />
</property>
<property name="connectionPoolSize" value="${memcached.connectionPoolSize}" />
<property name="failureMode" value="${memcached.failureMode}" />
</bean>
<!-- Use factory bean to build memcached client -->
<bean id="memcachedClient" factory-bean="memcachedClientBuilder" factory-method="build" destroy-method="shutdown" />
</beans>
public class XMemcachedSpring extends BaseTest {
private ApplicationContext app;
private MemcachedClient memcachedClient;
@Before
public void init() {
app = new ClassPathXmlApplicationContext("com/springmvc/config/app-context.xml");
memcachedClient = (MemcachedClient) app.getBean("memcachedClient");
}
@Test
public void test() {
try {
// 設定/擷取
memcachedClient.set("zlex", 36000, "set/get");
System.out.println(memcachedClient.get("zlex"));
// 替換
memcachedClient.replace("zlex", 36000, "replace");
System.out.println(memcachedClient.get("zlex"));
// 移除
memcachedClient.delete("zlex");
System.out.println(memcachedClient.get("zlex"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
參考:
http://blog.csdn.net/u013725455/article/details/52102170(以上内容轉自此篇文章)
http://www.cnblogs.com/liuriqi/p/4039212.html
http://blog.sina.com.cn/s/blog_613904cc0101ibub.html
http://blog.csdn.net/haozhongjun/article/details/52958175
http://blog.csdn.net/l1028386804/article/details/48464111
http://www.cnblogs.com/cl1234/p/5391401.html