jedis源码中ShardedJedis实现sharding

来源:互联网 发布:华迪实训基地网络设计 编辑:程序博客网 时间:2024/05/01 02:53

1、一个JedisShardInfo类,里面包含了jedis服务器的一些信息,比如

private int timeout;    private String host;    private int port;    private String password = null;    private String name = null;
最重要的是它的父类中有一个weight字段,作为本jedis服务器的权值。

这个类还有一个继承自父类的方法createResource,用来生成该类对应的Jedis对象


2、在构造ShardedJedis的时候传入一个JedisShardInfo的list列表。然后ShardedJedis的父类的父类及Sharede就会对这个list进行一些操作:

 public static final int DEFAULT_WEIGHT = 1;    private TreeMap<Long, S> nodes;    private final Hashing algo;    private final Map<ShardInfo<R>, R> resources = new LinkedHashMap<ShardInfo<R>, R>();

Sharded中的三个字段,nodes是用来模拟一致性哈希算法用的;algo是用来对字符串产生哈希值的hash函数,这里默认的是murmurhash,这个算法的随机分布特征表现比较好;resources这个map是用来存储JedisShardInfo与其对应的Jedis类之间的映射关系。


在上面提到的对list的操作:

private void initialize(List<S> shards) {        nodes = new TreeMap<Long, S>();        for (int i = 0; i != shards.size(); ++i) {            final S shardInfo = shards.get(i);            if (shardInfo.getName() == null)            for (int n = 0; n < 160 * shardInfo.getWeight(); n++) {            nodes.put(this.algo.hash("SHARD-" + i + "-NODE-" + n), shardInfo);            }            else            for (int n = 0; n < 160 * shardInfo.getWeight(); n++) {            nodes.put(this.algo.hash(shardInfo.getName() + "*" + shardInfo.getWeight() + n), shardInfo);            }            resources.put(shardInfo, shardInfo.createResource());        }    }


遍历list中的每一个shardInfo,将其权重weight*160生成n,然后用名字或者编号来生成n个哈希值(这个是为了保证哈希算法的平衡性而生成的虚拟节点),然后将其和本shardInfo的对应关系存储到treemap里面(这是在模拟一致性哈希算法中将虚拟节点映射到环上的操作),最后将shardInfo与对应的Jedis类的映射关系存储到resources里面。


3、在使用ShardedJedis进行操作的时候,每个方法都要先获得key经过hash后对应的Jedis对象,才能执行对应的方法,这个Jedis对象获取步骤如下:

1)、首先根据传入的key按照hash算法(默认为murmurhash)取得其value,然后用这个value到treemap中找key大于前面生成的value值的第一个键值对,这个键值对的value既是对应的shardedInfo

public S getShardInfo(byte[] key) {        SortedMap<Long, S> tail = nodes.tailMap(algo.hash(key));        if (tail.isEmpty()) {            return nodes.get(nodes.firstKey());        }        return tail.get(tail.firstKey());    }


2)、根据得到的shardedInfo从resources中取得对应的Jedis对象


以上提到的一致性哈希算法可参见上一篇转载自别人的文章。


原创粉丝点击