Home > Software engineering >  How to achieve synch. call from RabbitMQ in .NET Core microservice Architecture?
How to achieve synch. call from RabbitMQ in .NET Core microservice Architecture?

Time:12-28

  1. In my project there is a need of inter-service communication in synchronize manner. Is there anyway we can communicate between two microservice in synchronize manner using RabbitMQ or any other async methods ?

  2. Or following suggestion having any other meaning ? "If your microservice needs to raise an additional action in another microservice, if possible, do not perform that action synchronously and as part of the original microservice request and reply operation. Instead, do it asynchronously (using asynchronous messaging or integration events, queues, etc.). But, as much as possible, do not invoke the action synchronously as part of the original synchronous request and reply operation." Ref.

I tried gRPC and dependencies adding approach, via the following links any other approach is available for the sync communication ?

  1. https://docs.abp.io/en/commercial/latest/startup-templates/microservice/synchronous-interservice-communication
  2. https://www.c-sharpcorner.com/article/crud-operation-and-microservice-communication-using-grpc-in-net-core-6-web-api/

CodePudding user response:

if you are using masstransit on RabbitMQ then you can simply do as follow.
let say we want to fire event to submit order with response (synchronous manner as you said).
first we have Order message model or interface. i prefer interface.

public interface ISubmitOrder
    {
        Guid Id { get; set; }
        DateTime TimeStamp { get; set; }
        public string CustomerId { get; set; }
    }

and the response model/interface since you want response back.

public interface IOrderSubmisstionResponse
    {
        Guid Id { get; set; }
        DateTime TimeStamp { get; set; }
        public string CustomerId { get; set; }
    }

and this is the consumer which response back

public class SubmitOrderConsumer : IConsumer<ISubmitOrder>
    {


        private readonly ILogger<SubmitOrderConsumer> _logger;

        public SubmitOrderConsumer(ILogger<SubmitOrderConsumer> logger)
        {
            _logger = logger;
        }

        public async Task Consume(ConsumeContext<ISubmitOrder> context)
        {

            _logger.Log(LogLevel.Debug, $"Order Info( customer Id : {context.Message.CustomerId})");


            await context.RespondAsync<IOrderSubmisstionResponse>(new {

                TimeStamp = InVar.Timestamp,
                CustomerId = context.Message.CustomerId,
                Id = context.Message.Id
            
            });
        }
    }

masstransit configuration in Container

builder.Services.AddMassTransit(options =>
{

    options.AddConsumer<SubmitOrderConsumer>();

    options.UsingRabbitMq((ctx, conf) =>
    {
        conf.Host("amqp://guest:guest@localhost:5672");
        conf.UseMessageRetry(r => r.Immediate(2));
        conf.ConfigureEndpoints(ctx);
    });


    options.AddRequestClient<ISubmitOrder>();

});

inject IRequestClient

 private readonly IRequestClient<ISubmitOrder> _requestClient;

and this is how fire it

var result = await _requestClient.GetResponse<IOrderSubmisstionResponse>(new
            {
                Id = Id,
                TimeStamp = InVar.Timestamp,
                CustomerId = CustomerId
            });

masstransit request doc
awsome toturials from Chris Paterson


the reason to use asynchronous communication between services is to maintain them independent and atomic and consequently anonymous to each other. this also helps to maintain and develop services independently even by different teams. however some times synchronous communication become inevitable so in that case there could be rest or rpc communication with consideration of service coupling cautions.

CodePudding user response:

Is there anyway we can communicate between two microservice in synchronize manner using RabbitMQ or any other async methods ?

You can use Remote procedure call (RPC) pattern. In short publisher post a message and then waits for response in designated queue with some marker that this is response for this specific request (for example using CorrelationId) and marks that particular message as processed.

any other approach is available for the sync communication

Yes, you can use "traditional" Web API approaches like REST/OpenAPI/OData/GraphQL. Personally when synchronous communication is needed I would prefer one of these approaches (including gRPC) over the simulating synchronous calls over async messaging.

  • Related