redis源码解读总结(redis一致性哈希实现)

最近工作中一直在用redis进行缓存功能的实现,redis的源码虽然只有一万多行,但是确实值得研究一下,以下个人的一点研究和看法(本来打算用图表示,实在找不到一种好的画图工具来描述,因此就用文字描述了),希望能跟各位共勉之。
一、1.构建JedisShardInfo列表List<JedisShardInfo> jedisShardInfoList,其中JedisShardInfo包含了服务器IP,端口等信息,其源码如下:

[java]  view plain  copy
  1. public JedisShardInfo(String host, int port, String name) {  
  2. this(host, port, 2000, name);  
  3. }  
2.构建GenericObjectPoolConfig poolConfig这个里面主要设置缓存池的配置:最大连接数,最大等待时间等配置信息。
3.基于1和2去构建ShardedJedisPool对象,主要源码如下:

[java]  view plain  copy
  1. public ShardedJedisPool(final GenericObjectPoolConfig poolConfig,  
  2. List<JedisShardInfo> shards) {  
  3. this(poolConfig, shards, Hashing.MURMUR_HASH);  
  4. }  
构建此对象的过程中,同时构建了一个ShardedJedisFactory对象,这个对象很重要,后续会有详细讲解,构建此对象源码如下:

[java]  view plain  copy
  1. public ShardedJedisPool(final GenericObjectPoolConfig poolConfig,  
  2. List<JedisShardInfo> shards, Hashing algo, Pattern keyTagPattern) {  
  3. super(poolConfig, new ShardedJedisFactory(shards, algo, keyTagPattern));  
  4. }  
调用父类构造函数:

[java]  view plain  copy
  1. public Pool(final GenericObjectPoolConfig poolConfig,  
  2. PooledObjectFactory<T> factory) {  
  3. initPool(poolConfig, factory);  
  4. }  
调用初始化池initPool()方法,下面的代码只留关键源码:

[java]  view plain  copy
  1. public void initPool(final GenericObjectPoolConfig poolConfig,  
  2. PooledObjectFactory<T> factory) {  
  3. this.internalPool = new GenericObjectPool<T>(factory, poolConfig);  
  4. }  
上面的代码将之前说的一个非常重要的ShardedJedisFactory对象,装载到了GenericObjectPool类里面。
以上的所有信息都是为了后面的重要操作,像各种数据结构的操作,做铺垫。
二、在"一"的基础上进行以下操作,上面已经构建了ShardedJedisPool
1.调用ShardedJedisPool的getResource方法返回ShardedJedis进行get或者set操作

[java]  view plain  copy
  1. public T getResource() {  
  2. return internalPool.borrowObject();  
  3. }  
此处的internalPool对象即为1中最后的GenericObjectPool这个类的对象实例,最终会调用到此类中的create方法

[java]  view plain  copy
  1. private PooledObject<T> create() throws Exception {  
  2. final PooledObject<T> p;  
  3. try {  
  4. p = factory.makeObject();  
  5. catch (Exception e) {  
  6. createCount.decrementAndGet();  
  7. throw e;  
  8. }  
  9. return p;  
  10. }  
上面说过ShardedJedisFactory这个对象非常重要就在于此,factory.makeObject()操作中的factory就是
ShardedJedisFactory这个类,之前已经装载进去了,上面有说明;makeObject这个方法也是这个类里面最重要的一个方法

[java]  view plain  copy
  1. @Override  
  2. public PooledObject<ShardedJedis> makeObject() throws Exception {  
  3. ShardedJedis jedis = new ShardedJedis(shards, algo, keyTagPattern);  
  4. return new DefaultPooledObject<ShardedJedis>(jedis);  
  5. }  
makeObject这个方法(1)第一步就是构建了一个ShardedJedis对象,就是调用getResource()方法返回的对象,这个对象包含对数据结构的各种操作,
通过构造函数ShardedJedis(shards, algo, keyTagPattern)调用父类的构造方法,然后调用initialize方法,这个初始化方法就是redis中使用一致性哈希的
地方所在,循环shards(此处的shards就是上面的jedisShardInfoList这个变量,比如说list的size为4,相当于有四台服务器),每一个shards设置160个
节点,n台服务器就会有n*160个节点,节点的key值就是通过Hashing计算出来,这些节点其实就是已经被均匀的分部到一个闭合的
环中了,这样服务器多话就会增加利用率;nodes设置完之后,就会将n个shards与对应的jedis设置到MAP中去了:

[java]  view plain  copy
  1. public Sharded(List<S> shards, Hashing algo, Pattern tagPattern) {  
  2. this.algo = algo;  
  3. this.tagPattern = tagPattern;  
  4. initialize(shards);  
  5. }  
  6.   
  7. private void initialize(List<S> shards) {  
  8. nodes = new TreeMap<Long, S>();  
  9.   
  10. for (int i = 0; i != shards.size(); ++i) {  
  11. final S shardInfo = shards.get(i);  
  12. if (shardInfo.getName() == null)  
  13. for (int n = 0; n < 160 * shardInfo.getWeight(); n++) {  
  14. nodes.put(this.algo.hash("SHARD-" + i + "-NODE-" + n),  
  15. shardInfo);  
  16. }  
  17. else  
  18. for (int n = 0; n < 160 * shardInfo.getWeight(); n++) {  
  19. nodes.put(  
  20. this.algo.hash(shardInfo.getName() + "*"  
  21. + shardInfo.getWeight() + n), shardInfo);  
  22. }  
  23. resources.put(shardInfo, shardInfo.createResource());  
  24. }  
  25. }  
上面的初始化动作做完之后这样在后面做缓存的时候或者从缓存中取值的时候都会首先通过key调用Hashing类中相同的算法计算出一致性哈希值,计算出
哈希值之后,根据TreeMap的tailMap方法从上面的nodes中获取到大于或者等于这个哈希值的SortedMap,然后获取第一个key以及对应的shardInfo,
最终会从resources中获取到jedis:

[java]  view plain  copy
  1. public R getShard(String key) {  
  2. return resources.get(getShardInfo(key));  
  3. }  
  4.   
  5. public S getShardInfo(byte[] key) {  
  6. SortedMap<Long, S> tail = nodes.tailMap(algo.hash(key));  
  7. if (tail.isEmpty()) {  
  8. return nodes.get(nodes.firstKey());  
  9. }  
  10. return tail.get(tail.firstKey());  
  11. }  
[java]  view plain  copy
  1. public String set(String key, String value) {  
  2. Jedis j = getShard(key);  
  3. return j.set(key, value);  
  4. }  
(2)第二步构建了DefaultPooledObject对象,通过此对象返回ShardedJedis,这个对象就是第一步要做的事情。

2.通过上面获取到的ShardedJedis进行数据的缓存或者获取,现举一例进行简单说明之,调用set方法,首先根据上面说的一致性哈希算法获取到jedis
jedis里面定义了一个客户端Client:
调用Jedis的set方法,首先完成客户端的连接,然后发送命令,进行数据的缓存:

[java]  view plain  copy
  1. protected Connection sendCommand(final Command cmd, final byte[]... args) {  
  2. connect();  
  3. Protocol.sendCommand(outputStream, cmd, args);  
  4. pipelinedCommands++;  
  5. return this;  
  6. }  
  7.   
  8. public void connect() {  
  9. if (!isConnected()) {  
  10. try {  
  11. socket = new Socket();  
  12. // ->@wjw_add  
  13. socket.setReuseAddress(true);  
  14. socket.setKeepAlive(true); // Will monitor the TCP connection is  
  15. // valid  
  16. socket.setTcpNoDelay(true); // Socket buffer Whetherclosed, to  
  17. // ensure timely delivery of data  
  18. socket.setSoLinger(true0); // Control calls close () method,  
  19. // the underlying socket is closed  
  20. // immediately  
  21. // <-@wjw_add  
  22.   
  23. socket.connect(new InetSocketAddress(host, port), timeout);  
  24. socket.setSoTimeout(timeout);  
  25. outputStream = new RedisOutputStream(socket.getOutputStream());  
  26. inputStream = new RedisInputStream(socket.getInputStream());  
  27. catch (IOException ex) {  
  28. throw new JedisConnectionException(ex);  
  29. }  
  30. }  
  31. }  
  32.   
  33. public static void sendCommand(final RedisOutputStream os,  
  34. final Command command, final byte[]... args) {  
  35. sendCommand(os, command.raw, args);  
  36. }  
  37.   
  38. private static void sendCommand(final RedisOutputStream os,  
  39. final byte[] command, final byte[]... args) {  
  40. try {  
  41. os.write(ASTERISK_BYTE);  
  42. os.writeIntCrLf(args.length + 1);  
  43. os.write(DOLLAR_BYTE);  
  44. os.writeIntCrLf(command.length);  
  45. os.write(command);  
  46. os.writeCrLf();  
  47.   
  48. for (final byte[] arg : args) {  
  49. os.write(DOLLAR_BYTE);  
  50. os.writeIntCrLf(arg.length);  
  51. os.write(arg);  
  52. os.writeCrLf();  
  53. }  
  54. catch (IOException e) {  
  55. throw new JedisConnectionException(e);  
  56. }  
  57. }  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值