In the previous article of this series, we transformed an ordinary Spring Boot project into a service in the Spring Cloud framework. In this article, we will implement a Gateway service in order to call the modified Todo service.
Build a simple Maven project in IDEA, name the groupId: cn.com.hohistar.tutorial, and the artifactId: springcloud-gateway-srv, and then replace the content in the original pom.xml file with the following:
As you can see, we will use two components of Spring Cloud: netflix-zuul and netflix-eureka-client
Create a new package in the src/main/java directory: cn.com.hohistgar.tutorial.springcloudgatewaysrv, and then create a new class in the package, named: SpringcloudGatewaySrvApplication, copy the following code in the content:
In fact, SpringcloudGatewaySrvApplication is a SpringBoot startup class, but two annotations have been added: @EnableZuulProxy, @EnableEurekaClient.
@EnableEurekaClient-used to register itself (the current application service) to the registration and discovery service
@EnableZuulProxy-Enable the function of Gateway
Create a new file named: application.yaml in the src/main/resources directory, and copy the following content into the file:
As you can see, the entire configuration file is divided into four sections. The first and second sections are common Spring Boot project settings, indicating the port and project name of the project. The third paragraph is the client configuration of the registration service. Note that the defaultZone is replaced with the address and port of the registration service actually running in the environment. The last part is the configuration of the Gateway. In the current example, we only configure the routing to forward the access to the todo path to the cloud-todo-service.
Note: Before running Gateway, make sure that the future services in manuals one and two have been running
Start the application in IDEA, and then open it in the browser:
You can see that the todo service and gateway service have been registered in the registration server。
Then open it in the browser:
If it is normal, you should get the to-do list returned by cloud-todo-service, which is a json array.
In next step, we will add a current limiting function to the Gateway.