Spring Cloud Gateway学习笔记
一、网关的HelloWorld
1.新建SpringBoot项目,添加gateway依赖和eureka-client依赖:
1 2 3 4 5 6 7 8
| <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency>
|
2.在application.yml中配置网关地址自动映射和服务发现地址:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| spring: application: name: gatewaydemo cloud: gateway: discovery: locator: enabled: true lower-case-service-id: true server: port: 9999
eureka: client: service-url: defaultZone: http://inspiron-7537:8761/eureka
|
启动好微服务、注册中心和网关后,就可以通过访问网关:
1
| curl "http://localhost:9999/weather-forecast/api/v1/weather/forecast?location=Shanghai&time=today"
|
获取微服务结果了。
实验过程可以感觉到“约定大于配置”的思想,不用改代码,仅仅是配置就能完成基本功能。
二、手工配置服务映射
在前述实验基础上,将application.yml中spring配置项修改为:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| spring: application: name: gatewaydemo cloud: gateway: discovery: locator: enabled: false lower-case-service-id: true routes: - id: first uri: http://weather-forecast predicates: - Path=/api/** filters: - StripPrefix=1
|
routes配置一个数组,使用-表达数组中一个对象,其含义是配置一个指向 http://weather-forecast
的路由,将请求中带有/api/**的请求路径去除/api后转发过去。
启动网关服务和天气预报服务后,等待服务发现完毕,发送报文:
1 2
| curl "http://localhost:8025/v1/weather/forecast?location=Shanghai&time=today" curl "http://localhost:9999/api/v1/weather/forecast?location=Shanghai&time=today"
|
均可成功。
三、配置令牌桶限流过滤器
1.在 application.yml 中新增filters配置:
1 2 3 4 5 6 7 8 9 10
| filters: - StripPrefix=1 - name: RequestRateLimiter args: keyResolver: ‘#{@tokenBucketAlgorithm}’ redis-rate-limiter: replenishRate: 1 burstCapacity: 5
|
keyResolver是令牌桶工厂,需要继承KeyResolver类来实现。
redis-rate-limiter是已实现的方法,需要配置依赖和启动redis。
2.创建令牌桶工厂实现类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| package edu.ustb.gatewaydemo.keyresolver;
import reactor.core.publisher.Mono;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver; import org.springframework.stereotype.Component; import org.springframework.web.server.ServerWebExchange;
@Component public class TokenBucketAlgorithm implements KeyResolver {
@Override public Mono<String> resolve(ServerWebExchange exchange) { String hostAddress = exchange.getRequest().getRemoteAddress().getAddress().getHostAddress(); return Mono.just(hostAddress); } }
|
3.在pom.xml中添加依赖:
1 2 3 4
| <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
|
4.启动redis,进入redis-cli
,可以查看缓存情况:
5.模拟请求,再次查看缓存情况:
先用curl试一下:
1
| curl "http://localhost:9999/api/v1/weather/forecast?location=Beijing&time=today"
|
没有问题后打开JMeter,模拟一次10个线程的访问:
可以看到被拒绝的多余请求,返回的是状态码429。(正常请求返回状态码是200)
使用ab进行并发测试:
1
| ab -n 10 -c 5 "http://localhost:9999/api/v1/weather/forecast?location=Beijing&time=tomorrow"
|
从ab返回的结果中含有5个 “Non-2xx responses” 也能验证JMeter的结果:
评论
shortname
for Disqus. Please set it in_config.yml
.