WebFlux那点事儿:函数式编程

a 夏天 提交于 2019-12-26 16:13:35

【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>

        Mono<GatewayDslContext> dslContext = new Builder(context).build();
        return dslContext
                .filter(
                        dslCtx -> apiParamVerify(dslCtx, context.getApiConfig().getApiParamsConfigList())
                )
                .switchIfEmpty(Mono.defer(() -> Mono.error(PARAM_CONFIG_ERROR.ofEx())))
                .flatMap(
                        dslCtx -> Mono.fromCallable(
                                () -> doInvoke(context, dslCtx)
                        )
                )
                .switchIfEmpty(Mono.defer(() -> Mono.error(PIRATE_ERROR.ofEx())))
                .timeout(Duration.ofMillis(context.getApiConfig().getTimeoutInMilliSeconds()))
                .flatMap(GatewayInvokeHandler::createResponse)
                .publishOn(ExecutorsConfig.SYNC_SCHEDULER);
    }
    @Override
    public Mono<ServerResponse> handle(ServerRequest request) {
        ApiConfig apiConfig = (ApiConfig) request.attributes().get(ApiRouter.BEST_MATCH_API_ROUTER_ATTRIBUTE_KEY);

        ApiGatewayReqContext apiGatewayReqContext = new ApiGatewayReqContext();
        apiGatewayReqContext.setServerRequest(request);
        apiGatewayReqContext.setApiConfig(apiConfig);

        GatewayFilterChain filterChain = getFilterChain();
        return filterChain.handleRequest(apiGatewayReqContext)
                .flatMap(r -> {
                    if (r.getResponse() != null && r.getResponse().isSuccess()) {
                        return ServerResponse.ok()
                                .contentType(
                                        apiConfig.getResponseConfig().getMediaType() == null
                                                ? MediaType.APPLICATION_JSON_UTF8
                                                : apiConfig.getResponseConfig().getMediaType())
                                .syncBody(r.getResponse().getData());
                    } else {
                        return ServerResponse.ok()
                                .contentType(MediaType.APPLICATION_JSON_UTF8)
                                .syncBody(
                                        new ApiGatewayResponse(ApiResponseCodeEnum.ROUTE_NOT_FOUND.getCode(), r.getResponse().getErrors().get(0).getMessage()));
                    }
                }).onErrorResume(this::processApiException);
    }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!