What is Service Discovery?

In a microservices architecture, each service is often deployed independently. Service discovery allows services to locate one another without hardcoding their network locations. Eureka, a Netflix OSS project, serves as a service registry that helps in maintaining an up-to-date directory of services and their instances.

Setting Up Eureka Server

To get started, add the Eureka Server dependency to your project's pom.xml:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>

Enable the Eureka Server by annotating your main application class:

@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class, args);
    }
}

Configure the server properties in application.yml:

server:
  port: 8761

spring:
  application:
    name: eureka-server

eureka:
  client:
    register-with-eureka: false
    fetch-registry: false
  server:
    enable-self-preservation: false

Registering Services with Eureka

To register a service with Eureka, add the Eureka client dependency:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

Annotate your application with @EnableEurekaClient, and configure the client settings in application.yml:

spring:
  application:
    name: my-service

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/

Client-Side Service Discovery

Using Spring's RestTemplate, you can enable service discovery by resolving service names dynamically:

@RestController
@RequestMapping("/api")
public class ApiController {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/data")
    public String fetchData() {
        return restTemplate.getForObject("http://my-service/endpoint", String.class);
    }

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

Testing Your Setup

Start the Eureka server and registered services. Access the Eureka dashboard at http://localhost:8761 to view the registered instances. Test the dynamic service discovery using tools like Postman or cURL.

Conclusion

Spring Cloud Netflix Eureka provides a robust mechanism for service discovery, simplifying the communication between microservices. This article covered setting up a Eureka Server, registering services, and implementing client-side service discovery. By leveraging these features, you can build scalable and resilient microservices architectures.