Spring Cloud——Function

Function

        依赖说明:通过函数促进业务逻辑的实现,并支持跨无服务器提供商的统一编程模型,以及独立运行(本地或在PaaS中)的能力。

          SpringCloud Function作为SpringCloud家族成员最早在2017年提出,项目主要负责人为Mark Fisher,目前已经来到了3.0版本。SpringCloud Function的出现旨在为快速发展的Serverless市场提供一个Spring的接入路径,使用SpringCloud Function进行无服务(我这里直接称为函数式编程)的项目开发可以大大节约成本,同时对于SpringBoot熟悉的人可以迅速上手。


参考:

SpringCloud Function实践入门

Spring系列学习之Spring Cloud Function微服务功能目标实现


POM

<!--Function-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-function-context</artifactId>
</dependency>

XXX

### Spring Cloud Gateway 中 GlobalFilter 的异常处理 为了确保全局过滤器能够有效地捕获并处理异常,在 `Spring Cloud Gateway` 中可以采用多种方式来实现这一目标。一种常见的方式是在自定义的 `GlobalFilter` 实现类中直接编写逻辑,用于捕捉可能发生的错误情况,并对其进行适当响应。 #### 使用 Try-Catch 结构包裹业务逻辑 可以在重写的 `filter()` 方法内部利用 try-catch 块包围主要执行流程,从而允许任何未被捕获到此层面上游抛出的异常被截取下来[^1]: ```java import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.cloud.gateway.filter.GlobalFilter; import org.springframework.core.Ordered; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono; @Component public class ExceptionHandlingGlobalFilter implements GlobalFilter, Ordered { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { try { // 执行链路中的下一个过滤器 return chain.filter(exchange); } catch (Exception e) { // 处理异常 exchange.getResponse().setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR); return exchange.getResponse().writeWith(Mono.fromSupplier(() -> { byte[] bytes = "An error occurred".getBytes(); return exchange.getResponse().bufferFactory().wrap(bytes); })); } } @Override public int getOrder() { return HIGHEST_PRECEDENCE; } } ``` 上述代码展示了如何创建一个实现了 `GlobalFilter` 接口的新组件,该组件会在每次HTTP请求到达网关时自动触发。当发生异常时,会设置 HTTP 状态码为 500 并返回简单的错误消息给客户端[^2]。 #### 利用 WebExceptionHandler 进行统一管理 另一种更推荐的做法是通过注册专门负责处理异常事件的处理器——即继承自 `AbstractErrorWebExceptionHandler` 类的对象,这样不仅可以集中化地控制所有类型的异常状况,还可以更好地与其他框架特性集成在一起工作[^3]。 ```java import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.boot.autoconfigure.web.ResourceProperties; import org.springframework.boot.autoconfigure.web.reactive.error.AbstractErrorWebExceptionHandler; import org.springframework.boot.web.reactive.error.ErrorAttributes; import org.springframework.context.ApplicationContext; import org.springframework.core.io.buffer.DataBufferFactory; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.reactive.function.BodyInserters; import org.springframework.web.reactive.function.server.RequestPredicates; import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.ServerRequest; import org.springframework.web.reactive.function.server.ServerResponse; import reactor.core.publisher.Mono; import java.util.Map; @RequestMapping("${server.error.path:/error}") public class CustomErrorWebExceptionHandler extends AbstractErrorWebExceptionHandler { private final ObjectMapper objectMapper; public CustomErrorWebExceptionHandler(ErrorAttributes errorAttributes, ResourceProperties resourceProperties, ApplicationContext applicationContext, ObjectMapper objectMapper) { super(errorAttributes, resourceProperties, applicationContext); this.objectMapper = objectMapper; setErrorRoutes(); } private void setErrorRoutes() { RouterFunction<ServerResponse> routerFunction = RequestPredicates.all() .andRoute(request -> ServerResponse.status(500) .contentType(MediaType.APPLICATION_JSON_UTF8) .body(BodyInserters.fromObject(Map.of( "message", "Internal server error" )))); setRoutingFunction(routerFunction); } protected Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) { Throwable error = getError(request); return Map.of( "timestamp", System.currentTimeMillis(), "path", request.uri().getPath(), "status", 500, "error", "Internal Server Error", "exception", error.getClass().getName(), "message", error.getMessage() ); } } ``` 这段示例说明了怎样构建一个定制化的异常处理器实例,它能够在遇到问题时向调用方反馈更加详细的诊断信息,同时保持良好的用户体验和安全性考虑[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

十年梦归尘

愿意支持一下不(*^▽^*)

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值