Spring集成Memcached三种方式
2017-06-09 13:17
477 查看
Memcached Client目前有3种:
Memcached Client for
Java
SpyMemcached
XMemcached
这三种Client一直存在各种争议:
Memcached Client for Java 比 SpyMemcached更稳定、更早、更广泛;
SpyMemcached 比 Memcached Client for Java更高效;
XMemcached 比 SpyMemcache并发效果更好。
方式一:Memcached Client for Java
jar包准备:java_memcached-release_2.6.6.jar
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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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>
</property></property></bean>
<!-- Memcached配置 -->
<bean class="com.danga.MemCached.SockIOPool" destroy-method="shutDown" factory-method="getInstance" id="memcachedPool" init-method="initialize">
<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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:task="http://www.springframework.org/schema/task" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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 -->
<!-- aspectj-autoproxy /> -->
</mvc:annotation-driven></context:component-scan></bean></import></beans>
Memcached工具类:
/*
* 文件名:MemcachedUtils.java
* 版权:Copyright 2007-2016 517na Tech. Co. Ltd. All Rights Reserved.
* 描述: MemcachedUtils.java
* 修改人:peiyu
* 修改时间:2016年8月2日
* 修改内容:新增
*/
package com.springmvc.imooc.util;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import com.danga.MemCached.MemCachedClient;
/**
* @author peiyu
*/
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
jar包准备:spymemcached-2.10.3.jar
spymemcached.properties配置文件:
<!--?xml version="1.0" encoding="UTF-8"?-->
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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>
</property></property></bean>
<!-- Memcached配置 -->
<!--
枚举类型要想注入到类中,一定要先使用org.springframework.beans.factory.config.FieldRetrievingFactoryBean类将枚举类型进行转换
将DefaultHashAlgorithm.KETAMA_HASH转换为KETAMA_HASH这个bean,
然后在要注入的bean中使用<property name="hashAlg" ref="KETAMA_HASH" />引用即可。
-->
<bean class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean" id="KETAMA_HASH">
<property name="staticField" value="net.spy.memcached.DefaultHashAlgorithm.KETAMA_HASH">
</property></bean>
<bean class="net.spy.memcached.spring.MemcachedClientFactoryBean" id="memcachedClient">
<!-- 一个字符串,包括由空格或逗号分隔的主机或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">
</property></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}">
</property></property></property></property></property></property></property></property></bean>
<bean class="com.springmvc.imooc.util.SpyMemcachedManager" id="memcachedManager">
<property name="memcachedClient" ref="memcachedClient">
</property></bean>
</beans>SpyMemcachedManager 工具类:
方式三:XMemcached
jar包准备:xmemcached-1.4.1.jar
xmemcached.properties配置文件:
package com.springmvc.imooc.test;
import java.io.FileNotFoundException;
import org.apache.log4j.Logger;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.Log4jConfigurer;
/**
* @author guangyin
*/
@RunWith(SpringJUnit4ClassRunner.class)
/*
* @TransactionConfiguration(transactionManager = "transactionManager")
*
* @Transactional
*/
@ContextConfiguration("/com/springmvc/config/app-context.xml")
public class BaseTest {
/**
* 添加字段注释.
*/
protected Logger logger = Logger.getLogger(BaseTest.class);
static {
try {
Log4jConfigurer.initLogging("WebContent/WEB-INF/config/log4j.properties");
} catch (FileNotFoundException ex) {
System.err.println("Cannot Initialize log4j");
}
}
}
Memcached Client for
Java
SpyMemcached
XMemcached
这三种Client一直存在各种争议:
Memcached Client for Java 比 SpyMemcached更稳定、更早、更广泛;
SpyMemcached 比 Memcached Client for Java更高效;
XMemcached 比 SpyMemcache并发效果更好。
方式一:Memcached Client for Java
jar包准备:java_memcached-release_2.6.6.jar
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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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>
</property></property></bean>
<!-- Memcached配置 -->
<bean class="com.danga.MemCached.SockIOPool" destroy-method="shutDown" factory-method="getInstance" id="memcachedPool" init-method="initialize">
<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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:task="http://www.springframework.org/schema/task" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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 -->
<!-- aspectj-autoproxy /> -->
</mvc:annotation-driven></context:component-scan></bean></import></beans>
Memcached工具类:
/*
* 文件名:MemcachedUtils.java
* 版权:Copyright 2007-2016 517na Tech. Co. Ltd. All Rights Reserved.
* 描述: MemcachedUtils.java
* 修改人:peiyu
* 修改时间:2016年8月2日
* 修改内容:新增
*/
package com.springmvc.imooc.util;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import com.danga.MemCached.MemCachedClient;
/**
* @author peiyu
*/
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
jar包准备:spymemcached-2.10.3.jar
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=falseapp-context-spymemcached.xml配置bean:
<!--?xml version="1.0" encoding="UTF-8"?-->
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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>
</property></property></bean>
<!-- Memcached配置 -->
<!--
枚举类型要想注入到类中,一定要先使用org.springframework.beans.factory.config.FieldRetrievingFactoryBean类将枚举类型进行转换
将DefaultHashAlgorithm.KETAMA_HASH转换为KETAMA_HASH这个bean,
然后在要注入的bean中使用<property name="hashAlg" ref="KETAMA_HASH" />引用即可。
-->
<bean class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean" id="KETAMA_HASH">
<property name="staticField" value="net.spy.memcached.DefaultHashAlgorithm.KETAMA_HASH">
</property></bean>
<bean class="net.spy.memcached.spring.MemcachedClientFactoryBean" id="memcachedClient">
<!-- 一个字符串,包括由空格或逗号分隔的主机或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">
</property></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}">
</property></property></property></property></property></property></property></property></bean>
<bean class="com.springmvc.imooc.util.SpyMemcachedManager" id="memcachedManager">
<property name="memcachedClient" ref="memcachedClient">
</property></bean>
</beans>SpyMemcachedManager 工具类:
/* * 文件名:SpyMemcachedManager.java * 版权:Copyright 2007-2016 517na Tech. Co. Ltd. All Rights Reserved. * 描述: SpyMemcachedManager.java * 修改人:peiyu * 修改时间:2016年8月3日 * 修改内容:新增 */ package com.springmvc.imooc.util; 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; /** * TODO 添加类的一句话简单描述. * <p> * TODO 详细描述 * <p> * TODO 示例代码 <pre> * </pre> * * @author peiyu */ 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; } }测试:
/* * 文件名:XMemcachedSpring.java * 版权:Copyright 2007-2016 517na Tech. Co. Ltd. All Rights Reserved. * 描述: XMemcachedSpring.java * 修改人:peiyu * 修改时间:2016年8月3日 * 修改内容:新增 */ package com.springmvc.imooc.test; import org.junit.Before; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.springmvc.imooc.util.SpyMemcachedManager; /** * * @author peiyu */ 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
jar包准备:xmemcached-1.4.1.jar
xmemcached.properties配置文件:
#连接池大小即客户端个数 memcached.connectionPoolSize=1 memcached.failureMode=true #server1 memcached.server1.host=127.0.0.1 memcached.server1.port=11211 memcached.server1.weight=1app-context-xmemcached.xml配置文件:
<!--?xml version="1.0" encoding="UTF-8"?--> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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> </property></property></bean> <!-- Memcached配置 --> <!-- p:connectionPoolSize="${memcached.connectionPoolSize}" p:failureMode="${memcached.failureMode}" --> <bean class="net.rubyeye.xmemcached.XMemcachedClientBuilder" id="memcachedClientBuilder"> <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"> </bean></property> <property name="sessionLocator"> <bean class="net.rubyeye.xmemcached.impl.KetamaMemcachedSessionLocator"> </bean></property> <property name="transcoder"> <bean class="net.rubyeye.xmemcached.transcoders.SerializingTranscoder"> </bean></property> <property name="connectionPoolSize" value="${memcached.connectionPoolSize}"> <property name="failureMode" value="${memcached.failureMode}"> </property></property></bean> <!-- Use factory bean to build memcached client --> <bean destroy-method="shutdown" factory-bean="memcachedClientBuilder" factory-method="build" id="memcachedClient"> </bean></beans>测试:
/* * 文件名:XMemcachedSpring.java * 版权:Copyright 2007-2016 517na Tech. Co. Ltd. All Rights Reserved. * 描述: XMemcachedSpring.java * 修改人:peiyu * 修改时间:2016年8月3日 * 修改内容:新增 */ package com.springmvc.imooc.test; import org.junit.Before; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import net.rubyeye.xmemcached.MemcachedClient; /** * @author peiyu */ 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(); } } }BaseTest 类:
package com.springmvc.imooc.test;
import java.io.FileNotFoundException;
import org.apache.log4j.Logger;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.Log4jConfigurer;
/**
* @author guangyin
*/
@RunWith(SpringJUnit4ClassRunner.class)
/*
* @TransactionConfiguration(transactionManager = "transactionManager")
*
* @Transactional
*/
@ContextConfiguration("/com/springmvc/config/app-context.xml")
public class BaseTest {
/**
* 添加字段注释.
*/
protected Logger logger = Logger.getLogger(BaseTest.class);
static {
try {
Log4jConfigurer.initLogging("WebContent/WEB-INF/config/log4j.properties");
} catch (FileNotFoundException ex) {
System.err.println("Cannot Initialize log4j");
}
}
}
相关文章推荐
- Spring集成Memcached三种方式
- spring集成mybatis的三种方式
- spring和mybatis集成的三种方式
- Spring和resteasy集成三种方式
- ssh项目中集成spring的三种方式
- Spring 集成Hibernate的三种方式
- Spring和resteasy集成三种方式
- Memcached与Spring集成的方式(待实践)
- Spring中接口注入的三种方式
- 用Spring 更好地处理Struts 动作,三种整合Struts应用程序与 Spring 的方式
- 分享Spring中接口注入的三种方式
- Spring中接口注入的三种方式
- Spring中接口注入的三种方式
- Spring 和struts 整合的三种方式
- Spring与struts 整合的三种方式
- 三种整合 Struts 应用程序与 Spring 的方式
- Spring整合Struts三种方式
- Spring 和struts 整合的三种方式
- Spring配置数据源的三种方式
- 用 Spring 更好地处理 Struts 动作三种整合 Struts 应用程序与 Spring 的方式