I have two micro services M1 and M2 ,i need to send request to M2 from M1 ,and i need to wait for the response from M2 ,because the code works based on the response from M2 How to implement this in spring boot?
CodePudding user response:
Create a REST API in your M1 micro service through a controller and then call it from M2 using some API client library.
CodePudding user response:
There are many ways to do it. I will suggest you to implement a producer/consumer
pattern between M1 and M2 with a messaging tool such as Active MQ
, Rabbit MQ
or Kafka
.
- M1 produce a message to a queue Q1
- M2 process the message from Q1
- M2 returns a response to Q2
- M1 consume the message from Q2
Take a look here.
CodePudding user response:
You can use synchronous communication with the declarative Rest client "Spring Cloud OpenFeign" as bellow :
Spring Cloud - Synchronous Communication with Feign
CodePudding user response:
You create REST API in M2 that will consume or respond to your input from M1
for instance you may have following endpoint in your @RestController annotated class in M2:
@GetMapping("/consumer")
public ResponseEntity<YourResponseDTO> produceResponse(){
YourResponseDTO result = resultOfYourBusinessLogic();
return ResponseEntity.ok(result);
Then in your M1 service the easiest in my opinion is to use RestTemplate to call M2 Here is an example:
RestTemplate rt = new RestTemplate();
YourResponseDTO result = rt.getForObject("http://urlOfYourM2/consumer", YourResponseDTO.class);
Please note that this is just an example of call for GET request that produces "YourReponseDTO" Object. You gave very less details about the actual needs of the message exchange and thus the RestTemplate may be used in different ways (different types of request PUT/POST/etc...) you can customize it according needs with error handlers, connection timeout settings etc.
Downside of this approach is that you need to share between M1 and M2 a DTO model to properly map the response objects. But anyways RestTemplate is a client implementation you can use to communicate synchronously between microservices