jar rpc netty框架代码
时间: 2023-10-12 09:19:36 浏览: 111
以下是一个基于Netty框架的RPC实现示例代码:
1. 服务接口定义
```java
public interface HelloService {
String sayHello(String name);
}
```
2. 服务提供者实现
```java
public class HelloServiceImpl implements HelloService {
public String sayHello(String name) {
return "Hello, " + name;
}
}
```
3. RPC框架实现
```java
public class RpcServer {
private final EventLoopGroup bossGroup;
private final EventLoopGroup workerGroup;
public RpcServer() {
bossGroup = new NioEventLoopGroup();
workerGroup = new NioEventLoopGroup();
}
public void start(int port) throws InterruptedException {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
p.addLast(new ObjectEncoder());
p.addLast(new RpcServerHandler());
}
})
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture f = b.bind(port).sync();
System.out.println("Server started on port " + port);
f.channel().closeFuture().sync();
}
public void shutdown() {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
public class RpcServerHandler extends ChannelInboundHandlerAdapter {
private static final Map<String, Object> serviceMap = new ConcurrentHashMap<>();
static {
serviceMap.put(HelloService.class.getName(), new HelloServiceImpl());
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof RpcRequest) {
RpcRequest request = (RpcRequest) msg;
Object service = serviceMap.get(request.getClassName());
if (service != null) {
Method method = service.getClass().getMethod(request.getMethodName(), request.getParameterTypes());
Object result = method.invoke(service, request.getParameters());
RpcResponse response = new RpcResponse();
response.setRequestId(request.getRequestId());
response.setResult(result);
ctx.writeAndFlush(response);
}
} else {
super.channelRead(ctx, msg);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
}
}
```
4. RPC客户端实现
```java
public class RpcClient {
private final EventLoopGroup group;
private final Bootstrap bootstrap;
public RpcClient() {
group = new NioEventLoopGroup();
bootstrap = new Bootstrap();
bootstrap.group(group)
.channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
p.addLast(new ObjectEncoder());
p.addLast(new RpcClientHandler());
}
});
}
public void connect(String host, int port) throws InterruptedException {
ChannelFuture future = bootstrap.connect(host, port).sync();
future.channel().closeFuture().sync();
}
public void shutdown() {
group.shutdownGracefully();
}
}
public class RpcClientHandler extends ChannelInboundHandlerAdapter {
private final Map<String, RpcFuture> pendingRequests = new ConcurrentHashMap<>();
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof RpcResponse) {
RpcResponse response = (RpcResponse) msg;
RpcFuture future = pendingRequests.get(response.getRequestId());
if (future != null) {
pendingRequests.remove(response.getRequestId());
future.done(response.getResult());
}
} else {
super.channelRead(ctx, msg);
}
}
public RpcFuture sendRequest(RpcRequest request) {
RpcFuture future = new RpcFuture(request);
pendingRequests.put(request.getRequestId(), future);
ctx.writeAndFlush(request);
return future;
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
}
}
public class RpcFuture {
private final RpcRequest request;
private final CompletableFuture<Object> responseFuture;
public RpcFuture(RpcRequest request) {
this.request = request;
responseFuture = new CompletableFuture<>();
}
public void done(Object result) {
responseFuture.complete(result);
}
public CompletableFuture<Object> getResponseFuture() {
return responseFuture;
}
public RpcRequest getRequest() {
return request;
}
}
```
5. RPC请求/响应实体类定义
```java
public class RpcRequest implements Serializable {
private String requestId;
private String className;
private String methodName;
private Class<?>[] parameterTypes;
private Object[] parameters;
// getters and setters
}
public class RpcResponse implements Serializable {
private String requestId;
private Object result;
// getters and setters
}
```
使用示例:
```java
// 启动服务端
RpcServer server = new RpcServer();
server.start(8080);
// 创建客户端
RpcClient client = new RpcClient();
client.connect("localhost", 8080);
// 发送请求
RpcRequest request = new RpcRequest();
request.setRequestId(UUID.randomUUID().toString());
request.setClassName(HelloService.class.getName());
request.setMethodName("sayHello");
request.setParameterTypes(new Class[] { String.class });
request.setParameters(new Object[] { "World" });
RpcFuture future = client.sendRequest(request);
// 处理响应
future.getResponseFuture().thenAccept(result -> {
System.out.println(result);
});
// 关闭客户端和服务端
client.shutdown();
server.shutdown();
```
阅读全文