RabbitMQ (EasyNetQ) – Request/Response

Sometimes when we use message broker we will want to wait for a response (like in RPC mechanism) – instead of relying on the publish or subscribe (which i present here).

Here EasyNetQ comes to help. It offerds us messaging pattern – request / response.

Request / response

To make it easier to understand this, let me give you an example.

One application sends a request for product list and waits for a response from the second application.

Command class (this one we send):

public class ReturnProductList
{
    public int Records { get; set; }
}

Event class (this one we are waiting for):

public class ReturnedProductList
{
    public List<Product> ProductList { get; set; } 
}

And here is short example, in API I want to display a list product with the appropriate number of records that will return us from another service via respond.

[HttpGet]
public JsonResult Get (int listCount)
{
    var messageBus = RabbitHutch.CreateBus("host=localhost");

    var response = messageBus.Request<ReturnProductList, ReturnedProductList>(new ReturnProductList
    {
        Records = 5
    });

    return Json(JsonConvert.SerializeObject(response));
}

And the respond:

messageBus.Respond<ReturnProductList, ReturnedProductList>(request => new ReturnedProductList
{
    ProductList = GenerateProductList().Take(request.Records).ToList()
});

Thanks to this mechanism, we will receive a simple information exchange with the request response messaging pattern.

Here is full example.

 

Leave a Reply

Your email address will not be published. Required fields are marked *