netty学习
监听器学习参考:https://blog.51cto.com/u_15116285/5964656
参考学习地址:https://www.bilibili.com/video/BV1bM411M7Dd?p=23&spm_id_from=pageDriver&vd_source=f97080956039c326589b5b26607d960b
参考学习:https://blog.csdn.net/crazymakercircle/article/details/124588880
例子:
import com.zygh.tscmp.handle.NettyClientHandler; import io.netty.bootstrap.Bootstrap; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; import io.netty.handler.timeout.IdleStateHandler; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.util.concurrent.TimeUnit; /** * 系统建立连接 */ @Component @Slf4j public class NettyConnectUtils { /** * 解决静态属性注入null问题 */ @Value("${netty.port}") private int sourcePort; @Value("${netty.url}") private String sourceUrl; private static Integer port; private static String url; @PostConstruct public void init() { url = sourceUrl; port = sourcePort; } /** * 创建连接 */ public static void doConnect() { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group) .channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(1024, 16 * 1024, 1024 * 1024)) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); //设置心跳检测30秒时间 p.addLast(new IdleStateHandler(30, 30, 0, TimeUnit.SECONDS)); p.addLast("decoder", new StringDecoder()); p.addLast("encoder", new StringEncoder()); p.addLast(new NettyClientHandler()); } }); ChannelFuture future = b.connect(url, port) //增加重连监听器 .addListener((ChannelFuture futureListener) -> { final EventLoop eventLoop = futureListener.channel().eventLoop(); if (!futureListener.isSuccess()) { log.info("与服务端断开连接!在10s之后准备尝试重连!"); eventLoop.schedule(() -> doConnect(), 10, TimeUnit.SECONDS); } }) .sync(); future.channel().closeFuture().sync(); } catch (InterruptedException e) { throw new RuntimeException(e); } finally { log.error("连接失败"); group.shutdownGracefully(); } } }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库