Microservices (or REST APIs) can communicate with other Microservices (or REST APIs) or External Services by using
1. REST Templates
REST Templates establishes synchronous communication between APIs.
Example
RestTemplate restTemplate = new RestTemplate(); User user = restTemplate.getForObject("http://localhost:8082/users/1", User.class);
2. Web Clients
Web Clients establishes asynchronous as well asynchronous communication between APIs.
Example
WebClient.Builder webClientBuilder = WebClient.builder(); User user = webClientBuilder.build() .get() .uri("http://localhost:8082/users/1") .retrieve() .bodyToMono(User.class) .block();
As you can see in above code that we have hard-coded the URLs to communicate with other services. Hard-coding of URLs is obviously not recommended while communicating with REST APIs (or microservices).
Why hard-coding of URLs is bad while communicating with other services?
1. Changes require code updates – Every time when endpoint URL gets changes for any reason you are required to make code changes accordingly.
2. Dynamic URLs in cloud – When you deploy your application in cloud, your URLs are dynamic which is very common. So it is hard to identify the URLs and make the changes, so you end up with communication failure.
3. Load balancing – Basically, when load balancing takes place, you create multiple instances of your service and deploy on server. Load balancing works by calling different instances of your services based on the algorithm. You cannot achieve load balancing by hard-coding the URLs.
4. Multiple environments – When your application is in development or QA phase, you need to change the URLs according to the environment you are working on. It is not a good idea to change your URL configuration every time when your application is deployed on different environments.
To get rid of URLs hard-coding we need some pattern which resolves this issue and that is Service Discovery.