I have two Microservices. First Service for Customers and Second service for Invoice Service.
In Invoice MicroService, I will save only CustomerId. Using this CustomerId, I would like to retrieve all the related data for Customer Microservice. But i don't know to communicate async.
Any please get me some ideas.
What you are proposing - specifically one service making a direct HTTP call to another - is called tight coupling between services and is an antipattern in Microservices. It essentially turns your application into a distributed monolith - it should be avoided.
One example (there are many options) on how to properly do this asynchronously and with good, clean loose-coupled boundaries would be as follows:
Customers Service
generates a customer_created
eventInvoicing Service
subscribes to these events and, when received, makes necessary internal customer_id
updates (this is keeping its local data store updated - eventual consistency )Invoicing Service
creates an invoice that requires information from the Customers Service
, it generates a cust_invoice_pending
eventCustomers Service
subscribes to this event, and when it sees one, it generates a new message like invoice_customer_detail_push
on the bus (note, I'd use an invoice_id
in the payload of this message to tie them together)Invoicing Service
subscribes to and sees this data it needs which allows it to populate the rest of the invoiceIt may seem like a lot of extra work and complexity, and indeed it is. This is the "hard" part of successful microservices architecture. It takes more discipline and planning up front, but here are the advantages - in this simple case - of the resulting solution versus the distributed monolith you've proposed:
Invoicing Service
or Customers Service
with something completely different without ever touching the code in the other serviceSo, if the benefits are worth the tradeoffs in your case, have at it. But, any time you see two "microservices" communicating directly, it's likely you've lost sight a bit of coupling and need to re-examine how information flows through your system.
I think you need just to send a http request to your second service using the CustomerId
as query parameter (or post body, but probably not).
You need to CreateClient
in your apps, before to do http requests.
Make HTTP requests using IHttpClientFactory in ASP.NET Core
var request = new HttpRequestMessage(HttpMethod.Get,
"domain_second_service/controller/method?customerId=X");
request.Headers.Add("Accept", "application/json");
request.Headers.Add("User-Agent", "HttpClientFactory-Sample");
var client = _clientFactory.CreateClient();
var response = await client.SendAsync(request);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.