---
title: "memcached三种客户端的使用"
author: "TableMiao"
date: "2014-12-03T14:54:20Z"
tags: []
categories: ["移动开发"]
slug: "memcached"
draft: false
lastmod: "2014-12-03T17:31:30Z"
id: 2162906
url: "https://tablemiao.iteye.com/blog/2162906"
---

Memcached 三种客户端使用

废话说在前头

萌生写博客这个想法，主要在于好整理笔记和巩固知识，加深对在工作中遇到问题的印象，新手上路，请多指教，欢迎圈错，共同学习。

第一种

   []()[]()Com.danga 包下面的memcached，需引入jar(本人用的是memcached-2.5.2.jar 文末附上附件需要的可以下载)

第二种

spyMemcached

第三种

       XMemcached  （本人偏向这种）

 

###### 三者差异与性能比对

a.com.danga 包下的 memcached

    第一种出来的版本很早，资料也比较全。网上也有很多解释以及例子，但如今实际项目使用中几乎不用它，大概是性能与迸发低于后两种。

b. xmemcached与spymemcached

    xmemcached比spymemcached有更好的性能表现，在get、set、delete、multi-gets等操作的测试中都远远超过或者接近spymemcached。  
    xmemcached在win32和linux两个平台上都有极佳的性能表现。  
    xmemcached支持动态地添加或者移除memcached server,可以通过编程或者JMX来做到。  
    xmemcached支持JMX，可以通过jmx调整性能参数、添加/移除memcached节点、查看统计。  
    xmemcached有客户端统计，可以统计xmemcached客户端的各种操作的总次数。  
    xmemcached允许调整更多的网络层参数和优化选项。  
    xmemcached暂未支持二进制协议，计划在1.2版本中实现。  
    xmemcached的API模型是同步的，而spymemcached的API模型是异步模型，同步模型对应用编程来说更容易使用和直观。

    xmemcached的序列化机制，是使用了spymemcached的序列化机制，并做了部分改造。

 

###### 三者具体使用

   第一种

         1.配置文件memcached.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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd">
 
    <bean id="memcachedPool" class="com.danga.MemCached.SockIOPool"
        factory-method="getInstance" init-method="initialize">
        <constructor-arg>
            <value>neeaMemcachedPool</value>
        </constructor-arg>
        <!-- 服务器连接地址 -->
        <property name="servers">
            <list>
                <value>127.0.0.1:11211</value>
            </list>
        </property>
        
        <!-- 初始化连接数 -->
        <property name="initConn" value="20" />
        <!-- 最小连接数 -->
        <property name="minConn" value="10" />
        <!-- 最大连接数 -->
        <property name="maxConn" value="50" />
        <!-- 设置tcp连接参数   nagle演算法为false(具体是什么不知道)-->
        <property name="nagle" value="false" />
       	<!-- 连接超时时间 -->
        <property name="socketTO" value="3000" />
    </bean>
    
    <bean id="memcachedClient" class="com.danga.MemCached.MemCachedClient">
        <constructor-arg>
            <value>neeaMemcachedPool</value>
        </constructor-arg>
    </bean>
    
    <!-- 注入自己写的类 -->
    <bean id="memcachedUtils" class="com.sss.comm.MemcachedUtils" />
</beans>   
```

          2.封装的memcached的使用类

```
package com.sss.comm;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.danga.MemCached.MemCachedClient;

public class MemcachedUtils {

	protected org.slf4j.Logger logger = LoggerFactory
			.getLogger(this.getClass());

	@Autowired
	private MemCachedClient memcachedClient;

	/***
	 * 添加缓存
	 * 
	 * @param key
	 * @param value
	 * @param expiry
	 *            超时时间（单位：分钟）
	 * @throws Exception
	 */
	public void addCache(String key, Object value, int expiry) throws Exception {

		if (StringUtils.isEmpty(key) || value == null) {
			throw new IllegalArgumentException("参数错误！");
		}
		// 时间换成分钟
		Date date = new Date();
		date.setTime(date.getTime() + expiry * 60 * 1000);
		boolean isSuc = memcachedClient.set(key, value, date);
		if (!isSuc) {
			throw new IllegalStateException("缓存存储失败！");
		}
	}

	/***
	 * 查找
	 * 
	 * @param key
	 *            键值
	 * @return
	 * @throws Exception
	 */
	public Object findCache(String key) throws Exception {
		if (StringUtils.isEmpty(key)) {
			throw new IllegalArgumentException("参数错误！");
		}
		return memcachedClient.get(key);
	}

	/***
	 * 删除
	 * 
	 * @param key
	 *            键值
	 * @throws Exception
	 */
	public void deleteCache(String key) throws Exception {
		if (StringUtils.isEmpty(key)) {
			throw new IllegalArgumentException("参数错误！");
		}
		memcachedClient.delete(key);
	}

}
```

 3.使用方式

        获取到MemcachedUtils类调用其方法即可。

 

 

第二种

       1.附上与maven集成的依赖（不使用maven管理的，可以忽略，直接下载jar包即可，文末附上，有需要的可以下载）

 

```
            <dependency>
			<groupId>spy</groupId>
			<artifactId>spymemcached</artifactId>
			<version>2.8.12</version>
		</dependency>  
```

   2.配置文件 spy-memcached.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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd">
 
   <bean id="memcachedClient" class="net.spy.memcached.spring.MemcachedClientFactoryBean">  
    <property name="servers" value="127.0.0.1:11211"/>  
    <property name="protocol" value="BINARY"/>  
    <property name="transcoder">  
      <bean class="net.spy.memcached.transcoders.SerializingTranscoder">  
        <property name="compressionThreshold" value="1024"/>  
      </bean>  
    </property>  
    <property name="opTimeout" value="1000"/>  
    <property name="timeoutExceptionThreshold" value="1998"/>  
     <property name="hashAlg" value="KETAMA_HASH"/> 
    <property name="locatorType" value="CONSISTENT"/>   
    <property name="failureMode" value="Redistribute"/>  
    <property name="useNagleAlgorithm" value="false"/>  
  </bean>  
    
    <!-- 注入自己写的类 -->
    <bean id="memcachedUtils" class="com.sss.util.MemcachedUtils" />
</beans>
```

  3.封装的memcached使用类

         注：该方式与第一种类似，只是在set方法的时候，传入参数顺序调换。缓存时间需注意，若memcached的服务端装在windows上，可能会出现运行错误。

```
package com.sss.util;


import net.spy.memcached.MemcachedClient;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;


public class MemcachedUtils {

	protected org.slf4j.Logger logger = LoggerFactory
			.getLogger(this.getClass());

	@Autowired
	private MemcachedClient memcachedClient;
							
	/***
	 * 添加缓存
	 * 
	 * @param key
	 * @param value
	 * @param expiry
	 *            超时时间（单位：分钟）
	 * @throws Exception
	 */
	public void addCache(String key, Object value, int expiry) throws Exception {
		
		if (StringUtils.isEmpty(key) || value == null) {
			throw new IllegalArgumentException("参数错误！");
		}
		//Date date = new Date();
		//date.setTime(date.getTime() + expiry * 60 * 1000);
		memcachedClient.set(key, expiry, value);

	}

	public Object findCache(String key) throws Exception {
		if (StringUtils.isEmpty(key)) {
			throw new IllegalArgumentException("参数错误！");
		}
		return memcachedClient.get(key);
	}

	public void deleteCache(String key) throws Exception {
		if (StringUtils.isEmpty(key)) {
			throw new IllegalArgumentException("参数错误！");
		}
		memcachedClient.delete(key);
	}
	
}
       
```

 4.使用方式

         获取到memcachedUtils类，调用其方法即可。

 

 

第三种

      1.附上与maven集成的依赖（不用maven管理的忽略，直接下载jar包即可，文末附上，有需要的可以下载）

 

```
            <dependency>
			<groupId>com.googlecode.xmemcached</groupId>
			<artifactId>xmemcached</artifactId>
			 <version>2.0.0</version>
		</dependency>
```

  2.配置文件x-memcached.xml

```
<!-- 注入自己写的类 -->
	<bean id="cacheService" class="com.sss.util.XMemcachedClient">
	</bean>


	<bean name="memcachedClient"
		class="net.rubyeye.xmemcached.utils.XMemcachedClientFactoryBean"
		destroy-method="shutdown">
		<property name="servers">
			<value>127.0.0.1:11211</value>
		</property>
	</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:util="http://www.springframework.org/schema/util"
	xmlns:jee="http://www.springframework.org/schema/jee"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    	   http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
    	   http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">

	 <bean name="memcachedServers" class="java.net.InetSocketAddress"
		factory-method="getAddresses">
		<constructor-arg value="127.0.0.1:11211" />
	</bean>

	<bean name="memcachedClientBuilder" class="net.rubyeye.xmemcached.XMemcachedClientBuilder">
		<constructor-arg index="0" ref="memcachedServers" /> 
		<property name="connectionPoolSize" value="1"></property>
		<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" />
		</property>
	</bean>

	<bean name="memcachedClient" factory-bean="memcachedClientBuilder"
		factory-method="build" destroy-method="shutdown" /> 
	
	<!-- 注入自己写的类 -->
	<bean id="cacheService" class="com.sss.util.XMemcachedClient">
	</bean>

	
</beans> 
```

  3.封装的memcached使用类

```
package com.sss.util;

import net.rubyeye.xmemcached.MemcachedClient;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

public class XMemcachedClient {
	
	protected org.slf4j.Logger logger = LoggerFactory
			.getLogger(this.getClass());
	
	@Autowired
	private MemcachedClient memcachedClient;
	/***
	 * 添加缓存
	 * 
	 * @param key
	 * @param value
	 * @param expiry
	 *            超时时间（单位：分钟）
	 * @throws Exception
	 */
	public void addCache(String key, Object value, int expiry) throws Exception {
		
		if (StringUtils.isEmpty(key) || value == null) {
			throw new IllegalArgumentException("参数错误！");
		}
		 boolean isCache = memcachedClient.add(key, expiry*60, value);
		 
		if (!isCache) {
			throw new IllegalStateException("缓存存储失败！");
		}
	}

	public Object findCache(String key) throws Exception {
		if (StringUtils.isEmpty(key)) {
			throw new IllegalArgumentException("参数错误！");
		}
		return memcachedClient.get(key);
	}

	public void deleteCache(String key) throws Exception {
		if (StringUtils.isEmpty(key)) {
			throw new IllegalArgumentException("参数错误！");
		}
		memcachedClient.delete(key);
	}
}
      
```

 4.使用方式

         获取到XMemcached类调用其方法即可。

 

 

使用心得：

      第一种方式适合单机练手，熟悉memcached。第二、三种方式项目中使用的比较多，使用配置的xml文件最好带上.properties文件，便于统一管理参数。

 

 

 由于jar总是上传失败，我就上传到csdn了，不用分直接下载可用,需要的可以点击

[http://download.csdn.net/detail/u011269546/8221111](http://download.csdn.net/detail/u011269546/8221111 "spymemcached")

[http://download.csdn.net/detail/u011269546/8221139](http://download.csdn.net/detail/u011269546/8221139 "xmemcached")

[http://download.csdn.net/detail/u011269546/8220099](http://download.csdn.net/detail/u011269546/8220099 "danga下使用的memcached")

 

参考：

[http://www.iteye.com/news/7717-xmemcached---faster-than-spymemcached](http://www.iteye.com/news/7717-xmemcached---faster-than-spymemcached)

[http://www.lingzhong.cn/tech/40454.htm](http://www.lingzhong.cn/tech/40454.htm)