在开发、测试的时候,或者生产环境新版本发布,一般需要对服务进行灰度发布上线。常见的场景就是一个服务有多个版本,如旧版本v1,新版本v2。在灰度发布的时候,需要通过网关动态实时推送路由权重信息。
WeightRoutePredicateFactory 权重路由断言工厂
可以使用 Spring Cloud Gateway中的WeightRoutePredicateFactory 权重路由断言工厂,对URL进行权重路由。
![b53030fbe99203272b1518bd7e86bb45.png](https://img-blog.csdnimg.cn/img_convert/b53030fbe99203272b1518bd7e86bb45.png)
通过Spring Cloud Gateway网关,根据权重路由规则,针对特定的服务,把95%的请求流量分发给V1 版本,把剩余 5%的流量分发给V2版本。
具体开发实现过程,可以参考如下步骤。
1. 在Spring Cloud Gateway网关应用中,添加Maven依赖。
gateway依赖的jar包如下。
org.springframework.cloud
spring-cloud-starter-gateway
2. 在application.yml中配置权重路由信息。
Spring Cloud Gateway会根据配置的路由权重信息,将请求分发给不同的源服务上。
server.port: 8080
spring:
application:
name: ch18-3-gateway
cloud:
gateway:
routes:
- id: service1_v1
uri: http://localhost:8081/v1
predicates:
- Path=/test
- Weight=service1, 95
- id: service1_v2
uri: http://localhost:8081/v2
predicates:
- Path=/test
- Weight=service1, 5
logging:
level:
org.springframework.cloud.gateway: TRACE
org.springframework.http.server.reactive: DEBUG
org.springframework.web.reactive: DEBUG
reactor.ipc.netty: DEBUG
v1配置流量为 95%,v2配置流量为 5%。
logging.level.xxx.DEBUG 是设置只打印指定包的日志输出级别。
路由权重的核心配置信息,如下所示。
![badf474f6796d00f000f11e2e219ed9f.png](https://img-blog.csdnimg.cn/img_convert/badf474f6796d00f000f11e2e219ed9f.png)
3. Gateway网关应用启动的入口主程序。
这个比较简单,就是一般的spring boot应用启动程序。
@SpringBootApplication
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
4. 编写service provider程序,并且提供v1,v2两个版本。
为了配合达到测试效果,在新的service provider应用中,提供如下的service controller API接口。
@RestController
public class ServiceController {
@GetMapping(value = "/v1")
public String v1() {
return "v1";
}
@GetMapping(value = "/v2")
public String v2() {
return "v2";
}
}
5. 启动测试
分别启动gateway和serivce provider应用,然后访问 http://localhost:8080/test 网关设置的路径。
多数情况下(95%),会返回v1的信息。
![968b6d44f20c8e9e6e22d9e1d6619bfe.png](https://img-blog.csdnimg.cn/img_convert/968b6d44f20c8e9e6e22d9e1d6619bfe.png)
5%的概率,会返回 v2的信息。
![407714305f2c63301a4333a0f2d973e9.png](https://img-blog.csdnimg.cn/img_convert/407714305f2c63301a4333a0f2d973e9.png)