The Fibonacci task:
privatestaticintfib(int n){
if(n ==0)return0;
if(n ==1)return1;
returnfib(n-1)+fib(n-2);
}
We declare our fibonacci function. It assumes only valid positive integer input. (Don't expect this one to work for big numbers, and it's probably the slowest recursive implementation possible).
The code for our RPC server can be found here: RPCServer.java.
The server code is rather straightforward:
prefetchCount setting in channel.basicQos.basicConsume to access the queue, where we provide a callback in the
form of an object (DeliverCallback) that will do the work and send the response back.The code for our RPC client can be found here: RPCClient.java.
The client code is slightly more involved:
call method makes the actual RPC request.correlationId
number and save it - our consumer callback will use this value to
match the appropriate response.replyTo and correlationId.main thread before the response arrives.
Usage of CompletableFuture is one possible solution to do so.correlationId
is the one we're looking for. If so, it completes the CompletableFuture.main thread is waiting for the CompletableFuture to complete.Now is a good time to take a look at our full example source code (which includes basic exception handling) for RPCClient.java and RPCServer.java.
Compile and set up the classpath as usual (see tutorial one):
javac -cp$CP RPCClient.java RPCServer.java
Our RPC service is now ready. We can start the server:
java-cp$CP RPCServer
# => [x] Awaiting RPC requests
To request a fibonacci number run the client:
java-cp$CP RPCClient
# => [x] Requesting fib(30)
The design presented here is not the only possible implementation of a RPC service, but it has some important advantages:
RPCServer in a new console.queueDeclare
are required. As a result the RPC client needs only one network
round trip for a single RPC request.Our code is still pretty simplistic and doesn't try to solve more complex (but important) problems, like:
If you want to experiment, you may find the management UI useful for viewing the queues.