首页 > 其他分享 >心跳机制解决lettuce连接池断连问题

心跳机制解决lettuce连接池断连问题

时间:2022-10-24 16:11:12浏览次数:43  
标签:netty lettuce channel io 心跳 import public 连接池

心跳机制

Springboot 项目中Redis用lettuce连接池,如果长时间不用redis的话,就会断连,可以通过用netty的心跳机制来维持连接。

心跳是在TCP长连接中,客户端和服务端定时向对方发送数据包通知对方自己还在线,保证连接的有效性的一种机制。
在服务器和客户端之间一定时间内没有数据交互时, 即处于 idle 状态时, 客户端或服务器会发送一个特殊的数据包给对方, 当接收方收到这个数据报文后, 也立即发送一个特殊的数据报文, 回应发送方, 此即一个 PING-PONG 交互. 自然地, 当某一端收到心跳消息后, 就知道了对方仍然在线, 这就确保 TCP 连接的有效性。

import io.lettuce.core.resource.ClientResources;
import io.lettuce.core.resource.NettyCustomizer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration
public class ClientConfig {
 
    @Bean
    public ClientResources clientResources(){
 
        NettyCustomizer nettyCustomizer = new NettyCustomizer() {
 
            @Override
            public void afterChannelInitialized(Channel channel) {
                channel.pipeline().addLast(
                        //此处事件必须小于超时时间 
                        new IdleStateHandler(40, 0, 0));
                channel.pipeline().addLast(new ChannelDuplexHandler() {
                    @Override
                    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                        if (evt instanceof IdleStateEvent) {
                            ctx.disconnect();
                        }
                    }
                });
            }
 
            @Override
            public void afterBootstrapInitialized(Bootstrap bootstrap) {
 
            }
        };
        return ClientResources.builder().nettyCustomizer(nettyCustomizer ).build();
    }
}

原文链接:https://blog.csdn.net/qq_15123593/article/details/121507954

标签:netty,lettuce,channel,io,心跳,import,public,连接池
From: https://www.cnblogs.com/qq53462202/p/16821778.html

相关文章