当前位置:网站首页>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
边栏推荐
- JS reflect
- Educoder group purchase suspension box page production
- Error encountered in SQL statement, solve
- Radiant energy, irradiance and radiance
- Simple theoretical derivation of SVM (notes)
- JS deconstruction assignment
- Analysis of similarities and differences of various merged features (Union, merge, append, resolve) in ArcGIS
- SQL追加字段
- Day 12 advanced programming techniques
- Smart use of bitmap to achieve 100 million level massive data statistics
猜你喜欢
AI落地的新范式,就“藏”在下一场软件基础设施的重大升级里
When easycvr deploys a server cluster, what is the reason why one is online and the other is offline?
Day 11 script and game AI
基于海康EhomeDemo工具排查公网部署出现的视频播放异常问题
Sql语句遇到的错误,求解
(Reprinted) an article will take you to understand the reproducing kernel Hilbert space (RKHS) and various spaces
(04).NET MAUI实战 MVVM
An error occurs when sqlyog imports the database. Please help solve it!
Huawei cloud native - data development and datafactory
[note] Introduction to data analysis on June 7, 2022
随机推荐
基于ROS的SLAM建图、自动导航、避障(冰达机器人)
[Thesis reading | deep reading] dane:deep attributed network embedding
Sql语句遇到的错误,求解
win10系统使用浏览器下载后,内容无故移动或删除
Radiant energy, irradiance and radiance
[summary of skimming questions] database questions are summarized by knowledge points (continuous update / simple and medium questions have been completed)
毕业设计EMS办公管理系统(B/S结构)+J2EE+SQLserver8.0
(Reprinted) an article will take you to understand the reproducing kernel Hilbert space (RKHS) and various spaces
深度融合云平台,对象存储界的“学霸”ObjectScale来了
Thingsboard tutorial (II and III): calculating the temperature difference between two devices in a regular chain
Quick sort & merge sort
GIS related data
DO280私有仓库持久存储与章节实验
在大厂外包呆了三年,颠覆了我的认知!
The same node code will cause duplicate data
【模糊神经网络预测】基于模糊神经网络实现水质预测含Matlab源码
Knowledge - how to build rapport in sales with 3 simple skills
Green new power and "zero" burden of computing power -- JASMINER X4 series is popular
[operation] MySQL query operation 2 on May 25, 2022
《机器人SLAM导航核心技术与实战》第1季:第0章_SLAM发展综述