Memcached-java-client一致性哈希实现

本文介绍了如何在Memcached-java-client中实现一致性哈希。通过设置pool.setHashingAlg(SockIOPool.CONSISTENT_HASH)启用此算法。详细阐述了MemcachedClient和SockIOPool的初始化过程,以及一致性哈希的查找和服务器选择机制,包括哈希值计算和在虚拟节点圆环上的定位方法。
摘要由CSDN通过智能技术生成

一致性哈希算法介绍:一致性哈希算法

如果我们想使用一致性哈希算法,只需要添加pool.setHashingAlg(SockIOPool.CONSISTENT_HASH);这行代码即可

import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;

public class Test {
	public static void main(String[] args) {
		MemCachedClient client = new MemCachedClient();

		String[] servers = {"192.168.52.129:9999", 
				"192.168.52.131:9999"};
		Integer[] weights = {1, 1};

		SockIOPool pool = SockIOPool.getInstance();
		pool.setServers(servers);
		pool.setWeights(weights);
		pool.setInitConn(5);
		pool.setMinConn(5);
		pool.setMaxConn(250);
		pool.setMaxIdle(1000 * 60 * 60 * 6);
		pool.setMaintSleep(30);
		pool.setNagle(false);
		pool.setSocketTO(3000);
		pool.setSocketConnectTO(0);
		pool.setHashingAlg(SockIOPool.CONSISTENT_HASH); // 3
		pool.initialize();

		client.set("test", "This is a test String");
		String test = (String) client.get("test");
		
		System.out.println(test);
	}
}

来看下实际效果

sean@ubuntu1:~$ telnet 192.168.52.131 9999
Trying 192.168.52.131...
Connected to 192.168.52.131.
Escape character is '^]'.
get test
END

sean1@ubuntu2:~$ telnet 192.168.52.129 9999
Trying 192.168.52.129...
Connected to 192.168.52.129.
Escape character is '^]'.
get test
VALUE test 32 21
This is a test String
END

MemcachedClient的初始化方法,通过该方法可确定Client的具体实现类为AscIIClient

public MemCachedClient() {
	this(null, true, false);
}

public MemCachedClient(String var1, boolean var2, boolean var3) {
    this.BLAND_DATA_SIZE = "       ".getBytes();
    if(var3) {
        this.client = new BinaryClient(var1);
    } else {
        this.client = (MemCachedClient)(var2?
            new AscIIClient(var1):new AscIIUDPClient(var1));
    }
}

默认使用的连接池名称是default

public class AscIIClient extends MemCachedClient {

    // var1 = null
    public AscIIClient(String var1) {
        su
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值