---
title: "redisson-2.10.4源代码分析"
author: "1028826685"
date: "2018-06-26T23:50:58Z"
tags: []
categories: ["开源软件"]
slug: "redisson-2-10-4"
draft: false
lastmod: "2018-06-26T23:50:58Z"
id: 2425669
url: "https://1028826685.iteye.com/blog/2425669"
---

redis 学习问题总结

### [http://aperise.iteye.com/blog/2310639](http://aperise.iteye.com/blog/2310639)

ehcache memcached redis 缓存技术总结

### [http://aperise.iteye.com/blog/2296219](http://aperise.iteye.com/blog/2296219)

redis-stat 离线安装

### [http://aperise.iteye.com/blog/2310254](http://aperise.iteye.com/blog/2310254)

redis  cluster 非ruby方式启动

### [http://aperise.iteye.com/blog/2310254](http://aperise.iteye.com/admin/blogs/2315810 "http://aperise.iteye.com/admin/blogs/2315810")

redis-sentinel安装部署

### [http://aperise.iteye.com/blog/2342693](http://aperise.iteye.com/blog/2342693)

spring-data-redis使用

### [http://aperise.iteye.com/blog/2342615](http://aperise.iteye.com/blog/2342615)

redis客户端redisson实战

### [http://aperise.iteye.com/blog/2396196](http://aperise.iteye.com/blog/2396196)

redisson-2.10.4源代码分析

### [http://aperise.iteye.com/blog/2400528](http://aperise.iteye.com/blog/2400528)

tcmalloc jemalloc libc选择

### [http://blog.csdn.net/u010994304/article/details/49906819](http://blog.csdn.net/u010994304/article/details/49906819)

 

# 1.RedissonClient一主两从部署时连接池组成

       对如下图的**主从部署(1主2从)**：   
![](http://dl2.iteye.com/upload/attachment/0127/8893/bd29e573-5f71-3e0f-b4fd-9d1169a00887.jpg "点击查看原始大小图片")       **redisson纯java操作代码如下**： 

Java代码  [![收藏代码](http://aperise.iteye.com/images/icon_star.png)]()

01. Config config = new Config();// 创建配置
02. config.useMasterSlaveServers() // 指定使用主从部署方式
03. //.setReadMode(ReadMode.SLAVE) 默认值SLAVE，读操作只在从节点进行
04. //.setSubscriptionMode(SubscriptionMode.SLAVE) 默认值SLAVE，订阅操作只在从节点进行
05. //.setMasterConnectionMinimumIdleSize(10) 默认值10，针对每个master节点初始化10个连接
06. //.setMasterConnectionPoolSize(64) 默认值64，针对每个master节点初始化10个连接，最大可以扩展至64个连接
07. //.setSlaveConnectionMinimumIdleSize(10) 默认值10，针对每个slave节点初始化10个连接
08. //.setSlaveConnectionPoolSize(64) 默认值，针对每个slave节点初始化10个连接，最大可以扩展至64个连接
09. //.setSubscriptionConnectionMinimumIdleSize(1) 默认值1，在SubscriptionMode=SLAVE时候，针对每个slave节点初始化1个连接
10. //.setSubscriptionConnectionPoolSize(50) 默认值50，在SubscriptionMode=SLAVE时候，针对每个slave节点初始化1个连接，最大可以扩展至50个连接
11. .setMasterAddress("redis://192.168.29.24:6379")  // 设置redis主节点
12. .addSlaveAddress("redis://192.168.29.24:7000") // 设置redis从节点
13. .addSlaveAddress("redis://192.168.29.24:7001"); // 设置redis从节点
14. RedissonClient redisson = Redisson.create(config);// 创建客户端(发现这一操作非常耗时，基本在2秒-4秒左右)

       上面代码执行完毕后，如果在redis服务端所在服务器执行以下linux命令：

Java代码  [![收藏代码](http://aperise.iteye.com/images/icon_star.png)]()

1. #6379上建立了10个连接
2. netstat -ant |grep 6379|grep  ESTABLISHED
3. #7000上建立了11个连接
4. netstat -ant |grep 7000|grep  ESTABLISHED
5. #7001上建立了11个连接
6. netstat -ant |grep 7001|grep  ESTABLISHED

       你会发现**redisson连接到redis服务端总计建立了32个连接**，其中**masterpool占据10个连接，slavepool占据20个连接，另外pubSubConnectionPool占据2个连接**，连接池中池化对象分布如下图：  
![](http://dl2.iteye.com/upload/attachment/0127/9231/6e97555f-4960-3278-888d-2f6a00b03302.jpg "点击查看原始大小图片")

- MasterConnectionPool:默认针对每个不同的IP+port组合，初始化10个对象，最大可扩展至64个，因为只有一个master，**所以上图创建了10个连接；**
- **MasterPubSubConnectionPool**:默认针对每个不同的IP+port组合，初始化1个对象，最大可扩展至50个，因为**默认SubscriptionMode=SubscriptionMode.SLAVE，所以master上不会创建连接池**，**所以上图MasterPubSubConnectionPool里没有创建任何连接；**
- **SlaveConnectionPool**:默认针对每个不同的IP+port组合，初始化10个对象，最大可扩展至64个，因为有两个slave，每个slave上图创建了10个连接，**总计创建了20个连接；**
- **PubSubConnectionPool**:默认针对每个不同的IP+port组合，初始化1个对象，最大可扩展至50个，因为有两个slave，每个slave上图创建了1个连接，**总计创建了2个连接。**

       从上图可以看出，连接池是针对每个IP端口都有一个独立的池，连接池也按照主从进行划分，那么这些连接池是在**哪里初始化的？如何初始化的？读操作和写操作如何进行的？**这就是今天要解答的问题，要解答这些问题最好还是查看redisson的源码。

 

# 2.Redisson初始化连接池源码分析

## 2.1 Redisson.java

       RedissonClient.java是一个接口类，它的实现类是Redisson.java,对于Redisson.java的介绍先以一张Redisson的4大组件关系图开始，如下图：  
![](http://dl2.iteye.com/upload/attachment/0127/9052/f44287f6-cb3c-3c1e-9f05-82319b277a71.jpg "点击查看原始大小图片")  
       对Redisson.java的代码注释如下：

Java代码  [![收藏代码](http://aperise.iteye.com/images/icon_star.png)]()

01. /\**
02. * 根据配置Config创建redisson操作类RedissonClient
03. * @param config for Redisson
04. * @return Redisson instance
05. \*/
06. public static RedissonClient create(Config config) {
07. //调用构造方法
08. Redisson redisson = new Redisson(config);
09. if (config.isRedissonReferenceEnabled()) {
10. redisson.enableRedissonReferenceSupport();
11. }
12. return redisson;
13. }
14. /\**
15. * Redisson构造方法
16. * @param config for Redisson
17. * @return Redisson instance
18. \*/
19. protected Redisson(Config config) {
20. //赋值变量config
21. this.config = config;
22. //产生一份对于传入config的备份
23. Config configCopy = new Config(config);
24. //根据配置config的类型(主从模式、单机模式、哨兵模式、集群模式、亚马逊云模式、微软云模式)而进行不同的初始化
25. connectionManager = ConfigSupport.createConnectionManager(configCopy);
26. //连接池对象回收调度器
27. evictionScheduler = new EvictionScheduler(connectionManager.getCommandExecutor());
28. //Redisson的对象编码类
29. codecProvider = configCopy.getCodecProvider();
30. //Redisson的ResolverProvider，默认为org.redisson.liveobject.provider.DefaultResolverProvider
31. resolverProvider = configCopy.getResolverProvider();
32. }

       其中与连接池相关的就是**ConnectionManager**，ConnectionManager的初始化转交工具类ConfigSupport.java进行，ConfigSupport.java会根据部署方式(**主从模式、单机模式、哨兵模式、集群模式、亚马逊云模式、微软云模式**)的不同而分别进行。

 

## 2.2 ConfigSupport.java

       这里现将ConfigSupport.java创建ConnectionManager的核心代码注释如下： 

Java代码  [![收藏代码](http://aperise.iteye.com/images/icon_star.png)]()

01. /\**
02. * 据配置config的类型(主从模式、单机模式、哨兵模式、集群模式、亚马逊云模式、微软云模式)而进行不同的初始化
03. * @param configCopy for Redisson
04. * @return ConnectionManager instance
05. \*/
06. public static ConnectionManager createConnectionManager(Config configCopy) {
07. if (configCopy.getMasterSlaveServersConfig() != null) {//配置configCopy类型为主从模式
08. validate(configCopy.getMasterSlaveServersConfig());
09. return new MasterSlaveConnectionManager(configCopy.getMasterSlaveServersConfig(), configCopy);
10. } else if (configCopy.getSingleServerConfig() != null) {//配置configCopy类型为单机模式
11. validate(configCopy.getSingleServerConfig());
12. return new SingleConnectionManager(configCopy.getSingleServerConfig(), configCopy);
13. } else if (configCopy.getSentinelServersConfig() != null) {//配置configCopy类型为哨兵模式
14. validate(configCopy.getSentinelServersConfig());
15. return new SentinelConnectionManager(configCopy.getSentinelServersConfig(), configCopy);
16. } else if (configCopy.getClusterServersConfig() != null) {//配置configCopy类型为集群模式
17. validate(configCopy.getClusterServersConfig());
18. return new ClusterConnectionManager(configCopy.getClusterServersConfig(), configCopy);
19. } else if (configCopy.getElasticacheServersConfig() != null) {//配置configCopy类型为亚马逊云模式
20. validate(configCopy.getElasticacheServersConfig());
21. return new ElasticacheConnectionManager(configCopy.getElasticacheServersConfig(), configCopy);
22. } else if (configCopy.getReplicatedServersConfig() != null) {//配置configCopy类型为微软云模式
23. validate(configCopy.getReplicatedServersConfig());
24. return new ReplicatedConnectionManager(configCopy.getReplicatedServersConfig(), configCopy);
25. } else if (configCopy.getConnectionManager() != null) {//直接返回configCopy自带的默认ConnectionManager
26. return configCopy.getConnectionManager();
27. }else {
28. throw new IllegalArgumentException("server(s) address(es) not defined!");
29. }
30. }

       上面可以看到根据传入的配置Config.java的不同，会分别创建不同的ConnectionManager的实现类。

 

## 2.3 MasterSlaveConnectionManager.java

       这里开始介绍ConnectionManager，ConnectionManager.java是一个接口类，它有6个实现类，分别对应着不同的部署模式(**主从模式、单机模式、哨兵模式、集群模式、亚马逊云模式、微软云模式**),如下如所示：  
![](http://dl2.iteye.com/upload/attachment/0127/9056/07fc2d9d-b6a4-3c1b-abf7-8477f619d7be.png)       这里**以主从部署方式进行讲解**，先通过一张图了解**MasterSlaveConnectionManager**的组成：

![](http://dl2.iteye.com/upload/attachment/0127/9253/c45ffc15-b155-32f1-9e09-1a4e03ee7572.jpg "点击查看原始大小图片")  
       上图中最终要的组件要数**MasterSlaveEntry**，在后面即将进行介绍，这里注释**MasterSlaveConnectionManager.java**的核心代码如下：  

Java代码  [![收藏代码](http://aperise.iteye.com/images/icon_star.png)]()

001. /\**
002. * MasterSlaveConnectionManager的构造方法
003. * @param cfg for MasterSlaveServersConfig
004. * @param config for Config
005. \*/
006. public MasterSlaveConnectionManager(MasterSlaveServersConfig cfg, Config config) {
007. //调用构造方法
008. this(config);
009. //
010. initTimer(cfg);
011. this.config = cfg;
012. //初始化MasterSlaveEntry
013. initSingleEntry();
014. }
015. /\**
016. * MasterSlaveConnectionManager的构造方法
017. * @param cfg for Config
018. \*/
019. public MasterSlaveConnectionManager(Config cfg) {
020. //读取redisson的jar中的文件META-INF/MANIFEST.MF，打印出Bundle-Version对应的Redisson版本信息
021. Version.logVersion();
022. //EPOLL是linux的多路复用IO模型的增强版本，这里如果启用EPOLL，就让redisson底层netty使用EPOLL的方式，否则配置netty里的NIO非阻塞方式
023. if (cfg.isUseLinuxNativeEpoll()) {
024. if (cfg.getEventLoopGroup() == null) {
025. //使用linux IO非阻塞模型EPOLL
026. this.group = new EpollEventLoopGroup(cfg.getNettyThreads(), new DefaultThreadFactory("redisson-netty"));
027. } else {
028. this.group = cfg.getEventLoopGroup();
029. }
030. this.socketChannelClass = EpollSocketChannel.class;
031. } else {
032. if (cfg.getEventLoopGroup() == null) {
033. //使用linux IO非阻塞模型NIO
034. this.group = new NioEventLoopGroup(cfg.getNettyThreads(), new DefaultThreadFactory("redisson-netty"));
035. } else {
036. this.group = cfg.getEventLoopGroup();
037. }
038. this.socketChannelClass = NioSocketChannel.class;
039. }
040. if (cfg.getExecutor() == null) {
041. //线程池大小，对于2U 2CPU 8cores/cpu，意思是有2块板子，每个板子上8个物理CPU，那么总计物理CPU个数为16
042. //对于linux有个超线程概念，意思是每个物理CPU可以虚拟出2个逻辑CPU，那么总计逻辑CPU个数为32
043. //这里Runtime.getRuntime().availableProcessors()取的是逻辑CPU的个数，所以这里线程池大小会是64
044. int threads = Runtime.getRuntime().availableProcessors() * 2;
045. if (cfg.getThreads() != 0) {
046. threads = cfg.getThreads();
047. }
048. executor = Executors.newFixedThreadPool(threads, new DefaultThreadFactory("redisson"));
049. } else {
050. executor = cfg.getExecutor();
051. }
052. this.cfg = cfg;
053. this.codec = cfg.getCodec();
054. //一个可以获取异步执行任务返回值的回调对象，本质是对于java的Future的实现，监控MasterSlaveConnectionManager的shutdown进行一些必要的处理
055. this.shutdownPromise = newPromise();
056. //一个持有MasterSlaveConnectionManager的异步执行服务
057. this.commandExecutor = new CommandSyncService(this);
058. }
059. /\**
060. * 初始化定时调度器
061. * @param config for MasterSlaveServersConfig
062. \*/
063. protected void initTimer(MasterSlaveServersConfig config) {
064. //读取超时时间配置信息
065. int\[] timeouts = new int\[]{config.getRetryInterval(), config.getTimeout(), config.getReconnectionTimeout()};
066. Arrays.sort(timeouts);
067. int minTimeout = timeouts\[0];
068. //设置默认超时时间
069. if (minTimeout % 100 != 0) {
070. minTimeout = (minTimeout % 100) / 2;
071. } else if (minTimeout == 100) {
072. minTimeout = 50;
073. } else {
074. minTimeout = 100;
075. }
076. //创建定时调度器
077. timer = new HashedWheelTimer(Executors.defaultThreadFactory(), minTimeout, TimeUnit.MILLISECONDS, 1024);
078. // to avoid assertion error during timer.stop invocation
079. try {
080. Field leakField = HashedWheelTimer.class.getDeclaredField("leak");
081. leakField.setAccessible(true);
082. leakField.set(timer, null);
083. } catch (Exception e) {
084. throw new IllegalStateException(e);
085. }
086. //检测MasterSlaveConnectionManager的空闲连接的监视器IdleConnectionWatcher，会清理不用的空闲的池中连接对象
087. connectionWatcher = new IdleConnectionWatcher(this, config);
088. }
089. /\**
090. * 创建MasterSlaveConnectionManager的MasterSlaveEntry
091. \*/
092. protected void initSingleEntry() {
093. try {
094. //主从模式下0~16383加入到集合slots
095. HashSet&lt;ClusterSlotRange&gt; slots = new HashSet&lt;ClusterSlotRange&gt;();
096. slots.add(singleSlotRange);
097. MasterSlaveEntry entry;
098. if (config.checkSkipSlavesInit()) {//ReadMode不为MASTER并且SubscriptionMode不为MASTER才执行
099. entry = new SingleEntry(slots, this, config);
100. RFuture&lt;Void&gt; f = entry.setupMasterEntry(config.getMasterAddress());
101. f.syncUninterruptibly();
102. } else {//默认主从部署ReadMode=SLAVE,SubscriptionMode=SLAVE,这里会执行
103. entry = createMasterSlaveEntry(config, slots);
104. }
105. //将每个分片0~16383都指向创建的MasterSlaveEntry
106. for (int slot = singleSlotRange.getStartSlot(); slot &lt; singleSlotRange.getEndSlot() + 1; slot++) {
107. addEntry(slot, entry);
108. }
109. //DNS相关
110. if (config.getDnsMonitoringInterval() != -1) {
111. dnsMonitor = new DNSMonitor(this, Collections.singleton(config.getMasterAddress()),
112. config.getSlaveAddresses(), config.getDnsMonitoringInterval());
113. dnsMonitor.start();
114. }
115. } catch (RuntimeException e) {
116. stopThreads();
117. throw e;
118. }
119. }
120. /\**
121. * MasterSlaveEntry的构造方法
122. * @param config for MasterSlaveServersConfig
123. * @param slots for HashSet&lt;ClusterSlotRange&gt;
124. * @return MasterSlaveEntry
125. \*/
126. protected MasterSlaveEntry createMasterSlaveEntry(MasterSlaveServersConfig config, HashSet&lt;ClusterSlotRange&gt; slots) {
127. //创建MasterSlaveEntry
128. MasterSlaveEntry entry = new MasterSlaveEntry(slots, this, config);
129. //从节点连接池SlaveConnectionPool和PubSubConnectionPool的默认的最小连接数初始化
130. List&lt;RFuture&lt;Void&gt;&gt; fs = entry.initSlaveBalancer(java.util.Collections.&lt;URI&gt;emptySet());
131. for (RFuture&lt;Void&gt; future : fs) {
132. future.syncUninterruptibly();
133. }
134. 主节点连接池MasterConnectionPool和MasterPubSubConnectionPool的默认的最小连接数初始化
135. RFuture&lt;Void&gt; f = entry.setupMasterEntry(config.getMasterAddress());
136. f.syncUninterruptibly();
137. return entry;
138. }

       上面个人觉得有两处代码值得我们特别关注，特别说明如下：

- **entry.initSlaveBalancer：**从节点连接池**SlaveConnectionPool**和**PubSubConnectionPool**的默认的最小连接数初始化。
- **entry.setupMasterEntry：**主节点连接池**MasterConnectionPool**和**MasterPubSubConnectionPool**的默认的最小连接数初始化。

 

## 2.4 MasterSlaveEntry.java

       用一张图来解释MasterSlaveEntry的组件如下：  
![](http://dl2.iteye.com/upload/attachment/0127/9241/9d0cdf40-489f-3395-8540-7170f4cc51c8.jpg "点击查看原始大小图片")  
       MasterSlaveEntry.java里正是我们一直在寻找着的四个连接池**MasterConnectionPool、MasterPubSubConnectionPool、SlaveConnectionPool和PubSubConnectionPool**，这里注释MasterSlaveEntry.java的核心代码如下：

Java代码  [![收藏代码](http://aperise.iteye.com/images/icon_star.png)]()

001. /\**
002. * MasterSlaveEntry的构造方法
003. * @param slotRanges for Set&lt;ClusterSlotRange&gt;
004. * @param connectionManager for ConnectionManager
005. * @param config for MasterSlaveServersConfig
006. \*/
007. public MasterSlaveEntry(Set&lt;ClusterSlotRange&gt; slotRanges, ConnectionManager connectionManager, MasterSlaveServersConfig config) {
008. //主从模式下0~16383加入到集合slots
009. for (ClusterSlotRange clusterSlotRange : slotRanges) {
010. for (int i = clusterSlotRange.getStartSlot(); i &lt; clusterSlotRange.getEndSlot() + 1; i++) {
011. slots.add(i);
012. }
013. }
014. //赋值MasterSlaveConnectionManager给connectionManager
015. this.connectionManager = connectionManager;
016. //赋值config
017. this.config = config;
018. //创建LoadBalancerManager
019. //其实LoadBalancerManager里持有者从节点的SlaveConnectionPool和PubSubConnectionPool
020. //并且此时连接池里还没有初始化默认的最小连接数
021. slaveBalancer = new LoadBalancerManager(config, connectionManager, this);
022. //创建主节点连接池MasterConnectionPool，此时连接池里还没有初始化默认的最小连接数
023. writeConnectionHolder = new MasterConnectionPool(config, connectionManager, this);
024. //创建主节点连接池MasterPubSubConnectionPool,此时连接池里还没有初始化默认的最小连接数
025. pubSubConnectionHolder = new MasterPubSubConnectionPool(config, connectionManager, this);
026. }
027. /\**
028. * 从节点连接池SlaveConnectionPool和PubSubConnectionPool的默认的最小连接数初始化
029. * @param disconnectedNodes for Collection&lt;URI&gt;
030. * @return List&lt;RFuture&lt;Void&gt;&gt;
031. \*/
032. public List&lt;RFuture&lt;Void&gt;&gt; initSlaveBalancer(Collection&lt;URI&gt; disconnectedNodes) {
033. //这里freezeMasterAsSlave=true
034. boolean freezeMasterAsSlave = !config.getSlaveAddresses().isEmpty() && !config.checkSkipSlavesInit() && disconnectedNodes.size() &lt; config.getSlaveAddresses().size();
035. List&lt;RFuture&lt;Void&gt;&gt; result = new LinkedList&lt;RFuture&lt;Void&gt;&gt;();
036. //把主节点当作从节点处理，因为默认ReadMode=ReadMode.SLAVE,所以这里不会添加针对该节点的连接池
037. RFuture&lt;Void&gt; f = addSlave(config.getMasterAddress(), freezeMasterAsSlave, NodeType.MASTER);
038. result.add(f);
039. //读取从节点的地址信息，然后针对每个从节点地址创建SlaveConnectionPool和PubSubConnectionPool
040. //SlaveConnectionPool【初始化10个RedisConnection，最大可以扩展至64个】
041. //PubSubConnectionPool【初始化1个RedisPubSubConnection，最大可以扩展至50个】
042. for (URI address : config.getSlaveAddresses()) {
043. f = addSlave(address, disconnectedNodes.contains(address), NodeType.SLAVE);
044. result.add(f);
045. }
046. return result;
047. }
048. /\**
049. * 从节点连接池SlaveConnectionPool和PubSubConnectionPool的默认的最小连接数初始化
050. * @param address for URI
051. * @param freezed for boolean
052. * @param nodeType for NodeType
053. * @return RFuture&lt;Void&gt;
054. \*/
055. private RFuture&lt;Void&gt; addSlave(URI address, boolean freezed, NodeType nodeType) {
056. //创建到从节点的连接RedisClient
057. RedisClient client = connectionManager.createClient(NodeType.SLAVE, address);
058. ClientConnectionsEntry entry = new ClientConnectionsEntry(client,
059. this.config.getSlaveConnectionMinimumIdleSize(),
060. this.config.getSlaveConnectionPoolSize(),
061. this.config.getSubscriptionConnectionMinimumIdleSize(),
062. this.config.getSubscriptionConnectionPoolSize(), connectionManager, nodeType);
063. //默认只有主节点当作从节点是会设置freezed=true
064. if (freezed) {
065. synchronized (entry) {
066. entry.setFreezed(freezed);
067. entry.setFreezeReason(FreezeReason.SYSTEM);
068. }
069. }
070. //调用slaveBalancer来对从节点连接池SlaveConnectionPool和PubSubConnectionPool的默认的最小连接数初始化
071. return slaveBalancer.add(entry);
072. }
073. /\**
074. * 主节点连接池MasterConnectionPool和MasterPubSubConnectionPool的默认的最小连接数初始化
075. * @param address for URI
076. * @return RFuture&lt;Void&gt;
077. \*/
078. public RFuture&lt;Void&gt; setupMasterEntry(URI address) {
079. //创建到主节点的连接RedisClient
080. RedisClient client = connectionManager.createClient(NodeType.MASTER, address);
081. masterEntry = new ClientConnectionsEntry(
082. client,
083. config.getMasterConnectionMinimumIdleSize(),
084. config.getMasterConnectionPoolSize(),
085. config.getSubscriptionConnectionMinimumIdleSize(),
086. config.getSubscriptionConnectionPoolSize(),
087. connectionManager,
088. NodeType.MASTER);
089. //如果配置的SubscriptionMode=SubscriptionMode.MASTER就初始化MasterPubSubConnectionPool
090. //默认SubscriptionMode=SubscriptionMode.SLAVE，MasterPubSubConnectionPool这里不会初始化最小连接数
091. if (config.getSubscriptionMode() == SubscriptionMode.MASTER) {
092. //MasterPubSubConnectionPool【初始化1个RedisPubSubConnection，最大可以扩展至50个】
093. RFuture&lt;Void&gt; f = writeConnectionHolder.add(masterEntry);
094. RFuture&lt;Void&gt; s = pubSubConnectionHolder.add(masterEntry);
095. return CountListener.create(s, f);
096. }
097. //调用MasterConnectionPool使得连接池MasterConnectionPool里的对象最小个数为10个
098. //MasterConnectionPool【初始化10个RedisConnection，最大可以扩展至64个】
099. return writeConnectionHolder.add(masterEntry);
100. }

       上面代码个人觉得有四个地方值得我们特别关注，它们是一个连接池创建对象的入口，列表如下：

- **writeConnectionHolder.add(masterEntry)：**其实writeConnectionHolder的类型就是MasterConnectionPool，这里是连接池**MasterConnectionPool**里添加对象
- **pubSubConnectionHolder.add(masterEntry)：**其实pubSubConnectionHolder的类型是MasterPubSubConnectionPool，这里是连接池**MasterPubSubConnectionPool**添加对象
- **slaveConnectionPool.add(entry)：**这里是连接池**SlaveConnectionPool**里添加对象
- **pubSubConnectionPool.add(entry)：**这里是连接池**PubSubConnectionPool**里添加对象

 

 

## 2.5 LoadBalancerManager.java

       图解LoadBalancerManager.java的内部组成如下：  
![](http://dl2.iteye.com/upload/attachment/0127/9243/03ebf3c7-974d-3d8e-b461-4ff76a21adb5.jpg "点击查看原始大小图片")  
       LoadBalancerManager.java里面有着从节点相关的两个重要的连接池**SlaveConnectionPool**和**PubSubConnectionPool**，这里注释LoadBalancerManager.java的核心代码如下：

Java代码  [![收藏代码](http://aperise.iteye.com/images/icon_star.png)]()

01. /\**
02. * LoadBalancerManager的构造方法
03. * @param config for MasterSlaveServersConfig
04. * @param connectionManager for ConnectionManager
05. * @param entry for MasterSlaveEntry
06. \*/
07. public LoadBalancerManager(MasterSlaveServersConfig config, ConnectionManager connectionManager, MasterSlaveEntry entry) {
08. //赋值connectionManager
09. this.connectionManager = connectionManager;
10. //创建连接池SlaveConnectionPool
11. slaveConnectionPool = new SlaveConnectionPool(config, connectionManager, entry);
12. //创建连接池PubSubConnectionPool
13. pubSubConnectionPool = new PubSubConnectionPool(config, connectionManager, entry);
14. }
15. /\**
16. * LoadBalancerManager的连接池SlaveConnectionPool和PubSubConnectionPool里池化对象添加方法，也即池中需要对象时，调用此方法添加
17. * @param entry for ClientConnectionsEntry
18. * @return RFuture&lt;Void&gt;
19. \*/
20. public RFuture&lt;Void&gt; add(final ClientConnectionsEntry entry) {
21. final RPromise&lt;Void&gt; result = connectionManager.newPromise();
22. //创建一个回调监听器，在池中对象创建失败时进行2次莫仍尝试
23. FutureListener&lt;Void&gt; listener = new FutureListener&lt;Void&gt;() {
24. AtomicInteger counter = new AtomicInteger(2);
25. @Override
26. public void operationComplete(Future&lt;Void&gt; future) throws Exception {
27. if (!future.isSuccess()) {
28. result.tryFailure(future.cause());
29. return;
30. }
31. if (counter.decrementAndGet() == 0) {
32. String addr = entry.getClient().getIpAddr();
33. ip2Entry.put(addr, entry);
34. result.trySuccess(null);
35. }
36. }
37. };
38. //调用slaveConnectionPool添加RedisConnection对象到池中
39. RFuture&lt;Void&gt; slaveFuture = slaveConnectionPool.add(entry);
40. slaveFuture.addListener(listener);
41. //调用pubSubConnectionPool添加RedisPubSubConnection对象到池中
42. RFuture&lt;Void&gt; pubSubFuture = pubSubConnectionPool.add(entry);
43. pubSubFuture.addListener(listener);
44. return result;
45. }

       至此，**我们已经了解了开篇提到的四个连接池是在哪里创建的。**

 

# 3. Redisson的4类连接池

       这里我们来详细介绍下Redisson的连接池实现类，Redisson里有4种连接池，它们是**MasterConnectionPool、MasterPubSubConnectionPool、SlaveConnectionPool和PubSubConnectionPool**，它们的父类都是ConnectionPool，其类继承关系图如下：    
![](http://dl2.iteye.com/upload/attachment/0127/9245/8cf9fee7-dcde-3aaf-b1fb-bc2b81ab75de.jpg "点击查看原始大小图片")  
       通过上图我们了解了ConnectionPool类的继承关系图，再来一张图来了解下ConnectionPool.java类的组成，如下：  
![](http://dl2.iteye.com/upload/attachment/0127/9247/46946fd0-a4d5-3d83-bfac-44f37d6a4d68.jpg "点击查看原始大小图片")  
       好了，再来图就有点啰嗦了，注释ConnectionPool.java代码如下：

Java代码  [![收藏代码](http://aperise.iteye.com/images/icon_star.png)]()

001. abstract class ConnectionPool&lt;T extends RedisConnection&gt; {
002. private final Logger log = LoggerFactory.getLogger(getClass());
003. //维持着连接池对应的redis节点信息
004. //比如1主2从部署MasterConnectionPool里的entries只有一个主节点(192.168.29.24 6379)
005. //比如1主2从部署MasterPubSubConnectionPool里的entries为空，因为SubscriptionMode=SubscriptionMode.SLAVE
006. //比如1主2从部署SlaveConnectionPool里的entries有3个节点(192.168.29.24 6379，192.168.29.24 7000，192.168.29.24 7001，但是注意192.168.29.24 6379冻结属性freezed=true不会参与读操作除非2个从节点全部宕机才参与读操作)
007. //比如1主2从部署PubSubConnectionPool里的entries有2个节点(192.168.29.24 7000，192.168.29.24 7001),因为SubscriptionMode=SubscriptionMode.SLAVE,主节点不会加入
008. protected final List&lt;ClientConnectionsEntry&gt; entries = new CopyOnWriteArrayList&lt;ClientConnectionsEntry&gt;();
009. //持有者RedissonClient的组件ConnectionManager
010. final ConnectionManager connectionManager;
011. //持有者RedissonClient的组件ConnectionManager里的MasterSlaveServersConfig
012. final MasterSlaveServersConfig config;
013. //持有者RedissonClient的组件ConnectionManager里的MasterSlaveEntry
014. final MasterSlaveEntry masterSlaveEntry;
015. //构造函数
016. public ConnectionPool(MasterSlaveServersConfig config, ConnectionManager connectionManager, MasterSlaveEntry masterSlaveEntry) {
017. this.config = config;
018. this.masterSlaveEntry = masterSlaveEntry;
019. this.connectionManager = connectionManager;
020. }
021. //连接池中需要增加对象时候调用此方法
022. public RFuture&lt;Void&gt; add(final ClientConnectionsEntry entry) {
023. final RPromise&lt;Void&gt; promise = connectionManager.newPromise();
024. promise.addListener(new FutureListener&lt;Void&gt;() {
025. @Override
026. public void operationComplete(Future&lt;Void&gt; future) throws Exception {
027. entries.add(entry);
028. }
029. });
030. initConnections(entry, promise, true);
031. return promise;
032. }
033. //初始化连接池中最小连接数
034. private void initConnections(final ClientConnectionsEntry entry, final RPromise&lt;Void&gt; initPromise, boolean checkFreezed) {
035. final int minimumIdleSize = getMinimumIdleSize(entry);
036. if (minimumIdleSize == 0 || (checkFreezed && entry.isFreezed())) {
037. initPromise.trySuccess(null);
038. return;
039. }
040. final AtomicInteger initializedConnections = new AtomicInteger(minimumIdleSize);
041. int startAmount = Math.min(50, minimumIdleSize);
042. final AtomicInteger requests = new AtomicInteger(startAmount);
043. for (int i = 0; i &lt; startAmount; i++) {
044. createConnection(checkFreezed, requests, entry, initPromise, minimumIdleSize, initializedConnections);
045. }
046. }
047. //创建连接对象到连接池中
048. private void createConnection(final boolean checkFreezed, final AtomicInteger requests, final ClientConnectionsEntry entry, final RPromise&lt;Void&gt; initPromise,
049. final int minimumIdleSize, final AtomicInteger initializedConnections) {
050. if ((checkFreezed && entry.isFreezed()) || !tryAcquireConnection(entry)) {
051. int totalInitializedConnections = minimumIdleSize - initializedConnections.get();
052. Throwable cause = new RedisConnectionException(
053. "Unable to init enough connections amount! Only " + totalInitializedConnections + " from " + minimumIdleSize + " were initialized. Server: "
054. + entry.getClient().getAddr());
055. initPromise.tryFailure(cause);
056. return;
057. }
058. acquireConnection(entry, new Runnable() {
059. @Override
060. public void run() {
061. RPromise&lt;T&gt; promise = connectionManager.newPromise();
062. createConnection(entry, promise);
063. promise.addListener(new FutureListener&lt;T&gt;() {
064. @Override
065. public void operationComplete(Future&lt;T&gt; future) throws Exception {
066. if (future.isSuccess()) {
067. T conn = future.getNow();
068. releaseConnection(entry, conn);
069. }
070. releaseConnection(entry);
071. if (!future.isSuccess()) {
072. int totalInitializedConnections = minimumIdleSize - initializedConnections.get();
073. String errorMsg;
074. if (totalInitializedConnections == 0) {
075. errorMsg = "Unable to connect to Redis server: " + entry.getClient().getAddr();
076. } else {
077. errorMsg = "Unable to init enough connections amount! Only " + totalInitializedConnections
078. + " from " + minimumIdleSize + " were initialized. Redis server: " + entry.getClient().getAddr();
079. }
080. Throwable cause = new RedisConnectionException(errorMsg, future.cause());
081. initPromise.tryFailure(cause);
082. return;
083. }
084. int value = initializedConnections.decrementAndGet();
085. if (value == 0) {
086. log.info("{} connections initialized for {}", minimumIdleSize, entry.getClient().getAddr());
087. if (!initPromise.trySuccess(null)) {
088. throw new IllegalStateException();
089. }
090. } else if (value &gt; 0 && !initPromise.isDone()) {
091. if (requests.incrementAndGet() &lt;= minimumIdleSize) {
092. createConnection(checkFreezed, requests, entry, initPromise, minimumIdleSize, initializedConnections);
093. }
094. }
095. }
096. });
097. }
098. });
099. }
100. //连接池中租借出连接对象
101. public RFuture&lt;T&gt; get(RedisCommand&lt;?&gt; command) {
102. for (int j = entries.size() - 1; j &gt;= 0; j--) {
103. final ClientConnectionsEntry entry = getEntry();
104. if (!entry.isFreezed()
105. && tryAcquireConnection(entry)) {
106. return acquireConnection(command, entry);
107. }
108. }
109. List&lt;InetSocketAddress&gt; failedAttempts = new LinkedList&lt;InetSocketAddress&gt;();
110. List&lt;InetSocketAddress&gt; freezed = new LinkedList&lt;InetSocketAddress&gt;();
111. for (ClientConnectionsEntry entry : entries) {
112. if (entry.isFreezed()) {
113. freezed.add(entry.getClient().getAddr());
114. } else {
115. failedAttempts.add(entry.getClient().getAddr());
116. }
117. }
118. StringBuilder errorMsg = new StringBuilder(getClass().getSimpleName() + " no available Redis entries. ");
119. if (!freezed.isEmpty()) {
120. errorMsg.append(" Disconnected hosts: " + freezed);
121. }
122. if (!failedAttempts.isEmpty()) {
123. errorMsg.append(" Hosts disconnected due to \`failedAttempts\` limit reached: " + failedAttempts);
124. }
125. RedisConnectionException exception = new RedisConnectionException(errorMsg.toString());
126. return connectionManager.newFailedFuture(exception);
127. }
128. //连接池中租借出连接对象执行操作RedisCommand
129. public RFuture&lt;T&gt; get(RedisCommand&lt;?&gt; command, ClientConnectionsEntry entry) {
130. if ((!entry.isFreezed() || entry.getFreezeReason() == FreezeReason.SYSTEM) &&
131. tryAcquireConnection(entry)) {
132. return acquireConnection(command, entry);
133. }
134. RedisConnectionException exception = new RedisConnectionException(
135. "Can't aquire connection to " + entry);
136. return connectionManager.newFailedFuture(exception);
137. }
138. //通过向redis服务端发送PING看是否返回PONG来检测连接
139. private void ping(RedisConnection c, final FutureListener&lt;String&gt; pingListener) {
140. RFuture&lt;String&gt; f = c.async(RedisCommands.PING);
141. f.addListener(pingListener);
142. }
143. //归还连接对象到连接池
144. public void returnConnection(ClientConnectionsEntry entry, T connection) {
145. if (entry.isFreezed()) {
146. connection.closeAsync();
147. } else {
148. releaseConnection(entry, connection);
149. }
150. releaseConnection(entry);
151. }
152. //释放连接池中连接对象
153. protected void releaseConnection(ClientConnectionsEntry entry) {
154. entry.releaseConnection();
155. }
156. //释放连接池中连接对象
157. protected void releaseConnection(ClientConnectionsEntry entry, T conn) {
158. entry.releaseConnection(conn);
159. }
160. }

       用一张图来解释ConnectionPool干了些啥，如下图：  
![](http://dl2.iteye.com/upload/attachment/0127/9249/d593663c-2a2d-3bb5-97a4-80156b381779.jpg "点击查看原始大小图片")  
       都到这里了，不介意再送一张图了解各种部署方式下的连接池分布了，如下图：  
![](http://dl2.iteye.com/upload/attachment/0127/9251/7cb47e3d-8712-3a0a-b53d-a45ce3411d28.jpg "点击查看原始大小图片")

# 4.Redisson的读写操作句柄类RedissonObject

       对于Redisson的任何操作，都需要获取到**操作句柄类RedissonObject**，RedissonObject根据不同的数据类型有不同的RedissonObject实现类，**RedissonObject的类继承关系图**如下：  
![](http://dl2.iteye.com/upload/attachment/0127/9267/9d5aa436-5f0f-37d7-a24f-aa03b3e7fc57.jpg "点击查看原始大小图片")  
       例如想设置redis服务端的key=key的值value=123，你需要查询[Redis命令和Redisson对象匹配列表](https://github.com/redisson/redisson/wiki/11.-Redis%E5%91%BD%E4%BB%A4%E5%92%8CRedisson%E5%AF%B9%E8%B1%A1%E5%8C%B9%E9%85%8D%E5%88%97%E8%A1%A8)，找到如下对应关系：  
![](http://dl2.iteye.com/upload/attachment/0127/9269/d27935f2-96bd-34ef-941a-21015b050c0b.jpg "点击查看原始大小图片")  
       然后我们就知道调用代码这么写：

Java代码  [![收藏代码](http://aperise.iteye.com/images/icon_star.png)]()

01. Config config = new Config();// 创建配置
02. config.useMasterSlaveServers() // 指定使用主从部署方式
03. .setMasterAddress("redis://192.168.29.24:6379")  // 设置redis主节点
04. .addSlaveAddress("redis://192.168.29.24:7000") // 设置redis从节点
05. .addSlaveAddress("redis://192.168.29.24:7001"); // 设置redis从节点
06. RedissonClient redisson = Redisson.create(config);// 创建客户端(发现这一操作非常耗时，基本在2秒-4秒左右)
07. //任何Redisson操作首先需要获取对应的操作句柄
08. //RBucket是操作句柄之一，实现类是RedissonBucket
09. RBucket&lt;String&gt; rBucket = redissonClient.getBucket("key");
10. //通过操作句柄rBucket进行读操作
11. rBucket.get();
12. //通过操作句柄rBucket进行写操作
13. rBucket.set("123");

       至于其它的redis命令对应的redisson操作对象，都可以官网的[Redis命令和Redisson对象匹配列表](https://github.com/redisson/redisson/wiki/11.-Redis%E5%91%BD%E4%BB%A4%E5%92%8CRedisson%E5%AF%B9%E8%B1%A1%E5%8C%B9%E9%85%8D%E5%88%97%E8%A1%A8) 查到。

 

# 6.Redisson的读写操作源码分析

       从一个读操作的代码作为入口分析代码，如下：

Java代码  [![收藏代码](http://aperise.iteye.com/images/icon_star.png)]()

1. //任何Redisson操作首先需要获取对应的操作句柄,RBucket是操作句柄之一，实现类是RedissonBucket
2. RBucket&lt;String&gt; rBucket = redissonClient.getBucket("key");
3. //通过操作句柄rBucket进行读操作
4. rBucket.get();

       继续追踪上面RBucket的get方法，如下：  
![](http://dl2.iteye.com/upload/attachment/0127/9291/5d5624ce-3524-39e3-b7fc-e1d8d135baec.jpg "点击查看原始大小图片")  
       上面我们看到不管是读操作还是写操作都转交**CommandAsyncExecutor**进行处理，那么这里我们需要看一下**CommandAsyncExecutor.java**里关于读写操作处理的核心代码，注释代码如下：

Java代码  [![收藏代码](http://aperise.iteye.com/images/icon_star.png)]()

001. private NodeSource getNodeSource(String key) {
002. //通过公式CRC16.crc16(key.getBytes()) % MAX\_SLOT
003. //计算出一个字符串key对应的分片在0~16383中哪个分片
004. int slot = connectionManager.calcSlot(key);
005. //之前已经将0~16383每个分片对应到唯一的一个MasterSlaveEntry，这里取出来
006. MasterSlaveEntry entry = connectionManager.getEntry(slot);
007. //这里将MasterSlaveEntry包装成NodeSource【slot=null,addr=null,redirect=null,entry=MasterSlaveEntry】
008. return new NodeSource(entry);
009. }
010. @Override
011. public &lt;T, R&gt; RFuture&lt;R&gt; readAsync(String key, Codec codec, RedisCommand&lt;T&gt; command, Object... params) {
012. RPromise&lt;R&gt; mainPromise = connectionManager.newPromise();
013. //获取NodeSource【slot=null,addr=null,redirect=null,entry=MasterSlaveEntry】
014. NodeSource source = getNodeSource(key);
015. 调用异步执行方法async
016. async(true, source, codec, command, params, mainPromise, 0);
017. return mainPromise;
018. }
019. protected &lt;V, R&gt; void async(final boolean readOnlyMode, final NodeSource source, final Codec codec,
020. final RedisCommand&lt;V&gt; command, final Object\[] params, final RPromise&lt;R&gt; mainPromise, final int attempt) {
021. //操作被取消，那么直接返回
022. if (mainPromise.isCancelled()) {
023. free(params);
024. return;
025. }
026. //连接管理器无法连接，释放参数所占资源，然后返回
027. if (!connectionManager.getShutdownLatch().acquire()) {
028. free(params);
029. mainPromise.tryFailure(new RedissonShutdownException("Redisson is shutdown"));
030. return;
031. }
032. final AsyncDetails&lt;V, R&gt; details = AsyncDetails.acquire();
033. if (isRedissonReferenceSupportEnabled()) {
034. try {
035. for (int i = 0; i &lt; params.length; i++) {
036. RedissonReference reference = RedissonObjectFactory.toReference(getConnectionManager().getCfg(), params\[i]);
037. if (reference != null) {
038. params\[i] = reference;
039. }
040. }
041. } catch (Exception e) {
042. connectionManager.getShutdownLatch().release();
043. free(params);
044. mainPromise.tryFailure(e);
045. return;
046. }
047. }
048. //开始从connectionManager获取池中的连接
049. //这里采用异步方式，创建一个RFuture对象，等待池中连接，一旦获得连接，然后进行读和写操作
050. final RFuture&lt;RedisConnection&gt; connectionFuture;
051. if (readOnlyMode) {//对于读操作默认readOnlyMode=true,这里会执行
052. connectionFuture = connectionManager.connectionReadOp(source, command);
053. } else {//对于写操作默认readOnlyMode=false,这里会执行
054. connectionFuture = connectionManager.connectionWriteOp(source, command);
055. }
056. //创建RPromise，用于操作失败时候重试
057. final RPromise&lt;R&gt; attemptPromise = connectionManager.newPromise();
058. details.init(connectionFuture, attemptPromise, readOnlyMode, source, codec, command, params, mainPromise, attempt);
059. //创建FutureListener，监测外部请求是否已经取消了之前提交的读写操作，如果取消了，那么就让正在执行的读写操作停止
060. FutureListener&lt;R&gt; mainPromiseListener = new FutureListener&lt;R&gt;() {
061. @Override
062. public void operationComplete(Future&lt;R&gt; future) throws Exception {
063. if (future.isCancelled() && connectionFuture.cancel(false)) {
064. log.debug("Connection obtaining canceled for {}", command);
065. details.getTimeout().cancel();
066. if (details.getAttemptPromise().cancel(false)) {
067. free(params);
068. }
069. }
070. }
071. };
072. //创建TimerTask，用于操作失败后通过定时器进行操作重试
073. final TimerTask retryTimerTask = new TimerTask() {
074. @Override
075. public void run(Timeout t) throws Exception {
076. if (details.getAttemptPromise().isDone()) {
077. return;
078. }
079. if (details.getConnectionFuture().cancel(false)) {
080. connectionManager.getShutdownLatch().release();
081. } else {
082. if (details.getConnectionFuture().isSuccess()) {
083. if (details.getWriteFuture() == null || !details.getWriteFuture().isDone()) {
084. if (details.getAttempt() == connectionManager.getConfig().getRetryAttempts()) {
085. if (details.getWriteFuture().cancel(false)) {
086. if (details.getException() == null) {
087. details.setException(new RedisTimeoutException("Unable to send command: " + command + " with params: " + LogHelper.toString(details.getParams()) + " after " + connectionManager.getConfig().getRetryAttempts() + " retry attempts"));
088. }
089. details.getAttemptPromise().tryFailure(details.getException());
090. }
091. return;
092. }
093. details.incAttempt();
094. Timeout timeout = connectionManager.newTimeout(this, connectionManager.getConfig().getRetryInterval(), TimeUnit.MILLISECONDS);
095. details.setTimeout(timeout);
096. return;
097. }
098. if (details.getWriteFuture().isDone() && details.getWriteFuture().isSuccess()) {
099. return;
100. }
101. }
102. }
103. if (details.getMainPromise().isCancelled()) {
104. if (details.getAttemptPromise().cancel(false)) {
105. free(details);
106. AsyncDetails.release(details);
107. }
108. return;
109. }
110. if (details.getAttempt() == connectionManager.getConfig().getRetryAttempts()) {
111. if (details.getException() == null) {
112. details.setException(new RedisTimeoutException("Unable to send command: " + command + " with params: " + LogHelper.toString(details.getParams() + " after " + connectionManager.getConfig().getRetryAttempts() + " retry attempts")));
113. }
114. details.getAttemptPromise().tryFailure(details.getException());
115. return;
116. }
117. if (!details.getAttemptPromise().cancel(false)) {
118. return;
119. }
120. int count = details.getAttempt() + 1;
121. if (log.isDebugEnabled()) {
122. log.debug("attempt {} for command {} and params {}",
123. count, details.getCommand(), Arrays.toString(details.getParams()));
124. }
125. details.removeMainPromiseListener();
126. async(details.isReadOnlyMode(), details.getSource(), details.getCodec(), details.getCommand(), details.getParams(), details.getMainPromise(), count);
127. AsyncDetails.release(details);
128. }
129. };
130. //配置对于读写操作的超时时间
131. Timeout timeout = connectionManager.newTimeout(retryTimerTask, connectionManager.getConfig().getRetryInterval(), TimeUnit.MILLISECONDS);
132. details.setTimeout(timeout);
133. details.setupMainPromiseListener(mainPromiseListener);
134. //给connectionFuture增加监听事件，当从连接池中获取连接成功，成功的事件会被触发，通知这里执行后续读写动作
135. connectionFuture.addListener(new FutureListener&lt;RedisConnection&gt;() {
136. @Override
137. public void operationComplete(Future&lt;RedisConnection&gt; connFuture) throws Exception {
138. if (connFuture.isCancelled()) {//从池中获取连接被取消，直接返回
139. return;
140. }
141. if (!connFuture.isSuccess()) {//从池中获取连接失败
142. connectionManager.getShutdownLatch().release();
143. details.setException(convertException(connectionFuture));
144. return;
145. }
146. if (details.getAttemptPromise().isDone() || details.getMainPromise().isDone()) {//从池中获取连接失败，并且尝试了一定次数仍然失败，默认尝试次数为0
147. releaseConnection(source, connectionFuture, details.isReadOnlyMode(), details.getAttemptPromise(), details);
148. return;
149. }
150. //从池中获取连接成功，这里取出连接对象RedisConnection
151. final RedisConnection connection = connFuture.getNow();
152. //如果需要重定向，这里进行重定向
153. //重定向的情况有：集群模式对应的slot分布在其他节点，就需要进行重定向
154. if (details.getSource().getRedirect() == Redirect.ASK) {
155. List&lt;CommandData&lt;?, ?&gt;&gt; list = new ArrayList&lt;CommandData&lt;?, ?&gt;&gt;(2);
156. RPromise&lt;Void&gt; promise = connectionManager.newPromise();
157. list.add(new CommandData&lt;Void, Void&gt;(promise, details.getCodec(), RedisCommands.ASKING, new Object\[]{}));
158. list.add(new CommandData&lt;V, R&gt;(details.getAttemptPromise(), details.getCodec(), details.getCommand(), details.getParams()));
159. RPromise&lt;Void&gt; main = connectionManager.newPromise();
160. ChannelFuture future = connection.send(new CommandsData(main, list));
161. details.setWriteFuture(future);
162. } else {
163. if (log.isDebugEnabled()) {
164. log.debug("acquired connection for command {} and params {} from slot {} using node {}... {}",
165. details.getCommand(), Arrays.toString(details.getParams()), details.getSource(), connection.getRedisClient().getAddr(), connection);
166. }
167. //发送读写操作到RedisConnection，进行执行
168. ChannelFuture future = connection.send(new CommandData&lt;V, R&gt;(details.getAttemptPromise(), details.getCodec(), details.getCommand(), details.getParams()));
169. details.setWriteFuture(future);
170. }
171. //对于写操作增加监听事件回调，对写操作是否成功，失败原因进行日志打印
172. details.getWriteFuture().addListener(new ChannelFutureListener() {
173. @Override
174. public void operationComplete(ChannelFuture future) throws Exception {
175. checkWriteFuture(details, connection);
176. }
177. });
178. //返回RedisConnection连接到连接池
179. releaseConnection(source, connectionFuture, details.isReadOnlyMode(), details.getAttemptPromise(), details);
180. }
181. });
182. attemptPromise.addListener(new FutureListener&lt;R&gt;() {
183. @Override
184. public void operationComplete(Future&lt;R&gt; future) throws Exception {
185. checkAttemptFuture(source, details, future);
186. }
187. });
188. }

       上面的代码我用一张读写操作处理流程图总结如下：  
![](http://dl2.iteye.com/upload/attachment/0127/9293/4db8a568-724d-3a3c-af3a-5c0a2c17f347.jpg "点击查看原始大小图片")  
 

 

       至此，关于读写操作的源码讲解完毕。在上面的代码注释中，列出如下重点。

## 6.1 分片SLOT的计算公式

       **SLOT=CRC16.crc16(key.getBytes()) % MAX\_SLOT**

 

## 6.2 每个ConnectionPool持有的ClientConnectionsEntry对象冻结判断条件

       一个节点被判断为冻结，必须同时满足以下条件：

- **该节点有slave节点，并且从节点个数大于0；**
- **设置的配置ReadMode不为并且SubscriptionMode不为MASTER；**
- **该节点的从节点至少有一个存活着，也即如果有从节点宕机，宕机的从节点的个数小于该节点总的从节点个数**

## 6.3 读写负载图

   
![](http://dl2.iteye.com/upload/attachment/0127/9297/42172204-76c9-3731-a4ea-271544edb11a.jpg "点击查看原始大小图片")  
   
![](http://dl2.iteye.com/upload/attachment/0127/9299/4c7de205-f348-3b92-9988-a601915bb4bc.jpg "点击查看原始大小图片")

 

# 7.Redisson的读写操作从连接池获取连接对象源码分析和Redisson里RedisClient使用netty源码分析

       读写操作首先都需要获取到一个连接对象，在上面的分析中我们知道读写操作都是通过**CommandAsyncExecutor.java**里的如下代码获取连接对象：

Java代码  [![收藏代码](http://aperise.iteye.com/images/icon_star.png)]()

1. //开始从connectionManager获取池中的连接
2. //这里采用异步方式，创建一个RFuture对象，等待池中连接，一旦获得连接，然后进行读和写操作
3. final RFuture&lt;RedisConnection&gt; connectionFuture;
4. if (readOnlyMode) {//对于读操作默认readOnlyMode=true,这里会执行
5. connectionFuture = connectionManager.connectionReadOp(source, command);
6. } else {//对于写操作默认readOnlyMode=false,这里会执行
7. connectionFuture = connectionManager.connectionWriteOp(source, command);
8. }

       上面读操作调用了**connectionManager.connectionReadOp**从连接池获取连接对象，写操作调用了**connectionManager.connectionWriteOp**从连接池获取连接对象，我们继续跟进**connectionManager关于connectionReadOp和connectionWriteOp**的源代码，注释如下：

Java代码  [![收藏代码](http://aperise.iteye.com/images/icon_star.png)]()

01. /\**
02. * 读操作通过ConnectionManager从连接池获取连接对象
03. * @param source for NodeSource
04. * @param command for RedisCommand&lt;?&gt;
05. * @return RFuture&lt;RedisConnection&gt;
06. \*/
07. public RFuture&lt;RedisConnection&gt; connectionReadOp(NodeSource source, RedisCommand&lt;?&gt; command) {
08. //这里之前分析过source=NodeSource【slot=null,addr=null,redirect=null,entry=MasterSlaveEntry】
09. MasterSlaveEntry entry = source.getEntry();
10. if (entry == null && source.getSlot() != null) {//这里不会执行source里slot=null
11. entry = getEntry(source.getSlot());
12. }
13. if (source.getAddr() != null) {//这里不会执行source里addr=null
14. entry = getEntry(source.getAddr());
15. if (entry == null) {
16. for (MasterSlaveEntry e : getEntrySet()) {
17. if (e.hasSlave(source.getAddr())) {
18. entry = e;
19. break;
20. }
21. }
22. }
23. if (entry == null) {
24. RedisNodeNotFoundException ex = new RedisNodeNotFoundException("Node: " + source.getAddr() + " for slot: " + source.getSlot() + " hasn't been discovered yet");
25. return RedissonPromise.newFailedFuture(ex);
26. }
27. return entry.connectionReadOp(command, source.getAddr());
28. }
29. if (entry == null) {//这里不会执行source里entry不等于null
30. RedisNodeNotFoundException ex = new RedisNodeNotFoundException("Node: " + source.getAddr() + " for slot: " + source.getSlot() + " hasn't been discovered yet");
31. return RedissonPromise.newFailedFuture(ex);
32. }
33. //MasterSlaveEntry里从连接池获取连接对象
34. return entry.connectionReadOp(command);
35. }
36. /\**
37. * 写操作通过ConnectionManager从连接池获取连接对象
38. * @param source for NodeSource
39. * @param command for RedisCommand&lt;?&gt;
40. * @return RFuture&lt;RedisConnection&gt;
41. \*/
42. public RFuture&lt;RedisConnection&gt; connectionWriteOp(NodeSource source, RedisCommand&lt;?&gt; command) {
43. //这里之前分析过source=NodeSource【slot=null,addr=null,redirect=null,entry=MasterSlaveEntry】
44. MasterSlaveEntry entry = source.getEntry();
45. if (entry == null) {
46. entry = getEntry(source);
47. }
48. if (entry == null) {//这里不会执行source里entry不等于null
49. RedisNodeNotFoundException ex = new RedisNodeNotFoundException("Node: " + source.getAddr() + " for slot: " + source.getSlot() + " hasn't been discovered yet");
50. return RedissonPromise.newFailedFuture(ex);
51. }
52. //MasterSlaveEntry里从连接池获取连接对象
53. return entry.connectionWriteOp(command);
54. }

       我们看到上面调用**ConnectionManager**从连接池获取连接对象，但是**ConnectionManager**却将获取连接操作转交**MasterSlaveEntry**处理，我们再一次回顾一下**MasterSlaveEntry的组成**：   
![](http://dl2.iteye.com/upload/attachment/0127/9253/c45ffc15-b155-32f1-9e09-1a4e03ee7572.jpg "点击查看原始大小图片")  
       MasterSlaveEntry里持有中我们开篇所提到的**四个连接池**，那么这里我们继续关注**MasterSlaveEntry.java**的源代码：

Java代码  [![收藏代码](http://aperise.iteye.com/images/icon_star.png)]()

01. /\**
02. * 写操作从MasterConnectionPool连接池里获取连接对象
03. * @param command for RedisCommand&lt;?&gt;
04. * @return RFuture&lt;RedisConnection&gt;
05. \*/
06. public RFuture&lt;RedisConnection&gt; connectionWriteOp(RedisCommand&lt;?&gt; command) {
07. //我们知道writeConnectionHolder的类型为MasterConnectionPool
08. //这里就是从MasterConnectionPool里获取连接对象
09. return writeConnectionHolder.get(command);
10. }
11. /\**
12. * 写操作从LoadBalancerManager里获取连接对象
13. * @param command for RedisCommand&lt;?&gt;
14. * @return RFuture&lt;RedisConnection&gt;
15. \*/
16. public RFuture&lt;RedisConnection&gt; connectionReadOp(RedisCommand&lt;?&gt; command) {
17. if (config.getReadMode() == ReadMode.MASTER) {
18. //我们知道默认ReadMode=ReadMode.SLAVE,所以对于读操作这里不会执行
19. return connectionWriteOp(command);
20. }
21. //我们知道slaveBalancer里持有者SlaveConnectionPool和PubSubConnectionPool
22. //这里就是从SlaveConnectionPool里获取连接对象
23. return slaveBalancer.nextConnection(command);
24. }

       似乎又绕回来了，最终的获取连接对象都转交到了从连接池**ConnectionPool**里获取连接对象，注释**ConnectionPool**里的获取连接对象代码如下： 

Java代码  [![收藏代码](http://aperise.iteye.com/images/icon_star.png)]()

001. /\**
002. * 读写操作从ConnectionPool.java连接池里获取连接对象
003. * @param command for RedisCommand&lt;?&gt;
004. * @return RFuture&lt;T&gt;
005. \*/
006. public RFuture&lt;T&gt; get(RedisCommand&lt;?&gt; command) {
007. for (int j = entries.size() - 1; j &gt;= 0; j--) {
008. final ClientConnectionsEntry entry = getEntry();
009. if (!entry.isFreezed() && tryAcquireConnection(entry)) {
010. //遍历ConnectionPool里维持的ClientConnectionsEntry列表
011. //遍历的算法默认为RoundRobinLoadBalancer
012. //ClientConnectionsEntry里对应的redis节点为非冻结节点，也即freezed=false
013. return acquireConnection(command, entry);
014. }
015. }
016. //记录失败重试信息
017. List&lt;InetSocketAddress&gt; failedAttempts = new LinkedList&lt;InetSocketAddress&gt;();
018. List&lt;InetSocketAddress&gt; freezed = new LinkedList&lt;InetSocketAddress&gt;();
019. for (ClientConnectionsEntry entry : entries) {
020. if (entry.isFreezed()) {
021. freezed.add(entry.getClient().getAddr());
022. } else {
023. failedAttempts.add(entry.getClient().getAddr());
024. }
025. }
026. StringBuilder errorMsg = new StringBuilder(getClass().getSimpleName() + " no available Redis entries. ");
027. if (!freezed.isEmpty()) {
028. errorMsg.append(" Disconnected hosts: " + freezed);
029. }
030. if (!failedAttempts.isEmpty()) {
031. errorMsg.append(" Hosts disconnected due to \`failedAttempts\` limit reached: " + failedAttempts);
032. }
033. //获取连接失败抛出异常
034. RedisConnectionException exception = new RedisConnectionException(errorMsg.toString());
035. return connectionManager.newFailedFuture(exception);
036. }
037. /\**
038. * 读写操作从ConnectionPool.java连接池里获取连接对象
039. * @param command for RedisCommand&lt;?&gt;
040. * @param entry for ClientConnectionsEntry
041. * @return RFuture&lt;T&gt;
042. \*/
043. private RFuture&lt;T&gt; acquireConnection(RedisCommand&lt;?&gt; command, final ClientConnectionsEntry entry) {
044. //创建一个异步结果获取RPromise
045. final RPromise&lt;T&gt; result = connectionManager.newPromise();
046. //获取连接前首先将ClientConnectionsEntry里的空闲连接信号freeConnectionsCounter值减1
047. //该操作成功后将调用这里的回调函数AcquireCallback&lt;T&gt;
048. AcquireCallback&lt;T&gt; callback = new AcquireCallback&lt;T&gt;() {
049. @Override
050. public void run() {
051. result.removeListener(this);
052. //freeConnectionsCounter值减1成功，说明获取可以获取到连接
053. //这里才是真正获取连接的操作
054. connectTo(entry, result);
055. }
056. @Override
057. public void operationComplete(Future&lt;T&gt; future) throws Exception {
058. entry.removeConnection(this);
059. }
060. };
061. //异步结果获取RPromise绑定到上面的回调函数callback
062. result.addListener(callback);
063. //尝试将ClientConnectionsEntry里的空闲连接信号freeConnectionsCounter值减1，如果成功就调用callback从连接池获取连接
064. acquireConnection(entry, callback);
065. //返回异步结果获取RPromise
066. return result;
067. }
068. /\**
069. * 真正从连接池中获取连接
070. * @param entry for ClientConnectionsEntry
071. * @param promise for RPromise&lt;T&gt;
072. \*/
073. private void connectTo(ClientConnectionsEntry entry, RPromise&lt;T&gt; promise) {
074. if (promise.isDone()) {
075. releaseConnection(entry);
076. return;
077. }
078. //从连接池中取出一个连接
079. T conn = poll(entry);
080. if (conn != null) {
081. if (!conn.isActive()) {
082. promiseFailure(entry, promise, conn);
083. return;
084. }
085. connectedSuccessful(entry, promise, conn);
086. return;
087. }
088. //如果仍然获取不到连接，可能连接池中连接对象都被租借了，这里开始创建一个新的连接对象放到连接池中
089. createConnection(entry, promise);
090. }
091. /\**
092. * 从连接池中获取连接
093. * @param entry for ClientConnectionsEntry
094. * @return T
095. \*/
096. protected T poll(ClientConnectionsEntry entry) {
097. return (T) entry.pollConnection();
098. }
099. /\**
100. * 调用ClientConnectionsEntry创建一个连接放置到连接池中并返回此连接
101. * @param entry for ClientConnectionsEntry
102. * @param promise for RPromise&lt;T&gt;
103. \*/
104. private void createConnection(final ClientConnectionsEntry entry, final RPromise&lt;T&gt; promise) {
105. //调用ClientConnectionsEntry创建一个连接放置到连接池中并返回此连接
106. RFuture&lt;T&gt; connFuture = connect(entry);
107. connFuture.addListener(new FutureListener&lt;T&gt;() {
108. @Override
109. public void operationComplete(Future&lt;T&gt; future) throws Exception {
110. if (!future.isSuccess()) {
111. promiseFailure(entry, promise, future.cause());
112. return;
113. }
114. T conn = future.getNow();
115. if (!conn.isActive()) {
116. promiseFailure(entry, promise, conn);
117. return;
118. }
119. connectedSuccessful(entry, promise, conn);
120. }
121. });
122. }

       **ConnectionPool.java里获取读写操作的连接，是遍历ConnectionPool里维持的ClientConnectionsEntry列表，找到一非冻结的ClientConnectionsEntry，然后调用ClientConnectionsEntry里的freeConnectionsCounter尝试将值减1，如果成功，说明连接池中可以获取到连接，那么就从ClientConnectionsEntry里获取一个连接出来，如果拿不到连接，会调用ClientConnectionsEntry创建一个新连接放置到连接池中，并返回此连接**，这里回顾一下**ClientConnectionsEntry的组成图**：  
![](http://dl2.iteye.com/upload/attachment/0127/9297/42172204-76c9-3731-a4ea-271544edb11a.jpg "点击查看原始大小图片")       我们继续跟进**ClientConnectionsEntry.java的源代码**，注释如下：

Java代码  [![收藏代码](http://aperise.iteye.com/images/icon_star.png)]()

01. /\**
02. *  ClientConnectionsEntry里从freeConnections里获取一个连接并返回给读写操作使用
03. \*/
04. public RedisConnection pollConnection() {
05. return freeConnections.poll();
06. }
07. /\**
08. *  ClientConnectionsEntry里新创建一个连接对象返回给读写操作使用
09. \*/
10. public RFuture&lt;RedisConnection&gt; connect() {
11. //调用RedisClient利用netty连接redis服务端，将返回的netty的outboundchannel包装成RedisConnection并返回
12. RFuture&lt;RedisConnection&gt; future = client.connectAsync();
13. future.addListener(new FutureListener&lt;RedisConnection&gt;() {
14. @Override
15. public void operationComplete(Future&lt;RedisConnection&gt; future) throws Exception {
16. if (!future.isSuccess()) {
17. return;
18. }
19. RedisConnection conn = future.getNow();
20. onConnect(conn);
21. log.debug("new connection created: {}", conn);
22. }
23. });
24. return future;
25. }

       上面的代码说明如果**ClientConnectionsEntry**里的**freeConnections**有空闲连接，那么直接返回该连接，如果没有那么调用**RedisClient.connectAsync创建一个新的连接**，这里我继续注释一下**RedisClient.java**的源代码如下：

Java代码  [![收藏代码](http://aperise.iteye.com/images/icon_star.png)]()

001. package org.redisson.client;
002. import java.net.InetSocketAddress;
003. import java.net.URI;
004. import java.util.concurrent.ExecutorService;
005. import java.util.concurrent.Executors;
006. import java.util.concurrent.TimeUnit;
007. import org.redisson.api.RFuture;
008. import org.redisson.client.handler.RedisChannelInitializer;
009. import org.redisson.client.handler.RedisChannelInitializer.Type;
010. import org.redisson.misc.RPromise;
011. import org.redisson.misc.RedissonPromise;
012. import io.netty.bootstrap.Bootstrap;
013. import io.netty.channel.Channel;
014. import io.netty.channel.ChannelFuture;
015. import io.netty.channel.ChannelFutureListener;
016. import io.netty.channel.ChannelOption;
017. import io.netty.channel.EventLoopGroup;
018. import io.netty.channel.group.ChannelGroup;
019. import io.netty.channel.group.ChannelGroupFuture;
020. import io.netty.channel.group.DefaultChannelGroup;
021. import io.netty.channel.nio.NioEventLoopGroup;
022. import io.netty.channel.socket.SocketChannel;
023. import io.netty.channel.socket.nio.NioSocketChannel;
024. import io.netty.util.HashedWheelTimer;
025. import io.netty.util.Timer;
026. import io.netty.util.concurrent.Future;
027. import io.netty.util.concurrent.FutureListener;
028. import io.netty.util.concurrent.GlobalEventExecutor;
029. import org.redisson.misc.URIBuilder;
030. /\**
031. * 使用java里的网络编程框架Netty连接redis服务端
032. * 作者： Nikita Koksharov
033. \*/
034. public class RedisClient {
035. private final Bootstrap bootstrap;//Netty的工具类Bootstrap，用于连接建立等作用
036. private final Bootstrap pubSubBootstrap;//Netty的工具类Bootstrap，用于连接建立等作用
037. private final InetSocketAddress addr;//socket连接的地址
038. //channels是netty提供的一个全局对象，里面记录着当前socket连接上的所有处于可用状态的连接channel
039. //channels会自动监测里面的channel，当channel断开时，会主动踢出该channel，永远保留当前可用的channel列表
040. private final ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
041. private ExecutorService executor;//REACOTR模型的java异步执行线程池
042. private final long commandTimeout;//超时时间
043. private Timer timer;//定时器
044. private boolean hasOwnGroup;
045. private RedisClientConfig config;//redis连接配置信息
046. //构造方法
047. public static RedisClient create(RedisClientConfig config) {
048. if (config.getTimer() == null) {
049. config.setTimer(new HashedWheelTimer());
050. }
051. return new RedisClient(config);
052. }
053. //构造方法
054. private RedisClient(RedisClientConfig config) {
055. this.config = config;
056. this.executor = config.getExecutor();
057. this.timer = config.getTimer();
058. addr = new InetSocketAddress(config.getAddress().getHost(), config.getAddress().getPort());
059. bootstrap = createBootstrap(config, Type.PLAIN);
060. pubSubBootstrap = createBootstrap(config, Type.PUBSUB);
061. this.commandTimeout = config.getCommandTimeout();
062. }
063. //java的网路编程框架Netty工具类Bootstrap初始化
064. private Bootstrap createBootstrap(RedisClientConfig config, Type type) {
065. Bootstrap bootstrap = new Bootstrap()
066. .channel(config.getSocketChannelClass())
067. .group(config.getGroup())
068. .remoteAddress(addr);
069. //注册netty相关socket数据处理RedisChannelInitializer
070. bootstrap.handler(new RedisChannelInitializer(bootstrap, config, this, channels, type));
071. //设置超时时间
072. bootstrap.option(ChannelOption.CONNECT\_TIMEOUT\_MILLIS, config.getConnectTimeout());
073. return bootstrap;
074. }
075. //构造方法
076. @Deprecated
077. public RedisClient(String address) {
078. this(URIBuilder.create(address));
079. }
080. //构造方法
081. @Deprecated
082. public RedisClient(URI address) {
083. this(new HashedWheelTimer(), Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2), new NioEventLoopGroup(), address);
084. hasOwnGroup = true;
085. }
086. //构造方法
087. @Deprecated
088. public RedisClient(Timer timer, ExecutorService executor, EventLoopGroup group, URI address) {
089. this(timer, executor, group, address.getHost(), address.getPort());
090. }
091. //构造方法
092. @Deprecated
093. public RedisClient(String host, int port) {
094. this(new HashedWheelTimer(), Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2), new NioEventLoopGroup(), NioSocketChannel.class, host, port, 10000, 10000);
095. hasOwnGroup = true;
096. }
097. //构造方法
098. @Deprecated
099. public RedisClient(Timer timer, ExecutorService executor, EventLoopGroup group, String host, int port) {
100. this(timer, executor, group, NioSocketChannel.class, host, port, 10000, 10000);
101. }
102. //构造方法
103. @Deprecated
104. public RedisClient(String host, int port, int connectTimeout, int commandTimeout) {
105. this(new HashedWheelTimer(), Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2), new NioEventLoopGroup(), NioSocketChannel.class, host, port, connectTimeout, commandTimeout);
106. }
107. //构造方法
108. @Deprecated
109. public RedisClient(final Timer timer, ExecutorService executor, EventLoopGroup group, Class&lt;? extends SocketChannel&gt; socketChannelClass, String host, int port,
110. int connectTimeout, int commandTimeout) {
111. RedisClientConfig config = new RedisClientConfig();
112. config.setTimer(timer).setExecutor(executor).setGroup(group).setSocketChannelClass(socketChannelClass)
113. .setAddress(host, port).setConnectTimeout(connectTimeout).setCommandTimeout(commandTimeout);
114. this.config = config;
115. this.executor = config.getExecutor();
116. this.timer = config.getTimer();
117. addr = new InetSocketAddress(config.getAddress().getHost(), config.getAddress().getPort());
118. //java的网路编程框架Netty工具类Bootstrap初始化
119. bootstrap = createBootstrap(config, Type.PLAIN);
120. pubSubBootstrap = createBootstrap(config, Type.PUBSUB);
121. this.commandTimeout = config.getCommandTimeout();
122. }
123. //获取连接的IP地址
124. public String getIpAddr() {
125. return addr.getAddress().getHostAddress() + ":" + addr.getPort();
126. }
127. //获取socket连接的地址
128. public InetSocketAddress getAddr() {
129. return addr;
130. }
131. //获取超时时间
132. public long getCommandTimeout() {
133. return commandTimeout;
134. }
135. //获取netty的线程池
136. public EventLoopGroup getEventLoopGroup() {
137. return bootstrap.config().group();
138. }
139. //获取redis连接配置
140. public RedisClientConfig getConfig() {
141. return config;
142. }
143. //获取连接RedisConnection
144. public RedisConnection connect() {
145. try {
146. return connectAsync().syncUninterruptibly().getNow();
147. } catch (Exception e) {
148. throw new RedisConnectionException("Unable to connect to: " + addr, e);
149. }
150. }
151. //启动netty去连接redis服务端，设置java的Future尝试将netty连接上的OutBoundChannel包装成RedisConnection并返回RedisConnection
152. public RFuture&lt;RedisConnection&gt; connectAsync() {
153. final RPromise&lt;RedisConnection&gt; f = new RedissonPromise&lt;RedisConnection&gt;();
154. //netty连接redis服务端
155. ChannelFuture channelFuture = bootstrap.connect();
156. channelFuture.addListener(new ChannelFutureListener() {
157. @Override
158. public void operationComplete(final ChannelFuture future) throws Exception {
159. if (future.isSuccess()) {
160. //将netty连接上的OutBoundChannel包装成RedisConnection并返回RedisConnection
161. final RedisConnection c = RedisConnection.getFrom(future.channel());
162. c.getConnectionPromise().addListener(new FutureListener&lt;RedisConnection&gt;() {
163. @Override
164. public void operationComplete(final Future&lt;RedisConnection&gt; future) throws Exception {
165. bootstrap.config().group().execute(new Runnable() {
166. @Override
167. public void run() {
168. if (future.isSuccess()) {
169. if (!f.trySuccess(c)) {
170. c.closeAsync();
171. }
172. } else {
173. f.tryFailure(future.cause());
174. c.closeAsync();
175. }
176. }
177. });
178. }
179. });
180. } else {
181. bootstrap.config().group().execute(new Runnable() {
182. public void run() {
183. f.tryFailure(future.cause());
184. }
185. });
186. }
187. }
188. });
189. return f;
190. }
191. //获取订阅相关连接RedisPubSubConnection
192. public RedisPubSubConnection connectPubSub() {
193. try {
194. return connectPubSubAsync().syncUninterruptibly().getNow();
195. } catch (Exception e) {
196. throw new RedisConnectionException("Unable to connect to: " + addr, e);
197. }
198. }
199. //启动netty去连接redis服务端，设置java的Future尝试将netty连接上的OutBoundChannel包装成RedisPubSubConnection并返回RedisPubSubConnection
200. public RFuture&lt;RedisPubSubConnection&gt; connectPubSubAsync() {
201. final RPromise&lt;RedisPubSubConnection&gt; f = new RedissonPromise&lt;RedisPubSubConnection&gt;();
202. //netty连接redis服务端
203. ChannelFuture channelFuture = pubSubBootstrap.connect();
204. channelFuture.addListener(new ChannelFutureListener() {
205. @Override
206. public void operationComplete(final ChannelFuture future) throws Exception {
207. if (future.isSuccess()) {
208. //将netty连接上的OutBoundChannel包装成RedisPubSubConnection并返回RedisPubSubConnection
209. final RedisPubSubConnection c = RedisPubSubConnection.getFrom(future.channel());
210. c.&lt;RedisPubSubConnection&gt;getConnectionPromise().addListener(new FutureListener&lt;RedisPubSubConnection&gt;() {
211. @Override
212. public void operationComplete(final Future&lt;RedisPubSubConnection&gt; future) throws Exception {
213. bootstrap.config().group().execute(new Runnable() {
214. @Override
215. public void run() {
216. if (future.isSuccess()) {
217. if (!f.trySuccess(c)) {
218. c.closeAsync();
219. }
220. } else {
221. f.tryFailure(future.cause());
222. c.closeAsync();
223. }
224. }
225. });
226. }
227. });
228. } else {
229. bootstrap.config().group().execute(new Runnable() {
230. public void run() {
231. f.tryFailure(future.cause());
232. }
233. });
234. }
235. }
236. });
237. return f;
238. }
239. //关闭netty网络连接
240. public void shutdown() {
241. shutdownAsync().syncUninterruptibly();
242. if (hasOwnGroup) {
243. timer.stop();
244. executor.shutdown();
245. try {
246. executor.awaitTermination(15, TimeUnit.SECONDS);
247. } catch (InterruptedException e) {
248. Thread.currentThread().interrupt();
249. }
250. bootstrap.config().group().shutdownGracefully();
251. }
252. }
253. //异步关闭netty网络连接
254. public ChannelGroupFuture shutdownAsync() {
255. for (Channel channel : channels) {
256. RedisConnection connection = RedisConnection.getFrom(channel);
257. if (connection != null) {
258. connection.setClosed(true);
259. }
260. }
261. return channels.close();
262. }
263. @Override
264. public String toString() {
265. return "\[addr=" + addr + "]";
266. }
267. }

       **上面就是Redisson利用java网络编程框架netty连接redis的全过程**，如果你对**netty**比较熟悉，阅读上面的代码应该不是问题。

转载地址：http://aperise.iteye.com/blog/2400528