Spring Cloud Gateway-自定义异常处理

参考 https://blog.youkuaiyun.com/suyuaidan/article/details/132663141,写法不同于注入方式不一样

ErrorWebFluxAutoConfiguration

@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
@ConditionalOnClass(WebFluxConfigurer.class)
@AutoConfigureBefore(WebFluxAutoConfiguration.class)
@EnableConfigurationProperties({ ServerProperties.class, ResourceProperties.class })
public class ErrorWebFluxAutoConfiguration {

	private final ServerProperties serverProperties;

	public ErrorWebFluxAutoConfiguration(ServerProperties serverProperties) {
		this.serverProperties = serverProperties;
	}

	@Bean
	@ConditionalOnMissingBean(value = ErrorWebExceptionHandler.class, search = SearchStrategy.CURRENT)
	@Order(-1)
	public ErrorWebExceptionHandler errorWebExceptionHandler(ErrorAttributes errorAttributes,
			ResourceProperties resourceProperties, ObjectProvider<ViewResolver> viewResolvers,
			ServerCodecConfigurer serverCodecConfigurer, ApplicationContext applicationContext) {
		DefaultErrorWebExceptionHandler exceptionHandler = new DefaultErrorWebExceptionHandler(errorAttributes,
				resourceProperties, this.serverProperties.getError(), applicationContext);
		exceptionHandler.setViewResolvers(viewResolvers.orderedStream().collect(Collectors.toList()));
		exceptionHandler.setMessageWriters(serverCodecConfigurer.getWriters());
		exceptionHandler.setMessageReaders(serverCodecConfigurer.getReaders());
		return exceptionHandler;
	}

	@Bean
	@ConditionalOnMissingBean(value = ErrorAttributes.class, search = SearchStrategy.CURRENT)
	public DefaultErrorAttributes errorAttributes() {
		return new DefaultErrorAttributes();
	}

}

DefaultErrorWebExceptionHandler

public class DefaultErrorWebExceptionHandler extends AbstractErrorWebExceptionHandler {

	private static final MediaType TEXT_HTML_UTF8 = new MediaType("text", "html", StandardCharsets.UTF_8);

	private static final Map<HttpStatus.Series, String> SERIES_VIEWS;

	static {
		Map<HttpStatus.Series, String> views = new EnumMap<>(HttpStatus.Series.class);
		views.put(HttpStatus.Series.CLIENT_ERROR, "4xx");
		views.put(HttpStatus.Series.SERVER_ERROR, "5xx");
		SERIES_VIEWS = Collections.unmodifiableMap(views);
	}

	private final ErrorProperties errorProperties;

	/**
	 * Create a new {@code DefaultErrorWebExceptionHandler} instance.
	 * @param errorAttributes the error attributes
	 * @param resourceProperties the resources configuration properties
	 * @param errorProperties the error configuration properties
	 * @param applicationContext the current application context
	 */
	public DefaultErrorWebExceptionHandler(ErrorAttributes errorAttributes, ResourceProperties resourceProperties,
			ErrorProperties errorProperties, ApplicationContext applicationContext) {
		super(errorAttributes, resourceProperties, applicationContext);
		this.errorProperties = errorProperties;
	}

	@Override
	protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
		return route(acceptsTextHtml(), this::renderErrorView).andRoute(all(), this::renderErrorResponse);
	}

	/**
	 * Render the error information as an HTML view.
	 * @param request the current request
	 * @return a {@code Publisher} of the HTTP response
	 */
	protected Mono<ServerResponse> renderErrorView(ServerRequest request) {
		Map<String, Object> error = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.TEXT_HTML));
		int errorStatus = getHttpStatus(error);
		ServerResponse.BodyBuilder responseBody = ServerResponse.status(errorStatus).contentType(TEXT_HTML_UTF8);
		return Flux.just(getData(errorStatus).toArray(new String[] {}))
				.flatMap((viewName) -> renderErrorView(viewName, responseBody, error))
				.switchIfEmpty(this.errorProperties.getWhitelabel().isEnabled()
						? renderDefaultErrorView(responseBody, error) : Mono.error(getError(request)))
				.next();
	}

	private List<String> getData(int errorStatus) {
		List<String> data = new ArrayList<>();
		data.add("error/" + errorStatus);
		HttpStatus.Series series = HttpStatus.Series.resolve(errorStatus);
		if (series != null) {
			data.add("error/" + SERIES_VIEWS.get(series));
		}
		data.add("error/error");
		return data;
	}

	/**
	 * Render the error information as a JSON payload.
	 * @param request the current request
	 * @return a {@code Publisher} of the HTTP response
	 */
	protected Mono<ServerResponse> renderErrorResponse(ServerRequest request) {
		Map<String, Object> error = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL));
		return ServerResponse.status(getHttpStatus(error)).contentType(MediaType.APPLICATION_JSON)
				.body(BodyInserters.fromValue(error));
	}

	protected ErrorAttributeOptions getErrorAttributeOptions(ServerRequest request, MediaType mediaType) {
		ErrorAttributeOptions options = ErrorAttributeOptions.defaults();
		if (this.errorProperties.isIncludeException()) {
			options = options.including(Include.EXCEPTION);
		}
		if (isIncludeStackTrace(request, mediaType)) {
			options = options.including(Include.STACK_TRACE);
		}
		if (isIncludeMessage(request, mediaType)) {
			options = options.including(Include.MESSAGE);
		}
		if (isIncludeBindingErrors(request, mediaType)) {
			options = options.including(Include.BINDING_ERRORS);
		}
		return options;
	}

	/**
	 * Determine if the stacktrace attribute should be included.
	 * @param request the source request
	 * @param produces the media type produced (or {@code MediaType.ALL})
	 * @return if the stacktrace attribute should be included
	 */
	@SuppressWarnings("deprecation")
	protected boolean isIncludeStackTrace(ServerRequest request, MediaType produces) {
		switch (this.errorProperties.getIncludeStacktrace()) {
		case ALWAYS:
			return true;
		case ON_PARAM:
		case ON_TRACE_PARAM:
			return isTraceEnabled(request);
		default:
			return false;
		}
	}

	/**
	 * Determine if the message attribute should be included.
	 * @param request the source request
	 * @param produces the media type produced (or {@code MediaType.ALL})
	 * @return if the message attribute should be included
	 */
	protected boolean isIncludeMessage(ServerRequest request, MediaType produces) {
		switch (this.errorProperties.getIncludeMessage()) {
		case ALWAYS:
			return true;
		case ON_PARAM:
			return isMessageEnabled(request);
		default:
			return false;
		}
	}

	/**
	 * Determine if the errors attribute should be included.
	 * @param request the source request
	 * @param produces the media type produced (or {@code MediaType.ALL})
	 * @return if the errors attribute should be included
	 */
	protected boolean isIncludeBindingErrors(ServerRequest request, MediaType produces) {
		switch (this.errorProperties.getIncludeBindingErrors()) {
		case ALWAYS:
			return true;
		case ON_PARAM:
			return isBindingErrorsEnabled(request);
		default:
			return false;
		}
	}

	/**
	 * Get the HTTP error status information from the error map.
	 * @param errorAttributes the current error information
	 * @return the error HTTP status
	 */
	protected int getHttpStatus(Map<String, Object> errorAttributes) {
		return (int) errorAttributes.get("status");
	}

	/**
	 * Predicate that checks whether the current request explicitly support
	 * {@code "text/html"} media type.
	 * <p>
	 * The "match-all" media type is not considered here.
	 * @return the request predicate
	 */
	protected RequestPredicate acceptsTextHtml() {
		return (serverRequest) -> {
			try {
				List<MediaType> acceptedMediaTypes = serverRequest.headers().accept();
				acceptedMediaTypes.removeIf(MediaType.ALL::equalsTypeAndSubtype);
				MediaType.sortBySpecificityAndQuality(acceptedMediaTypes);
				return acceptedMediaTypes.stream().anyMatch(MediaType.TEXT_HTML::isCompatibleWith);
			}
			catch (InvalidMediaTypeException ex) {
				return false;
			}
		};
	}

}

观察上面的代码,我们可以知道我们要做两步工作

  1. 全局处理异常怎么操作(实现ErrorWebExceptionHandler,或者直接继承他的子类DefaultErrorWebExceptionHandler)
  2. 如何把异常处理注入到框架中(自定CustomErrorWebFluxAutoConfiguration)

自定义ErrorWebExceptionHandler

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.*;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * 自定义异常处理器
 */
@Slf4j
public class CustomErrorWebExceptionHandler extends DefaultErrorWebExceptionHandler {
    public CustomErrorWebExceptionHandler(ErrorAttributes errorAttributes, ResourceProperties resourceProperties,
                                          ErrorProperties errorProperties, ApplicationContext applicationContext) {
        super(errorAttributes, resourceProperties, errorProperties, applicationContext);
    }

    @Override
    protected Mono<ServerResponse> renderErrorResponse(ServerRequest request) {
        // 原始的异常信息可以用getError方法取得
        Throwable throwable = getError(request);
        // 这里和父类的做法一样,取得DefaultErrorAttributes整理出来的所有异常信息
        Map<String, Object> errorAttributes = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL));
        HttpStatus status = HttpStatus.valueOf((Integer) errorAttributes.get("status"));

        // todo 写你自己的逻辑也可根据status封装不同的结果集枚举
        Map<String, Object> responseBodyMap = new HashMap<>();
        responseBodyMap.put("code", "my error code");
        responseBodyMap.put("msg", throwable.getMessage());
        return ServerResponse
                // http返回码
                .status(HttpStatus.INTERNAL_SERVER_ERROR)
                // 类型和以前一样
                .contentType(MediaType.APPLICATION_JSON)
                // 响应body的内容
                .body(BodyInserters.fromValue(responseBodyMap));
    }


    @Override
    protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
        return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
    }

}

自定义CustomErrorWebFluxAutoConfiguration

import com.hatzi.gateway.plus.handler.CustomErrorWebExceptionHandler;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.condition.SearchStrategy;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.reactive.error.DefaultErrorAttributes;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.config.WebFluxConfigurer;
import org.springframework.web.reactive.result.view.ViewResolver;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description
 * @Author weiwenbin
 * @Date 2024/6/6 15:01
 */
@Configuration
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
@ConditionalOnClass(WebFluxConfigurer.class)
@AutoConfigureBefore(WebFluxAutoConfiguration.class)
@EnableConfigurationProperties({ServerProperties.class, ResourceProperties.class})
public class CustomErrorWebFluxAutoConfiguration {

    private final ServerProperties serverProperties;

    private final ApplicationContext applicationContext;

    private final ResourceProperties resourceProperties;

    private final List<ViewResolver> viewResolvers;

    private final ServerCodecConfigurer serverCodecConfigurer;

    public CustomErrorWebFluxAutoConfiguration(ServerProperties serverProperties,
                                               ResourceProperties resourceProperties,
                                               ObjectProvider<ViewResolver> viewResolversProvider,
                                               ServerCodecConfigurer serverCodecConfigurer,
                                               ApplicationContext applicationContext) {
        this.serverProperties = serverProperties;
        this.applicationContext = applicationContext;
        this.resourceProperties = resourceProperties;
        this.viewResolvers = viewResolversProvider.orderedStream()
                .collect(Collectors.toList());
        this.serverCodecConfigurer = serverCodecConfigurer;
    }

    @Bean
    @ConditionalOnMissingBean(value = ErrorWebExceptionHandler.class,
            search = SearchStrategy.CURRENT)
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public ErrorWebExceptionHandler errorWebExceptionHandler(ErrorAttributes errorAttributes) {
        CustomErrorWebExceptionHandler exceptionHandler = new CustomErrorWebExceptionHandler(
                errorAttributes,
                resourceProperties,
                this.serverProperties.getError(),
                applicationContext);
        exceptionHandler.setViewResolvers(this.viewResolvers);
        exceptionHandler.setMessageWriters(this.serverCodecConfigurer.getWriters());
        exceptionHandler.setMessageReaders(this.serverCodecConfigurer.getReaders());
        return exceptionHandler;
    }

  @Bean
    @ConditionalOnMissingBean(value = ErrorAttributes.class, search = SearchStrategy.CURRENT)
    public DefaultErrorAttributes errorAttributes() {
        return new DefaultErrorAttributes();
    }
}
<think>嗯,用户现在想了解SpringCloud Gateway作为API网关的作用和功能。之前我们讨论过OpenFeign的服务间调用,现在转向API网关,可能需要先理清两者的关系。用户可能是在构建微服务架构,需要了解不同组件的分工。SpringCloud Gateway和OpenFeign都属于SpringCloud生态,但职责不同,前者负责入口流量管理,后者处理服务间调用。首先,我需要根据提供的引用内容整理Gateway的作用。引用[1]提到它处理请求路由、认证授权、限流降级,高性能且与Spring生态集成。引用[2]补充了负载均衡、服务发现等功能。引用[4]提到Filter分为GatewayFilter和GlobalFilter,用于处理请求。用户的问题可能希望得到详细的功能分类,比如路由、过滤、负载均衡等。需要确保每个功能点都有对应的引用支持。同时,用户之前的讨论涉及OpenFeign的声明式调用和负载均衡,这里可以对比Gateway的负载均衡是服务端还是客户端?根据引用[2],Gateway自己处理负载均衡,可能集成Ribbon或者SpringCloud LoadBalancer。 需要注意回答的结构,按照核心作用分点,每个点下展开子功能。比如路由转发作为第一点,包括动态路由、路径匹配等。然后安全相关,如认证授权,接着是流量控制,如限流降级。还有过滤器机制,集成监控等。此外,要区分与Zuul的差异,比如性能更高,基于异步非阻塞模型。可能用户没有明确问比较,但提到其他网关如Zuul,可以简要说明优势。同时,确保每个功能点都有引用标注,比如动态路由引用[1][2],过滤器引用[4],限流引用[1][2]等。需要避免技术术语过于复杂,用易懂的语言解释。比如动态代理和路由的区别,可能需要关联用户之前了解的OpenFeign动态代理,但这里是网关级别的路由。另外,问题部分需要生成相关问题,可能涉及配置步骤、过滤器使用、性能优化、与Zuul对比、限流实现等,确保问题有逻辑关联,帮助用户深入理解。</think>### Spring Cloud Gateway作为API网关的作用与功能 --- #### 1. **统一入口与路由转发** - **动态路由配置**:通过简单的YAML或Java配置,将外部请求路由到不同的微服务实例[^1][^2]。例如,将`/user/**`的请求转发到用户服务,`/order/**`的请求转发到订单服务。 - **路径匹配与重写**:支持通配符、正则表达式匹配请求路径,并可对请求路径进行重写[^3]。 - **负载均衡**:集成服务发现(如Eureka、Consul),自动从注册中心获取服务实例列表,并通过负载均衡策略(如轮询、权重)分配请求[^2]。 #### 2. **安全控制与权限管理** - **认证与鉴权**:通过集成OAuth2、JWT等机制,实现请求的身份验证(如校验Token)和权限控制(如角色校验)[^1][^2]。 - **请求头处理**:可添加、修改或删除请求头,例如透传认证信息或添加自定义标头。 #### 3. **流量控制与容错保护** - **限流(Rate Limiting)**:基于令牌桶、漏桶算法限制接口的请求频率,防止突发流量压垮服务[^1][^2]。例如配置每秒最多100次请求。 - **熔断降级**:与Hystrix或Resilience4j集成,在服务响应超时或异常时触发熔断,返回预设的降级响应(如默认错误页)[^1]。 - **重试机制**:针对服务调用失败的情况,配置重试次数和条件(如仅对GET请求重试)。 #### 4. **请求与响应处理** - **过滤器链(Filters)**:通过内置或自定义的`GatewayFilter`和`GlobalFilter`,实现请求的预处理和响应的后处理[^4]。例如: - **日志记录**:记录请求参数和响应状态。 - **请求耗时统计**:添加计时过滤器统计接口性能。 - **请求体修改**:压缩请求内容或加密敏感数据。 - **跨域处理(CORS)**:统一配置跨域请求的允许来源、方法和头部信息。 #### 5. **监控与可观测性** - **集成监控工具**:支持对接Prometheus、Spring Boot Actuator,暴露网关的流量指标(如请求量、延迟、错误率)[^1]。 - **链路追踪**:通过集成Sleuth和Zipkin,为请求添加唯一Trace ID,实现全链路追踪。 #### 6. **性能优化** - **异步非阻塞模型**:基于Netty和Reactor实现高并发处理能力,对比传统同步网关(如Zuul 1.x)性能提升显著[^3]。 - **响应缓存**:缓存高频请求的响应结果,减少后端服务压力。 --- ### 示例:路由配置 ```yaml spring: cloud: gateway: routes: - id: user_service uri: lb://user-service # 负载均衡到user-service服务 predicates: - Path=/api/user/** filters: - StripPrefix=2 # 移除路径前缀/api/user - AddRequestHeader=X-Request-From, gateway ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值