RPC,全稱為Remote Procedure Call,即遠(yuǎn)程過程調(diào)用,它是一個(gè)計(jì)算機(jī)通信協(xié)議。它允許像調(diào)用本地服務(wù)一樣調(diào)用遠(yuǎn)程服務(wù)。它可以有不同的實(shí)現(xiàn)方式。如RMI(遠(yuǎn)程方法調(diào)用)、Hessian、Http invoker等。另外,RPC是與語言無關(guān)的。
來張圖:

如上圖所示,假設(shè)Computer1在調(diào)用sayHi()方法,對于Computer1而言調(diào)用sayHi()方法就像調(diào)用本地方法一樣,調(diào)用 –>返回。但從后續(xù)調(diào)用可以看出Computer1調(diào)用的是Computer2中的sayHi()方法,RPC屏蔽了底層的實(shí)現(xiàn)細(xì)節(jié),讓調(diào)用者無需關(guān)注網(wǎng)絡(luò)通信,數(shù)據(jù)傳輸?shù)燃?xì)節(jié)。
好了,直接上代碼:git地址 https://github.com/JeffySnail/simple-rpc

- api 定義了業(yè)務(wù)接口
- client 定義了客戶的端的測試代碼 maven依賴 rpc-frame和api
- rpc-frame 定義實(shí)現(xiàn)rpc的框架代碼
- server 實(shí)現(xiàn)業(yè)務(wù)api定義的接口 maven依賴 rpc-frame和api
API 代碼:
package com.ibort.api;
/**
* @author jeffy
* @date 2018-06-16
*/
public interface HelloService {
/**
* 定義一個(gè)API
* @param name
* @return
*/
String sayHi(String name);
}
client 代碼測試類
package com.ibort.client.main;
import com.ibort.api.HelloService;
import com.ibort.frame.server.RPCClient;
import java.net.InetSocketAddress;
/**
* @author jeffy
* @date 2018/6/16
**/
public class Main {
public static void main(String[] args) {
HelloService service = RPCClient.getRemoteProxyObj(HelloService.class, new InetSocketAddress("localhost", 8088));
System.out.println("客戶端調(diào)用接口,返回結(jié)果為:" + service.sayHi("test"));
}
}
rpc-frame 實(shí)現(xiàn)內(nèi)部框架封裝總共三個(gè)類
- RPCClient供客戶端調(diào)用使用
- Server 定義服務(wù)端方法
- ServerCenter 實(shí)現(xiàn)Server類
package com.ibort.frame.server;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.InetSocketAddress;
import java.net.Socket;
/**
* @author jeffy
* @date 2018/6/16
**/
public class RPCClient<T> {
public static <T> T getRemoteProxyObj(final Class<?> serviceInterface, final InetSocketAddress addr) {
return (T) Proxy.newProxyInstance(serviceInterface.getClassLoader(), new Class<?>[]{serviceInterface}, new InvocationHandlerImp(addr, serviceInterface));
}
private static class InvocationHandlerImp implements InvocationHandler {
private final InetSocketAddress addr;
private Class<?> serviceInterface;
public InvocationHandlerImp(InetSocketAddress addr, Class<?> serviceInterface) {
this.addr = addr;
this.serviceInterface = serviceInterface;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Socket socket = null;
ObjectOutputStream output = null;
ObjectInputStream input = null;
try {
// 2.創(chuàng)建Socket客戶端,根據(jù)指定地址連接遠(yuǎn)程服務(wù)提供者
socket = new Socket();
socket.connect(addr);
// 3.將遠(yuǎn)程服務(wù)調(diào)用所需的接口類、方法名、參數(shù)列表等編碼后發(fā)送給服務(wù)提供者
output = new ObjectOutputStream(socket.getOutputStream());
output.writeUTF(serviceInterface.getName());
output.writeUTF(method.getName());
output.writeObject(method.getParameterTypes());
output.writeObject(args);
// 4.同步阻塞等待服務(wù)器返回應(yīng)答,獲取應(yīng)答后返回
input = new ObjectInputStream(socket.getInputStream());
return input.readObject();
} finally {
if (socket != null) socket.close();
if (output != null) output.close();
if (input != null) input.close();
}
}
}
}
package com.ibort.frame.server;
import java.io.IOException;
/**
* @author jeffy
*/
public interface Server {
/**
* 停止
*/
void stop();
/**
* 啟動
*
* @throws IOException
*/
void start() throws IOException;
/**
* 注冊服務(wù)
*
* @param serviceInterface
* @param impl
*/
void register(Class serviceInterface, Class impl);
/**
* 判斷是否在運(yùn)行
*
* @return
*/
boolean isRunning();
/**
* 獲取端口號
*
* @return
*/
int getPort();
}
package com.ibort.frame.server;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author jeffy
* @date 2018/6/15
**/
public class ServerCenter implements Server {
private static final ExecutorService EXECUTOR_SERVICE = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
private static final HashMap<String, Class> serviceRegistry = new HashMap<String, Class>();
private static boolean isRunning = false;
private int port;
public ServerCenter(int port) {
this.port = port;
}
public void stop() {
isRunning = false;
EXECUTOR_SERVICE.shutdown();
}
public void start() throws IOException {
ServerSocket serverSocket = new ServerSocket();
serverSocket.bind(new InetSocketAddress(port));
try {
while (true) {
// 1.監(jiān)聽客戶端的TCP連接,接到TCP連接后將其封裝成task,由線程池執(zhí)行
EXECUTOR_SERVICE.execute(new ServiceTask(serverSocket.accept()));
}
} finally {
serverSocket.close();
}
}
public void register(Class serviceInterface, Class impl) {
serviceRegistry.put(serviceInterface.getName(), impl);
}
public boolean isRunning() {
return isRunning;
}
public int getPort() {
return this.port;
}
private class ServiceTask implements Runnable {
Socket client = null;
public ServiceTask(Socket client) {
this.client = client;
}
public void run() {
ObjectInputStream input = null;
ObjectOutputStream output = null;
try {
input = new ObjectInputStream(client.getInputStream());
String serviceName = input.readUTF();
String methodName = input.readUTF();
Class<?>[] parameterTypes = (Class<?>[]) input.readObject();
Object[] arguments = (Object[]) input.readObject();
Class serviceClass = serviceRegistry.get(serviceName);
if (serviceClass == null) {
throw new ClassNotFoundException(serviceName + " not found");
}
Method method = serviceClass.getMethod(methodName, parameterTypes);
Object result = method.invoke(serviceClass.newInstance(), arguments);
output = new ObjectOutputStream(client.getOutputStream());
output.writeObject(result);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (client != null) {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
server 模塊包含兩個(gè)類
- HelloServiceImpl api的實(shí)現(xiàn)
- Main 服務(wù)端啟動類
package com.ibort.service;
import com.ibort.api.HelloService;
/**
* @author jeffy
* @date 2018/6/15
**/
public class HelloServiceImpl implements HelloService {
/**
* 實(shí)現(xiàn)api定義的接口
* @param name
* @return
*/
public String sayHi(String name) {
System.out.println("收到客戶端請求,參數(shù)為: " + name);
return "Hi, " + name;
}
}
package com.ibort.main;
import com.ibort.api.HelloService;
import com.ibort.frame.server.Server;
import com.ibort.frame.server.ServerCenter;
import com.ibort.service.HelloServiceImpl;
import java.io.IOException;
/**
* @author jeffy
* @date 2018/6/17
**/
public class Main {
/**
* start server
* @param args
*/
public static void main(String[] args) {
Server serviceServer = new ServerCenter(8088);
serviceServer.register(HelloService.class, HelloServiceImpl.class);
try {
System.err.println("server start");
serviceServer.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
啟動順序
- 啟動server模塊中的main方法,控制臺看到server start
server start……
- 啟動客戶端測試類,控制臺輸出
客戶端調(diào)用接口,返回結(jié)果為:Hi, test
同時(shí),在服務(wù)端看到控制臺輸出:
收到客戶端請求,參數(shù)為: test
至此,代碼調(diào)試成功
這篇文章主要是對rpc原理的實(shí)現(xiàn)介紹,如果要實(shí)現(xiàn)一個(gè)rpc框架還有很多需要優(yōu)化和考量的。這里實(shí)現(xiàn)的簡單RPC框架是使用Java語言開發(fā),與Java語言高度耦合,并且通信方式采用的Socket是基于BIO實(shí)現(xiàn)的,IO效率不高,還有Java原生的序列化機(jī)制占內(nèi)存太多,運(yùn)行效率也不高??梢钥紤]從下面幾種方法改進(jìn)。
- 可以采用基于JSON數(shù)據(jù)傳輸?shù)腞PC框架;
- 可以使用NIO或直接使用Netty替代BIO實(shí)現(xiàn);
- 使用開源的序列化機(jī)制,如Hadoop Avro與Google protobuf等;
- 服務(wù)注冊可以使用Zookeeper進(jìn)行管理,能夠讓應(yīng)用更加穩(wěn)定。
目前主要流行的rpc款框架有阿里的dubbo 美團(tuán)點(diǎn)評的pigeon,還有thrift等。
后邊的文章會對pigeon進(jìn)行源碼解析。