Java field to say that the most convincing RPC framework is Dubbo, for a number of reasons, but the most attractive to me is that it is the remote invocation of this thing designed in a very artistic way.
1, Dubbo has more advantages, I only love one of them!
1.1. Advantages
The industry for the call between the micro-service framework to choose more, the mainstream is Spring Cloud's Rest way and Dubbo way, I use Dubbo way most of the time. Dubbo industrial-grade available, stable and efficient, by the major companies in the research and development of the students' favorite.
Dubbo has more advantages such as:
- high performance: Dubbo uses a custom communication protocol based on Netty, which provides efficient binary data transfer, allowing for a dramatic increase in the performance of remote service calls.
- modular design: Dubbo's architecture is very modular , mainly consists of five core modules : Remote Call Module (RPC), Cluster Module , Load Balancing Module , Fault Tolerance Module and Registry Module .
- Each component supports multiple protocols: Each component supports multiple protocols, such as the registry, which supports ZK, Redis, Nacos, and more.
- Load balancing and fault tolerance: Dubbo provides a variety of fault-tolerant mechanisms , such as failure retry , failover , etc. . It also supports a variety of load balancing , such as random , polling , consistent hashing and so on.
- Service registration and discovery: Dubbo introduces the concept of a registry that enables automatic registration and discovery of services.
- SPI Extension Mechanism: inmemorize eight-study essays (idiom); fig. to study from memoryScenario, Dubbo has been mentioned most is the use of a Java-like SPI mechanism to improve scalability, which is benevolent and wise it.
1.2. One of the favorites
But what's most appealing about Dubbo, thehalf a cigarette
Think instead of its RPC calls.Dubbo's position is an RPC framework, which is its core and foothold, so Dubbo will be transparent RPC call process, so that developers can focus on business logic, without having to pay attention to the underlying communication issues.
An RPC framework will only be noticed if it focuses on the module of getting its RPC call process right first, and the rest of the benefits come after that, slowly and iteratively.
The authors have abstracted this process of RPC calls into theA mechanism for transporting protocol messagesand then through theControlling thread waits and wakeups, to implement remote method calls. This design idea is really wonderful and fully experience the wisdom of the author.
2、RPC simple example
Learning Dubbo, the first thing is to learn the author of this design concept and thinking. Based on this, to implement a simple remote method call to Dubbo's RPC process simple.
2.1 Example steps
Simple RPC process steps are as follows, roughly divided into five steps, still using Netty role of the socket communication tools.
- Two Java processes are used to simulate the calls between two systems, process A and process B. The process A and process B are used to simulate the calls between two systems.
- A method of process A calls a method of process B using a network request.
- The method of process A is then in a waiting state.
- When the method of process B has finished executing, it is notified to process A using the network.
- Then the methods of process A are woken up and execution continues down the line.
2.2. Sample Code
- Process B acts as a server and starts the network service
public class BProcessServer {
private final int port;
public BProcessServer(int port) {
= port;
}
public void start() throws InterruptedException {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
(bossGroup, workerGroup)
.channel()
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
().addLast(new BProcessServerHandler());
}
});
ChannelFuture future = (port).sync();
("BService activated.,port number: " + port);
().closeFuture().sync();
} finally {
();
();
}
}
public static void main(String[] args) throws InterruptedException {
new BProcessServer(8088).start();
}
}
- The B process accepts the network request parameters, deserializes them, executes the corresponding methods, and then returns the results:
public class BProcessServerHandler extends SimpleChannelInboundHandler<ByteBuf> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
String reqData = (CharsetUtil.UTF_8);
("Process B has accepted the request data: " + reqData);
executeMethod(ctx);
}
/**
* executeMethod
*
* @param ctx
* @throws InterruptedException
*/
private void executeMethod(ChannelHandlerContext ctx) throws InterruptedException {
// TODO Parsing the request message into method names, method parameters, etc. according to some rules is actually the process of deserialization.
("Do deserialization on the accepted data and then start executing the method specified in the message body...") ;
// Simulate method execution
(2000); // Simulate method execution.
("Execution is complete. Returning results...") ;)
// Notify process A of the result
ByteBuf dataByteBuf = ().buffer().writeBytes("Task completed".getBytes(CharsetUtil.UTF_8)); (dataByteBuf); ; // Notify process A of the result.
(dataByteBuf);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
();
();
}
}
- Process A starts the Netty client, establishes communication with process B, and then initiates the remote call, which is in a waiting state.
public class AProcessClient {
private final String host;
private final int port;
private final Object lock = new Object(); // monitor object
public AProcessClient(String host, int port) {
= host;
= port;
}
public void start() throws InterruptedException {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
(group)
.channel()
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
().addLast(new AProcessClientHandler(lock));
}
});
ChannelFuture future = (host, port).sync();
("Aprocess andBThe process establishes a communication connection");
Channel channel = ();
// Initiate a remote call
callRemoteMethod(channel);
().sync();
} finally {
();
}
}
/**
* Method of implementation
*
* @param channel
* @throws InterruptedException
*/
private void callRemoteMethod(Channel channel) throws InterruptedException {
//TODO Here you need to include the called method and the parameter,Serialization by protocol。Let's skip the process for now.。
("Aprocess will Requested methods and parameters serialize,thence toBThe process initiates a network call...");
ByteBuf dataByteBuf = ().buffer().writeBytes("Start call method".getBytes(CharsetUtil.UTF_8));
(dataByteBuf);
// utilizationwaitwait forBProcess notification
synchronized (lock) {
("A进程wait forBProcess response...");
(); // wait for通知
}
("AThe process receivedBProcess response通知,Keep going down....");
}
public static void main(String[] args) throws InterruptedException {
new AProcessClient("localhost", 8088).start();
}
}
- Process A receives a response from process B while being woken up, and then the above
()
Subsequent code can continue to be executed.
public class AProcessClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
private final Object lock;
public AProcessClientHandler(Object lock) {
= lock;
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
String resData = (CharsetUtil.UTF_8);
("AThe process receives the response data: " + resData);
// B Process mandate completion,utilization notify Wake up a waiting thread
synchronized (lock) {
(); // awakens A step
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
();
();
}
}
3. Summary
There are many great design ideas for Dubbo, and I only love one of them, which is the RPC invocation process. The above is an example of a simple RPC remote call for understanding the principles and source code of Dubbo, I hope it helps you!
The end of this article! Welcome to pay attention to, add V (ylxiao) exchange, the whole network can be searched (programmers half a cigarette)
Link to original article:/s/J0fzDH-iqGnnnjqaXMLs-A