Java写一个RPC框架
时间: 2023-05-22 14:06:29 浏览: 108
用java写一个简单RPC框架
实现RPC框架的关键在于实现远程过程调用的功能。具体来说,需要完成以下步骤:
1. 定义RPC接口
2. 实现RPC框架
3. 编写客户端和服务端的代码
以下是一个简单的Java实现RPC框架的代码示例:
1. 定义RPC接口
```java
public interface HelloService {
String sayHello(String name);
}
```
2. 实现RPC框架
```java
public class RPCFramework {
// 暴露服务
public static void export(Object service, int port) throws Exception {
ServerSocket server = new ServerSocket(port);
while (true) {
Socket socket = server.accept();
new Thread(() -> {
try {
ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
String methodName = input.readUTF();
Class<?>[] parameterTypes = (Class<?>[]) input.readObject();
Object[] args = (Object[]) input.readObject();
Method method = service.getClass().getMethod(methodName, parameterTypes);
Object result = method.invoke(service, args);
output.writeObject(result);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
// 引用服务
public static <T> T refer(Class<T> interfaceClass, String host, int port) throws Exception {
Socket socket = new Socket(host, port);
ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
output.writeUTF(interfaceClass.getName());
output.writeUTF("sayHello");
output.writeObject(new Class<?>[]{String.class});
output.writeObject(new Object[]{"world"});
Object result = input.readObject();
return (T) result;
}
}
```
3. 编写客户端和服务端的代码
服务端:
```java
public class HelloServiceImpl implements HelloService {
@Override
public String sayHello(String name) {
return "Hello, " + name + "!";
}
}
public class Server {
public static void main(String[] args) throws Exception {
HelloService helloService = new HelloServiceImpl();
RPCFramework.export(helloService, 1234);
}
}
```
客户端:
```java
public class Client {
public static void main(String[] args) throws Exception {
HelloService helloService = RPCFramework.refer(HelloService.class, "localhost", 1234);
System.out.println(helloService.sayHello("world"));
}
}
```
这样,客户端向服务端发起远程调用后就会得到服务端返回的结果。
阅读全文