Here is an example of how you can create a Eureka server in a Spring Boot application, along with a simple car microservice that registers itself with the Eureka server.
- Eureka Server:
First, create a Spring Boot project and add the following dependencies to your pom.xml
file:
1 2 3 4 5 6 |
<dependencies> <dependency> <groupid>org.springframework.cloud</groupid> <artifactid>spring-cloud-starter-netflix-eureka-server</artifactid> </dependency> </dependencies> |
Next, add the @EnableEurekaServer
annotation to your main class to configure the Eureka server:
1 2 3 4 5 6 7 8 |
@SpringBootApplication @EnableEurekaServer public class EurekaServerApplication { public static void main(String[] args) { SpringApplication.run(EurekaServerApplication.class, args); } } |
And add the following properties to your application.properties
or application.yml
file:
1 2 3 4 5 |
server.port: 8761 eureka.instance.hostname: localhost eureka.client.register-with-eureka: false eureka.client.fetch-registry: false |
- Car Microservice:
Create another Spring Boot project and add the following dependencies to your pom.xml
file:
1 2 3 4 5 6 7 |
<dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> </dependencies> |
Next, add the @EnableDiscoveryClient
annotation to your main class to enable the discovery client:
1 2 3 4 5 6 7 8 |
@SpringBootApplication @EnableDiscoveryClient public class CarApplication { public static void main(String[] args) { SpringApplication.run(CarApplication.class, args); } } |
And add the following properties to your application.properties
or application.yml
file:
1 2 3 |
server.port: 8081 eureka.client.service-url.defaultZone: http://localhost:8761/eureka/ |
Finally, create a simple REST endpoint in your CarApplication class:
1 2 3 4 5 6 7 8 |
@RestController public class CarController { @GetMapping("/car") public String getCar() { return "Audi"; } } |
That’s it! You can now run both the Eureka server and the car microservice, and the car microservice should register itself with the Eureka server. You can access the car endpoint by making a GET request to http://localhost:8081/car
.