- Cloud-Native Applications in Java
- Ajay Mahajan Munish Kumar Gupta Shyam Sundar
- 227字
- 2021-06-24 19:07:18
Creating a product client
We have created a dynamic product registry and even registered our service. Now, let's use this lookup to access the product service.
We will use the Netflix Ribbon project, which provides a load balancer as well as having address lookup from the service registry. Spring Cloud makes it easier to configure and use this.
For now, let's run the client within the same project as the service itself. The client will make an HTTP call to the service after looking up the product definition in Eureka. All this will be done by the Ribbon library, and we will just be using it as an endpoint:
- Add a dependency to the Maven POM of the product project as follows:

- Create a ProductClient class, which simply listens on /client and then forwards the request after doing a lookup to the actual product service:

The URL construction http://PRODUCT/ will be translated at runtime by Ribbon after doing a lookup. We are nowhere giving an IP address of the service.
- The restTemplate is injected here through auto-wiring. However, it needs to be initialized in the latest Spring versions. Hence, declare it as follows in the main application class, which also acts as a configuration class:

The @LoadBalanced annotation tells Spring to use the Ribbon load balancer (as Ribbon is in the classpath due to Maven).