最简单的RPC框架实例
所属分类 rpc
浏览量 994
java原生序列化 Socket短连接 动态代理 反射
服务提供者 负责提供服务接口定义和服务实现类
服务发布者 负责将本地服务发布成远程服务
本地服务代理,运行RPC客户端,通过代理调用远程服务提供者,然后将结果进行封装返回给本地消费者
HelloService
HelloServiceImpl
RpcExporter 服务发布
RpcImporter 服务导入
RpcTest
关键代码
RpcExporter
ObjectInputStream inputStream = new ObjectInputStream(client.getInputStream());
String interfaceName = inputStream.readUTF();
Class> service = Class.forName(interfaceName);
String methodName = inputStream.readUTF();
Class> [] parameterTypes = (Class> [])inputStream.readObject();
Object [] arguments = (Object [])inputStream.readObject();
Method method = service.getMethod(methodName,parameterTypes);
Object result = method.invoke(service.newInstance(),arguments);
ObjectOutputStream outputStream = new ObjectOutputStream(client.getOutputStream());
outputStream.writeObject(result);
RpcImporter
public S importer(final Class> serviceClass, final InetSocketAddress address) {
return (S) Proxy.newProxyInstance(serviceClass.getClassLoader(), new Class>[]{serviceClass.getInterfaces()[0]},
new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Socket socket = new Socket();
socket.connect(address);
ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
outputStream.writeUTF(serviceClass.getName());
outputStream.writeUTF(method.getName());
outputStream.writeObject(method.getParameterTypes());
outputStream.writeObject(args);
ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
return inputStream.readObject();
RpcTest
final int port = 8083;
System.out.println("port="+port);
new Thread(new Runnable() {
public void run() {
try {
RpcExporter.exporter("localhost", port);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
RpcImporter importer = new RpcImporter();
HelloService hello = importer.importer(HelloServiceImpl.class, new InetSocketAddress("localhost", port));
System.out.println(hello.sayHello("tiger"));
System.out.println(hello.sayHello("cat"));
完整代码
https://gitee.com/dyyx/demos/tree/master/playrpc
springcloud核心组件 feign ribbon 独立使用例子
上一篇
下一篇
励志歌曲系列
jdk16 ZGC 改进
字符串编辑距离 Levenstein edit distance
aerospike lua 构建有序列表
接口幂等几种实现
java NIO 服务端例子2