RabbitMQ tutorial - Remote procedure call (RPC)
Remote procedure call (RPC)
(using the AMQP 1.0 .NET client)
Prerequisites
This tutorial assumes RabbitMQ is installed and running on
localhost on the standard port (5672). In case you
use a different host, port or credentials, connections settings would require
adjusting.
Where to get help
If you're having trouble going through this tutorial you can contact us through GitHub Discussions or RabbitMQ community Discord.
In the previous tutorial we used topic exchanges. In this tutorial we implement request/reply (RPC): a client sends a request and waits for a response.
The sample RPC service computes Fibonacci numbers on the server. The server uses IResponder on a quorum queue rpc_queue; the client uses IRequester to publish requests and await replies.
Server (RPCServer)
IResponder responder = await connection.ResponderBuilder()
.RequestQueue(rpcQueueName)
.Handler((ctx, request) =>
{
string response = "";
try
{
string message = Encoding.UTF8.GetString(request.Body()!);
int n = int.Parse(message);
Console.WriteLine($" [.] fib({message})");
response += Fib(n);
}
catch (Exception e)
{
Console.WriteLine($" [.] {e.Message}");
}
return Task.FromResult(ctx.Message(Encoding.UTF8.GetBytes(response)));
})
.BuildAsync();
Client (RPCClient)
IRequester requester = await connection.RequesterBuilder()
.RequestAddress()
.Queue("rpc_queue")
.Requester()
.BuildAsync();
IMessage request = new AmqpMessage(Encoding.UTF8.GetBytes(iStr));
IMessage reply = await requester.PublishAsync(request);
The tutorial client requests fib(0) through fib(31) in a loop, matching the other AMQP 1.0 tutorial ports.
Running
dotnet run --project RPCServer/RPCServer.csproj
dotnet run --project RPCClient/RPCClient.csproj
Source
A note on RPC
RPC is common but easy to misuse: keep clear which calls are local vs remote, document dependencies, and handle broker or server outages. When in doubt, prefer asynchronous pipelines over blocking RPC.
For more on AMQP 1.0 and RabbitMQ, see AMQP in RabbitMQ and AMQP 1.0 client libraries.