Spring Cloud课题实验手册(四)

在本系列的 上一篇文章 中,我们实现了一个基于 Zuul 的 Gateway, 并通过 Gateway 访问了 todo 微服务。本文中,我们将演示在 Gateway 中实现简单的流量限制功能。

增加依赖库

上一篇文章 已完成的Gateway的项目中增加如下依赖库:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<dependency>
<groupId>com.marcosbarbero.cloud</groupId>
<artifactId>spring-cloud-zuul-ratelimit</artifactId>
<version>2.2.0.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>

因为在 Spring Cloud 提供的集成 Netflix Zuul 并没有提供通过简单配置的方式来完成限流功能,所以我们这里使用一个第三方库: spring-cloud-zuul-ratelimit 官网, 该库实现了多种方式的限流。

修改配置文件

修改原有的 application.xml 文件,增加限流功能。在示例中,我们简单的限定在10秒内只允许进行3才访问。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
zuul:
prefix: /api
routes:
todo-by-service:
path: /todo/*
serviceId: cloud-todo-service
ratelimit:
enabled: true
repository: JPA
policy-list:
todo-by-service:
- limit: 3
refresh-interval: 30
type:
- origin

对比原来的 application.yaml 文件,可以看到只是在 zuul 配置段里增加了 ratelimit 的内容, **注意: policy-list 中的每一个配置项需要对应在 routes 中配置的路由名字。

运行并验证

运行项目,接着在浏览其中打开:

1
http://localhost:9098/api/todo/todo

第一次看到正确结果后,快速刷新浏览器,可以看到,在30秒内多于三次时,页面如下返回错误信息:

1
2
3
4
5
6
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Sat Nov 02 16:42:47 CST 2019
There was an unexpected error (type=Too Many Requests, status=429).
429

后台也可以看到抛出了 ZuulException 异常

1
2
3
4
5
6
o.s.c.n.z.filters.post.SendErrorFilter   : Error during filtering

com.netflix.zuul.exception.ZuulException: 429
at com.marcosbarbero.cloud.autoconfigure.zuul.ratelimit.support.RateLimitExceededException.<init>(RateLimitExceededException.java:13) ~[spring-cloud-zuul-ratelimit-core-2.2.0.RELEASE.jar:2.2.0.RELEASE]
at com.marcosbarbero.cloud.autoconfigure.zuul.ratelimit.filters.RateLimitPreFilter.lambda$run$0(RateLimitPreFilter.java:106) ~[spring-cloud-zuul-ratelimit-core-2.2.0.RELEASE.jar:2.2.0.RELEASE]
at java.util.ArrayList.forEach(ArrayList.java:1257) ~[na:1.8.0_191]

本文标题:Spring Cloud课题实验手册(四)

文章作者:Morning Star

发布时间:2019年11月01日 - 16:11

最后更新:2021年04月16日 - 15:04

原始链接:https://www.mls-tech.info/microservice/spring-cloud/springcloud-practise-manual-04/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。