简易RPC框架实现——4、客户端非阻塞处理

本章将NettyClient中发送请求后的阻塞改为异步非阻塞,利用CompletableFutue.get(),将阻塞环节放置到了代理类中,能更大地提高服务器地吞吐量。本章地commit为8dcf034

使用future获取相应结果具体流程如下:
future获取相应

利用Map缓存未处理地请求

将每一个请求以及其对应的CompletableFuture放入缓存中,之后通过异步地方式去获取请求地结果,首先需要建一个UnprocessedRequest用来缓存request对应地处理结果,为了使得缓存全局唯一,使用单例工厂模式创建UnprocessedRequest:

public class UnprocessedRequest {
    private static final Logger logger = LoggerFactory.getLogger(UnprocessedRequest.class);
    private static Map<String, CompletableFuture<RpcResponse>> unprocessedMap = new ConcurrentHashMap<>();

    public void put(String rpcRequestId,CompletableFuture<RpcResponse> future){
        unprocessedMap.put(rpcRequestId,future);
    }

    public void remove(String rpcRequestId){
        unprocessedMap.remove(rpcRequestId);
    }

    public void complete(RpcResponse rpcResponse){
        CompletableFuture<RpcResponse> future = unprocessedMap.remove(rpcResponse.getRequestId());
        if(future != null){
            future.complete(rpcResponse);
        }else{
            logger.error("异步获取结果出现错误");
            throw new RpcException(RpcError.COMPLETABLE_ERROR);
        }
    }
}

修改客户端数据获取方式

之前在客户端获取入站处理器处理后的数据是通过AttributeKey全局获取的,但是为了确保拿到的不为null值,因此我们将写入过程阻塞了。我们引入一个CompletableFuture用来存储入站处理器处理后的数据,之后在代理类中异步调用处理结果,这样能够很大程度提高整个服务器的吞吐量:

public class NettyClientHandler extends SimpleChannelInboundHandler<RpcResponse> {

    private static final Logger logger = LoggerFactory.getLogger(NettyClientHandler.class);
    private final UnprocessedRequest unprocessedRequest = SingletonFactory.getInstance(UnprocessedRequest.class);
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcResponse msg) throws Exception {
        try {
            logger.info("客户端获取到服务端返回的信息:{}",msg);
            unprocessedRequest.complete(msg);
            ctx.channel().close();
        } finally {
            ReferenceCountUtil.release(msg);
        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("在信息从服务端返回客户端发生错误");
        cause.printStackTrace();
        ctx.close();
    }
}

在代理类中拿到Rpcresponse:

	@Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        RpcRequest rpcRequest = RpcRequest.builder()
                .requestId(UUID.randomUUID().toString())
                .interfaceName(method.getDeclaringClass().getName())
                .methodName(method.getName())
                .parameterTypes(method.getParameterTypes())
                .parameters(args)
                .build();
        CompletableFuture<RpcResponse> result = null;
        if(client instanceof SocketClient){
            return ((RpcResponse) client.sendRequest(rpcRequest,host,port)).getData();
        }
        if(client instanceof NettyClient){
            result = (CompletableFuture<RpcResponse>) client.sendRequest(rpcRequest,host,port);
        }
      return result.get().getData();
    }

客户端的sendRequest即可以设置为非阻塞的:

    @Override
    public CompletableFuture<RpcResponse> sendRequest(RpcRequest rpcRequest, String host, int port) {
        Channel channel = ChannelProvider.get(new InetSocketAddress(host,port),serializer);
        CompletableFuture<RpcResponse> future = new CompletableFuture<>();
        unprocessedRequest.put(rpcRequest.getRequestId(),future);
        channel.writeAndFlush(rpcRequest).addListener((ChannelFutureListener) future1 -> {
            if(future1.isSuccess()){
                logger.info("成功向服务器发送请求:{}",rpcRequest);
            }else{
                future1.channel().close();
                logger.error("向服务器发送消息失败:{}",future1.cause());
                future.completeExceptionally(future1.cause());
            }
        });
        return future;
    }

服务端不需要做任何修改

测试

测试代码无任何改动,结果如下:
服务端:

[main] INFO cn.fzzfrjf.core.DefaultServerPublisher - 向接口:[interface cn.fzzfrjf.entity.HelloService]注册服务:cn.fzzfrjf.service.HelloServiceImpl
[main] INFO cn.fzzfrjf.core.DefaultServerPublisher - 向接口:[interface cn.fzzfrjf.entity.ByeService]注册服务:cn.fzzfrjf.service.ByeServiceImpl
[main] WARN io.netty.bootstrap.ServerBootstrap - Unknown channel option 'SO_KEEPALIVE' for channel '[id: 0x21ad7250]'
[nioEventLoopGroup-2-1] INFO io.netty.handler.logging.LoggingHandler - [id: 0x21ad7250] REGISTERED
[nioEventLoopGroup-2-1] INFO io.netty.handler.logging.LoggingHandler - [id: 0x21ad7250] BIND: 0.0.0.0/0.0.0.0:10000
[nioEventLoopGroup-2-1] INFO io.netty.handler.logging.LoggingHandler - [id: 0x21ad7250, L:/0:0:0:0:0:0:0:0:10000] ACTIVE
[nioEventLoopGroup-2-1] INFO io.netty.handler.logging.LoggingHandler - [id: 0x21ad7250, L:/0:0:0:0:0:0:0:0:10000] READ: [id: 0x4cf92cbc, L:/127.0.0.1:10000 - R:/127.0.0.1:60873]
[nioEventLoopGroup-2-1] INFO io.netty.handler.logging.LoggingHandler - [id: 0x21ad7250, L:/0:0:0:0:0:0:0:0:10000] READ COMPLETE
[nioEventLoopGroup-3-1] INFO cn.fzzfrjf.core.NettyServerHandler - 服务器接收到请求:cn.fzzfrjf.entity.RpcRequest@73f95071
[nioEventLoopGroup-2-1] INFO io.netty.handler.logging.LoggingHandler - [id: 0x21ad7250, L:/0:0:0:0:0:0:0:0:10000] READ: [id: 0x4a9347a0, L:/127.0.0.1:10000 - R:/127.0.0.1:60874]
[nioEventLoopGroup-2-1] INFO io.netty.handler.logging.LoggingHandler - [id: 0x21ad7250, L:/0:0:0:0:0:0:0:0:10000] READ COMPLETE
[nioEventLoopGroup-3-2] INFO cn.fzzfrjf.core.NettyServerHandler - 服务器接收到请求:cn.fzzfrjf.entity.RpcRequest@715c8fc

Process finished with exit code 130

服务端:

[nioEventLoopGroup-2-1] INFO cn.fzzfrjf.core.ChannelProvider - 获取channel连接成功,连接到服务器activate.navicat.com:10000
[nioEventLoopGroup-2-1] INFO cn.fzzfrjf.core.NettyClient - 成功向服务器发送请求:cn.fzzfrjf.entity.RpcRequest@10cc8b10
[nioEventLoopGroup-2-1] INFO cn.fzzfrjf.core.NettyClientHandler - 客户端获取到服务端返回的信息:RpcResponse(code=200, requestId=14a50ff6-8e3c-4b44-9e3a-4adfa9f94caa, data=这是id为:2发送的:This is NettyClient!)
[nioEventLoopGroup-2-2] INFO cn.fzzfrjf.core.ChannelProvider - 获取channel连接成功,连接到服务器activate.navicat.com:10000
[nioEventLoopGroup-2-2] INFO cn.fzzfrjf.core.NettyClient - 成功向服务器发送请求:cn.fzzfrjf.entity.RpcRequest@286ffbfa
[nioEventLoopGroup-2-2] INFO cn.fzzfrjf.core.NettyClientHandler - 客户端获取到服务端返回的信息:RpcResponse(code=200, requestId=faa2278e-18a0-4ae4-8b32-6e577881f00a, data=(This is NettyClient!),bye!)
这是id为:2发送的:This is NettyClient!
(This is NettyClient!),bye!

在客户端输出中,我们可以明显看到,发送请求与进行反射调用很明显不是顺序调用了,到达了我们需要的效果。
未完。。。。。。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值