pom配置

报错配置:spring.main.web-application-type: reactive
或者移除web

  1. <dependency>
  2. <!-- 如果启动GateWay报错 可能是GateWay模块引入了web和监控的starter依赖,需要移除-->
  3. <groupId>org.springframework.cloud</groupId>
  4. <artifactId>spring-cloud-starter-gateway</artifactId>
  5. </dependency>

yml配置

  1. spring:
  2. application:
  3. name: cloud-gateway
  4. cloud:
  5. gateway:
  6. discovery:
  7. locator:
  8. enabled: true #开启从注册中心动态创建路由的功能,利用微服务名进行路由
  9. routes:
  10. - id: payment_routh #payment_route #路由的ID,没有固定规则但要求唯一,建议配合服务名
  11. #uri: http://localhost:8001 #匹配后提供服务的路由地址
  12. uri: lb://cloud-payment-service #匹配后提供服务的路由地址
  13. predicates:
  14. - Path=/payment/get/** # 断言,路径相匹配的进行路由
  15. - id: payment_routh2 #payment_route #路由的ID,没有固定规则但要求唯一,建议配合服务名
  16. #uri: http://localhost:8001 #匹配后提供服务的路由地址
  17. uri: lb://cloud-payment-service #匹配后提供服务的路由地址
  18. predicates:
  19. - Path=/payment/lb/** # 断言,路径相匹配的进行路由
  20. - After=2020-03-08T10:59:34.102+08:00[Asia/Shanghai] # 断言,ZonedDateTime now()只有在这个时间后才可以访问,否则404
  21. # - Before=2020-03-08T10:59:34.102+08:00[Asia/Shanghai]
  22. # - Between=2020-03-08T10:59:34.102+08:00[Asia/Shanghai] , 2020-03-08T10:59:34.102+08:00[Asia/Shanghai]
  23. # curl http://localhost:9527/payment/lb --cookie "username=zzyy"
  24. # - Cookie=username,zzyy #Cookie=cookieName,正则表达式
  25. # 请求头要有X-Request-Id属性并且值为整数的正则表达式 curl http://localhost:9527/payment/lb --cookie "username=zzyy" -H "X-Request-Id:11"
  26. # - Header=X-Request-Id, \d+
  27. # - Host=**.atguigu.com # curl http://localhost:9527/payment/lb -H "Host:afae.atguigu.com"

yml配置2

  1. server:
  2. port: 8009
  3. spring:
  4. application:
  5. name: demo-seata
  6. # cloud:
  7. # nacos:
  8. # server-addr: 192.168.2.20:30010
  9. # username: nacos
  10. # password: nacos
  11. sentinel:
  12. transport:
  13. dashboard: 192.168.2.20:31596 # 控制台的安装位置
  14. main:
  15. web-application-type: reactive
  16. cloud:
  17. gateway:
  18. discovery:
  19. locator:
  20. enabled: true
  21. routes:
  22. - id: demo-eureka-client
  23. uri: lb://demo-eureka-client
  24. predicates:
  25. - Path=/eureka-client/**
  26. # profiles:
  27. # active: public
  28. # port: 8719 # 与sentinel单独连接的端口
  29. # client-ip: 192.168.2.6 # 本机的ip,如果sentinel装在虚拟机,必须配这个
  30. # port: 30195 # 与sentinel单独连接的端口
  31. # client-ip: 192.168.2.20 # 本机的ip,如果sentinel装在虚拟机,必须配这个
  32. eureka:
  33. client:
  34. service-url:
  35. defaultZone: http://localhost:7001/eureka
  36. logging:
  37. level:
  38. root: debug

gateway响应式异常处理

handler

  1. package com.demo.gateway.common.filter;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.springframework.boot.autoconfigure.web.ErrorProperties;
  4. import org.springframework.boot.autoconfigure.web.ResourceProperties;
  5. import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler;
  6. import org.springframework.boot.web.error.ErrorAttributeOptions;
  7. import org.springframework.boot.web.reactive.error.ErrorAttributes;
  8. import org.springframework.context.ApplicationContext;
  9. import org.springframework.http.HttpStatus;
  10. import org.springframework.http.MediaType;
  11. import org.springframework.web.reactive.function.BodyInserters;
  12. import org.springframework.web.reactive.function.server.RequestPredicates;
  13. import org.springframework.web.reactive.function.server.RouterFunction;
  14. import org.springframework.web.reactive.function.server.RouterFunctions;
  15. import org.springframework.web.reactive.function.server.ServerRequest;
  16. import org.springframework.web.reactive.function.server.ServerResponse;
  17. import reactor.core.publisher.Mono;
  18. import java.util.HashMap;
  19. import java.util.Map;
  20. import java.util.Objects;
  21. /**
  22. * <p>
  23. * 全局异常处理
  24. * </p>
  25. */
  26. @Slf4j
  27. public class GlobalExceptionHandler extends DefaultErrorWebExceptionHandler {
  28. public GlobalExceptionHandler(ErrorAttributes errorAttributes, ResourceProperties resourceProperties, ErrorProperties errorProperties, ApplicationContext applicationContext) {
  29. super(errorAttributes, resourceProperties, errorProperties, applicationContext);
  30. }
  31. /**
  32. * 统一处理异常信息
  33. */
  34. protected Map<String, Object> getErrorMap(ServerRequest request, Throwable error) {
  35. Map<String, Object> errorAttributes = new HashMap<>(8);
  36. errorAttributes.put("message", error.getMessage());
  37. errorAttributes.put("code", HttpStatus.INTERNAL_SERVER_ERROR.value());
  38. errorAttributes.put("method", request.methodName());
  39. errorAttributes.put("path", request.path());
  40. return errorAttributes;
  41. }
  42. /**
  43. * 统一处理异常信息
  44. */
  45. @Override
  46. @SuppressWarnings(value = "unchecked")
  47. protected Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {
  48. Throwable error = super.getError(request);
  49. //调用处理异常的方法,并将对象转换成map
  50. return getErrorMap(request, error);
  51. }
  52. /**
  53. * Extract the error attributes from the current request, to be used to populate error
  54. * views or JSON payloads.
  55. * @param request the source request
  56. * @param options options to control error attributes
  57. * @return the error attributes as a Map
  58. */
  59. @Override
  60. protected Map<String, Object> getErrorAttributes(ServerRequest request, ErrorAttributeOptions options) {
  61. Throwable error = super.getError(request);
  62. return getErrorMap(request, error);
  63. }
  64. @Override
  65. protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
  66. return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
  67. }
  68. @Override
  69. protected Mono<ServerResponse> renderErrorResponse(ServerRequest request) {
  70. boolean includeStackTrace = isIncludeStackTrace(request, MediaType.ALL);
  71. Map<String, Object> error = getErrorAttributes(request, includeStackTrace);
  72. return ServerResponse
  73. .status(getHttpStatus(error))
  74. .contentType(MediaType.APPLICATION_JSON)
  75. .body(BodyInserters.fromValue(error));
  76. }
  77. @Override
  78. protected int getHttpStatus(Map<String, Object> errorAttributes) {
  79. HttpStatus status = (HttpStatus) errorAttributes.get("status");
  80. if (Objects.isNull(status)) {
  81. return HttpStatus.OK.value();
  82. }
  83. return status.value();
  84. }
  85. }

config

  1. package com.demo.gateway.common.config;
  2. import com.demo.gateway.common.filter.GlobalExceptionHandler;
  3. import org.springframework.beans.factory.ObjectProvider;
  4. import org.springframework.boot.autoconfigure.web.ResourceProperties;
  5. import org.springframework.boot.autoconfigure.web.ServerProperties;
  6. import org.springframework.boot.context.properties.EnableConfigurationProperties;
  7. import org.springframework.boot.web.reactive.error.ErrorAttributes;
  8. import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
  9. import org.springframework.context.ApplicationContext;
  10. import org.springframework.context.annotation.Bean;
  11. import org.springframework.core.annotation.Order;
  12. import org.springframework.http.codec.ServerCodecConfigurer;
  13. import org.springframework.stereotype.Component;
  14. import org.springframework.web.reactive.result.view.ViewResolver;
  15. import java.util.Collections;
  16. import java.util.List;
  17. /**
  18. * @author yuwenbo
  19. */
  20. @Component
  21. @EnableConfigurationProperties({ServerProperties.class, ResourceProperties.class})
  22. public class ErrorHandlerConfiguration {
  23. private final ServerProperties serverProperties;
  24. private final ApplicationContext applicationContext;
  25. private final ResourceProperties resourceProperties;
  26. private final List<ViewResolver> viewResolvers;
  27. private final ServerCodecConfigurer serverCodecConfigurer;
  28. public ErrorHandlerConfiguration(ServerProperties serverProperties,
  29. ResourceProperties resourceProperties,
  30. ObjectProvider<List<ViewResolver>> viewResolversProvider,
  31. ServerCodecConfigurer serverCodecConfigurer,
  32. ApplicationContext applicationContext) {
  33. this.serverProperties = serverProperties;
  34. this.applicationContext = applicationContext;
  35. this.resourceProperties = resourceProperties;
  36. this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
  37. this.serverCodecConfigurer = serverCodecConfigurer;
  38. }
  39. @Bean
  40. @Order(Integer.MIN_VALUE)
  41. public ErrorWebExceptionHandler errorWebExceptionHandler(ErrorAttributes errorAttributes) {
  42. GlobalExceptionHandler exceptionHandler = new GlobalExceptionHandler(
  43. errorAttributes,
  44. this.resourceProperties,
  45. this.serverProperties.getError(),
  46. this.applicationContext);
  47. exceptionHandler.setViewResolvers(this.viewResolvers);
  48. exceptionHandler.setMessageWriters(this.serverCodecConfigurer.getWriters());
  49. exceptionHandler.setMessageReaders(this.serverCodecConfigurer.getReaders());
  50. return exceptionHandler;
  51. }
  52. }

参考

异常处理:https://www.cnblogs.com/duanxz/p/14786337.html