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 socket = createSocket( servers[i] );
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 );}