Microservice call

I was looking for a similar question, but could not find. I have a microservice created using the drop-wizard that works in localhost: 9000.

I am working on another project (with spring mvc), launched in 8080. I want to call the above service, which returns me a string from any of my controllers in the main project. For example, the path is "localhost: 9000 / giveMeString".

+5
source share
2 answers

You can use the Apache HTTP client. See This Example, borrowed from their documentation:

// Create an instance of HttpClient. HttpClient client = new HttpClient(); // Create a method instance. GetMethod method = new GetMethod("http://localhost:9000/giveMeString"); // Execute the method. int statusCode = client.executeMethod(method); // Read the response body. byte[] responseBody = method.getResponseBody(); //Print the response System.out.println(new String(responseBody)); 
+4
source

If you really omit the microservice path, note that creating an HTTP client for each request and executing synchronous blocking requests will not really scale.

Here are some ideas:

Create one instance of RestTemplate

You can create a single instance of RestTemplate and enter it in several places in your application.

 @Configuration public class MyConfiguration { @Bean public RestTemplate restTemplate() { return new RestTemplate(new HttpComponentsClientHttpRequestFactory()); } } 

Better wrap this REST client cache

Check out Sagan will take it .

Better yet, go asynchronously

You can use AsyncRestTemplate ; very useful, especially if your controllers need to complete several requests, and if you do not want to block the webapp stream. Your controller may even return DeferredResult or ListenableFuture , which will make your webapp more scalable.

And Spring Cloud + Netflix

You can also check out Spring Cloud and Spring Cloud Netflix . You will see interesting features: load balancing, recovery, circuit breakers, etc.

+4
source

Source: https://habr.com/ru/post/1205203/


All Articles