当前位置:网站首页>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
- Unity échappe à l'entrée de caractères lors de l'entrée de chaînes dans l'éditeur
- thinkphp5实现导入功能
- Solve the problem of Navicat connecting to the database
- Modifier of JS regular expression
- 工程安全和工程质量
- JS static method
- [fuzzy neural network prediction] water quality prediction based on fuzzy neural network, including Matlab source code
- Pig-Latin (UVA492)
- 【WEBRTC】ADM: rtc_include_internal_audio_device 触发 RTC_DCHECK(adm) 断言
猜你喜欢

Radiant energy, irradiance and radiance

两个月拿到N个offer,什么难搞的面试官在我这里都不算事

Cloud native -- websocket of Web real-time communication technology

You know AI, database and computer system

尝试链接数据库时出现链接超时报错,如何解决?

在大厂外包呆了三年,颠覆了我的认知!

如何通过进程启动来分析和解决EasyCVR内核端口报错问题?
![[Thesis reading | deep reading] dane:deep attributed network embedding](/img/c7/60f36c2748b8cd7544b7ef14dc309e.png)
[Thesis reading | deep reading] dane:deep attributed network embedding

Sql语句遇到的错误,求解

【论文阅读|深读】Role2Vec:Role-Based Graph Embeddings
随机推荐
SQL append field
Unity when entering a string in the editor, escape the input of characters
[operation] write CSV to database on May 28, 2022
网络层详解
SQL server2005中SUM函数中条件筛选(IF)语法报错
Ananagrams(UVA156)
Interpretation score of bilstm-crf in NER_ sentence
第十一天 脚本与游戏AI
Simple theoretical derivation of SVM (notes)
基于海康EhomeDemo工具排查公网部署出现的视频播放异常问题
Everyone, Flink 1.13.6, mysql-cdc2.2.0, the datetime (6) class extracted
When easycvr deploys a server cluster, what is the reason why one is online and the other is offline?
节点CODE相同会导致数据重复
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
Unity 在編輯器中輸入字符串時,轉義字符的輸入
An error occurs when sqlyog imports the database. Please help solve it!
Educoder group purchase suspension box page production
A solution to the problem of "couldn't open file /mnt/repodata/repomd.xml"
Day 10 data saving and loading
[note] on May 28, 2022, data is obtained from the web page and written into the database