当前位置:网站首页>Myrpc version 1
Myrpc version 1
2022-06-30 04:12:00 【Winter dream chaser】
RPC The concept of
Background knowledge
- RPC Basic concepts of , Core functions

common RPC frame
Duboo Basic function
- Telematics
- Transparent remote procedure call based on interface method
- Load balancing
- Service registry
RPC The process
client Call the remote method -> request serialize -> Protocol code -> Network transmission -> Server side -> Deserialization request -> Call the local method to get response -> serialize -> code ->……
Version iteration process
Catalog
from 0 At the beginning RPC Iterative process of :
- version0 edition : Complete a with less than 100 lines of code RPC Example
- version1 edition : Improve the common message format (request,response), The client's dynamic proxy completes the request Encapsulation of message formats
- version2 edition : Support the server to expose multiple service interfaces , Server program abstraction , Normalization
- version3 edition : Use a high-performance network framework netty The realization of network communication , And the refactoring of client code
- version4 edition : Custom message format , Support multiple serialization methods (java Native , json…)
- version5 edition : Implementation of server registration and discovery ,zookeeper As a registry
- version6 edition : Implementation of load balancing strategy
1.MyRPC edition 1
Background knowledge
- Reflection
- A dynamic proxy
Questions in this section
How to make the client request remote methods to support multiple ?
How to make the types of return values of the server diverse ?
Version upgrade process
to update 1: Defines a general Request The object of ( The message format )
/** * In the last example , our Request Just sent one id Parameter past , This is clearly unreasonable , * Because the server will not have only one service and one method , So just passing the parameters doesn't know which method to call * So a RPC In request ,client Sending should be called Service The interface name , Method name , Parameters , Parameter type * In this way, the server can call the corresponding method according to this information and reflection * Or use java Built in serialization */
@Data
@Builder
public class RPCRequest implements Serializable {
// Service class name , The client only knows the interface name , Point to the implementation class with the interface name in the server
private String interfaceName;
// Method name
private String methodName;
// parameter list
private Object[] params;
// Parameter type
private Class<?>[] paramsTypes;
}
to update 2: Defines a general Response The object of ( The message format )
/** * In the previous example response The transmission is User object , Obviously, in an application, we can't transmit only one type of data * Therefore, we abstract the transmission object into Object * Rpc It needs to be transmitted over the network , It's possible to fail , Be similar to http, The status code and status information are introduced to indicate whether the service call is successful or failed */
@Data
@Builder
public class RPCResponse implements Serializable {
// State information
private int code;
private String message;
// Specific data
private Object data;
public static RPCResponse success(Object data) {
return RPCResponse.builder().code(200).data(data).build();
}
public static RPCResponse fail() {
return RPCResponse.builder().code(500).message(" Server error ").build();
}
}
Therefore, the network transmission process is request And response Data in format , The client and server should be responsible for encapsulating and parsing the above structural data
to update 3: The server accepts request request , And call request The corresponding method in
public interface UserService {
// The client calls the implementation class of the server through this interface
User getUserByUserId(Integer id);
// Add a function to this service
Integer insertUserId(User user);
}
The implementation class of the server UserServiceImpl To realize the added functions
@Override
public Integer insertUserId(User user) {
System.out.println(" Insert data succeeded :"+user);
return 1;
}
The server accepts parsing reuqest Send with encapsulation response object
public class RPCServer {
public static void main(String[] args) {
UserServiceImpl userService = new UserServiceImpl();
try {
ServerSocket serverSocket = new ServerSocket(8899);
System.out.println(" The server has started ");
// BIO Mode of monitoring Socket
while (true){
Socket socket = serverSocket.accept();
// Start a thread to process , The functions this class is responsible for are too complex , In future code refactoring , This part of the function should be separated
new Thread(()->{
try {
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
// Read from the client request
RPCRequest request = (RPCRequest) ois.readObject();
// Reflection calls the corresponding method
Method method = userService.getClass().getMethod(request.getMethodName(), request.getParamsTypes());
Object invoke = method.invoke(userService, request.getParams());
// encapsulation , write in response object
oos.writeObject(RPCResponse.success(invoke));
oos.flush();
}catch (IOException | ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e){
e.printStackTrace();
System.out.println(" from IO Error reading data in ");
}
}).start();
}
} catch (IOException e) {
e.printStackTrace();
System.out.println(" Server start failed ");
}
}
}
to update 4: The client depends on Service Dynamic agent :
Proxy object enhanced Public behavior : Put different Service Method Packaged as a unified Request Object format , And establish a relationship with Server Communication for
- Underlying communication
public class IOClient {
// It is responsible for the communication between the bottom layer and the server , Sent Request, It is accepted that Response object
// The client initiates a request call ,Socket Establishing a connection , Initiate request Request, Get a response Response
// there request It's packaged ( The upper layer is encapsulated ), Different service Different packaging is required , The client only knows Service Interface , A layer of dynamic proxy is needed to encapsulate different objects according to reflection Service
public static RPCResponse sendRequest(String host, int port, RPCRequest request){
try {
Socket socket = new Socket(host, port);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
System.out.println(request);
objectOutputStream.writeObject(request);
objectOutputStream.flush();
RPCResponse response = (RPCResponse) objectInputStream.readObject();
return response;
} catch (IOException | ClassNotFoundException e) {
System.out.println();
return null;
}
}
}
- Dynamic agent encapsulation request object
@AllArgsConstructor
public class ClientProxy implements InvocationHandler {
// Pass in the parameter Service Interface class object , Reflection is encapsulated into a request
private String host;
private int port;
// jdk A dynamic proxy , Every time a proxy object calls a method , Will be enhanced by this method ( Reflection acquisition request object ,socket Send to client )
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// request The construction of , Used lombok Medium builder, The code is concise
RPCRequest request = RPCRequest.builder().interfaceName(method.getDeclaringClass().getName())
.methodName(method.getName())
.params(args).paramsTypes(method.getParameterTypes()).build();
// The data transfer
RPCResponse response = IOClient.sendRequest(host, port, request);
//System.out.println(response);
return response.getData();
}
<T>T getProxy(Class<T> clazz){
Object o = Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{
clazz}, this);
return (T)o;
}
}
- The client calls different methods
public class RPCClient {
public static void main(String[] args) {
ClientProxy clientProxy = new ClientProxy("127.0.0.1", 8899);
UserService proxy = clientProxy.getProxy(UserService.class);
// Method of service 1
User userByUserId = proxy.getUserByUserId(10);
System.out.println(" From the server user by :" + userByUserId);
// Method of service 2
User user = User.builder().userName(" Zhang San ").id(100).sex(true).build();
Integer integer = proxy.insertUserId(user);
System.out.println(" Insert data into the server :"+integer);
}
}
result


summary
- Define a more general message format :Request And Response Format , Different methods may be called from here , And return various types of data .
- Dynamic proxy is used for different service methods Request Encapsulation ,
- The client is more loosely coupled , No longer associated with a particular Service,host,port binding
Existing pain points
- On the server side, we directly bind UserService service , What if there are other service interfaces exposed ?( Registration of multiple services )
- Server side BIO Whether the mode performance is too low ,
- The server functions are too complex : monitor , Handle . Loose coupling is required
边栏推荐
- Grasp grpc communication framework in simple terms
- Semantic segmentation resources
- 使用IDEAL连接数据库,运行出来了 结果显示一些警告,这部分怎么处理
- (Reprinted) an article will take you to understand the reproducing kernel Hilbert space (RKHS) and various spaces
- Magical Union
- Interface testing -- how to analyze an interface?
- JS reflect
- Es2016 key summary
- lego_loam 代码阅读与总结
- Thinkphp5 implements import function
猜你喜欢

Machine learning notes

Technology sharing | broadcast function design in integrated dispatching

Graduation project EMS office management system (b/s structure) +j2ee+sqlserver8.0

lego_ Reading and summary of loam code

NER中BiLSTM-CRF解读score_sentence

第十二天 进阶编程技术

毕业设计EMS办公管理系统(B/S结构)+J2EE+SQLserver8.0

The school training needs to make a registration page. It needs to open the database and save the contents entered on the registration page into the database

学校实训要做一个注册页面,要打开数据库把注册页面输入的内容存进数据库但是

【论文阅读|深读】Role2Vec:Role-Based Graph Embeddings
随机推荐
[summary of skimming questions] database questions are summarized by knowledge points (continuous update / simple and medium questions have been completed)
Maya Calendar(POJ1008)
第九天 脚本與資源管理
An error occurs when sqlyog imports the database. Please help solve it!
Grasp grpc communication framework in simple terms
Knowledge - how to build rapport in sales with 3 simple skills
NER中BiLSTM-CRF解读score_sentence
如何通过进程启动来分析和解决EasyCVR内核端口报错问题?
Unity échappe à l'entrée de caractères lors de l'entrée de chaînes dans l'éditeur
Interpretation score of bilstm-crf in NER_ sentence
[note] Introduction to data analysis on June 7, 2022
Pytorch Profiler+ Tensorboard + VS Code
Postman learning sharing
技术分享| 融合调度中的广播功能设计
JS proxy
各位大佬,flink 1.13.6,mysql-cdc2.2.0,抽取上来的datetime(6)类
Node red series (28): communication with Siemens PLC based on OPC UA node
win10系统使用浏览器下载后,内容无故移动或删除
idea灰屏问题
. Net 7 JWT configuration is too convenient!