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(); } } }
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号