Wednesday, March 31, 2021

Spring Boot and Eureka

Today I tried Netflix Eureka for the first time with Spring Boot. What is it for? Imagine we have many services that run on different host and port, each of them are independent and managed by different project team. How can we monitor all those services? We need a tool to do that and Eureka is the tool. All those services will register themselves to Eureka server and Eureka server will be able to monitor those services. Let's do this with Spring Boot.

As an example we will create a Eureka server and two Eureka clients. Client here means our own service that registers to Eureka.

Eureka Server

You can start to develop the Eureka server from scratch using the super Spring initializer page. The maven xml should include below dependencies:


Then annotate the Spring Boot application with @EnableEurekaServer as shown below:

Next step is to set Eureka server to a specified port and to prevent Eureka server from registering itself by setting below values in application.properties file:


That's it. Just run the application and point out our browser to http://localhost:9876/ and you will see the Spring Eureka page says that there is no registered instance at the moment.

Eureka Client

Now that we have Eureka server set up and run, it's time to create some services that will register to it. We will create two services for this purpose.

Just like the server, we can create the service using Spring initializer page and add the following dependency to the maven xml.




As a service, add the following Rest Controller and Request Mapping. When hit, it will get information from Discovery Client and print it out to the browser.


Lastly, add below information to the application.properties. Here we set the application name that will be shown in the Eureka Server, set our service port value, and tell the service to register itself to a specified Eureka Server url.


Run the application and refresh the Eureka Server page. Our service is now registered with Eureka Server.


Now go to the browser and hit the service with eureka-client as the parameter applicationName. Information about the service will be printed out.


Create one more service with the following information on Rest Controller and application.properties. Here we set the port to another unused port.



Run this service and refresh the Eureka Server page. Our new service is now registered there.


Hit the service on the browser and the greeting message will be printed out.


 

©2009 Stay the Same | by TNB