package com.jsowell.pile.rpc; import com.jsowell.common.protocol.RpcRequest; import com.jsowell.common.protocol.RpcResponse; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.DefaultEventLoopGroup; import io.netty.channel.EventLoopGroup; import io.netty.channel.SimpleChannelInboundHandler; public class RpcRequestHandler extends SimpleChannelInboundHandler { private final static EventLoopGroup worker = new DefaultEventLoopGroup(Runtime.getRuntime().availableProcessors() + 1); @Override protected void channelRead0(ChannelHandlerContext ctx, RpcRequest msg) throws Exception { // 为避免占用网络io,此处异步进行处理 worker.submit(() -> { System.out.println("[RpcRequestHandler] "+ Thread.currentThread().getName() +" 处理请求,msg: " + msg); // 模拟处理耗时 try { Thread.sleep(3000); } catch (InterruptedException e) { throw new RuntimeException(e); } RpcResponse rpcResponse = new RpcResponse(); rpcResponse.setId(msg.getId()); rpcResponse.setResult("处理" + msg.getParam()); ctx.writeAndFlush(rpcResponse); }); } }