繁体   English   中英

Spring集成流响应HTTP 400

[英]Spring integration flow respond with HTTP 400

我有一个Spring集成流程,需要一个“routingkey”消息头。 如果不存在,我想将HTTP 400响应发送回客户端。 我怎样才能做到这一点? 您将在下面看到determineRoutingKey方法,我可以确定路由密钥是否作为标头传递。

@Bean
public IntegrationFlow webToRabbit(RabbitTemplate amqpTemplate)
{
    return IntegrationFlows
            .from
            (
                Http.inboundGateway("/tunnel")
                    .replyTimeout(Integer.valueOf(timeout))
                    .mappedRequestHeaders("*")
                    .mappedResponseHeaders("*")
            )
            .log()
            .handle
            (
                Amqp.outboundGateway(amqpTemplate)
                    .exchangeName(exchangeName)
                    .routingKeyFunction(f->determineRoutingKey(f))
                    .mappedRequestHeaders("*")
                    .mappedReplyHeaders("*")
            )
            .log()
            .bridge(null)
            .get();
}

private String determineRoutingKey(Message<?> message) 
{
    MessageHeaders headers = message.getHeaders();
    if(headers.containsKey(HEADER_ROUTINGKEY))
    {
        String routingKey = Objects.toString(headers.get(HEADER_ROUTINGKEY));
        log.debug("Using routing key: " + routingKey);
        return routingKey;
    }
    else
    {
        log.error("Headers found: " + Objects.toString(headers));

        //Here I get an exception stating that MessageHeaaders is immutable
        message.getHeaders().put(HttpHeaders.STATUS_CODE, HttpStatus.BAD_REQUEST);
        return null;
    }
}

先谢谢您的帮助。

有一个逻辑:

private HttpStatus resolveHttpStatusFromHeaders(MessageHeaders headers) {
    Object httpStatusFromHeader = headers.get(org.springframework.integration.http.HttpHeaders.STATUS_CODE);
    return buildHttpStatus(httpStatusFromHeader);
}

所以,你需要的是只需定期(字符串错误讯息?)回复和适当HttpStatus.BAD_REQUEST作为http_statusCode头。

在任何例外中都没有理由。

UPDATE

由于您处于流程的中间并且距离回复还很远,因此您可以坚持使用该异常方法。

你所要做的有返回正确的响应400是errorChannelHttp.inboundGateway()和一些简单的变压器回报Message用适当HttpHeaders.STATUS_CODE头:

Http.inboundGateway("/tunnel")
    .errorChannel("httpErrorFlow.input")
...

@Bean
public IntegrationFlow httpErrorFlow() {
    return f -> f
            .<RuntimeException, Message<?>>transform(payload -> {
                if (payload.getCause() instanceof MyRoutingKeyException) {
                    return MessageBuilder.withPayload("Bad routing key")
                            .setHeader(HttpHeaders.STATUS_CODE, HttpStatus.BAD_REQUEST)
                            .build();
                }
                throw payload;
            });
}

但同样:你不能只是抛出异常。

那是

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM