---
title: "memcached客户端源码分析"
author: "Alex_hyts"
date: "2016-05-06T15:42:43Z"
tags: []
categories: ["开源软件"]
slug: "memcached"
draft: false
lastmod: "2016-05-06T15:43:17Z"
id: 2296350
url: "https://alex4java.iteye.com/blog/2296350"
---

### 转载：[memcached客户端源码分析](http://jameswxx.iteye.com/blog/1168711)

memcached的[Java](http://lib.csdn.net/base/17 "Java EE知识库")客户端有好几种，[http://code.google.com/p/memcached/wiki/Clients](http://code.google.com/p/memcached/wiki/Clients) 罗列了以下几种

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

01. spymemcached
02. * http://www.couchbase.org/code/couchbase/java
03. o An improved Java API maintained by Matt Ingenthron and others at Couchbase.
04. o Aggressively optimised, ability to run async, supports binary protocol, support Membase and Couchbase features, etc. See site for details.
05. Java memcached client
06. * http://www.whalin.com/memcached
07. o A Java API is maintained by Greg Whalin from Meetup.com.
08. More Java memcached clients
09. * http://code.google.com/p/javamemcachedclient
10. * http://code.google.com/p/memcache-client-forjava
11. * http://code.google.com/p/xmemcached
12. Integrations
13. * http://code.google.com/p/simple-spring-memcached
14. * http://code.google.com/p/memcached-session-manager

 

 

我看的是第二个：Java memcached client源码，代码很简洁，一共只有9个类，最主要的有以下三个  
MemcachedClient.java     客户端，负责提供外出程序接口，如get/set方法等等

SockIOPool.java          一个自平衡的连接池  
NativeHandler.java       负责部分数据类型的序列化

 

它包含以下几个部分  
1：key的服务端分布  
2：数据序列化和压缩  
3：连接池(连接方式和池的动态自动平衡)  
4：failover和failback机制  
5：和memcached服务器的通讯协议   
关于这几个点，我从key的set/get说起，会贯穿上面列举的4个部分。这个文章写下来，本来是作为一个笔记，思维比较跳跃，可能不是很连贯，如有疑问，欢迎站内交流。这个client的代码

很简洁明了，我也没有加过多注释，只是理了一个脉络。

 

 

**从客户端自带的测试代码开始**

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

01. package com.meetup.memcached.test;
02. import com.meetup.memcached.\*;
03. import org.apache.log4j.\*;
04. public class TestMemcached  {
05. public static void main(String\[] args) {
06. BasicConfigurator.configure();
07. String\[] servers = { "127.0.0.1:12000"};
08. SockIOPool pool = SockIOPool.getInstance();
09. pool.setServers( servers );
10. pool.setFailover( true );//故障转移
11. pool.setInitConn( 10 ); //初始化连接为10
12. pool.setMinConn( 5 );//最小连接为5
13. pool.setMaxConn( 250 );//最大连接为250
14. pool.setMaintSleep( 30 );//平衡线程休眠时间为30ms
15. pool.setNagle( false );//Nagle标志为false
16. pool.setSocketTO( 3000 );//响应超时时间为3000ms
17. pool.setAliveCheck( true );//需要可用状态检查
18. //初始化连接池，默认名称为"default"
19. pool.initialize();
20. //新建一个memcached客户端，如果没有给名字
21. MemcachedClient mcc = new MemcachedClient();
22. // turn off most memcached client logging:
23. com.meetup.memcached.Logger.getLogger( MemcachedClient.class.getName() ).setLevel( com.meetup.memcached.Logger.LEVEL\_WARN );
24. for ( int i = 0; i &lt; 10; i++ ) {
25. boolean success = mcc.set( "" + i, "Hello!" );
26. String result = (String)mcc.get( "" + i );
27. System.out.println( String.format( "set( %d ): %s", i, success ) );
28. System.out.println( String.format( "get( %d ): %s", i, result ) );
29. }
30. System.out.println( "\\n\\t -- sleeping --\\n" );
31. try { Thread.sleep( 10000 ); } catch ( Exception ex ) { }
32. for ( int i = 0; i &lt; 10; i++ ) {
33. boolean success = mcc.set( "" + i, "Hello!" );
34. String result = (String)mcc.get( "" + i );
35. System.out.println( String.format( "set( %d ): %s", i, success ) );
36. System.out.println( String.format( "get( %d ): %s", i, result ) );
37. }
38. }
39. }

 

   
以上代码大概做了这几件事情：  
初始化一个连接池  
新建一个memcached客户端  
set一个key/value  
get一个key，并且打印出value  
这是我们实际应用中很常见的场景。

**连接池的创建和初始化**   
        连接池SockIOPool是非常重要的部分，它的好坏直接决定了客户端的性能。SockIOPool用一个HashMap持有多个连接池对象，连接池以名称作为标识，默认为"default"。看看

SockIOPool的getInstance方法就知道了。

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

1. public static SockIOPool getInstance() {
2. return getInstance("default");
3. }
4. public static synchronized SockIOPool getInstance(String poolName) {
5. if (pools.containsKey(poolName)) return pools.get(poolName);
6. SockIOPool pool = new SockIOPool();
7. pools.put(poolName, pool);
8. return pool;
9. }

 

 

**连接池实例化完成后，还需要初始化，看看pool.initialize()做了什么：**

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

01. public void initialize() {
02. //这里以自身作为同步锁，防止被多次初始化
03. synchronized (this) {
04. // 如果已经被初始化了则终止初始化过程
05. if (initialized && (buckets != null || consistentBuckets != null) && (availPool != null)&& (busyPool != null)) {
06. log.error("++++ trying to initialize an already initialized pool");
07. return;
08. }
09. &lt;span style="color: #ff0000;"&gt;  // 可用连接集合&lt;/span&gt;
10. availPool = new HashMap&lt;String, Map&lt;SockIO, Long&gt;&gt;(servers.length * initConn);
11. //工作连接集合
12. busyPool = new HashMap&lt;String, Map&lt;SockIO, Long&gt;&gt;(servers.length * initConn);
13. // 不可用连接集合
14. deadPool = new IdentityHashMap&lt;SockIO, Integer&gt;();
15. hostDeadDur = new HashMap&lt;String, Long&gt;();
16. hostDead = new HashMap&lt;String, Date&gt;();
17. maxCreate = (poolMultiplier &gt; minConn) ? minConn : minConn / poolMultiplier;
18. if (log.isDebugEnabled()) {
19. log.debug("++++ initializing pool with following settings:");
20. log.debug("++++ initial size: " + initConn);
21. log.debug("++++ min spare   : " + minConn);
22. log.debug("++++ max spare   : " + maxConn);
23. }
24. if (servers == null || servers.length &lt;= 0) {
25. log.error("++++ trying to initialize with no servers");
26. throw new IllegalStateException("++++ trying to initialize with no servers");
27. }
28. // initalize our internal hashing structures
29. if (this.hashingAlg == CONSISTENT\_HASH) populateConsistentBuckets();
30. else populateBuckets();
31. // mark pool as initialized
32. this.initialized = true;
33. // start maint thread
34. if (this.maintSleep &gt; 0) this.startMaintThread();
35. }
36. }

   
 

 

 

**连接池的关闭**

很简单，只是重置清空相关参数而已

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

01. public void shutDown() {
02. synchronized (this) {
03. if (log.isDebugEnabled()) log.debug("++++ SockIOPool shutting down...");
04. if (maintThread != null && maintThread.isRunning()) {
05. // stop the main thread
06. stopMaintThread();
07. // wait for the thread to finish
08. while (maintThread.isRunning()) {
09. if (log.isDebugEnabled()) log.debug("++++ waiting for main thread to finish run +++");
10. try {
11. Thread.sleep(500);
12. } catch (Exception ex) {
13. }
14. }
15. }
16. if (log.isDebugEnabled()) log.debug("++++ closing all internal pools.");
17. closePool(availPool);
18. closePool(busyPool);
19. availPool = null;
20. busyPool = null;
21. buckets = null;
22. consistentBuckets = null;
23. hostDeadDur = null;
24. hostDead = null;
25. maintThread = null;
26. initialized = false;
27. if (log.isDebugEnabled()) log.debug("++++ SockIOPool finished shutting down.");
28. }
29. }

 

 

 

 

**连接池的自动平衡**  
SockIOPool的initialize()方法最后有这么一行代码

// start maint thread  
if (this.maintSleep &gt; 0) this.startMaintThread();  
 

 这是在初始化完成后，启动线程池平衡线程

  

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

01. protected void startMaintThread() {
02. if (maintThread != null) {
03. if (maintThread.isRunning()) {
04. log.error("main thread already running");
05. } else {
06. maintThread.start();
07. }
08. } else {
09. maintThread = new MaintThread(this);
10. maintThread.setInterval(this.maintSleep);
11. maintThread.start();
12. }
13. }

  

 

**MaintThread的run方法**

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

01. public void run() {
02. this.running = true;
03. while (!this.stopThread) {
04. try {
05. Thread.sleep(interval);
06. // if pool is initialized, then
07. // run the maintenance method on itself
08. if (pool.isInitialized()) pool.selfMaint();
09. } catch (Exception e) {
10. break;
11. }
12. }
13. this.running = false;

   
 **其实最终的平衡方法是SockIOPool.selfMaint()**

  

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

001. protected void selfMaint() {
002. if (log.isDebugEnabled()) log.debug("++++ Starting self maintenance....");
003. // go through avail sockets and create sockets
004. // as needed to maintain pool settings
005. Map&lt;String, Integer&gt; needSockets = new HashMap&lt;String, Integer&gt;();
006. synchronized (this) {
007. // 先统计每个服务器实例的可用连接是否小于最小可用连接数
008. for (Iterator&lt;String&gt; i = availPool.keySet().iterator(); i.hasNext();) {
009. String host = i.next();
010. Map&lt;SockIO, Long&gt; sockets = availPool.get(host);
011. if (log.isDebugEnabled()) log.debug("++++ Size of avail pool for host (" + host + ") = "
012. + sockets.size());
013. // if pool is too small (n &lt; minSpare)
014. if (sockets.size() &lt; minConn) {
015. // need to create new sockets
016. int need = minConn - sockets.size();
017. needSockets.put(host, need);
018. }
019. }
020. }
021. // 如果小于最小可用连接数，则要新建增加可用连接
022. Map&lt;String, Set&lt;SockIO&gt;&gt; newSockets = new HashMap&lt;String, Set&lt;SockIO&gt;&gt;();
023. for (String host : needSockets.keySet()) {
024. Integer need = needSockets.get(host);
025. if (log.isDebugEnabled()) log.debug("++++ Need to create " + need + " new sockets for pool for host: "
026. + host);
027. Set&lt;SockIO&gt; newSock = new HashSet&lt;SockIO&gt;(need);
028. for (int j = 0; j &lt; need; j++) {
029. SockIO socket = createSocket(host);
030. if (socket == null) break;
031. newSock.add(socket);
032. }
033. newSockets.put(host, newSock);
034. }
035. // synchronize to add and remove to/from avail pool
036. // as well as clean up the busy pool (no point in releasing
037. // lock here as should be quick to pool adjust and no
038. // blocking ops here)
039. synchronized (this) {
040. //将新建的连接添加到可用连接集合里
041. for (String host : newSockets.keySet()) {
042. Set&lt;SockIO&gt; sockets = newSockets.get(host);
043. for (SockIO socket : sockets)
044. addSocketToPool(availPool, host, socket);
045. }
046. for (Iterator&lt;String&gt; i = availPool.keySet().iterator(); i.hasNext();) {
047. String host = i.next();
048. Map&lt;SockIO, Long&gt; sockets = availPool.get(host);
049. if (log.isDebugEnabled()) log.debug("++++ Size of avail pool for host (" + host + ") = "
050. + sockets.size());
051. //如果可用连接超过了最大连接数，则要关闭一些
052. if (sockets.size() &gt; maxConn) {
053. // need to close down some sockets
054. int diff = sockets.size() - maxConn;
055. int needToClose = (diff &lt;= poolMultiplier) ? diff : (diff) / poolMultiplier;
056. if (log.isDebugEnabled()) log.debug("++++ need to remove " + needToClose
057. + " spare sockets for pool for host: " + host);
058. for (Iterator&lt;SockIO&gt; j = sockets.keySet().iterator(); j.hasNext();) {
059. if (needToClose &lt;= 0) break;
060. // remove stale entries
061. SockIO socket = j.next();
062. long expire = sockets.get(socket).longValue();
063. // 这里回收可用连接池的闲置连接,连接设置到可用连接池里时,expire设置为当前时间。如果 (expire + maxIdle) &lt; System.currentTimeMillis()为true，则表
064. 明，该连接在可用连接池呆得太久了，需要回收
065. if ((expire + maxIdle) &lt; System.currentTimeMillis()) {
066. if (log.isDebugEnabled()) log.debug("+++ removing stale entry from pool as it is past its idle timeout and pool is over max spare");
067. // remove from the availPool
068. deadPool.put(socket, ZERO);
069. j.remove();
070. needToClose--;
071. }
072. }
073. }
074. }
075. //清理正在工作的连接集合
076. for (Iterator&lt;String&gt; i = busyPool.keySet().iterator(); i.hasNext();) {
077. String host = i.next();
078. Map&lt;SockIO, Long&gt; sockets = busyPool.get(host);
079. if (log.isDebugEnabled()) log.debug("++++ Size of busy pool for host (" + host + ")  = "
080. + sockets.size());
081. // loop through all connections and check to see if we have any hung connections
082. for (Iterator&lt;SockIO&gt; j = sockets.keySet().iterator(); j.hasNext();) {
083. // remove stale entries
084. SockIO socket = j.next();
085. long hungTime = sockets.get(socket).longValue();
086. //如果工作时间超过maxBusyTime，则也要回收掉，超过maxBusyTime，可能是服务器响应时间过长
087. if ((hungTime + maxBusyTime) &lt; System.currentTimeMillis()) {
088. log.error("+++ removing potentially hung connection from busy pool ... socket in pool for "
089. + (System.currentTimeMillis() - hungTime) + "ms");
090. // remove from the busy pool
091. deadPool.put(socket, ZERO);
092. j.remove();
093. }
094. }
095. }
096. }
097. // 最后清理不可用连接集合
098. Set&lt;SockIO&gt; toClose;
099. synchronized (deadPool) {
100. toClose = deadPool.keySet();
101. deadPool = new IdentityHashMap&lt;SockIO, Integer&gt;();
102. }
103. for (SockIO socket : toClose) {
104. try {
105. socket.trueClose(false);
106. } catch (Exception ex) {
107. log.error("++++ failed to close SockIO obj from deadPool");
108. log.error(ex.getMessage(), ex);
109. }
110. socket = null;
111. }
112. if (log.isDebugEnabled()) log.debug("+++ ending self maintenance.");
113. }

   
 

 

 

**key的服务器端分布**

初始化方法其实就是根据每个服务器的权重，建立一个服务器地址集合，如果选择了一致性哈希，则对服务器地址进行一致性哈希分布，一致性哈希算法比较简单，如果不了解的同学，可以

自行google一下，initialize() 方法里有这段代码：

//一致性哈希

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

1. if (this.hashingAlg == CONSISTENT\_HASH){
2. populateConsistentBuckets();
3. }else populateBuckets();

   
 **看看populateConsistentBuckets()方法**

// 用一致性哈希算法将服务器分布在一个2的32次方的环里，服务器的分布位置&lt;=servers.length\*40\*4

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

01. private void populateConsistentBuckets() {
02. if (log.isDebugEnabled()) log.debug("++++ initializing internal hashing structure for consistent hashing");
03. // store buckets in tree map
04. this.consistentBuckets = new TreeMap&lt;Long, String&gt;();
05. MessageDigest md5 = MD5.get();
06. if (this.totalWeight &lt;= 0 && this.weights != null) {
07. for (int i = 0; i &lt; this.weights.length; i++)
08. this.totalWeight += (this.weights\[i] == null) ? 1 : this.weights\[i];
09. } else if (this.weights == null) {
10. this.totalWeight = this.servers.length;
11. }
12. for (int i = 0; i &lt; servers.length; i++) {
13. int thisWeight = 1;
14. if (this.weights != null && this.weights\[i] != null) thisWeight = this.weights\[i];
15. //这个值永远小于40 * this.servers.length,因为thisWeight/totalWeight永远小于1

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

01. double factor = Math.floor(((double) (40 * this.servers.length * thisWeight)) / (double) this.totalWeight);
02. //服务器的分布位置为factor\*4,factor&lt;=40\*this.servers.length,所以服务器的分布位置& lt;=40\*this.servers.length\*4。
03. for (long j = 0; j &lt; factor; j++) {
04. //md5值的二进制数组为16位
05. byte\[] d = md5.digest((servers\[i] + "-" + j).getBytes());
06. //16位二进制数组每4位为一组，每组第4个值左移24位，第三个值左移16位，第二个值左移8位，第一个值不移位。进行或运算，得到一个小于2的32 次方的long值。
07. for (int h = 0; h &lt; 4; h++) {
08. Long k = ((long) (d\[3 + h * 4] & 0xFF) &lt;&lt; 24) | ((long) (d\[2 + h * 4] & 0xFF) &lt;&lt; 16)
09. | ((long) (d\[1 + h * 4] & 0xFF) &lt;&lt; 8) | ((long) (d\[0 + h * 4] & 0xFF));
10. consistentBuckets.put(k, servers\[i]);
11. if (log.isDebugEnabled()) log.debug("++++ added " + servers\[i] + " to server bucket");
12. }
13. }
14. // create initial connections
15. if (log.isDebugEnabled()) log.debug("+++ creating initial connections (" + initConn + ") for host: "
16. + servers\[i]);
17. //创建连接
18. for (int j = 0; j &lt; initConn; j++) {
19. SockIO socket = createSocket(servers\[i]);
20. if (socket == null) {
21. log.error("++++ failed to create connection to: " + servers\[i] + " -- only " + j + " created.");
22. break;
23. }
24. //添加到可用连接池
25. addSocketToPool(availPool, servers\[i], socket);
26. if (log.isDebugEnabled()) log.debug("++++ created and added socket: " + socket.toString()
27. + " for host " + servers\[i]);
28. }
29. }

    

 

   如果不是一致性哈希，则只是普通分布，很简单，只是根据权重将服务器地址放入buckets这个List里

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

01. private void populateBuckets() {
02. if (log.isDebugEnabled()) log.debug("++++ initializing internal hashing structure for consistent hashing");
03. // store buckets in tree map
04. this.buckets = new ArrayList&lt;String&gt;();
05. for (int i = 0; i &lt; servers.length; i++) {
06. if (this.weights != null && this.weights.length &gt; i) {
07. for (int k = 0; k &lt; this.weights\[i].intValue(); k++) {
08. this.buckets.add(servers\[i]);
09. if (log.isDebugEnabled()) log.debug("++++ added " + servers\[i] + " to server bucket");
10. }
11. } else {
12. this.buckets.add(servers\[i]);
13. if (log.isDebugEnabled()) log.debug("++++ added " + servers\[i] + " to server bucket");
14. }
15. // create initial connections
16. if (log.isDebugEnabled()) log.debug("+++ creating initial connections (" + initConn + ") for host: "
17. + servers\[i]);
18. for (int j = 0; j &lt; initConn; j++) {
19. SockIO socket = createSocket(servers\[i]);
20. if (socket == null) {
21. log.error("++++ failed to create connection to: " + servers\[i] + " -- only " + j + " created.");
22. break;
23. }
24. //新建连接后，加入到可用连接集合里
25. addSocketToPool(availPool, servers\[i], socket);
26. if (log.isDebugEnabled()) log.debug("++++ created and added socket: " + socket.toString()
27. + " for host " + servers\[i]);
28. }
29. }
30. }

   
 

 

 

**如何创建socket连接**

在上面的private void populateBuckets()方法里，createSocket(servers\[i])是创建到服务器的连接，看看这个方法

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

01. protected SockIO createSocket(String host) {
02. SockIO socket = null;
03. //hostDeadLock是一个可重入锁,它的变量声明为
04. private final ReentrantLock             hostDeadLock    = new ReentrantLock();
05. hostDeadLock.lock();
06. try {
07. //hostDead.containsKey(host)为true表示曾经连接过该服务器，但没有成功。
08. //hostDead是一个HashMap，key为服务器地址，value为当时连接不成功的时间
09. //hostDeadDur是一个HashMap，key为服务器地址，value为设置的重试间隔时间
10. if (failover && failback && hostDead.containsKey(host) && hostDeadDur.containsKey(host)) {
11. Date store = hostDead.get(host);
12. long expire = hostDeadDur.get(host).longValue();
13. if ((store.getTime() + expire) &gt; System.currentTimeMillis()) return null;
14. }
15. } finally {
16. hostDeadLock.unlock();
17. }
18. try {
19. socket = new SockIO(this, host, this.socketTO, this.socketConnectTO, this.nagle);
20. if (!socket.isConnected()) {
21. log.error("++++ failed to get SockIO obj for: " + host + " -- new socket is not connected");
22. deadPool.put(socket, ZERO);
23. socket = null;
24. }
25. } catch (Exception ex) {
26. log.error("++++ failed to get SockIO obj for: " + host);
27. log.error(ex.getMessage(), ex);
28. socket = null;
29. }
30. // if we failed to get socket, then mark
31. // host dead for a duration which falls off
32. hostDeadLock.lock();
33. try {
34. //到了这里,socket仍然为null，说明这个server悲剧了，无法和它创建连接，则要把该server丢到不可用的主机集合里
35. if (socket == null) {
36. Date now = new Date();
37. hostDead.put(host, now);
38. //如果上次就不可用了，到期了仍然不可用，就要这次的不可用时间设为上次的2倍，否则初始时长为1000ms
39. long expire = (hostDeadDur.containsKey(host)) ? (((Long) hostDeadDur.get(host)).longValue() * 2) : 1000;
40. if (expire &gt; MAX\_RETRY\_DELAY) expire = MAX\_RETRY\_DELAY;
41. hostDeadDur.put(host, new Long(expire));
42. if (log.isDebugEnabled()) log.debug("++++ ignoring dead host: " + host + " for " + expire + " ms");
43. // 既然这个host都不可用了，那与它的所有连接当然要从可用连接集合"availPool"里删除掉
44. clearHostFromPool(availPool, host);
45. } else {
46. if (log.isDebugEnabled()) log.debug("++++ created socket (" + socket.toString() + ") for host: " + host);
47. //连接创建成功，如果上次不成功，那么这次要把该host从不可用主机集合里删除掉
48. if (hostDead.containsKey(host) || hostDeadDur.containsKey(host)) {
49. hostDead.remove(host);
50. hostDeadDur.remove(host);
51. }
52. }
53. } finally {
54. hostDeadLock.unlock();
55. }
56. return socket;
57. }

  

 

   **SockIO构造函数**

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

01. public SockIO(SockIOPool pool, String host, int timeout, int connectTimeout, boolean noDelay)
02. throws IOException,
03. UnknownHostException {
04. this.pool = pool;
05. String\[] ip = host.split(":");
06. // get socket: default is to use non-blocking connect
07. sock = getSocket(ip\[0], Integer.parseInt(ip\[1]), connectTimeout);
08. if (timeout &gt;= 0) this.sock.setSoTimeout(timeout);
09. // testing only
10. sock.setTcpNoDelay(noDelay);
11. // wrap streams
12. in = new DataInputStream(new BufferedInputStream(sock.getInputStream()));
13. out = new BufferedOutputStream(sock.getOutputStream());
14. this.host = host;
15. }

   
 

    **getSocket方法**

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

1. protected static Socket getSocket(String host, int port, int timeout) throws IOException {
2. SocketChannel sock = SocketChannel.open();
3. sock.socket().connect(new InetSocketAddress(host, port), timeout);
4. return sock.socket();
5. }

  可以看到，socket连接是用nio方式创建的。

 

 

 

 **新建MemcachedClient**   
MemcachedClient mcc = new MemcachedClient();新建了一个memcached客户端，看看构造函数，没作什么，只是设置参数而已。

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

01. /\**
02. * Creates a new instance of MemCachedClient.
03. \*/
04. public MemcachedClient() {
05. init();
06. }
07. private void init() {
08. this.sanitizeKeys       = true;
09. this.primitiveAsString  = false;
10. this.compressEnable     = true;
11. this.compressThreshold  = COMPRESS\_THRESH;
12. this.defaultEncoding    = "UTF-8";
13. this.poolName           = ( this.poolName == null ) ? "default" : this.poolName;
14. // get a pool instance to work with for the life of this instance
15. this.pool               = SockIOPool.getInstance( poolName );
16. }

 

 

 

 

 

 **set方法如何工作**

到此memcached客户端初始化工作完成。再回到测试类TestMemcached，看看for循环里的

boolean success = mcc.set( ""  + i, "Hello!" );  
 String result = (String)mcc.get( "" + i );  
 初始化后，就可以set，get了。看看set是怎么工作的。

 

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

001. /\**
002. * Stores data on the server; only the key and the value are specified.
003. \*
004. * @param key key to store data under
005. * @param value value to store
006. * @return true, if the data was successfully stored
007. \*/
008. public boolean set( String key, Object value ) {
009. return set( "set", key, value, null, null, primitiveAsString );
010. }
011. //这个set方法比较长
012. private boolean set( String cmdname, String key, Object value, Date expiry, Integer hashCode, boolean asString ) {
013. if ( cmdname == null || cmdname.trim().equals( "" ) || key == null ) {
014. log.error( "key is null or cmd is null/empty for set()" );
015. return false;
016. }
017. try {
018. key = sanitizeKey( key );
019. }
020. catch ( UnsupportedEncodingException e ) {
021. // if we have an errorHandler, use its hook
022. if ( errorHandler != null )
023. errorHandler.handleErrorOnSet( this, e, key );
024. log.error( "failed to sanitize your key!", e );
025. return false;
026. }
027. if ( value == null ) {
028. log.error( "trying to store a null value to cache" );
029. return false;
030. }
031. // get SockIO obj
032. SockIOPool.SockIO sock = pool.getSock( key, hashCode );
033. if ( sock == null ) {
034. if ( errorHandler != null )
035. errorHandler.handleErrorOnSet( this, new IOException( "no socket to server available" ), key );
036. return false;
037. }
038. if ( expiry == null )
039. expiry = new Date(0);
040. // store flags
041. int flags = 0;
042. // byte array to hold data
043. byte\[] val;
044. //这些类型自己序列化，否则由java序列化处理
045. if ( NativeHandler.isHandled( value ) ) {
046. if ( asString ) {
047. //如果是字符串，则直接getBytes
048. try {
049. if ( log.isInfoEnabled() )
050. log.info( "++++ storing data as a string for key: " + key + " for class: " + value.getClass().getName() );
051. val = value.toString().getBytes( defaultEncoding );
052. }
053. catch ( UnsupportedEncodingException ue ) {
054. // if we have an errorHandler, use its hook
055. if ( errorHandler != null )
056. errorHandler.handleErrorOnSet( this, ue, key );
057. log.error( "invalid encoding type used: " + defaultEncoding, ue );
058. sock.close();
059. sock = null;
060. return false;
061. }
062. }
063. else {
064. try {
065. if ( log.isInfoEnabled() )
066. log.info( "Storing with native handler..." );
067. flags |= NativeHandler.getMarkerFlag( value );
068. val    = NativeHandler.encode( value );
069. }
070. catch ( Exception e ) {
071. // if we have an errorHandler, use its hook
072. if ( errorHandler != null )
073. errorHandler.handleErrorOnSet( this, e, key );
074. log.error( "Failed to native handle obj", e );
075. sock.close();
076. sock = null;
077. return false;
078. }
079. }
080. }
081. else {
082. // 否则用java的序列化
083. try {
084. if ( log.isInfoEnabled() )
085. log.info( "++++ serializing for key: " + key + " for class: " + value.getClass().getName() );
086. ByteArrayOutputStream bos = new ByteArrayOutputStream();
087. (new ObjectOutputStream( bos )).writeObject( value );
088. val = bos.toByteArray();
089. flags |= F\_SERIALIZED;
090. }
091. catch ( IOException e ) {
092. // if we have an errorHandler, use its hook
093. if ( errorHandler != null )
094. errorHandler.handleErrorOnSet( this, e, key );
095. // if we fail to serialize, then
096. // we bail
097. log.error( "failed to serialize obj", e );
098. log.error( value.toString() );
099. // return socket to pool and bail
100. sock.close();
101. sock = null;
102. return false;
103. }
104. }
105. //压缩内容
106. if ( compressEnable && val.length &gt; compressThreshold ) {
107. try {
108. if ( log.isInfoEnabled() ) {
109. log.info( "++++ trying to compress data" );
110. log.info( "++++ size prior to compression: " + val.length );
111. }
112. ByteArrayOutputStream bos = new ByteArrayOutputStream( val.length );
113. GZIPOutputStream gos = new GZIPOutputStream( bos );
114. gos.write( val, 0, val.length );
115. gos.finish();
116. gos.close();
117. // store it and set compression flag
118. val = bos.toByteArray();
119. flags |= F\_COMPRESSED;
120. if ( log.isInfoEnabled() )
121. log.info( "++++ compression succeeded, size after: " + val.length );
122. }
123. catch ( IOException e ) {
124. // if we have an errorHandler, use its hook
125. if ( errorHandler != null )
126. errorHandler.handleErrorOnSet( this, e, key );
127. log.error( "IOException while compressing stream: " + e.getMessage() );
128. log.error( "storing data uncompressed" );
129. }
130. }
131. // now write the data to the cache server
132. try {
133. //按照memcached协议组装命令
134. String cmd = String.format( "%s %s %d %d %d\\r\\n", cmdname, key, flags, (expiry.getTime() / 1000), val.length );
135. sock.write( cmd.getBytes() );
136. sock.write( val );
137. sock.write( "\\r\\n".getBytes() );
138. sock.flush();
139. // get result code
140. String line = sock.readLine();
141. if ( log.isInfoEnabled() )
142. log.info( "++++ memcache cmd (result code): " + cmd + " (" + line + ")" );
143. if ( STORED.equals( line ) ) {
144. if ( log.isInfoEnabled() )
145. log.info("++++ data successfully stored for key: " + key );
146. sock.close();
147. sock = null;
148. return true;
149. }
150. else if ( NOTSTORED.equals( line ) ) {
151. if ( log.isInfoEnabled() )
152. log.info( "++++ data not stored in cache for key: " + key );
153. }
154. else {
155. log.error( "++++ error storing data in cache for key: " + key + " -- length: " + val.length );
156. log.error( "++++ server response: " + line );
157. }
158. }
159. catch ( IOException e ) {
160. // if we have an errorHandler, use its hook
161. if ( errorHandler != null )
162. errorHandler.handleErrorOnSet( this, e, key );
163. // exception thrown
164. log.error( "++++ exception thrown while writing bytes to server on set" );
165. log.error( e.getMessage(), e );
166. try {
167. sock.trueClose();
168. }
169. catch ( IOException ioe ) {
170. log.error( "++++ failed to close socket : " + sock.toString() );
171. }
172. sock = null;
173. }
174. //用完了，就要回收哦，sock.close()不是真正的关闭，只是放入到可用连接集合里。
175. if ( sock != null ) {
176. sock.close();
177. sock = null;
178. }
179. return false;
180. }

 通过set方法向服务器设置key和value，涉及到以下几个点  
数据的压缩和序列化 （如果是get方法，则和set方法基本是相反的）  
为key分配服务器 对于一些常用类型，采用自定义的序列化，具体要看NativeHander.java，这个类比较简单，有兴趣可以自己看看

 

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

01. public static boolean isHandled( Object value ) {
02. return (
03. value instanceof Byte            ||
04. value instanceof Boolean         ||
05. value instanceof Integer         ||
06. value instanceof Long            ||
07. value instanceof Character       ||
08. value instanceof String          ||
09. value instanceof StringBuffer    ||
10. value instanceof Float           ||
11. value instanceof Short           ||
12. value instanceof Double          ||
13. value instanceof Date            ||
14. value instanceof StringBuilder   ||
15. value instanceof byte\[]
16. )
17. ? true
18. : false;
19. }

 其他类型则用java的默认序列化

 

 

 

**为key选择服务器**   
SockIOPool.SockIO sock = pool.getSock( key, hashCode );就是为key选择服务器

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

01. public SockIO getSock(String key, Integer hashCode) {
02. if (log.isDebugEnabled()) log.debug("cache socket pick " + key + " " + hashCode);
03. if (!this.initialized) {
04. log.error("attempting to get SockIO from uninitialized pool!");
05. return null;
06. }
07. // if no servers return null
08. if ((this.hashingAlg == CONSISTENT\_HASH && consistentBuckets.size() == 0)
09. || (buckets != null && buckets.size() == 0)) return null;
10. // if only one server, return it
11. if ((this.hashingAlg == CONSISTENT\_HASH && consistentBuckets.size() == 1)
12. || (buckets != null && buckets.size() == 1)) {
13. SockIO sock = (this.hashingAlg == CONSISTENT\_HASH) ? getConnection(consistentBuckets.get(consistentBuckets.firstKey())) : getConnection(buckets.get(0));
14. if (sock != null && sock.isConnected()) {
15. if (aliveCheck) {//健康状态检查
16. if (!sock.isAlive()) {
17. sock.close();
18. try {
19. sock.trueClose();//有问题，真的关闭socket
20. } catch (IOException ioe) {
21. log.error("failed to close dead socket");
22. }
23. sock = null;
24. }
25. }
26. } else {//连接不正常，放入不可用连接集合里
27. if (sock != null) {
28. deadPool.put(sock, ZERO);
29. sock = null;
30. }
31. }
32. return sock;
33. }
34. Set&lt;String&gt; tryServers = new HashSet&lt;String&gt;(Arrays.asList(servers));
35. // get initial bucket
36. long bucket = getBucket(key, hashCode);
37. String server = (this.hashingAlg == CONSISTENT\_HASH) ? consistentBuckets.get(bucket) : buckets.get((int) bucket);
38. while (!tryServers.isEmpty()) {
39. // try to get socket from bucket
40. SockIO sock = getConnection(server);
41. if (log.isDebugEnabled()) log.debug("cache choose " + server + " for " + key);
42. if (sock != null && sock.isConnected()) {
43. if (aliveCheck) {
44. if (sock.isAlive()) {
45. return sock;
46. } else {
47. sock.close();
48. try {
49. sock.trueClose();
50. } catch (IOException ioe) {
51. log.error("failed to close dead socket");
52. }
53. sock = null;
54. }
55. } else {
56. return sock;
57. }
58. } else {
59. if (sock != null) {
60. deadPool.put(sock, ZERO);
61. sock = null;
62. }
63. }
64. // if we do not want to failover, then bail here
65. if (!failover) return null;
66. // log that we tried
67. tryServers.remove(server);
68. if (tryServers.isEmpty()) break;
69. //注意哦，下面是failover机制
70. int rehashTries = 0;
71. while (!tryServers.contains(server)) {
72. String newKey = String.format("%s%s", rehashTries, key);
73. if (log.isDebugEnabled()) log.debug("rehashing with: " + newKey);
74. bucket = getBucket(newKey, null);
75. server = (this.hashingAlg == CONSISTENT\_HASH) ? consistentBuckets.get(bucket) : buckets.get((int) bucket);
76. rehashTries++;
77. }
78. }
79. return null;
80. }

   
 

 

   下面这个方法是真正的从服务器获取连接

 

      
   

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

01. public SockIO getConnection(String host) {
02. if (!this.initialized) {
03. log.error("attempting to get SockIO from uninitialized pool!");
04. return null;
05. }
06. if (host == null) return null;
07. synchronized (this) {
08. // if we have items in the pool
09. // then we can return it
10. if (availPool != null && !availPool.isEmpty()) {
11. // take first connected socket
12. Map&lt;SockIO, Long&gt; aSockets = availPool.get(host);
13. if (aSockets != null && !aSockets.isEmpty()) {
14. for (Iterator&lt;SockIO&gt; i = aSockets.keySet().iterator(); i.hasNext();) {
15. SockIO socket = i.next();
16. if (socket.isConnected()) {
17. if (log.isDebugEnabled()) log.debug("++++ moving socket for host (" + host
18. + ") to busy pool ... socket: " + socket);
19. // remove from avail pool
20. i.remove();
21. // add to busy pool
22. addSocketToPool(busyPool, host, socket);
23. // return socket
24. return socket;
25. } else {
26. // add to deadpool for later reaping
27. deadPool.put(socket, ZERO);
28. // remove from avail pool
29. i.remove();
30. }
31. }
32. }
33. }
34. }
35. // create one socket -- let the maint thread take care of creating more
36. SockIO socket = createSocket(host);
37. if (socket != null) {
38. synchronized (this) {
39. addSocketToPool(busyPool, host, socket);
40. }
41. }
42. return socket;
43. }

  

 

 

 **failover和failback**

这两者都是发生在获取可用连接这个环节。

failover，如果为key选择的服务器不可用，则对key重新哈希选择下一个服务器，详见getSock方法的末尾。

failback，用一个hashmap存储连接失败的服务器和对应的失效持续时间，每次获取连接时，都探测是否到了重试时间。