java写RPC客户端服务端
时间: 2023-10-18 20:22:08 浏览: 36
Java可以使用多种方式来实现RPC客户端服务端,比如使用Netty、Java RMI、Apache Thrift等。
以下是使用Netty实现RPC客户端服务端的示例代码:
服务端代码:
```java
public class RpcServer {
public void start(int port) throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline()
.addLast(new ObjectDecoder(ClassResolvers
.weakCachingConcurrentResolver(null)))
.addLast(new ObjectEncoder())
.addLast(new RpcServerHandler());
}
});
ChannelFuture future = bootstrap.bind(port).sync();
System.out.println("Server started on port " + port);
future.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
new RpcServer().start(8080);
}
}
```
客户端代码:
```java
public class RpcClient {
private final String host;
private final int port;
public RpcClient(String host, int port) {
this.host = host;
this.port = port;
}
public Object sendRequest(RpcRequest request) throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline()
.addLast(new ObjectDecoder(ClassResolvers
.weakCachingConcurrentResolver(null)))
.addLast(new ObjectEncoder())
.addLast(new RpcClientHandler());
}
});
ChannelFuture future = bootstrap.connect(host, port).sync();
future.channel().writeAndFlush(request).sync();
future.channel().closeFuture().sync();
return RpcClientHandler.getResponse();
} finally {
group.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
RpcClient client = new RpcClient("localhost", 8080);
RpcRequest request = new RpcRequest();
request.setClassName("com.example.MyService");
request.setMethodName("sayHello");
request.setParameterTypes(new Class[]{String.class});
request.setArguments(new Object[]{"World"});
Object response = client.sendRequest(request);
System.out.println(response);
}
}
```
其中,RpcRequest是一个自定义的类,用于封装RPC请求的信息。RpcServerHandler和RpcClientHandler则分别是服务端和客户端的处理器,用于处理具体的请求和响应。