Here is an example of how you can create a Spring API Gateway in a Spring Boot application along with a simple car microservice.
- API Gateway:
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-zuul</artifactid> </dependency> </dependencies> |
Next, add the @EnableZuulProxy
annotation to your main class to enable the Zuul proxy:
1 2 3 4 5 6 7 8 |
@SpringBootApplication @EnableZuulProxy public class ApiGatewayApplication { public static void main(String[] args) { SpringApplication.run(ApiGatewayApplication.class, args); } } |
- Car Microservice:
Create another Spring Boot project and add the following REST endpoint in your main class:
1 2 3 4 5 6 7 8 |
@RestController public class CarController { @GetMapping("/car") public String getCar() { return "Audi"; } } |
And add the following properties to your application.properties
or application.yml
file:
1 2 |
server.port: 8081 |
That’s it! You can now run both the API gateway and the car microservice. You can access the car endpoint through the API gateway by making a GET request to http://localhost:8080/car-service/car
, where car-service
is the name of your car microservice. Note that you need to configure the API gateway to know about the car microservice, which you can do by adding a mapping in the application.properties
or application.yml
file of the API gateway:
1 2 3 |
zuul.routes.car-service.path: /car-service/** zuul.routes.car-service.url: http://localhost:8081 |