Dubbo底层使用Netty作为网络通信框架。

【网络传输问题】: 相对于传统的RPC或者RMI等方式的远程服务过程调用采用了同步阻塞IO,当客户端的并发压力或者网络时延增长之后,同步阻塞I/O会由于频繁的等待导致I/O线程经常性阻塞,由于线程无法高效的工作,I/O处理能力自然会下降。
【序列化性能差】: 无法跨语言、码流长、性能差。链接
【线程模型问题】: 采用同步阻塞IO,这会导致每个TCP连接都占用 1个线程,由于线程资源是JVM虚拟机非常宝贵的资源,当I/O读写阻塞导致线程无法释放时,会导致性能急剧下降。

# 一、设计思想

模仿Dubbo的消费者和提供者约定接口和协议,消费者远程调用提供者,提供者返回数据,消费者打印提供者返回的数据。
【1】创建一个接口,定义抽象方法。用于消费者和提供者之间的约定。
【2】创建一个提供者,该类需要监听消费者的请求,并按照约定返回数据。
【3】创建一个消费者,该类需要透明的调用自己不存在的方法,内部需要使用Netty请求提供者返回数据。

# 二、服务端

【1】添加Netty Maven依赖:

<dependencies>
    <dependency>
        <groupId>io.netty</groupId>
        <artifactId>netty-all</artifactId>
        <version>4.1.16.Final</version>
    </dependency>
</dependencies>
1
2
3
4
5
6
7

【2】首先准备客户端和服务端需要的公共接口:

public interface HelloInterface {
    String hello(String msg);
}
1
2
3

【3】服务端实现HelloInterface接口:

public class HelloImpl implements HelloInterface {
    @Override
    public String hello(String msg) {
        //返回客户端的消息
        return msg != null ? msg + " -----> I am fine." : "I am fine.";
    }
}
1
2
3
4
5
6
7

【4】实现Netty Server端代码(代码固定,通常作为公共代码使用):

public class Provider {

    static void startServer(String hostName, int port) {
        //配置服务端的 NIO 线程组
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();
                            //字符串的编解码器
                            p.addLast(new StringDecoder());
                            p.addLast(new StringEncoder());
                            p.addLast(new HelloHandler());
                        }
                    });
            //绑定端口,同步等待成功
            ChannelFuture f = bootstrap.bind(hostName, port).sync();
            //等待服务端监听端口关闭
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            //优雅退出释放线程池资源
            //bossGroup.shutdownGracefully();
            //workerGroup.shutdownGracefully();
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

【5】服务端对应的HelloHandler类的实现:实现ChannelInboundHandlerAdapter适配器,对客户端发送的消息进行处理。这里显示判断了是否符合约定(并没有使用复杂的协议,只是一个字符串判断),然后创建一个具体实现类,并调用方法写回客户端。

public class HelloHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {

             // 如何符合约定,则调用本地方法,返回数据
             if (msg.toString().startsWith(ClientBootstrap.providerName)) {
                   String result = new HelloImpl()
                       .hello(msg.toString().substring(msg.toString().lastIndexOf("#") + 1));
                   ctx.writeAndFlush(result);
                 }
           }
}
1
2
3
4
5
6
7
8
9
10
11
12

【6】服务端启动类:先运行服务端,后运行客户端;

public class Bootstrap {
   public static void main(String[] args) {
             Provider.startServer("localhost", 8088);
   }
}
1
2
3
4
5

# 三、客户端

消费者有一个需要注意的地方,就是调用需要透明,也就是说,框架使用者不用关心底层的网络实现。这里我们可以使用JDK的动态代理链接来实现这个目的。思路是客户端调用代理方法,返回一个实现了HelloService接口的代理对象,调用代理对象的方法,返回结果。当调用代理方法的时候,我们需要初始化Netty客户端,还需要向服务端请求数据,并返回数据。

【1】首先创建代理相关的类:该类有 2个方法,创建代理和初始化客户端。初始化客户端逻辑: 创建一个Netty的客户端,并连接提供者,并设置一个自定义handler,和一些String类型的编解码器。创建代理逻辑:使用JDK的动态代理技术,代理对象中的invoke方法实现如下:如果client没有初始化,则初始化client,这个client 既是handler,也是一个Callback。将参数设置进client ,使用线程池调用clientcall方法并阻塞等待数据返回。

public class Consumer {
    private static ExecutorService executor = Executors
            .newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    private static HelloClientHandler client;

    /**
     * 创建一个代理对象
     */
    public Object createProxy(final Class<?> serviceClass,
                              final String providerName) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class<?>[]{serviceClass}, (proxy, method, args) -> {
                    if (client == null) {
                        initClient();
                    }
                    // 设置参数
                    client.setPara(providerName + args[0]);
                    return executor.submit(client).get();
                });
    }

    /**
     * 初始化客户端
     */
    private static void initClient() {
        client = new HelloClientHandler();
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();
                            p.addLast(new StringDecoder());
                            p.addLast(new StringEncoder());
                            p.addLast(client);
                        }
                    });
            //发起异步连接操作
            ChannelFuture f = b.connect("localhost", 8088).sync();
            //等待客户端关闭连接
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            //group.shutdownGracefully();
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53

【2】客户端NettyHelloClientHandler类的实现:该类缓存了ChannelHandlerContext,用于下次使用,有两个属性:返回结果和请求参数。当成功连接后,缓存ChannelHandlerContext,当调用call方法的时候,将请求参数发送到服务端,等待。当服务端收到并返回数据后,调用channelRead方法,将返回值赋值个result,并唤醒等待在call方法上的线程。此时,代理对象返回数据。

public class HelloClientHandler extends ChannelInboundHandlerAdapter implements Callable {

    private ChannelHandlerContext context;
    private String result;
    private String para;

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        context = ctx;
    }

    /**
     * 收到服务端数据,唤醒等待线程
     */
    @Override
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) {
        result = msg.toString();
        notify();
    }

    /**
     * 写出数据,开始等待唤醒
     */
    @Override
    public synchronized Object call() throws InterruptedException {
        context.writeAndFlush(para);
        wait();
        return result;
    }

    void setPara(String para) {
        this.para = para;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

# 四、测试

首先创建了一个代理对象,然后每隔一秒钟调用代理的 hello 方法,并打印服务端返回的结果。

public class ClientBootstrap {
    public static final String providerName = "HelloService#hello#";

    public static void main(String[] args) throws InterruptedException {

        Consumer consumer = new Consumer();
        // 创建一个代理对象
        HelloInterface service = (HelloInterface) consumer
                .createProxy(HelloInterface.class, providerName);
        for (; ; ) {
            Thread.sleep(1000);
            System.out.println(service.hello("are you ok ?"));
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

结果展示:

are you ok ? -----> i am finle.
are you ok ? -----> i am finle.
are you ok ? -----> i am finle.
are you ok ? -----> i am finle.
are you ok ? -----> i am finle.
1
2
3
4
5
(adsbygoogle = window.adsbygoogle || []).push({});