主要是基于这几种方式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

Memcached与Spring集成的方式(待实践)的更多相关文章

  1. memcached与spring集成

    一.背景 销售CRM(项目A)将负责管理项目信息系统(项目B)的支付与权限 上级要求为避免频繁调用CRM接口,中间放一级缓存,但要做到缓存中保证最新数据 因项目B已使用memcache作缓存,所以决定 ...

  2. Memcached和Spring集成开发

    xml配置文件 <bean id="memcachedPool" class="com.danga.MemCached.SockIOPool" facto ...

  3. 从零开始学 Java - Spring 集成 Memcached 缓存配置(二)

    Memcached 客户端选择 上一篇文章 从零开始学 Java - Spring 集成 Memcached 缓存配置(一)中我们讲到这篇要谈客户端的选择,在 Java 中一般常用的有三个: Memc ...

  4. 从零开始学 Java - Spring 集成 Memcached 缓存配置(一)

    硬盘和内存的作用是什么 硬盘的作用毫无疑问我们大家都清楚,不就是用来存储数据文件的么?如照片.视频.各种文档或等等,肯定也有你喜欢的某位岛国老师的动作片,这个时候无论我们电脑是否关机重启它们永远在那里 ...

  5. Spring集成Redis方案(spring-data-redis)(基于Jedis的单机模式)(待实践)

    说明:请注意Spring Data Redis的版本以及Spring的版本!最新版本的Spring Data Redis已经去除Jedis的依赖包,需要自行引入,这个是个坑点.并且会与一些低版本的Sp ...

  6. spring+springMVC集成(annotation方式)

    spring+springMVC集成(annotation方式) SpringMVC+Spring4.0+Hibernate 简单的整合 MyBatis3整合Spring3.SpringMVC3

  7. Memcached理解笔2---XMemcached&Spring集成

    一.Memcached Client简要介绍 Memcached Client目前有3种: Memcached Client for Java SpyMemcached XMemcached 这三种C ...

  8. 160530、memcached集群(spring集成的配置)

    第一步:在linux机或windows机上安装memcached服务端(server) linux中安装memcached:centos中命令 yum -y install memcached 如果没 ...

  9. Memcached笔记——(二)XMemcached&Spring集成

    今天研究Memcached的Java的Client,使用XMemcached 1.3.5,做个简单的测试,并介绍如何与Spring集成. 相关链接: Memcached笔记--(一)安装&常规 ...

随机推荐

  1. Android 在代码中安装 APK 文件

    废话不说,上代码 private void install(String filePath) { Log.i(TAG, "开始执行安装: " + filePath); File a ...

  2. MSSQL 重新生成索引,重新组织索引

    > 5% 且 < = 30% ALTER INDEX REORGANIZE > 30% ALTER INDEX REBUILD WITH (ONLINE = ON)* * 重新生成索 ...

  3. pthread Win32多线程编程的一些知识和感想

    研究遗传算法的一大诟病就是每次运行程序的结果并不是完全一样的,有时候能找到最优解有时候找不到最优解,这就是遗传算法的概率性导致的.那么怎么评价你的方法的好坏呐,这时候就要多次独立运行程序最后取结果的平 ...

  4. image和TFRecord互相转换

    关说不练假把式.手上正好有车牌字符的数据集,想把他们写成TFRecord格式,然后读进来,构建一个简单的cnn训练看看.然后发现准确率只有0.0x.随机猜也比这要好点吧.只能一步步检查整个过程.暂时想 ...

  5. 使用Caliburn.Micro系列2:Convention

    CM中实现一个比较有意思的特性,就是智能匹配. 通常使用MVVM的写法:在匹配 View和ViewModel时会使用DataContext,在匹配数据属性时使用Binding,在匹配事件命令时使用Co ...

  6. Windows文件自删除的两种方法

    可执行模块的自删除技术已经被讨论的很多, 有很多极富创意的思路和想法被提出, 但有些似是而非的方案往往使人误入歧途. 举个例子来说, 很多文章认为下面的一小段代码可以实现自删除:void main(v ...

  7. vue之$mount

    数据挂载 在实例化Vue的时候,两种方式挂载数据 方法一:最常用的方法 var app=new vue({ el:"#app", data(){} ````` }) 注:文档中最常 ...

  8. PHP笔录(韩顺平)

    这里记录下韩顺平视频学习记录 http://www.php.cn/code/11753.html

  9. 15数据库与ADO.Net

    数据库与ADO.Net 数据库与ADO.Net 8.1   数据库基本概念 数据库提供了一种将信息集合在一起的方法.数据库应用系统主要由三部分组成:数据库管理系统(DBMS),是针对所有应用的,例如A ...

  10. ansible API(开发应用)

    7. ansible API(开发应用) 官网链接