Springboot整合Netty实现RPC服务器

本文展示了如何利用Springboot与Netty构建RPC服务器,详细解释了配置过程和关键代码,包括BossGroup和WorkerGroup的设置,JsonDecoder和JsonEncoder的使用,以及RpcInboundHandler处理RPC请求的方法。此外,还介绍了客户端的实现,包括连接建立、发送请求、处理响应和心跳维持。通过动态代理和FactoryBean,实现了接口调用的透明化。
摘要由CSDN通过智能技术生成

try {

ServerBootstrap bootstrap = new ServerBootstrap();

bootstrap.group(boss, worker)

.childHandler(new ChannelInitializer() {

@Override

protected void initChannel(SocketChannel ch) throws Exception {

ChannelPipeline pipeline = ch.pipeline();

pipeline.addLast(new IdleStateHandler(0, 0, 60));

pipeline.addLast(new JsonDecoder());

pipeline.addLast(new JsonEncoder());

pipeline.addLast(new RpcInboundHandler(rpcServices));

}

})

.channel(NioServerSocketChannel.class);

ChannelFuture future = bootstrap.bind(port).sync();

log.info(“RPC 服务器启动, 监听端口:” + port);

future.channel().closeFuture().sync();

}catch (Exception e){

e.printStackTrace();

boss.shutdownGracefully();

worker.shutdownGracefully();

}

}).start();

}

}

RpcServerInboundHandler 负责处理RPC请求

@Slf4j

public class RpcServerInboundHandler extends ChannelInboundHandlerAdapter {

private Map<String, Object> rpcServices;

public RpcServerInboundHandler(Map<String, Object> rpcServices){

this.rpcServices = rpcServices;

}

@Override

public void channelActive(ChannelHandlerContext ctx) throws Exception {

log.info(“客户端连接成功,{}”, ctx.channel().remoteAddress());

}

public void channelInactive(ChannelHandlerContext ctx) {

log.info(“客户端断开连接,{}”, ctx.channel().remoteAddress());

ctx.channel().close();

}

@Override

public void channelRead(ChannelHandlerContext ctx, Object msg){

RpcRequest rpcRequest = (RpcRequest) msg;

log.info(“接收到客户端请求, 请求接口:{}, 请求方法:{}”, rpcRequest.getClassName(), rpcRequest.getMethodName());

RpcResponse response = new RpcResponse();

response.setRequestId(rpcRequest.getRequestId());

Object result = null;

try {

result = this.handleRequest(rpcRequest);

response.setResult(result);

} catch (Exception e) {

e.printStackTrace();

response.setSuccess(false);

response.setErrorMessage(e.getMessage());

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值