欢迎访问Spring Cloud中国社区

《重新定义Spring Cloud实战》由Spring Cloud中国社区倾力打造,基于Spring Cloud的Finchley.RELEASE版本,本书内容宽度足够广、深度足够深,而且立足于生产实践,直接从生产实践出发,包含大量生产实践的配置。欢迎加微信Software_King进群答疑,国内谁在使用Spring Cloud?欢迎登记

Spring Cloud Finchley系列(一)Spring Cloud Gateway

三分之一程序员 · 2月前 · 1849 ·

一、概述

1.关于Spring Cloud Finchley

Spring Cloud Finchley是6月19日Spring官方正式发布GA版本,Finchley.Release支持了Spring Boot2.0,要求起步JDK8,支持JDK9,Finchley版本带了新的子项目,包括对原先版本的子项目的升级,原先支持的组件现在已经全部为2.0.0.Release,并且在官方的版本生命周期公告中说明,Camden release已经到了终止状态,Dalston release将于2018年12月结束,Edgware release将遵循Spring Boot 1.5.x系列的生命周期结束。Spring Boot2.0的新特性本文不再赘述,本文主要介绍Spring Cloud新的开源子项目Spring Cloud Gateway。

2.关于Spring Cloud Gateway

Spring Cloud Gateway是由spring官方基于Spring5.0,Spring Boot2.0,Project Reactor等技术开发的网关,目的是代替原先版本中的Spring Cloud Netfilx Zuul,目前Netfilx已经开源了Zuul2.0,但Spring 没有考虑集成,而是推出了自己开发的Spring Cloud GateWay。该项目提供了一个构建在Spring Ecosystem之上的API网关,旨在提供一种简单而有效的途径来发送API,并向他们提供交叉关注点,例如:安全性,监控/指标和弹性.

二、实践

以下将介绍Spring Cloud Gateway的一些重点功能和扩展方式,关于基础使用不再文中赘述,如有需要请查阅相关文档。

1.自定义GatewayFilter

GatewayFiltery有两种类型的filter,分别为pre和post类型,以下提供一个demo的配置

定义PreGatewayFilter:

  1. public class PreGatewayFilterFactory extends AbstractGatewayFilterFactory {
  2. public PreGatewayFilterFactory() {
  3. super(Config.class);
  4. }
  5. public GatewayFilter apply() {
  6. return apply(o -> {
  7. });
  8. }
  9. @Override
  10. public GatewayFilter apply(Config config) {
  11. // grab configuration from Config object
  12. return (exchange, chain) -> {
  13. //If you want to build a "pre" filter you need to manipulate the
  14. //request before calling change.filter ServerHttpRequest.Builder builder = exchange.getRequest().mutate();
  15. builder.header("GatewayFilter", "PreGatewayFilterFactory success");
  16. //use builder to manipulate the request
  17. return chain.filter(exchange.mutate().request(builder.build()).build());
  18. };
  19. }
  20. public static class Config {
  21. //Put the configuration properties for your filter here
  22. }
  23. }

定义PostGatewayFilter:

  1. public class PostGatewayFilterFactory extends AbstractGatewayFilterFactory {
  2. private Logger logger = LoggerFactory.getLogger(PostGatewayFilterFactory.class);
  3. public PostGatewayFilterFactory() {
  4. super(Config.class);
  5. }
  6. public GatewayFilter apply() {
  7. return apply(o -> {
  8. });
  9. }
  10. @Override
  11. public GatewayFilter apply(Config config) {
  12. return (exchange, chain) -> {
  13. logger.info("PostGatewayFilter...");
  14. return chain.filter(exchange).then(Mono.fromRunnable(() -> {
  15. ServerHttpResponse response = exchange.getResponse();
  16. //Manipulate the response in some way
  17. }));
  18. };
  19. }
  20. public static class Config {
  21. //Put the configuration properties for your filter here
  22. }
  23. }

自定义GatewayFilter需要在RouteLocator中配置为具体Route项加入,下文RouteLocator配置中会提供demo.

2.全局过滤器(GlobalFilter)

  1. @Configuration
  2. public class GlobalRouteFilter implements GlobalFilter {
  3. @Override
  4. public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
  5. ServerHttpRequest.Builder builder = exchange.getRequest().mutate();
  6. builder.header("GlobalFilter","GlobalFilter success");
  7. chain.filter(exchange.mutate().request(builder.build()).build());
  8. return chain.filter(exchange.mutate().request(builder.build()).build());
  9. }
  10. }

自定义GlobalFilter只要使用了@Configuration注解或者配置为一个spring bean就会生效,不需要在RouteLocator中配置。

3.请求限流过滤器(RequestRateLimiter)

目前限流Spring Cloud提供了redis的实现,不过可以自定义RequestRateLimiter的实现。Spring Cloud提供的redis实现基于lua加redis桶实现,需要引入Redis的依赖和Redis的相关数据源配置,Redis依赖如下:

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-data-redis-reactive</artifactId>
  4. </dependency>

Redis限流有两个参数需要配置,redis-rate-limiter.replenishRate是您希望允许用户每秒处理多少个请求,而不会丢失任何请求;redis-rate-limiter.burstCapacity是用户允许在一秒钟内完成的最大请求数,这是令牌桶可以容纳的令牌的数量,将此值设置为零将阻止所有请求。

过滤器采用可选的keyResolver参数特定于限流,可选参数可以自定义设置,以下为一个根据romoteAddress的demo配置(注意需要配置为一个spring bean):

  1. @Configuration
  2. public class RequestRateLimiterConfig {
  3. @Bean
  4. public KeyResolver addressKeyResolver() {
  5. return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress());
  6. }
  7. }

RequestRateLimiter属于GatewayFilter Factories一种,所以需要在RouteLocator中加入为具体Route项加入或者在配置文件application.yml中配置:

如采用redis限流application.yml配置如下:

  1. spring:
  2. cloud:
  3. gateway:
  4. routes:
  5. - id: requestratelimiter_route
  6. uri: http://example.org
  7. filters:
  8. - name: RequestRateLimiter
  9. args:
  10. redis-rate-limiter.replenishRate: 10
  11. redis-rate-limiter.burstCapacity: 20

如果自定义RequestRateLimiter的application.yml配置如下:

  1. spring:
  2. cloud:
  3. gateway:
  4. routes:
  5. - id: requestratelimiter_route
  6. uri: http://example.org
  7. filters:
  8. - name: RequestRateLimiter
  9. args:
  10. rate-limiter: "#{@myRateLimiter}"
  11. key-resolver: "#{@userKeyResolver}"

使用SpEL按名称引用bean。#{@ myRateLimiter}是引用名为myRateLimiter的bean的SpEL表达式。

使用RouteLocator中加入为具体Route项配置在下文RouteLocator配置中会提供demo.

4.权重路由(WeightRoutePredicateFactory)

WeightRoutePredicateFactory是一个路由断言工厂,采用分组的方式来实现权重路由,同样可以采用application.yml或者RouteLocator进行配置:

  1. spring:
  2. application:
  3. name: gateway
  4. cloud:
  5. gateway:
  6. routes:
  7. - id: provide1
  8. uri: http://localhost:8080/provide
  9. predicates:
  10. - Path=/test
  11. - Weight=provide, 90
  12. - id: provide2
  13. uri: http://localhost:8081/provide
  14. predicates:
  15. - Path=/test
  16. - Weight=provide, 10

RouteLocator配置下文中会提供demo。

5.Hystrix GatewayFilter Factory、 LoadBalancerClient Filter、DiscoveryClient Route Definition Locator的使用

Spring Cloud Gateway提供的这三个功能比较重要且基本都会用到,但比较简单放一块来说明。

Hystrix GatewayFilter Factory需要引入如下依赖:

  1. <dependency>
  2. <groupId>org.springframework.cloud</groupId>
  3. <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
  4. </dependency>

配置如下:

  1. hystrix:
  2. command:
  3. default:
  4. execution:
  5. isolation:
  6. thread:
  7. timeoutInMilliseconds: 3000

DiscoveryClient Route Definition Locatorr需要在启动类加上@EnableDiscoveryClient注解并在配置文件中添加eureka或其他注册中心的配置,并且加入如下配置

  1. spring:
  2. cloud:
  3. gateway:
  4. discovery:
  5. locator:
  6. enabled: true

eureka的依赖如下:

  1. <dependency>
  2. <groupId>org.springframework.cloud</groupId>
  3. <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
  4. </dependency>

LoadBalancerClient Filter的使用比较简单,只需在url前加上lb,以下是这三部分综合使用的一个demo

  1. spring:
  2. cloud:
  3. gateway:
  4. discovery:
  5. locator:
  6. enabled: true
  7. routes:
  8. - id: Hystrix
  9. uri: lb://user
  10. predicates:
  11. - Path=/test/**
  12. filters:
  13. - name: Hystrix
  14. args:
  15. name: fallbackcmd
  16. fallbackUri: forward:/fallback

其中user是一个向注册中心注册名为user的服务。

7.Websocket Routing Filter

websocket的路由也比较简单在url前加上ws,如果还要使用LoadBalancerClient Filter和DiscoveryClient Route只需 lb: ws://serviceid 这样写url就可以。

8.RouteLocator

Spring Cloud Gateway为了在Java中进行简单的配置,在RouteLocatorBuilder bean中定义了流畅的API,以下提供与上文相关的demo配置:

  1. @Configuration
  2. public class RoutesConfig {
  3. @Autowired
  4. private KeyResolver addressKeyResolver;
  5. @Bean
  6. public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
  7. return builder.routes()
  8. //权重路由
  9. .route(r->r.weight("provide",90).and().path("/test/weight").filters(f -> f.retry(3).filter(new PreGatewayFilterFactory().apply()).filter(new PostGatewayFilterFactory().apply()).requestRateLimiter().rateLimiter(RedisRateLimiter.class,config -> config.setBurstCapacity(1).setReplenishRate(1)).configure(config -> config.setKeyResolver(addressKeyResolver)).stripPrefix(1).hystrix(config -> config.setFallbackUri("forward:/fallback").setName("fallbackcmd"))).uri("http://localhost:3001/test/weight"))
  10. .route(r->r.weight("provide",5).and().path("/test/weight").filters(f -> f.retry(3).filter(new PreGatewayFilterFactory().apply()).filter(new PostGatewayFilterFactory().apply()).requestRateLimiter().rateLimiter(RedisRateLimiter.class,config -> config.setBurstCapacity(1).setReplenishRate(1)).configure(config -> config.setKeyResolver(addressKeyResolver)).stripPrefix(1).hystrix(config -> config.setFallbackUri("forward:/fallback").setName("fallbackcmd"))).uri("http://localhost:3002/test/weight"))
  11. //集成了可能会用到的各种filter
  12. .route(r -> r.path("/test/**").filters(f -> f.retry(3).filter(new PreGatewayFilterFactory().apply()).filter(new PostGatewayFilterFactory().apply()).requestRateLimiter().rateLimiter(RedisRateLimiter.class,config -> config.setBurstCapacity(1).setReplenishRate(1)).configure(config -> config.setKeyResolver(addressKeyResolver)).stripPrefix(1).hystrix(config -> config.setFallbackUri("forward:/fallback").setName("fallbackcmd"))).uri("lb://user"))
  13. .build();
  14. }
  15. }