netty4.x学习六使netty实现自己的RPC

2018-12-26  本文已影响9人  昨日已逝去

一提到netty实现rpc,就让人情不自禁的想起Dubbo服务间的调用。下面就根据问题实现rpc。

dubbo服务调用时,service是没有实现类的,service层调用的方法如何被处理?

        NettyClient client = new NettyClient();

        HelloService service =  (HelloService)client.getBean(HelloService.class);

        service.hello("are you ok?");
    public Object getBean(final Class<?> serviceClass) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class<?>[]{serviceClass}, (proxy, method, args) -> {
                    if (client == null) {
                        initClient();
                    }
                    // 设置参数
                    client.setPara( method.getName() +"#"+ args[0]);
                    return executor.submit(client).get();
                });
    }

服务端如何得知是哪个类调用的哪个方法?

        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class<?>[]{serviceClass}, (proxy, method, args) -> {
                    if (client == null) {
                        initClient();
                    }
                    // 设置参数,用于调用方法判断
                    client.setPara( method.getName() +"#"+ args[0]);
                    return executor.submit(client).get();
                });
 if (msg.toString().startsWith(StringConfig.providerName)) {

            HelloService helloService = new HelloServiceImpl();
            String substring = msg.toString().substring(msg.toString().lastIndexOf("#"));
            String hello = helloService.hello(substring);
            ctx.writeAndFlush(hello);
            System.out.println("服务端发送成功!");
        }

客户端如何获取返回的结果?

 public synchronized void channelRead(ChannelHandlerContext ctx, Object msg){
        result = msg.toString();
        System.out.println("收到服务发送的消息:"+result);
        notify();

    }
    @Override
    public synchronized Object call() throws InterruptedException {
        context.writeAndFlush(para);
        wait();
        return result;
    }

项目地址 https://github.com/DespairYoke/netty/tree/master/netty-rpc

上一篇下一篇

猜你喜欢

热点阅读