简单实现通过netty通信,后续提供基于protobuf传输协议的rpc框架

后续也会提供service-mesh简单的代码实现
netty通信和socket通信大致是类似的,在socket的基础上对其进行封装,当然你也可以实现netty功能,但是我给你一句话。
image.png
为什么要用netty呢,官方给出这样的解释。确实,netty是一个很不错的框架,我们可以基于netty来实现简单的rpc调用

image.png

package org.gfu.base.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
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.util.CharsetUtil;

import java.util.Date;


/**
 * netty client
 *
 * @author 719383495@qq.com |719383495qq@gmail.com |gfu
 * @date 2019/9/27
 */
class NettyClient {

    private String host;
    private int port;
    private String jsonStr;


    NettyClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    NettyClient setMessage(String jsonStr) {
        this.jsonStr = jsonStr;
        return this;
    }

    void run() {
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(workerGroup)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8));
                            ch.pipeline().addLast(new StringDecoder(CharsetUtil.UTF_8));
                            ch.pipeline().addLast(new NettyClientHandler(jsonStr));
                        }
                    });
            ChannelFuture channelFuture = bootstrap.connect(host, port).addListener(
                    f -> {
                        if (f.isSuccess()) {
                            System.out.println("连接成功:" + host + ":" + port);
                        } else {
                            System.out.println(new Date() + "-- 连接失败:" + host + ":" + port);
                        }
                    }
            ).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }

}
package org.gfu.base.netty;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Scanner;

/**
 * netty server handler
 *
 * @author 719383495@qq.com |719383495qq@gmail.com |gfu
 * @date 2019/9/27
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter {

    private ChannelHandlerContext ctx;
    private String jsonStr;

    public NettyClientHandler(String jsonStr) {
        this.jsonStr = jsonStr;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        this.ctx = ctx;
        ctx.writeAndFlush(jsonStr);
    }
}

package org.gfu.base.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.sctp.nio.NioSctpServerChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

import java.util.Date;

/**
 * netty server
 *
 * @author 719383495@qq.com |719383495qq@gmail.com |gfu
 * @date 2019/9/27
 */
class NettyServer {

    private String host;
    private int port;

    NettyServer(String host, int port) {
        this.host = host;
        this.port = port;
    }

    void run() {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8));
                            ch.pipeline().addLast(new StringDecoder(CharsetUtil.UTF_8));
                            ch.pipeline().addLast(new NettyServerHandler());
                        }
                    }).option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);
            ChannelFuture channelFuture = serverBootstrap.bind(host, port).
                    addListener(f -> {
                        if (f.isSuccess()) {
                            System.out.println("绑定成功:" + host + ":" + port);
                        } else {
                            System.out.println(new Date() + "--绑定失败:" + host + ":" + port);
                        }
                    }).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

package org.gfu.base.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.*;

/**
 * netty server handler
 *
 * @author 719383495@qq.com |719383495qq@gmail.com |gfu
 * @date 2019/9/27
 */
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    private String msg;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println(msg);
        this.msg = msg.toString();
        this.channelActive(ctx);
    }

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

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(msg);
        ctx.writeAndFlush(msg + "server accept success");
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱学习的小伙子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值