如何在循环中动态修改HttpRequestExecutingMessageHandler的URI参数?
解决方案:动态修改Spring Integration HTTP Outbound Gateway的URI参数
1. 传递日期参数到消息中
修改produceHttpCall方法,把遍历到的LocalDate作为消息Payload传递给Gateway通道:
public void produceHttpCall(LocalDate param) { MessageChannel gateway = context.getBean("gatewayChannel", DirectChannel.class); // 将日期作为消息Payload发送 gateway.send(new GenericMessage<>(param)); }
2. 配置支持动态URI的Outbound Gateway
利用Spring Expression Language(SpEL)让Gateway在每次处理消息时动态生成URI,替代初始化时固定的URI:
场景1:日期作为路径参数(如/api/2024-05-20)
@ServiceActivator(inputChannel = "gatewayChannel") @Bean public HttpRequestExecutingMessageHandler outBoundGatewayCall(@Value("${ws.uri}") String baseUri) { // 定义带变量的基础URI模板 String dynamicUriTemplate = baseUri + "/{date}"; HttpRequestExecutingMessageHandler handler = new HttpRequestExecutingMessageHandler(dynamicUriTemplate); // 配置URI变量的SpEL表达式:将Payload中的LocalDate格式化为指定字符串 handler.setUriVariableExpressions(Collections.singletonMap("date", new SpelExpressionParser().parseExpression( "payload.format(T(java.time.format.DateTimeFormatter).ofPattern('yyyy-MM-dd'))" ))); handler.setHttpMethod(HttpMethod.GET); handler.setExpectedResponseType(String.class); handler.setOutputChannel(myOutputChannel()); return handler; }
场景2:日期作为查询参数(如/api?date=2024-05-20)
@ServiceActivator(inputChannel = "gatewayChannel") @Bean public HttpRequestExecutingMessageHandler outBoundGatewayCall(@Value("${ws.uri}") String baseUri) { // 使用SpEL直接拼接带查询参数的完整URI String dynamicUri = baseUri + "?date=" + "#{payload.format(T(java.time.format.DateTimeFormatter).ofPattern('yyyy-MM-dd'))}"; HttpRequestExecutingMessageHandler handler = new HttpRequestExecutingMessageHandler(dynamicUri); handler.setHttpMethod(HttpMethod.GET); handler.setExpectedResponseType(String.class); handler.setOutputChannel(myOutputChannel()); return handler; }
原理说明
HttpRequestExecutingMessageHandler支持通过SpEL表达式动态解析URI,每次处理消息时会根据当前消息的Payload(或Header)计算出实际请求的URI,而非初始化时固定死。这样循环中每次传递不同的LocalDate,就会生成对应的目标URI。
内容的提问来源于stack exchange,提问作者matteo88
相关产品推荐
相关产品推荐

