日期:2014-05-20  浏览次数:20863 次

memcached 客户端代码 Java memcached client学习2(socket如何建立))
好了 继续我的代码研究之旅。
昨天晚上 看了一致性hash算法 拍案叫绝
请看如下代码:
//创建链接
for ( int j = 0; j < initConn; j++ ) {
				SockIO socket = createSocket( servers[i] );
				if ( socket == null ) {
					log.error( "++++ failed to create connection to: " + servers[i] + " -- only " + j + " created." );
					break;
				}
//加入socket到连接池 这里慢慢谈
	addSocketToPool( availPool, servers[i], socket );
		if ( log.isDebugEnabled() )
					log.debug( "++++ created and added socket: " + socket.toString() + " for host " + servers[i] );
}


先创建SockIO
SockIO socket = createSocket( servers[i] );

创建socket代码如下:
protected static Socket getSocket( String host, int port, int timeout ) throws IOException {
			SocketChannel sock = SocketChannel.open();
			sock.socket().connect( new InetSocketAddress( host, port ), timeout );
			return sock.socket();
		}


那如何将数据添加到可用池中呢?
如下代码:
protected void addSocketToPool( Map<String,Map<SockIO,Long>> pool, String host, SockIO socket ) {

		if ( pool.containsKey( host ) ) {
			Map<SockIO,Long> sockets = pool.get( host );

			if ( sockets != null ) {
				sockets.put( socket, new Long( System.currentTimeMillis() ) );
				return;
			}
		}

		Map<SockIO,Long> sockets =
			new IdentityHashMap<SockIO,Long>();

		sockets.put( socket, new Long( System.currentTimeMillis() ) );
		pool.put( host, sockets );
	}