Redis客户端Lettuce源码「二」Lettuce是如何基于Netty建立连接的
lipiwang 2024-11-15 22:02 14 浏览 0 评论
lettuce-core版本: 5.1.7.RELEASE
先看一下Lettuce的基本使用方法,使用Lettuce大概分为如下几步:
- 基于Redis连接信息创建RedisClient
- 基于RedisClient创建StatefulRedisConnection
- 从Connection中获取Command,基于Command执行Redis命令操作。
/**
* @author xiaobing
* @date 2019/12/20
*/
public class LettuceSimpleUse {
private void testLettuce() throws ExecutionException, InterruptedException {
//构建RedisClient对象,RedisClient包含了Redis的基本配置信息,可以基于RedisClient创建RedisConnection
RedisClient client = RedisClient.create("redis://localhost");
//创建一个线程安全的StatefulRedisConnection,可以多线程并发对该connection操作,底层只有一个物理连接.
StatefulRedisConnection<String, String> connection = client.connect();
//获取SyncCommand。Lettuce支持SyncCommand、AsyncCommands、ActiveCommand三种command
RedisStringCommands<String, String> sync = connection.sync();
String value = sync.get("key");
System.out.println("get redis value with lettuce sync command, value is :" + value);
//获取SyncCommand。Lettuce支持SyncCommand、AsyncCommands、ActiveCommand三种command
RedisAsyncCommands<String, String> async = connection.async();
RedisFuture<String> getFuture = async.get("key");
value = getFuture.get();
System.out.println("get redis value with lettuce async command, value is :" + value);
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
new LettuceSimpleUse().testLettuce();
}
}
先看一张建立连接的时序图,有一个直观的印象。
lettuce源码--建立redis连接
RedisClient
一个可扩展、线程安全的RedisClient,支持sync、async、reactor执行模式。
RedisClient.create只是传入了一些配置信息,此时并没有创建连接。
// 使用默认的ClientResource
public static RedisClient create(String uri) {
LettuceAssert.notEmpty(uri, "URI must not be empty");
return new RedisClient(null, RedisURI.create(uri));
}
// ClientResources中包含了一些配置和线程池信息,是一个比较重的资源,多个RedisClient可以共享同一个ClientResource
protected RedisClient(ClientResources clientResources, RedisURI redisURI) {
super(clientResources);
assertNotNull(redisURI);
this.redisURI = redisURI;
setDefaultTimeout(redisURI.getTimeout());
}
RedisClient.connnect
可以看到connect方法有一些重载方法,默认的是用UTF8 String对key和value序列化,通过传入RedisCodec支持自定义的对Key和Value的序列化方式。
public StatefulRedisConnection<String, String> connect() {
return connect(newStringStringCodec());
}
public <K, V> StatefulRedisConnection<K, V> connect(RedisCodec<K, V> codec) {
checkForRedisURI();
//connectStandaloneAsync是异步创建connection,返回的是Future对象,通过getConnection转为同步操作
return getConnection(connectStandaloneAsync(codec, this.redisURI, timeout));
}
//异步转同步操作
protected <T> T getConnection(ConnectionFuture<T> connectionFuture) {
try {
return connectionFuture.get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw RedisConnectionException.create(connectionFuture.getRemoteAddress(), e);
} catch (Exception e) {
if (e instanceof ExecutionException) {
throw RedisConnectionException.create(connectionFuture.getRemoteAddress(), e.getCause());
}
throw RedisConnectionException.create(connectionFuture.getRemoteAddress(), e);
}
}
RedisClient.connectStandaloneAsync
private <K, V> ConnectionFuture<StatefulRedisConnection<K, V>> connectStandaloneAsync(RedisCodec<K, V> codec,
RedisURI redisURI, Duration timeout) {
assertNotNull(codec);
checkValidRedisURI(redisURI);
logger.debug("Trying to get a Redis connection for: " + redisURI);
//创建一个有状态的EndPoint用于抽象底层channel的实现,DefaultEndpoint内部封装断线重连、重连后成功后回放连接失败期间的command。同时封装了AT_MOST_ONCE、AT_LEAST_ONCE的可靠性实现(该逻辑是基于内存的,所以并不可靠)。
DefaultEndpoint endpoint = new DefaultEndpoint(clientOptions, clientResources);
RedisChannelWriter writer = endpoint;
//进一步封装,添加支持过期时间的执行命令
if (CommandExpiryWriter.isSupported(clientOptions)) {
writer = new CommandExpiryWriter(writer, clientOptions, clientResources);
}
//创建StatefulRedisConnectionImpl对象,StatefulRedisConnectionImpl对外提供RedisCommand对象,内部基于writer发送命令。此时并没有真正的创建物理连接,该类本身是无状态、线程安全的。
StatefulRedisConnectionImpl<K, V> connection = newStatefulRedisConnection(writer, codec, timeout);
//异步创建Redis物理连接,返回future对象。后面可以看到future中返回的对象其实还是上面的connection
ConnectionFuture<StatefulRedisConnection<K, V>> future = connectStatefulAsync(connection, codec, endpoint, redisURI,
() -> new CommandHandler(clientOptions, clientResources, endpoint));
future.whenComplete((channelHandler, throwable) -> {
if (throwable != null) {
connection.close();
}
});
return future;
}
//StatefulRedisConnectionImpl的构造函数,此时已经创建了sync、async、reactive三种类型的RedisCommand。基于RedisCodec对key和value序列化,通过write把命令真正的发出去。
public StatefulRedisConnectionImpl(RedisChannelWriter writer, RedisCodec<K, V> codec, Duration timeout) {
super(writer, timeout);
this.codec = codec;
this.async = newRedisAsyncCommandsImpl();
this.sync = newRedisSyncCommandsImpl();
this.reactive = newRedisReactiveCommandsImpl();
}
RedisClient.connectStatefulAsync
private <K, V, S> ConnectionFuture<S> connectStatefulAsync(StatefulRedisConnectionImpl<K, V> connection,
RedisCodec<K, V> codec, Endpoint endpoint,
RedisURI redisURI, Supplier<CommandHandler> commandHandlerSupplier) {
//构建ConnectionBuidler,通过ConnectionBuilder来创建connection
ConnectionBuilder connectionBuilder;
if (redisURI.isSsl()) {
SslConnectionBuilder sslConnectionBuilder = SslConnectionBuilder.sslConnectionBuilder();
sslConnectionBuilder.ssl(redisURI);
connectionBuilder = sslConnectionBuilder;
} else {
connectionBuilder = ConnectionBuilder.connectionBuilder();
}
//填充StatefulRedisConnectionImpl
connectionBuilder.connection(connection);
//控制RedisClient行为的一些配置参数
connectionBuilder.clientOptions(clientOptions);
//ClientResource包含了一些EventLoopGroup信息
connectionBuilder.clientResources(clientResources);
//配置commandHandlerSupplier,这个commandHandler很重要,是实现StatefulRedisConnectionImpl线程安全的关键,后面会详细讲。
connectionBuilder.commandHandler(commandHandlerSupplier).endpoint(endpoint);
//connectionBuilder填充Bootstrap等更多的信息
//getSocketAddressSupplier是根据redisURI获取真正的Redis连接信息,如:sentinel模式下,需要从sentinel获取到真实的redis连接地址
connectionBuilder(getSocketAddressSupplier(redisURI), connectionBuilder, redisURI);
//配置netty的channeltype
channelType(connectionBuilder, redisURI);
if (clientOptions.isPingBeforeActivateConnection()) {
if (hasPassword(redisURI)) {
connectionBuilder.enableAuthPingBeforeConnect();
} else {
connectionBuilder.enablePingBeforeConnect();
}
}
//初始化channel,在这一步才真正的异步的去创建物理连接
ConnectionFuture<RedisChannelHandler<K, V>> future = initializeChannelAsync(connectionBuilder);
ConnectionFuture<?> sync = future;
if (!clientOptions.isPingBeforeActivateConnection() && hasPassword(redisURI)) {
//连接成功之后发送auth命令,做密码的验证
sync = sync.thenCompose(channelHandler -> {
CommandArgs<K, V> args = new CommandArgs<>(codec).add(redisURI.getPassword());
return connection.async().dispatch(CommandType.AUTH, new StatusOutput<>(codec), args);
});
}
//设置clientName,从Redis服务端执行client list可以看到clientname
if (LettuceStrings.isNotEmpty(redisURI.getClientName())) {
sync = sync.thenApply(channelHandler -> {
connection.setClientName(redisURI.getClientName());
return channelHandler;
});
}
//选择db
if (redisURI.getDatabase() != 0) {
sync = sync.thenCompose(channelHandler -> {
CommandArgs<K, V> args = new CommandArgs<>(codec).add(redisURI.getDatabase());
return connection.async().dispatch(CommandType.SELECT, new StatusOutput<>(codec), args);
});
}
//返回connection对象
return sync.thenApply(channelHandler -> (S) connection);
}
RedisClient.connectionBuilder
//为ConnectionBuidler填充更多的信息,如Bootstrap、channelGroup
protected void connectionBuilder(Mono<SocketAddress> socketAddressSupplier, ConnectionBuilder connectionBuilder,
RedisURI redisURI) {
//创建Netty客户端的Bootstrap对象
Bootstrap redisBootstrap = new Bootstrap();
//Bootstrap的一些配置参数,具体可以参考Netty的相关书籍(Netty权威指南)
redisBootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
redisBootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
redisBootstrap.option(ChannelOption.ALLOCATOR, BUF_ALLOCATOR);
SocketOptions socketOptions = getOptions().getSocketOptions();
redisBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
Math.toIntExact(socketOptions.getConnectTimeout().toMillis()));
if (LettuceStrings.isEmpty(redisURI.getSocket())) {
//keepAlive参数,默认为true
redisBootstrap.option(ChannelOption.SO_KEEPALIVE, socketOptions.isKeepAlive());
//tcp_nodelay参数,默认为true
redisBootstrap.option(ChannelOption.TCP_NODELAY, socketOptions.isTcpNoDelay());
}
connectionBuilder.timeout(redisURI.getTimeout());
connectionBuilder.password(redisURI.getPassword());
//把构建出来的bootStrap对象赋值给connectionBuidler,由connectionBuilder创建连接
connectionBuilder.bootstrap(redisBootstrap);
//Netty的相关参数配置,待研究
connectionBuilder.channelGroup(channels).connectionEvents(connectionEvents).timer(timer);
//配置socket地址提供者
connectionBuilder.socketAddressSupplier(socketAddressSupplier);
}
RedisClient.initializeChannelAsync
//初始化redis连接,返回ChannelFuture对象
protected <K, V, T extends RedisChannelHandler<K, V>> ConnectionFuture<T> initializeChannelAsync(
ConnectionBuilder connectionBuilder) {
Mono<SocketAddress> socketAddressSupplier = connectionBuilder.socketAddress();
if (clientResources.eventExecutorGroup().isShuttingDown()) {
throw new IllegalStateException("Cannot connect, Event executor group is terminated.");
}
//创建socketAddressFuture 对象,当socketAddressSupplier异步获取SocketAddress成功之后会把SocketAddress数据放入该对象中
CompletableFuture<SocketAddress> socketAddressFuture = new CompletableFuture<>();
//创建channelReadyFuture,当连接建立成功之后会把Channel对象放入该对象中
CompletableFuture<Channel> channelReadyFuture = new CompletableFuture<>();
//配置获取SocketAddress异步操作之后的操作:
//1. 把SocketAddress对象放入socketAddressFuture中
//2. 基于SocketAddress调用initializeChannelAsync0方法真正去建立连接
socketAddressSupplier.doOnError(socketAddressFuture::completeExceptionally).doOnNext(socketAddressFuture::complete)
.subscribe(redisAddress -> {
if (channelReadyFuture.isCancelled()) {
return;
}
//异步建立真正的连接,如果建立成功会把生产的Channel对象放入channelReadyFuture中
initializeChannelAsync0(connectionBuilder, channelReadyFuture, redisAddress);
}, channelReadyFuture::completeExceptionally);
//建立连接成功之后返回的还是connectionBuilder的connection对象,即StatefulRedisConnectionImpl
return new DefaultConnectionFuture<>(socketAddressFuture, channelReadyFuture.thenApply(channel -> (T) connectionBuilder
.connection()));
}
RedisClient.initializeChannelAsync0
//真正的去建立Redis物理连接,这里面有很多基于Future的异步操作,如果看不太懂,建议先看看Future的相关知识,多看几遍。
private void initializeChannelAsync0(ConnectionBuilder connectionBuilder, CompletableFuture<Channel> channelReadyFuture,
SocketAddress redisAddress) {
logger.debug("Connecting to Redis at {}", redisAddress);
Bootstrap redisBootstrap = connectionBuilder.bootstrap();
//创建PlainChannelInitializer对象,PlainChannelIntializer对象会在Channel初始化的时候添加很多Handlers(Netty的Handler概念可以参考Netty权威指南),如:CommandEncoder、CommandHandler(非常重要的Handler)、ConnectionWatchdog(实现断线重连)
RedisChannelInitializer initializer = connectionBuilder.build();
//RedisChannelInitializer配置到Bootstrap中
redisBootstrap.handler(initializer);
//调用一些通过ClientResources自定义的回调函数
clientResources.nettyCustomizer().afterBootstrapInitialized(redisBootstrap);
//获取initFuture 对象,如果Channel初始化完成,可以通过该对象获取到初始化的结果
CompletableFuture<Boolean> initFuture = initializer.channelInitialized();
//真正的通过Netty异步的方式去建立物理连接,返回ChannelFuture对象
ChannelFuture connectFuture = redisBootstrap.connect(redisAddress);
//配置异常处理
channelReadyFuture.whenComplete((c, t) -> {
if (t instanceof CancellationException) {
connectFuture.cancel(true);
initFuture.cancel(true);
}
});
connectFuture.addListener(future -> {
//异常处理
if (!future.isSuccess()) {
logger.debug("Connecting to Redis at {}: {}", redisAddress, future.cause());
connectionBuilder.endpoint().initialState();
//赋值channelReadyFuture告知出现异常了
channelReadyFuture.completeExceptionally(future.cause());
return;
}
//当Channel初始化完成之后,根据初始化的结果做判断
initFuture.whenComplete((success, throwable) -> {
//如果异常为空,则初始化成功。
if (throwable == null) {
logger.debug("Connecting to Redis at {}: Success", redisAddress);
RedisChannelHandler<?, ?> connection = connectionBuilder.connection();
connection.registerCloseables(closeableResources, connection);
//把成功之后的结果赋值给channelReadyFuture对象
channelReadyFuture.complete(connectFuture.channel());
return;
}
//如果初始化Channel的过程中出现异常的处理逻辑
logger.debug("Connecting to Redis at {}, initialization: {}", redisAddress, throwable);
connectionBuilder.endpoint().initialState();
Throwable failure;
if (throwable instanceof RedisConnectionException) {
failure = throwable;
} else if (throwable instanceof TimeoutException) {
failure = new RedisConnectionException("Could not initialize channel within "
+ connectionBuilder.getTimeout(), throwable);
} else {
failure = throwable;
}
//赋值channelReadyFuture告知出现异常了
channelReadyFuture.completeExceptionally(failure);
});
});
}
至此,Redis的Connection的建立连接的主流程就结束了,具体的一些逻辑如:断线重连是如何实现的,Redis模式下是怎么基于Sentinel获取Redis实际连接的等等会在后续的文章中介绍。
相关推荐
- Go语言图书管理RESTful API开发实战
-
Go(Golang)是最近流行起来,且相对较新的编程语言。它小而稳定,使用和学习简单,速度快,经过编译(原生代码),并大量用于云工具和服务(Docker、Kubernetes...)。考虑到它所带来的...
- 轻松搞定Golang 中的内存管理(golang设置内存大小)
-
除非您正在对服务进行原型设计,否则您可能会关心应用程序的内存使用情况。内存占用更小,基础设施成本降低,扩展变得更容易/延迟。尽管Go以不消耗大量内存而闻名,但仍有一些方法可以进一步减少消耗。其中一...
- golang实现deepseek 聊天功能(golang deepcopy)
-
在搭建完deepseek环境后在docker内部署deepseekrag环境,我们可以用golang实现聊天功能。在实现这个功能之前,我们先了解下提示词工程(prompt)。大模型虽然知道的东西多...
- golang slice的扩容机制(golang设置内存大小)
-
在Go语言中,切片(slice)是一种动态数组,其长度可以在运行时改变。当向切片中添加元素时,如果切片的容量不足以容纳新元素,就会触发扩容机制。下面详细介绍Go语言切片的扩容机制。扩容触发条件...
- Etcd服务注册与发现封装实现--golang
-
服务注册register.gopackageregisterimport("fmt""time"etcd3"github.com/cor...
- 嘿,轻松获取区间内所有日期的Golang小技巧!
-
在Go语言中,获取两个日期之间的所有日期可以手动实现一个函数来完成。以下是一个示例函数,它会返回一个日期切片,包含从开始日期到结束日期(包括这两个日期)的所有日期:packagemainimpo...
- 仓颉、Java、Golang性能测试——数组扩容
-
版本信息仓颉版本0.53.18Golang版本1.22.8Java版本corretto-1.8.0_452源码仓颉packagecangjie_testimportstd.collect...
- Golang 58个坑 – 中级篇:36-51(golang cef)
-
36.关闭HTTP的响应体37.关闭HTTP连接38.将JSON中的数字解码为interface类型39.struct、array、slice和map的值比较40.从panic...
- 一篇文章学会golang语法,golang简明教程快速入门
-
Go(又称Golang)是Google开发的一种静态强类型、编译型、并发型,并具有垃圾回收功能的编程语言。——Go-wikipedia.org1Go安装最新版本下载地址官方下载https...
- 运维大神如何使用 Golang 日志监控应用程序
-
你是如何使用Golang日志监控你的应用程序的呢?Golang没有异常,只有错误。因此你的第一印象可能就是开发Golang日志策略并不是一件简单的事情。不支持异常事实上并不是什么问题,异常在...
- Golang操作elasticsearch(golang操作word)
-
简介开源的Elasticsearch是目前全文搜索引擎的首选,很多日志都是放到elasticsearch里面,然后再根据具体的需求进行分析。目前我们的运维系统是使用golang开发的,需要定时到e...
- 一文带你看懂Golang最新特性(golang x)
-
作者:腾讯PCG代码委员会经过十余年的迭代,Go语言逐渐成为云计算时代主流的编程语言。下到云计算基础设施,上到微服务,越来越多的流行产品使用Go语言编写。可见其影响力已经非常强大。一、Go语言发展历史...
- Golang 最常用函数(备用查询)(golang函数和方法)
-
hello.gopackagemainimport"fmt"funcmain(){fmt.Println("Hello,world!")}直...
- Golang:将日志以Json格式输出到Kafka
-
在上一篇文章中我实现了一个支持Debug、Info、Error等多个级别的日志库,并将日志写到了磁盘文件中,代码比较简单,适合练手。有兴趣的可以通过这个链接前往:https://github.com/...
- 如何从 PHP 过渡到 Golang?(php转go需要多久)
-
我是PHP开发者,转Go两个月了吧,记录一下使用Golang怎么一步步开发新项目。本着有坑填坑,有错改错的宗旨,从零开始,开始学习。因为我司没有专门的Golang大牛,所以我也只能一步步自己去...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- maven镜像 (69)
- undefined reference to (60)
- zip格式 (63)
- oracle over (62)
- date_format函数用法 (67)
- 在线代理服务器 (60)
- shell 字符串比较 (74)
- x509证书 (61)
- localhost (65)
- java.awt.headless (66)
- syn_sent (64)
- settings.xml (59)
- 弹出窗口 (56)
- applicationcontextaware (72)
- my.cnf (73)
- httpsession (62)
- pkcs7 (62)
- session cookie (63)
- java 生成uuid (58)
- could not initialize class (58)
- beanpropertyrowmapper (58)
- word空格下划线不显示 (73)
- jar文件 (60)
- jsp内置对象 (58)
- makefile编写规则 (58)