Spring与Memcached-xmemcached整合

1 简介
Xmemcached是一个高性能的基于java nio的memcached客户端。在经过三个RC版本后,正式发布1.10-final版本。
xmemcached特性一览:
1、高性能
2、支持完整的memcached文本协议,二进制协议将在1.2版本实现。
3、支持JMX,可以通过MBean调整性能参数、动态添加/移除server、查看统计等。
4、支持客户端统计
5、支持memcached节点的动态增减。
6、支持memcached分布:余数分布和一致性哈希分布。
7、更多的性能调整选项。


2 与Spring整合
XMemcached从1.1.2开始,能灵活方便的与Spring Framework整合在一起使用。
<bean name="memcachedClient"
		class="net.rubyeye.xmemcached.utils.XMemcachedClientFactoryBean">
		<property name="servers">
			<value>${memcached.server.ip}:${memcached.server.port} ${memcached.server.ip2}:${memcached.server.port2}</value>
		</property>
		<property name="weights">
			<list>
				<value>1</value>
				<value>1</value>
			</list>
		</property>
		<property name="connectionPoolSize" value="${memcached.server.connectionPoolSize}"></property>
		<property name="commandFactory">
			<bean class="net.rubyeye.xmemcached.command.BinaryCommandFactory"></bean>
		</property>
		<property name="sessionLocator">
			<bean class="net.rubyeye.xmemcached.impl.KetamaMemcachedSessionLocator"></bean>
		</property>
		<property name="transcoder">
			<bean class="net.rubyeye.xmemcached.transcoders.SerializingTranscoder" />
		</property>
		<property name="bufferAllocator">
			<bean class="net.rubyeye.xmemcached.buffer.SimpleBufferAllocator"></bean>
		</property>
	</bean>
	<bean id="memcachedService" class="com.right.framework.cache.MemcachedService">
		<property name="memcachedClient" ref="memcachedClient" />
	</bean>
import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.TimeoutException;

import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.exception.MemcachedException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

/**
 * Memcached客户端工具类
 * @author wangqinghua 2015-08-08
 */
public class MemcachedService {
    private static final Logger LOG = LoggerFactory.getLogger(MemcachedService.class);

	private MemcachedClient memcachedClient;

	private static Long DEFAULT_OP_TIMEOUT = 10000L;//10min
	
	//@Value("${cache.default.expire.time}")
	//public static int defaultExpireTime = 2592000;//一个月缓存
	public static int defaultExpireTime = 86400;//默认缓存1天:24*60*60=86400

	/**
	 * Memcached是否可用
	 * @return
	 * @author wangqinghua 2015-08-08
	 */
	@Deprecated
	public boolean isAvaliable() {
		if (memcachedClient.isShutdown()) {
            LOG.error("memcached客户端已关闭");
			return false;
		}
		Map<InetSocketAddress, String> map = null;
		try {
			map = memcachedClient.getVersions();
		} catch (Exception e) {
            LOG.error("获取memcached server version时异常", e);
		}
		if (map == null || map.size() == 0) {
            LOG.error("当前没有可用的memcached server");
			return false;
		}
		//cache正常可用
		return true;
	}

	/**
	 * @param key
	 * @return
	 * @author wangqinghua 2015-08-08
	 */
	public Object getValue(String key) {
		Object value = null;
		Assert.notNull(key);
		try {
			value = memcachedClient.get(key);
		} catch (TimeoutException e) {
            LOG.error("Cache TimeoutException", e);
		} catch (InterruptedException e) {
            LOG.error("Cache InterruptedException", e);
		} catch (MemcachedException e) {
            LOG.error("Cache MemcachedException", e);
		}
		return value;
	}
	
	/**
	 * @param key
	 * @param t
	 * @return
	 * @author wangqinghua 2015-08-08
	 */
	public <T> T getValue(String key, Class<T> t) {
		T value = null;
		Assert.notNull(key);
		try {
			value = this.memcachedClient.get(key);
		} catch (TimeoutException e) {
            LOG.error("Cache TimeoutException", e);
		} catch (InterruptedException e) {
            LOG.error("Cache InterruptedException", e);
		} catch (MemcachedException e) {
            LOG.error("Cache MemcachedException", e);
		}
		return value;
	}
	
	/**
	 * 在cache中保存value
	 * @param key
	 * @param value
	 * @author wangqinghua 2015-08-08
	 */
	public void setValue(String key, Object value) {
		Assert.notNull(key,"cache key is null.");
		try {
			memcachedClient.set(key, defaultExpireTime, value);
		} catch (TimeoutException e) {
            LOG.error("Cache TimeoutException", e);
		} catch (InterruptedException e) {
            LOG.error("Cache InterruptedException", e);
		} catch (MemcachedException e) {
            LOG.error("Cache MemcachedException", e);
		}
	}

	/**
	 * 在cache中保存value
	 * @param key
	 * @param value
	 * @param exp 表示被保存的时长,单位:秒
	 * @author wangqinghua 2015-08-08
	 */
	public void setValue(String key, int exp, Object value) {
		Assert.notNull(key,"cache key is null.");
		Assert.notNull(exp>0,"exp must greate than zero.");
		try {
			memcachedClient.set(key, exp, value);
		} catch (TimeoutException e) {
            LOG.error("Cache TimeoutException", e);
		} catch (InterruptedException e) {
            LOG.error("Cache InterruptedException", e);
		} catch (MemcachedException e) {
            LOG.error("Cache MemcachedException", e);
		}
	}
	
	/**
	 * 删除cache保存的value
	 * @param key
	 * @return
	 * @author wangqinghua 2015-08-08
	 */
	public Boolean remove(String key){
		try {
			return memcachedClient.delete(key, DEFAULT_OP_TIMEOUT);
		} catch (TimeoutException e) {
            LOG.error("Cache TimeoutException", e);
		} catch (InterruptedException e) {
            LOG.error("Cache InterruptedException", e);
		} catch (MemcachedException e) {
            LOG.error("Cache MemcachedException", e);
		}
		return Boolean.FALSE;
	}


	/**
	 * 删除cache保存的value,设置超时时间
	 * @param key
	 * @param opTimeout
	 * @return
	 * @author wangqinghua 2015-08-08
	 */
	public Boolean remove(String key, Long opTimeout){
		try {
			return memcachedClient.delete(key, opTimeout);
		} catch (TimeoutException e) {
            LOG.error("Cache TimeoutException", e);
		} catch (InterruptedException e) {
            LOG.error("Cache InterruptedException", e);
		} catch (MemcachedException e) {
            LOG.error("Cache MemcachedException", e);
		}
		return Boolean.FALSE;
	}

	public MemcachedClient getMemcachedClient() {
		return memcachedClient;
	}

	public void setMemcachedClient(MemcachedClient memcachedClient) {
		this.memcachedClient = memcachedClient;
	}

}






其中各参数的意义:

参数
含义

servers
服务器列表,格式:ip:port

weights
主机映射:host1对应1号、host2对应2号..

sessionLocator
Session 分配器,有自带的,影响分布式

transcoder
通信编码方式

bufferAllocator
缓冲区分配器
spring+xmemcached aop切面 需要xmemcached-1.2.5+spring-2.5.6 <bean name="factoryMemcachedClient" class="net.rubyeye.xmemcached.utils.XMemcachedClientFactoryBean" destroy-method="shutdown"> <property name="servers"> <value>${XMemcached_servers}</value> </property> <!-- server's weights --> <property name="weights"> <list> <value>1</value> <value>2</value> <value>3</value> </list> </property> <!-- nio connection pool size --> <property name="connectionPoolSize" value="${XMemcached_connectionPoolSize}"></property> <!-- Use binary protocol,default is TextCommandFactory, BinaryCommandFactory KestrelCommandFactory --> <property name="commandFactory"> <bean class="net.rubyeye.xmemcached.command.BinaryCommandFactory"></bean> </property> <!-- Distributed strategy KetamaMemcachedSessionLocator--> <property name="sessionLocator"> <bean class="net.rubyeye.xmemcached.impl.KetamaMemcachedSessionLocator"></bean> </property> <!-- Serializing transcoder --> <property name="transcoder"> <bean class="net.rubyeye.xmemcached.transcoders.SerializingTranscoder" /> </property> <!-- ByteBuffer allocator --> <property name="bufferAllocator"> <bean class="net.rubyeye.xmemcached.buffer.SimpleBufferAllocator"></bean> </property> </bean> <bean id="cachingClient" class="com.dmx.cache.caching.impl.CachingXMemcachedClient" init-method="init" destroy-method="destroy"> <property name="memcachedClient" ref="factoryMemcachedClient" /> <property name="isflushAll" value="${XMemcached_isflushAll}" /> </bean> <bean id="cachingManager" class="com.dmx.cache.caching.impl.CachingManagerImpl"> <property name="cachingClient" ref="cachingClient" /> </bean> <bean id="cacheBeforeAdvice" class="com.dmx.cache.interceptor.advice.CacheBeforeAdvice"></bean> <bean id="cacheAfterAdvice" class="com.dmx.cache.interceptor.advice.CacheAfterAdvice"></bean> <bean id="cacheInterceptor" class="com.dmx.cache.interceptor.CacheInterceptor"> <property name="cachingManager" ref="cachingManager" /> <property name="cacheAttributes"> <props> <prop key="save*">update</prop> <prop key="remove*">update</prop> <prop key="add*">update</prop> <prop key="del*">update</prop> <prop key="get*">readOnly</prop> <prop key="getPlaybill">readOnly=10</prop> </props> </property> </bean> <bean id="cacheProxyFactoryBean" class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="interceptorNames"> <list> <value>cacheBeforeAdvice</value> <value>cacheAfterAdvice</value> <value>cacheInterceptor</value> </list> </property> </bean> <bean id="demoDao" parent="cacheProxyFactoryBean"> <property name="target" ref="demoDaotarget" /> </bean>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一屁小肥咩

您的鼓励将是我创作的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值