Prerequisites:
- Java Development Kit (JDK) 8 or later installed
- Maven installed
- Spring Boot IDE or any preferred IDE
Step 1: Create Eureka Server
- Create a new Spring Boot project with the following dependencies:
- Eureka Server
- Open the
src/main/resources/application.properties
file and configure the Eureka server:
spring.application.name=eureka-server
server.port=8761
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
- Add the
@EnableEurekaServer
annotation to your main application class:
- Run the Eureka Server application.
Step 2: Create Microservice 1
- Create a new Spring Boot project with the following dependencies:
- Eureka Discovery
- Web
- Open the
src/main/resources/application.properties
file and configure the microservice:
spring.application.name=microservice1
server.port=8081
eureka.client.service-url.default-zone=http://localhost:8761/eureka/
- Create a simple controller for testing:
- Run Microservice 1.
Step 3: Create Microservice 2
- Create another Spring Boot project with the following dependencies:
- Eureka Discovery
- Web
- Open the
src/main/resources/application.properties
file and configure the microservice:
spring.application.name=microservice2
server.port=8082
eureka.client.service-url.default-zone=http://localhost:8761/eureka/
- Create a simple controller for testing:
- Run Microservice 2.
Step 4: Create Spring Cloud Gateway
- Create a new Spring Boot project with the following dependencies:
- Eureka Discovery
- Gateway
- Web
- Open the
src/main/resources/application.properties
file and configure the gateway:
spring.application.name=gateway
server.port=8080
spring.cloud.gateway.routes[0].id=microservice1
spring.cloud.gateway.routes[0].uri=lb://microservice1
spring.cloud.gateway.routes[0].predicates[0]=Path=/microservice1/**
spring.cloud.gateway.routes[1].id=microservice2
spring.cloud.gateway.routes[1].uri=lb://microservice2
spring.cloud.gateway.routes[1].predicates[0]=Path=/microservice2/**
eureka.client.service-url.default-zone=http://localhost:8761/eureka/
- Run the Gateway application.
- Access the microservices through the gateway:
- Microservice 1: http://localhost:8080/microservice1/api/hello
- Microservice 2: http://localhost:8080/microservice2/api/hello
That’s it! You’ve successfully set up a Spring Cloud Gateway with Eureka and two microservices. You can expand this setup by adding more routes to the gateway and additional microservices.