Register and discover other services in Consul using Spring Cloud Consul

In the previous tutorial, I showed you how to register a service to Consul using the Consul API. If your application uses Java and Spring framework, you can also do this using Spring Cloud Consul. We can also discover information about other services using this Spring Cloud Consul module. How is it in detail? In this tutorial, we will learn together how to connect to Consul, get information about services registered with Consul and call them, using Spring Cloud Consul!

First, I will create a new Spring Boot project with Spring Web, Actuator and Spring Cloud Consul Service Discovery as follows:

Spring Web is for building web applications, Actuator is for exposing healthcheck endpoint so Consul can heal check that service!

With the auto-configuration mechanism of Spring Cloud Consul Service Discovery, you just need to declare the information of the Consul server in the configuration file of Spring Boot:

then, our application can connect to the Consul server, register and discover registered services inside this Consul server.

One thing to note is that you need to declare the property spring.application.name with the name of the application so that Spring Cloud Consul can use it to register with Consul! And if your service is deployed on a different server than Consul, you can use the property spring.cloud.consul.discovery.hostname to declare the server name information, for example as follows:

The application name must start with a letter, end with a letter or number and we only use letters, numbers or hyphens in the application name.

By default, Spring Cloud Consul registers the health check endpoint using the “/health” endpoint of Actuator, so you also need to expose this endpoint:

If now, I run this example application and go to the address listing the services registered with Consul http://localhost:8500/ui/dc1/services, you will see the result like me, as follows:

huongdanjava-service is the service that I registered in the tutorial Register service with Consul using Consul API!

So our service has successfully registered with Consul.

You can disable the auto-registration mechanism and discover other services using the following properties:

By default, the value of these properties is true!

To get information about registered services in Consul, you can use the bean of the DiscoveryClient class, for example, as follows:

Run this example application, you will see the result as follows:

To get information about a service and call it, you can use the getInstances() method of the DiscoveryClient class. The parameter of this getInstances() method is the name of the service! The returned information will be a list of corresponding instances of this service.

My example is as follows:

Result:

So we have got the information about the services registered in the Consul server.

Add Comment