当前位置:网站首页>Myrpc version 0
Myrpc version 0
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
0. One of the simplest RPC call
Background knowledge
- java Basics
- java socket Introduction to programming
- Project use maven build , For the time being, only lombok package
Questions in this section
- What is? RPC, How to complete one RPC?
One RPC The simplest The process is client side call A method of the server , The server returns the return value of the execution method to the customer service . Next, I will use an example of fetching data from a database to conduct a simulation RPC A complete process of the process .
Assume There is such a service :
Server side :
There is one User surface
- UserServiceImpl Realized UserService Interface
- UserService There is only one function in the : getUserByUserId(Integer id)
client :
Pass a Id To the server , The server finds User Object returned to client
The process
- First we have to have User object , This is known to both the client and the server , The client needs to get this pojo Object data , The server needs to operate this object
@Builder
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {
// Both client and server share
private Integer id;
private String userName;
private Boolean sex;
}
- To define the client, you need to call , The service interface that the server needs to provide
public interface UserService {
// The client calls the implementation class of the server through this interface
User getUserByUserId(Integer id);
}
- The server needs to implement Service Function of interface
public class UserServiceImpl implements UserService {
@Override
public User getUserByUserId(Integer id) {
System.out.println(" The client inquired "+id+" Users of ");
// Simulate the behavior of fetching users from the database
Random random = new Random();
User user = User.builder().userName(UUID.randomUUID().toString())
.id(id)
.sex(random.nextBoolean()).build();
return user;
}
}
- Client creation Socket Connect , transmission Id To the server , Get back User object
public class RPCClient {
public static void main(String[] args) {
try {
// establish Socket Connect
Socket socket = new Socket("127.0.0.1", 8899);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
// To the server id
objectOutputStream.writeInt(new Random().nextInt());
objectOutputStream.flush();
// Server query data , Returns the corresponding object
User user = (User) objectInputStream.readObject();
System.out.println(" Returned by the server User:"+user);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
System.out.println(" Client failed to start ");
}
}
}
- Server side BIO Mode of monitoring Socket, If you have data , Call the implementation class of the corresponding service to execute the task , Returns the result to the client
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
new Thread(()->{
try {
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
// Read from the client id
Integer id = ois.readInt();
User userByUserId = userService.getUserByUserId(id);
// write in User Object to the client
oos.writeObject(userByUserId);
oos.flush();
} catch (IOException e){
e.printStackTrace();
System.out.println(" from IO Error reading data in ");
}
}).start();
}
} catch (IOException e) {
e.printStackTrace();
System.out.println(" Server start failed ");
}
}
}
result :


summary :
This example takes less than a hundred lines of code , A remote procedure call between client and server is realized , Very suitable for getting started , Of course it is And its imperfections Of , Even the message format is not unified , We will gradually improve it in the next version update .
this RPC The biggest pain point of :
- Only the server can be called Service The only sure way , What if there are two methods to call ?(Reuest Need to be abstract )
- The return value only supports User object , If you need to pass a string or a Dog,String What about objects? (Response Need to be abstract )
- The client is not universal enough ,host,port, Is specific to the method being called ( Need to be abstract )
边栏推荐
- [note] Introduction to data analysis on June 7, 2022
- RPC correction
- [cloud native] AI cloud development platform - Introduction to AI model foundry (developers can experience AI training model for free)
- Do280 private warehouse persistent storage and chapter experiment
- matplotlib. pyplot. Hist parameter introduction
- oslo_ config. cfg. ConfigFileParseError: Failed to parse /etc/glance/glance-api. Conf: a solution to errors
- You know AI, database and computer system
- Error encountered in SQL statement, solve
- Machine learning notes
- Smart use of bitmap to achieve 100 million level massive data statistics
猜你喜欢

How to solve the problem of link hyperlinks when trying to link the database?

You know AI, database and computer system

Analysis of similarities and differences of various merged features (Union, merge, append, resolve) in ArcGIS

Day 11 script and game AI

第十一天 脚本与游戏AI

Interface testing -- how to analyze an interface?

巧用 Bitmap 实现亿级海量数据统计

The new paradigm of AI landing is "hidden" in the next major upgrade of software infrastructure

lego_ Reading and summary of loam code

基于ROS的SLAM建图、自动导航、避障(冰达机器人)
随机推荐
【图像融合】基于交叉双边滤波器和加权平均实现多焦点和多光谱图像融合附matlab代码
Ananagrams(UVA156)
[note] May 23, 2022 MySQL
thinkphp5实现导入功能
知识点滴 - 如何用3个简单的技巧在销售中建立融洽的关系
Geometric objects in shapely
基于海康EhomeDemo工具排查公网部署出现的视频播放异常问题
Unity 在编辑器中输入字符串时,转义字符的输入
Postman learning sharing
(04). Net Maui actual MVVM
I get n offers in two months. I don't have any difficult interviewers here
Idea grey screen problem
Jour 9 Gestion des scripts et des ressources
Quick sort & merge sort
Grasp grpc communication framework in simple terms
SQL追加字段
各位大佬,flink 1.13.6,mysql-cdc2.2.0,抽取上来的datetime(6)类
[summary of skimming questions] database questions are summarized by knowledge points (continuous update / simple and medium questions have been completed)
Error encountered in SQL statement, solve
oslo_ config. cfg. ConfigFileParseError: Failed to parse /etc/glance/glance-api. Conf: a solution to errors