1. Add Dependencies:
In your microservice projects, add the following dependencies to your build file (typically pom.xml
for Maven or build.gradle
for Gradle):
org.springframework
.cloud
spring-cloud-starter
-netflix-eureka-client
This dependency includes the necessary libraries for integrating your microservice with Eureka.
2. Configure Application Properties:
In each microservice’s application.properties
or application.yml
file, specify the Eureka server’s location:
spring:
application:
name: your-service-name
eureka:
client:
serviceUrl: defaultZone
: http://eureka-server-host:8761/eureka/
your-service-name
is the name of your microservice.eureka-server-host
is the hostname where the Eureka Naming Server is running.
3. Annotate the Application Class:
In your microservice’s main application class, annotate it with @EnableEurekaClient
. This annotation registers the microservice with Eureka and enables service discovery.
import org.springframework
.boot.SpringApplication;
import org.springframework
.boot.autoconfigure.SpringBootApplication;
import org.springframework
.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
public class YourServiceApplication {
public static void main(String[] args)
{ SpringApplication.run
(YourServiceApplication.class, args);
}
}
4. Service Registration and Discovery:
Once your microservices are configured as Eureka clients, they will automatically register themselves with the Eureka Naming Server when they start up. You can also use the @LoadBalanced
annotation with your REST client to perform load-balanced service discovery. Here’s an example of using Feign, a popular declarative HTTP client in Spring Cloud:
@FeignClient("your-service-name")
public interface YourServiceClient {
@GetMapping("/your-endpoint")
String yourMethod();
}
In this example, @FeignClient("your-service-name")
instructs Feign to look up the service name in Eureka and perform load-balanced requests to that service.
5. Start Eureka Naming Server:
Before running your microservices, ensure that the Eureka Naming Server is up and running. Start the Eureka server by running a project with Eureka Server configuration, which includes the @EnableEurekaServer
annotation.
With these configurations in place, your microservices will automatically register with the Eureka server when they start and will be able to discover other services by their registered names. This enables dynamic service discovery and load balancing in your microservices architecture.