一步一步学SpringCloud--getway配置详解

灰太狼 2022-03-19 15:51 831阅读 0赞

SpringCloud Gateway配置详解

  • 前言
  • 一、引入pom依赖
  • 二、配置文件
    • 1、路由配置
    • 2、跨域配置
  • 三、重要的filter
    • 1、StripPrefix
    • 2、Hystrix熔断
    • 3、自定义gateway filter
    • 4、自定义限流gateway filter

前言

在上一篇文章中简单的介绍了SpringCloud Gateway,同时也对比了一下springcloud的gateway和Netflix的zuul,相信大家也有了一定的认识。此篇文章主要介绍一下gateway是如何配置的。同其他

一、引入pom依赖

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

二、配置文件

1、路由配置

  1. spring:
  2. application:
  3. name: gateway
  4. profiles:
  5. active: dev
  6. cloud:
  7. gateway:
  8. discovery:
  9. locator:
  10. enabled: true
  11. lower-case-service-id: true
  12. routes:
  13. - id: foo # foo服务
  14. uri: lb://integral-foo
  15. predicates:
  16. - Path=/foo-web/**
  17. filters:
  18. - StripPrefix=1
  19. server:
  20. port: 1001
  21. eureka:
  22. instance:
  23. instance-id: ${ spring.application.name}:${ random.int}
  24. prefer-ip-address: true
  25. client:
  26. service-url:
  27. defaultZone: http://localhost:8761/eureka
  • routes:具体的路由信息,是一个数组

    • id:这个路由的唯一id,不定义的话默认为一个uuid
    • uri:http请求为lb://前缀+服务id;ws请求为lb:ws://前缀+服务id,表示将请求负载到哪个服务上
    • predicates:表示这个路由的请求匹配规则,只有符合这个规则的请求才会走这个路由。每个规则为并且的关系。
    • filters:请求转发前的filter
    • order:这个路由的执行order

2、跨域配置

  1. spring:
  2. application:
  3. name: gateway
  4. profiles:
  5. active: dev
  6. cloud:
  7. gateway:
  8. globalcors:
  9. corsConfigurations:
  10. '[/**]':
  11. maxAge: 1800
  12. allowedOrigins: "*"
  13. allowCredentials: true
  14. allowedMethods:
  15. - GET
  16. - POST
  17. - PUT
  18. - DELETE
  • allowedOrigins:允许的请求
  • allowCredentials:允许凭证
  • allowedMethods:允许的方法请求方式

关于跨域的配置SpringCloud Gateway官网上写的已经很详细了。但是有一点没有提到,前后端交互的时候OPTIONS请求没有跨过去,yml文件里面只能配置get,post,put,delete等等这些请求,配置了OPTIONS不起作用。那么就需要我们再添加一个配置类来专门处理OPTIONS请求。

  1. /** * @author 刘子腾 * @DESCRIPTION 网关跨域 * @create 2019/3/12 */
  2. @Configuration
  3. public class CorsConfig {
  4. private static final String ALL = "*";
  5. private static final String MAX_AGE = "18000";
  6. @Bean
  7. public WebFilter corsFilter() {
  8. return (ServerWebExchange ctx, WebFilterChain chain) -> {
  9. ServerHttpRequest request = ctx.getRequest();
  10. if (!CorsUtils.isCorsRequest(request)) {
  11. return chain.filter(ctx);
  12. }
  13. HttpHeaders requestHeaders = request.getHeaders();
  14. ServerHttpResponse response = ctx.getResponse();
  15. HttpMethod requestMethod = requestHeaders.getAccessControlRequestMethod();
  16. HttpHeaders headers = response.getHeaders();
  17. headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, requestHeaders.getOrigin());
  18. headers.addAll(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, requestHeaders.getAccessControlRequestHeaders());
  19. if (requestMethod != null) {
  20. headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, requestMethod.name());
  21. }
  22. headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
  23. headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, ALL);
  24. headers.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, MAX_AGE);
  25. if (request.getMethod() == HttpMethod.OPTIONS) {
  26. response.setStatusCode( HttpStatus.OK);
  27. return Mono.empty();
  28. }
  29. return chain.filter(ctx);
  30. };
  31. }
  32. }

三、重要的filter

1、StripPrefix

  1. spring:
  2. cloud:
  3. gateway:
  4. routes:
  5. - id: nameRoot
  6. uri: lb://nameservice
  7. predicates:
  8. - Path=/name/**
  9. filters:
  10. - StripPrefix=1

/name/bar/foo的请求会被转发为http://nameserviceip:nameserviceport/bar/foo

2、Hystrix熔断

1)引入pom依赖

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

2)配置文件

  1. spring:
  2. cloud:
  3. gateway:
  4. default-filters:
  5. routes:
  6. #------------------------------------------------------------------------
  7. - id: i5xforyou-biz-auth
  8. uri: lb://i5xforyou-biz-auth
  9. predicates:
  10. - Path= ${ server.servlet.context-path}/auth/**
  11. filters:
  12. - StripPrefix= 1
  13. - name: Hystrix
  14. args:
  15. name: authHystrixCommand
  16. fallbackUri: forward:/hystrixTimeout
  17. #设置断路由的超时时间,毫秒
  18. hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds= 30000

name表示HystrixCommand代码的名称,fallbackUri表示触发断路由后的跳转请求url

3、自定义gateway filter

自定义一个用来检验jwt是否合法的gateway filter为例进行说明。

1)定义一个JwtCheckGatewayFilterFactory类实现GatewayFilterFactory接口。
类名一定要为filterName + GatewayFilterFactory,如这里定义为JwtCheckGatewayFilterFactory的话,它的filterName就是JwtCheck

2)实现gateway filter的业务逻辑

  1. @Component
  2. public class JwtCheckGatewayFilterFactory extends AbstractGatewayFilterFactory<Object> {
  3. @Override
  4. public GatewayFilter apply(Object config) {
  5. return (exchange, chain) -> {
  6. //return chain.filter(exchange);
  7. String jwtToken = exchange.getRequest().getHeaders().getFirst("Authorization");
  8. //校验jwtToken的合法性
  9. if (JwtUtil.verifyToken(jwtToken) != null) {
  10. //合法
  11. return chain.filter(exchange);
  12. }
  13. //不合法
  14. ServerHttpResponse response = exchange.getResponse();
  15. //设置headers
  16. HttpHeaders httpHeaders = response.getHeaders();
  17. httpHeaders.add("Content-Type", "application/json; charset=UTF-8");
  18. httpHeaders.add("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0");
  19. //设置body
  20. JsonPackage jsonPackage = new JsonPackage();
  21. jsonPackage.setStatus(110);
  22. jsonPackage.setMessage("未登录或登录超时");
  23. DataBuffer bodyDataBuffer = response.bufferFactory().wrap(jsonPackage.toJSONString().getBytes());
  24. return response.writeWith(Mono.just(bodyDataBuffer));
  25. };
  26. }
  27. }

3)配置文件

  1. spring:
  2. cloud:
  3. gateway:
  4. default-filters:
  5. routes:
  6. #------------------------------------------------------------------------
  7. - id: i5xforyou-biz-auth
  8. uri: lb://i5xforyou-biz-auth
  9. predicates:
  10. - Path= ${ server.servlet.context-path}/auth/**
  11. filters:
  12. - StripPrefix= 1
  13. - JwtCheck

4、自定义限流gateway filter

gateway自带的RequestRateLimiter可定制的内容太少,真正用的话,需要:

  1. 自定义限流后的response返回值
  2. 不同的key(即接口)限流数不同

发表评论

表情:
评论列表 (有 0 条评论,831人围观)

还没有评论,来说两句吧...

相关阅读

    相关 配置Spring

    本文旨在从一个空工程一步一步地配置Spring,空工程见上一篇文章[创建Maven父子工程][Maven]。 \\一、spring基本配置 \\\1. 添加spring依赖