use of com.luastar.swift.rpc.serialize.RpcDecoder in project swift by luastar.
the class RpcClient method send.
public RpcResponse send(RpcRequest request) throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
try {
// 创建并初始化 Netty 客户端 Bootstrap 对象
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group);
bootstrap.channel(NioSocketChannel.class);
bootstrap.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel channel) throws Exception {
ChannelPipeline pipeline = channel.pipeline();
// 编码 RPC 请求
pipeline.addLast(new RpcEncoder(RpcRequest.class, rpcSerialize));
pipeline.addLast(new LengthFieldBasedFrameDecoder(65536, 0, 4, 0, 0));
// 解码 RPC 响应
pipeline.addLast(new RpcDecoder(RpcResponse.class, rpcSerialize));
// 处理 RPC 响应
pipeline.addLast(RpcClient.this);
}
});
bootstrap.option(ChannelOption.TCP_NODELAY, true);
// 连接 RPC 服务器
ChannelFuture future = bootstrap.connect(host, port).sync();
// 写入 RPC 请求数据并关闭连接
Channel channel = future.channel();
channel.writeAndFlush(request).sync();
channel.closeFuture().sync();
// 返回 RPC 响应对象
return response;
} finally {
group.shutdownGracefully();
}
}
use of com.luastar.swift.rpc.serialize.RpcDecoder in project swift by luastar.
the class RpcServer method start.
public void start() {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel channel) throws Exception {
ChannelPipeline pipeline = channel.pipeline();
pipeline.addLast(new LengthFieldBasedFrameDecoder(65536, 0, 4, 0, 0));
pipeline.addLast(new RpcDecoder(RpcRequest.class, rpcSerialize));
pipeline.addLast(new RpcEncoder(RpcResponse.class, rpcSerialize));
pipeline.addLast(new RpcServerChannelHandler(handlerMap));
}
});
bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
Channel channel = bootstrap.bind(port).sync().channel();
logger.info("SwiftRpcServer started on port {}", port);
// 注册 RPC 服务地址
String serviceAddress = RpcConstant.CURRENT_SERVER_ADDRESS + ":" + port;
for (String interfaceName : handlerMap.keySet()) {
serviceRegistry.register(interfaceName, serviceAddress);
}
channel.closeFuture().sync();
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
Aggregations