netty 心跳檢測

心跳檢測在很多分布式應用中都存在 mongodb redis ...

服務器端代碼

  • 1,MyServer.java
public class MyServer {

    public static void main(String... arg) throws Exception {

        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();

        try {

            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(boss, workGroup).channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ServerInitializer());

            ChannelFuture channelFuture = bootstrap.bind(8899).sync();
            channelFuture.channel().closeFuture().sync();

        } finally {
            boss.shutdownGracefully();
            workGroup.shutdownGracefully();
        }


    }
}
  • 2,ServerInitializer.java
public class ServerInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

        //心跳handler 超時時間 讀 15秒  寫30秒  讀寫50
        pipeline.addLast(new IdleStateHandler(15,30,50, TimeUnit.SECONDS));

        pipeline.addLast(new DelimiterBasedFrameDecoder(4096, Delimiters.lineDelimiter()));

        pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
        pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));

        pipeline.addLast(new MyServerHandler());


    }
}
  • 3, MyServerHandler.java
public class MyServerHandler extends SimpleChannelInboundHandler<String> {

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        String ip = channel.remoteAddress().toString();

        System.out.println("add ip:    " + ip);
        channel.writeAndFlush("【服務器】"+ LocalDateTime.now()+"\n");
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        String ip = ctx.channel().remoteAddress().toString();

        System.out.println("remove ip:    " + ip);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            String eventType = null;
            switch (event.state()) {
                case ALL_IDLE:
                    eventType = "讀寫空閑";
                    break;
                case WRITER_IDLE:
                    eventType = "寫空閑";
                    break;
                case READER_IDLE:
                    eventType = "讀空閑";
                    break;
            }

            System.out.println(ctx.channel().remoteAddress()+" 超時時間 "+eventType);


        }
    }


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        Channel channel = ctx.channel();
        String ip = channel.remoteAddress().toString();
        System.out.println(ip+" ---------- "+msg);
        channel.writeAndFlush("【服務器】"+ LocalDateTime.now()+"\n");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
       ctx.channel().close();
    }
}

客戶端

  • 1,MyClient.java
public class MyClient {
    public static void main(String... arg) throws Exception {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();

        try {

            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
                    .handler(new ClientInitializer());

            Channel channel = bootstrap.connect("127.0.0.1",8899).sync().channel();

            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            while (true){
                channel.writeAndFlush(br.readLine()+"\r\n");
            }

        } finally {
            eventLoopGroup.shutdownGracefully();
        }

    }

}
  • 2, ClientInitializer.java
public class ClientInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();


        pipeline.addLast(new DelimiterBasedFrameDecoder(4096, Delimiters.lineDelimiter()));

        pipeline.addLast(new StringDecoder());
        pipeline.addLast(new StringEncoder());

        pipeline.addLast(new ClientHander());


    }
}
  • 3,ClientHander.java
public class ClientHander extends SimpleChannelInboundHandler<String> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {

        System.out.println(" 接收到數據 " + msg);

    }
}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,881評論 18 139
  • Spring Boot 參考指南 介紹 轉載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,941評論 6 342
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,116評論 25 708
  • 崽崽: 你不是一直想再長高一點嗎? 昨晚媽媽去小語家坐了會兒。 小語爸爸建議我們每晚做10-20次拉伸, 然后睡前...
    liqi_carol閱讀 225評論 0 0
  • 今天中午直接從醫院趕去上班,下班后也是直奔醫院,每當這個時候,我真希望自己是一位全職媽媽。 還記得今年6月份的時候...
    雅雅寫日記閱讀 351評論 0 1