---
title: "Memcached学习——（二）"
author: "beyond429"
date: "2012-11-28T17:08:52Z"
tags: []
categories: ["编程语言"]
slug: "memcached"
draft: false
lastmod: "2012-11-28T17:08:52Z"
id: 1736750
url: "https://beyond429.iteye.com/blog/1736750"
---

原文地址： http://snowolf.iteye.com/blog/1471805

 

今天研究[Memcached](http://memcached.org/)的Java的Client，使用XMemcached 1.3.5，做个简单的测试，并介绍如何与Spring集成。 

**相关链接：**   
**[Memcached笔记——（一）安装&常规错误&监控](http://snowolf.iteye.com/blog/1447348)**   
**[Memcached笔记——（二）XMemcached&Spring集成](http://snowolf.iteye.com/blog/1471805)**   
**[Memcached笔记——（三）Memcached使用总结](http://snowolf.iteye.com/blog/1576818)**   
**[Memcached笔记——（四）应对高并发攻击](http://snowolf.iteye.com/blog/1677495)** 

**一、Memcached Client简要介绍**   
Memcached Client目前有3种： 

- [Memcached Client for Java](http://code.google.com/p/memcache-client-forjava/)
- [SpyMemcached](http://code.google.com/p/spymemcached/)
- [XMemcached](http://code.google.com/p/xmemcached/)

这三种Client一直存在各种争议： 

- Memcached Client for Java 比 SpyMemcached更稳定、更早、更广泛；
- SpyMemcached 比 Memcached Client for Java更高效；
- XMemcached 比 SpyMemcache并发效果更好。

用数据来说话，参考官方性能对比：   
Memcached Client for Java：[https://github.com/gwhalin/Memcached-Java-Client/wiki/PERFORMANCE](https://github.com/gwhalin/Memcached-Java-Client/wiki/PERFORMANCE)   
XMemcached：[http://xmemcached.googlecode.com/svn/trunk/benchmark/benchmark.html](http://xmemcached.googlecode.com/svn/trunk/benchmark/benchmark.html) 

**二、XMemcached特性**   
XMemcached特性： 

- 高性能
- 支持完整的memcached文本协议,二进制协议。
- 支持JMX，可以通过MBean调整性能参数、动态添加/移除server、查看统计等。
- 支持客户端统计
- 支持memcached节点的动态增减。
- 支持memcached分布:余数分布和一致性哈希分布。
- 更多的性能调整选项。

此外，XMemcached更容易与Spring集成。而且，属于中国原创！![](http://snowolf.iteye.com/images/smiles/icon_biggrin.gif)  

**三、XMemcached简单实现** 

**MemcachedClientBuilder**是MemcachedClient核心接口，用来控制Client的构建（build()方法）和关闭（shutdown()方法）。   
**XMemcachedClientBuilder**一般通过构造方法配置地址列表，通常还要配置权重，代码如下： 

Java代码  [![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

01. public XMemcachedClientBuilder(List&lt;InetSocketAddress&gt; addressList) {
02. if (addressList != null) {
03. for (InetSocketAddress addr : addressList) {
04. this.addressMap.put(addr, null);
05. }
06. }
07. }
08. public XMemcachedClientBuilder(List&lt;InetSocketAddress&gt; addressList,
09. int\[] weights) {
10. if (addressList != null) {
11. for (InetSocketAddress addr : addressList) {
12. this.addressMap.put(addr, null);
13. }
14. }
15. this.weights = weights;
16. }

不过这哥们如果用this()可以省点代码，![](http://snowolf.iteye.com/images/smiles/icon_biggrin.gif) 还有给加点注释吧！![](http://snowolf.iteye.com/images/smiles/icon_smile.gif)   
此外，还需要设置连接池大小，使用二进制协议/文本协议等。   
通过build()方法获得**MemcachedClient**   
然后就可以通过Memcached进行set、get、replace、delete等Memcached操作了！![](http://snowolf.iteye.com/images/smiles/icon_biggrin.gif)   
上代码： 

Java代码  [![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

01. import static junit.framework.Assert.\*;
02. import java.io.IOException;
03. import java.util.concurrent.TimeoutException;
04. import net.rubyeye.xmemcached.MemcachedClient;
05. import net.rubyeye.xmemcached.MemcachedClientBuilder;
06. import net.rubyeye.xmemcached.XMemcachedClientBuilder;
07. import net.rubyeye.xmemcached.command.BinaryCommandFactory;
08. import net.rubyeye.xmemcached.exception.MemcachedException;
09. import net.rubyeye.xmemcached.utils.AddrUtil;
10. import org.junit.Test;
11. public class MemcachedClientTest {
12. @Test
13. public void test() {
14. MemcachedClientBuilder builder = new XMemcachedClientBuilder(
15. AddrUtil.getAddresses("10.11.155.26:11211 10.11.155.41:11211 10.10.76.31:11211 10.10.76.35:11211"),
16. new int\[] { 1, 1, 1, 1 });
17. // 设置连接池大小，即客户端个数
18. builder.setConnectionPoolSize(50);
19. // 宕机报警
20. builder.setFailureMode(true);
21. // 使用二进制文件
22. builder.setCommandFactory(new BinaryCommandFactory());
23. MemcachedClient memcachedClient = null;
24. try {
25. memcachedClient = builder.build();
26. try {
27. // 设置/获取
28. memcachedClient.set("zlex", 36000, "set/get");
29. assertEquals("set/get", memcachedClient.get("zlex"));
30. // 替换
31. memcachedClient.replace("zlex", 36000, "replace");
32. assertEquals("replace", memcachedClient.get("zlex"));
33. // 移除
34. memcachedClient.delete("zlex");
35. assertNull(memcachedClient.get("zlex"));
36. } catch (TimeoutException e) {
37. // TODO Auto-generated catch block
38. e.printStackTrace();
39. } catch (InterruptedException e) {
40. // TODO Auto-generated catch block
41. e.printStackTrace();
42. } catch (MemcachedException e) {
43. // TODO Auto-generated catch block
44. e.printStackTrace();
45. }
46. } catch (IOException e) {
47. // TODO Auto-generated catch block
48. e.printStackTrace();
49. } finally {
50. if (memcachedClient != null) {
51. try {
52. memcachedClient.shutdown();
53. } catch (IOException e) {
54. // TODO Auto-generated catch block
55. e.printStackTrace();
56. }
57. }
58. }
59. }
60. }

**四、XMemcached与Spring集成**   
XMemcached与Spring集成可以参考[http://code.google.com/p/xmemcached/wiki/Spring\_Integration](http://code.google.com/p/xmemcached/wiki/Spring_Integration)，这里只说最常用的方法。   
memcached.properties做基本配置： 

Properties代码  [![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

01. #连接池大小即客户端个数
02. memcached.connectionPoolSize=50
03. memcached.failureMode=true
04. #server1
05. memcached.server1.host=10.11.155.26
06. memcached.server1.port=11211
07. memcached.server1.weight=4
08. #server2
09. memcached.server2.host=10.11.155.41
10. memcached.server2.port=11211
11. memcached.server2.weight=3
12. #server3
13. memcached.server3.host=10.10.76.31
14. memcached.server3.port=11211
15. memcached.server3.weight=2
16. #server4
17. memcached.server4.host=10.10.76.35
18. memcached.server4.port=11211
19. memcached.server4.weight=1

XML配置文件： 

Xml代码  [![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

01. &lt;?xml version="1.0" encoding="UTF-8"?&gt;
02. &lt;beans
03. xmlns="http://www.springframework.org/schema/beans"
04. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
05. xmlns:context="http://www.springframework.org/schema/context"
06. xmlns:p="http://www.springframework.org/schema/p"
07. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
08. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"&gt;
09. &lt;!-- http://code.google.com/p/xmemcached/wiki/Spring\_Integration --&gt;
10. &lt;context:property-placeholder location="memcached.properties" /&gt;
11. &lt;bean
12. id="memcachedClientBuilder"
13. class="net.rubyeye.xmemcached.XMemcachedClientBuilder"
14. p:connectionPoolSize="${memcached.connectionPoolSize}"
15. p:failureMode="${memcached.failureMode}"&gt;
16. &lt;!-- XMemcachedClientBuilder have two arguments.First is server list,and
17. second is weights array. --&gt;
18. &lt;constructor-arg&gt;
19. &lt;list&gt;
20. &lt;bean class="java.net.InetSocketAddress"&gt;
21. &lt;constructor-arg&gt;
22. &lt;value&gt;${memcached.server1.host}&lt;/value&gt;
23. &lt;/constructor-arg&gt;
24. &lt;constructor-arg&gt;
25. &lt;value&gt;${memcached.server1.port}&lt;/value&gt;
26. &lt;/constructor-arg&gt;
27. &lt;/bean&gt;
28. &lt;bean class="java.net.InetSocketAddress"&gt;
29. &lt;constructor-arg&gt;
30. &lt;value&gt;${memcached.server2.host}&lt;/value&gt;
31. &lt;/constructor-arg&gt;
32. &lt;constructor-arg&gt;
33. &lt;value&gt;${memcached.server2.port}&lt;/value&gt;
34. &lt;/constructor-arg&gt;
35. &lt;/bean&gt;
36. &lt;bean class="java.net.InetSocketAddress"&gt;
37. &lt;constructor-arg&gt;
38. &lt;value&gt;${memcached.server3.host}&lt;/value&gt;
39. &lt;/constructor-arg&gt;
40. &lt;constructor-arg&gt;
41. &lt;value&gt;${memcached.server3.port}&lt;/value&gt;
42. &lt;/constructor-arg&gt;
43. &lt;/bean&gt;
44. &lt;bean class="java.net.InetSocketAddress"&gt;
45. &lt;constructor-arg&gt;
46. &lt;value&gt;${memcached.server4.host}&lt;/value&gt;
47. &lt;/constructor-arg&gt;
48. &lt;constructor-arg&gt;
49. &lt;value&gt;${memcached.server4.port}&lt;/value&gt;
50. &lt;/constructor-arg&gt;
51. &lt;/bean&gt;
52. &lt;/list&gt;
53. &lt;/constructor-arg&gt;
54. &lt;constructor-arg&gt;
55. &lt;list&gt;
56. &lt;value&gt;${memcached.server1.weight}&lt;/value&gt;
57. &lt;value&gt;${memcached.server2.weight}&lt;/value&gt;
58. &lt;value&gt;${memcached.server3.weight}&lt;/value&gt;
59. &lt;value&gt;${memcached.server4.weight}&lt;/value&gt;
60. &lt;/list&gt;
61. &lt;/constructor-arg&gt;
62. &lt;property name="commandFactory"&gt;
63. &lt;bean class="net.rubyeye.xmemcached.command.TextCommandFactory" /&gt;
64. &lt;/property&gt;
65. &lt;property name="sessionLocator"&gt;
66. &lt;bean class="net.rubyeye.xmemcached.impl.KetamaMemcachedSessionLocator" /&gt;
67. &lt;/property&gt;
68. &lt;property name="transcoder"&gt;
69. &lt;bean class="net.rubyeye.xmemcached.transcoders.SerializingTranscoder" /&gt;
70. &lt;/property&gt;
71. &lt;/bean&gt;
72. &lt;!-- Use factory bean to build memcached client --&gt;
73. &lt;bean
74. id="memcachedClient"
75. factory-bean="memcachedClientBuilder"
76. factory-method="build"
77. destroy-method="shutdown" /&gt;
78. &lt;/beans&gt;

这里的**memcachedClientBuilder**节点完成**MemcachedClientBuilder**，然后通过**memcachedClient**节点配置**factory-method**，调用**MemcachedClientBuilder**的build()方法产生**MemcachedClient**，并配置**destroy-method**进行关闭。   
不过我还是疑惑，这里的异常由谁来处理？Spring容器吗？![](http://snowolf.iteye.com/images/smiles/icon_confused.gif) 或者需要另一个代理Bean包装一下？ 

有了Spring容器支持，我们不需要在代码中进行配置，也不需要重复调用build()跟shutdown()方法，这些操作交给Spring来完成。   
代码如下： 

Java代码  [![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

01. import static junit.framework.Assert.\*;
02. import java.util.concurrent.TimeoutException;
03. import net.rubyeye.xmemcached.MemcachedClient;
04. import net.rubyeye.xmemcached.exception.MemcachedException;
05. import org.junit.Before;
06. import org.junit.Test;
07. import org.springframework.context.ApplicationContext;
08. import org.springframework.context.support.ClassPathXmlApplicationContext;
09. public class MemcachedSpringTest {
10. private ApplicationContext app;
11. private MemcachedClient memcachedClient;
12. @Before
13. public void init() {
14. app = new ClassPathXmlApplicationContext("applicationContext.xml");
15. memcachedClient = (MemcachedClient) app.getBean("memcachedClient");
16. }
17. @Test
18. public void test() {
19. try {
20. // 设置/获取
21. memcachedClient.set("zlex", 36000, "set/get");
22. assertEquals("set/get", memcachedClient.get("zlex"));
23. // 替换
24. memcachedClient.replace("zlex", 36000, "replace");
25. assertEquals("replace", memcachedClient.get("zlex"));
26. // 移除
27. memcachedClient.delete("zlex");
28. assertNull(memcachedClient.get("zlex"));
29. } catch (TimeoutException e) {
30. // TODO Auto-generated catch block
31. e.printStackTrace();
32. } catch (InterruptedException e) {
33. // TODO Auto-generated catch block
34. e.printStackTrace();
35. } catch (MemcachedException e) {
36. // TODO Auto-generated catch block
37. e.printStackTrace();
38. }
39. }
40. }