Spring Boot is a popular Java framework for building microservices, and Eureka is a service discovery tool that is often used with Spring Boot. Eureka allows services to register themselves with the registry and to discover other services that are registered. In this article, we will discuss how to configure Spring Boot with Eureka.
- Add Eureka dependency First, we need to add the Eureka dependency to the pom.xml file of the Spring Boot project:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
<version>3.0.3</version>
</dependency>
- Configure application.properties Next, we need to configure the application.properties file with the following properties:
spring.application.name=eureka-server
server.port=8761
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
The spring.application.name
property sets the name of the Eureka server, and server.port
sets the port that the server will listen on. The eureka.client.register-with-eureka
and eureka.client.fetch-registry
properties are set to false because this is the Eureka server and it will not register or fetch services.
- Enable Eureka server To enable the Eureka server, we need to add the
@EnableEurekaServer
annotation to the main class of the Spring Boot application:
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication
{
public static void main(String[] args)
{
SpringApplication.run(EurekaServerApplication.class, args);
}
}
- Create a new Client Project, and Add Eureka client dependency To register a service with Eureka, we need to add the Eureka client dependency to the pom.xml file:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>3.0.3</version>
</dependency>
- Configure Eureka client Next, we need to configure the Eureka client in the application.properties file:
spring.application.name=my-service
server.port=8080
eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
The spring.application.name
property sets the name of the service, and server.port
sets the port that the service will listen on. The eureka.client.service-url.defaultZone
property sets the URL of the Eureka server.
- Register service with Eureka To register the service with Eureka, we need to add the
@EnableDiscoveryClient
annotation to the main class of the Spring Boot application:
@SpringBootApplication
@EnableDiscoveryClient
public class MyServiceApplication
{
public static void main(String[] args)
{
SpringApplication.run(MyServiceApplication.class, args);
}
}
With these steps, the Spring Boot application is now configured to work with Eureka for service discovery. The Eureka server can be accessed at http://localhost:8761/
, and the registered services can be viewed in the Eureka dashboard.
Leave a Reply