目录
1. 目标
2. 理解lettuce连接
2.1. 连接模型
2.2. 连接工厂模型
2.3. 共享连接
2.4. 连接提供者
连接池
单例连接
2.5. redis客户端
2.6. 获取native连接入口
2.7. 验证共享native连接
2.8. 验证事务独占连接
1. 目标
默认情况,Lettuce 对 所有非阻塞和非事务型操作 共享 同一个线程安全的本地连接。可配置LettucePool,为阻塞和事务操作,提供独占连接。通过源码与debug验证这些特性。
2. 理解lettuce连接
2.1. 连接模型
org.springframework.data.redis.connection.lettuce.LettuceConnection
// native连接提供者
private final LettuceConnectionProvider connectionProvider;
// 共享native连接
private final @Nullable StatefulConnection asyncSharedConn;
// 独占native连接
private @Nullable StatefulConnection asyncDedicatedConn;
// 当前lettuce连接是否在执行事务
private boolean isMulti = false;
// 当前lettuce连接是否在执行管道
private boolean isPipelined = false;
2.2. 连接工厂模型
org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory
private final LettuceClientConfiguration clientConfiguration;
// native连接提供者
private @Nullable LettuceConnectionProvider connectionProvider;
// 共享native连接
private boolean shareNativeConnection = true;
// 共享的连接
private @Nullable SharedConnection connection;
// 获取lettuce连接
org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory#getConnection
// 获取共享native连接
org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory#getOrCreateSharedConnection
2.3. 共享连接
org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory.SharedConnection
2.4. 连接提供者
连接池
// 连接池。每种类型对应一个pool,存于field pools。pool与连接(持有channel)的反向关系,存于field poolRef.
org.springframework.data.redis.connection.lettuce.LettucePoolingConnectionProvider
主要field
主要看下pools

红色:连接类型
蓝色:pool
绿色:pool中生成的连接list
紫色:连接封装
看下poolRef

红色:连接归属哪个pool
绿色:代表一个独立Redis连接的封装

绿色:真正的网络连接

绿色:真正的网络连接
单例连接
// 单例连接
org.springframework.data.redis.connection.lettuce.StandaloneConnectionProvider
2.5. redis客户端
// 封装了netty相关交互
io.lettuce.core.RedisClient
2.6. 获取native连接入口
获取连接的同步API。返回连接的同步API。针对事务,使用独占连接;否则采用共享连接。
org.springframework.data.redis.connection.lettuce.LettuceConnection#getConnection()
获取连接的异步API。返回连接的异步API。针对事务,使用独占连接;否则采用共享连接。
org.springframework.data.redis.connection.lettuce.LettuceConnection#getAsyncConnection
RedisTemplate每条指令都会获取一个新的lettuceConnection,注意:共享连接是相同的。所以对于非事务操作,lettuce共享native连接。
2.7. 验证共享native连接
// filed位置
org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory#shareNativeConnection
private boolean shareNativeConnection = true;
// 观察是否共享一个连接
org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory#getConnection

通过观察该field是否为同一对象,以此判断是否共享连接。可更进一步打开,查看其内部channel是否一致。
结论:对于非事务指令,无论是否配置pool,均共享一个连接。
2.8. 验证事务独占连接
执行事务需要使用类似如下方法,不可直接使用redistemplate.multi/exec等。至于原因可见上述红色文字。
// 采取的redisTemplate方法
org.springframework.data.redis.core.RedisTemplate#execute(org.springframework.data.redis.core.RedisCallback)
// 事例事务代码
RedisSerializer keySerializer = redisTemplate.getKeySerializer();
RedisSerializer valueSerializer = redisTemplate.getValueSerializer();
List