经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Java » 查看文章
Spring Cloud 之 Gateway.
来源:cnblogs  作者:JMCui  时间:2019/7/29 9:19:25  对本文有异议

一、Gateway 和 Zuul 的区别

Zuul 基于servlet 2.5 (works with 3.x),使用阻塞API。它不支持任何长期的连接,如websocket。

Gateway建立在Spring Framework 5,Project Reactor 和Spring Boot 2 上,使用非阻塞API。支持Websocket,因为它与Spring紧密集成,所以它是一个更好的开发者体验。

为什么 Spring Cloud 最初选择了使用 Netflix 几年前开源的 Zuul 作为网关,之后又选择了自建 Gateway 呢?有一种说法是,高性能版的 Zuul2 在经过了多次跳票之后,对于 Spring 这样的整合专家可能也不愿意再继续等待,所以 Spring Cloud Gateway 应运而生。

本文不对 Spring Cloud Gateway 和 Zuul 的性能作太多赘述,基本可以肯定的是 Gateway 作为现在 Spring Cloud 主推的网关方案, Finchley 版本后的 Gateway 比 zuul 1.x 系列的性能和功能整体要好。

二、快速入门

我们来搭建一个基于 Eureka 注册中心的简单网关,不对 Gateway 的全部功能做过多解读,毕竟官方文档已经写的很详细了,或者可以阅读中文翻译文档

SpringBoot 版本号:2.1.6.RELEASE

SpringCloud 版本号:Greenwich.RELEASE

1. pom.xml

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.cloud</groupId>
  4. <artifactId>spring-cloud-starter-gateway</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework.cloud</groupId>
  8. <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
  9. </dependency>
  10. <dependency>
  11. <groupId>org.springframework.cloud</groupId>
  12. <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
  13. </dependency>
  14. <dependency>
  15. <groupId>org.springframework.boot</groupId>
  16. <artifactId>spring-boot-starter-data-redis-reactive</artifactId>
  17. </dependency>
  18. <dependency>
  19. <groupId>org.springframework.boot</groupId>
  20. <artifactId>spring-boot-starter-actuator</artifactId>
  21. </dependency>
  22. </dependencies>
  • spring-cloud-starter-gateway:Spring Cloud Gateway 的启动类
  • spring-cloud-starter-netflix-hystrix:Hystrix 作为网关的熔断方案
  • spring-cloud-starter-netflix-eureka-client:将网关纳入 Eureka 注册中心管理
  • spring-boot-starter-data-redis-reactive:限流方案,Spring Cloud Gateway 默认以 redis 实现限流
  • spring-boot-starter-actuator:用来监控 Gateway 的路由信息。

2. application.yml

  1. spring:
  2. application:
  3. name: cloud-gateway
  4. redis:
  5. host: 127.0.0.1
  6. timeout: 3000
  7. password: xxxx
  8. jedis:
  9. pool:
  10. max-active: 8
  11. max-idle: 4
  12. cloud:
  13. gateway:
  14. enabled: true
  15. metrics:
  16. enabled: true
  17. discovery:
  18. locator:
  19. enabled: true
  20. routes:
  21. # 普通服务的路由配置
  22. - id: cloud-eureka-client
  23. uri: lb://cloud-eureka-client
  24. order: 0
  25. predicates:
  26. - Path=/client/**
  27. filters:
  28. # parts 参数指示在将请求发送到下游之前,要从请求中去除的路径中的节数。比如我们访问 /client/hello,调用的时候变成 http://localhost:2222/hello
  29. - StripPrefix=1
  30. # 熔断器
  31. - name: Hystrix
  32. args:
  33. name: fallbackcmd
  34. # 降级处理
  35. fallbackUri: forward:/fallback
  36. # 限流器
  37. # 这定义了每个用户 10 个请求的限制。允许 20 个突发,但下一秒只有 10 个请求可用。
  38. - name: RequestRateLimiter
  39. args:
  40. # SPEL 表达式获取 Spring 中的 Bean,这个参数表示根据什么来限流
  41. key-resolver: '#{@ipKeyResolver}'
  42. # 允许用户每秒执行多少请求(令牌桶的填充速率)
  43. redis-rate-limiter.replenishRate: 10
  44. # 允许用户在一秒内执行的最大请求数。(令牌桶可以保存的令牌数)。将此值设置为零将阻止所有请求。
  45. redis-rate-limiter.burstCapacity: 20
  46. # websocket 的路由配置
  47. - id: websocket service
  48. uri: lb:ws://serviceid
  49. predicates:
  50. - Path=/websocket/**
  51. management:
  52. endpoints:
  53. web:
  54. exposure:
  55. # 开启指定端点
  56. include: gateway,metrics
  57. eureka:
  58. client:
  59. service-url:
  60. defaultZone: http://user:password@localhost:1111/eureka/
  • spring.redis.*: redis 相关配置是为了实现 Gateway 的限流方案。
  • eureka.client.*:eureka 注册中心信息。
  • spring.cloud.gateway.discovery.locator.enabled:将网关配置为基于使用兼容 DiscoveryClient 注册中心注册的服务来创建路由。
  • spring.cloud.gateway.routes.*:配置路由信息
    • id:路由唯一标识
    • uri:路由转发地址,以 lb 开头的路由,会由 ribbon 处理,转发到 cloud-eureka-client 的服务处理。也可配置成 http 的单机路由 — http://localhost:2222。
    • order:路由执行顺序(也可理解成过滤器的执行顺序),执行顺序是从小到大执行,较高的值被解释为较低的优先级。
    • predicates:路由断言,匹配访问路径为 "/client/**" 的请求。
    • filters:网关的过滤器配置
  • management.endpoints.web.exposure.include:暴露 actuator 可以访问的端点
    • /actuator/gateway/routes 查看路由列表
    • /actuator/gateway/globalfilters 检索全局路由 — 对所有路由生效
    • /actuator/gateway/routefilters 检索局部路由 — 可配置只对单个路由生效
    • /actuator/gateway/refresh 清理路由缓存
    • /actuator/metrics/gateway.requests 获得路由请求数据

3. GatewayApplication.java

  1. @SpringBootApplication
  2. @EnableDiscoveryClient
  3. public class GatewayApplication {
  4. public static void main(String[] args) {
  5. SpringApplication.run(GatewayApplication.class, args);
  6. }
  7. /**
  8. * 限流的键定义,根据什么来限流
  9. */
  10. @Bean
  11. public KeyResolver ipKeyResolver() {
  12. return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
  13. }
  14. }

三、过滤器

Spring Cloud Gateway 同 Zuul 类似,有 “pre” 和 “post” 两种方式的 filter。客户端的请求先经过 “pre” 类型的 filter,然后将请求转发到具体的业务服务,收到业务服务的响应之后,再经过“post”类型的filter处理,最后返回响应到客户端。

与 Zuul 不同的是,filter 除了分为 “pre” 和 “post” 两种方式的 filter 外,在 Spring Cloud Gateway 中,filter 从作用范围可分为另外两种,一种是针对于单个路由的 gateway filter,它需要像上面 application.yml 中的 filters 那样在单个路由中配置;另外一种是针对于全部路由的global gateway filter,不需要单独配置,对所有路由生效。

全局过滤器

我们通常用全局过滤器实现鉴权、验签、限流、日志输出等。

通过实现 GlobalFilter 接口来自定义 Gateway 的全局过滤器;通过实现 Ordered 接口或者使用 @Order 注解来定义过滤器的执行顺序,执行顺序是从小到大执行,较高的值被解释为较低的优先级。

  1. @Bean
  2. @Order(-1)
  3. public GlobalFilter a() {
  4. return (exchange, chain) -> {
  5. log.info("first pre filter");
  6. return chain.filter(exchange).then(Mono.fromRunnable(() -> {
  7. log.info("third post filter");
  8. }));
  9. };
  10. }
  11. @Bean
  12. @Order(0)
  13. public GlobalFilter b() {
  14. return (exchange, chain) -> {
  15. log.info("second pre filter");
  16. return chain.filter(exchange).then(Mono.fromRunnable(() -> {
  17. log.info("second post filter");
  18. }));
  19. };
  20. }
  21. @Bean
  22. @Order(1)
  23. public GlobalFilter c() {
  24. return (exchange, chain) -> {
  25. log.info("third pre filter");
  26. return chain.filter(exchange).then(Mono.fromRunnable(() -> {
  27. log.info("first post filter");
  28. }));
  29. };
  30. }

优先级最高的 filter ,它的 “pre” 过滤器最先执行,“post” 过滤器最晚执行。

局部过滤器

我们来定义一个 “pre” 类型的局部过滤器:

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

其中,需要的过滤器参数配置在 PreGatewayFilterFactory.Config 中。然后,接下来我们要做的,就是把局部过滤器配置在需要的路由上,根据 SpringBoot 约定大于配置的思想,我们只需要配置 PreGatewayFilterFactory.java 中,前面的参数就行了,即

  1. spring:
  2. cloud:
  3. gateway:
  4. routes:
  5. - id: cloud-eureka-client
  6. uri: lb://cloud-eureka-client
  7. order: 0
  8. predicates:
  9. - Path=/client/**
  10. filters:
  11. - pre

tips:可以去阅读下 Gateway 中默认提供的几种过滤器,比如 StripPrefixGatewayFilterFactory.java 等。

四、动态路由

Spring Cloud Gateway 实现动态路由主要利用 RouteDefinitionWriter 这个 Bean:

  1. public interface RouteDefinitionWriter {
  2. Mono<Void> save(Mono<RouteDefinition> route);
  3. Mono<Void> delete(Mono<String> routeId);
  4. }

之前翻阅了网上的一些文章,基本都是通过自定义 controller 和出入参,然后利用 RouteDefinitionWriter 实现动态网关。但是,我在翻阅 Spring Cloud Gateway 文档的时候,发现 Gateway 已经提供了类似的功能:

  1. @RestControllerEndpoint(id = "gateway")
  2. public class GatewayControllerEndpoint implements ApplicationEventPublisherAware {
  3. /*---省略前面代码---*/
  4. @PostMapping("/routes/{id}")
  5. @SuppressWarnings("unchecked")
  6. public Mono<ResponseEntity<Void>> save(@PathVariable String id, @RequestBody Mono<RouteDefinition> route) {
  7. return this.routeDefinitionWriter.save(route.map(r -> {
  8. r.setId(id);
  9. log.debug("Saving route: " + route);
  10. return r;
  11. })).then(Mono.defer(() ->
  12. Mono.just(ResponseEntity.created(URI.create("/routes/"+id)).build())
  13. ));
  14. }
  15. @DeleteMapping("/routes/{id}")
  16. public Mono<ResponseEntity<Object>> delete(@PathVariable String id) {
  17. return this.routeDefinitionWriter.delete(Mono.just(id))
  18. .then(Mono.defer(() -> Mono.just(ResponseEntity.ok().build())))
  19. .onErrorResume(t -> t instanceof NotFoundException, t -> Mono.just(ResponseEntity.notFound().build()));
  20. }
  21. /*---省略后面代码---*/
  22. }

要创建一个路由,发送POST请求 /actuator/gateway/routes/{id_route_to_create},参数为JSON结构,具体参数数据结构:

  1. {
  2. "id": "first_route",
  3. "predicates": [{
  4. "name": "Path",
  5. "args": {"_genkey_0":"/first"}
  6. }],
  7. "filters": [],
  8. "uri": "http://www.uri-destination.org",
  9. "order": 0
  10. }]

要删除一个路由,发送 DELETE请求 /actuator/gateway/routes/{id_route_to_delete}

五、附录

原文链接:http://www.cnblogs.com/jmcui/p/11259200.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号