In this series of previous article, we implemented a Zuul-based Gateway and accessed the todo microservice through the Gateway. In this article, we will demonstrate how to implement a simple flow restriction function in Gateway.
Increase dependency library
In the (% post_link microservice/spring-cloud/spring-cloud-tutorial-03_en previous article %) the completed Gateway project adds the following dependency libraries:
1 | <dependency> |
Because the integrated Netflix Zuul provided by Spring Cloud does not provide a simple configuration method to complete the current limiting function, we use a third-party library here: spring-cloud-zuul-ratelimit Official website, this library implements current limiting in multiple ways.
Modify the configuration file
Modify the original application.xml file to increase the current limiting function. In the example, we simply restrict access to 3 within 10 seconds.
1 | zuul: |
Comparing the original application.yaml file, you can see that only the ratelimit content is added in the zuul configuration section. Note: Each configuration item in the policy-list needs to correspond to the route name configured in the routes.
Run and verify
Run the project, then open it in the browser:
1 | http://localhost:9098/api/todo/todo |
After seeing the correct result for the first time, quickly refresh the browser and you can see that if there are more than three times within 30 seconds, the page returns an error message as follows:
1 | Whitelabel Error Page |
You can also see ZuulException thrown in the background
1 | o.s.c.n.z.filters.post.SendErrorFilter : Error during filtering |