Apache Camel:如何在 HTTP URI 中动态设置 header 值?
Apache Camel: How to dynamically set header value in HTTP URI?
我正在学习 Camel 并创建了如下路线:
from("timer:stream?period={{inbound.timer.period}}")
...
.setHeader(Exchange.HTTP_URI, simple(outboundUri()))
...
.multicast()
.to(
"stream:header",
"file://build?autoCreate=false",
outboundHttp
);
outboundUri()
方法 returns 路径中带有占位符的 URI,${header.CamelFileName}
。我想做的是使用某种 header 映射器解决这个问题,我可以在其中按优先顺序查看一些 headers,如果存在 none,则设置一个CamelFileName
.
的默认值
如何使用 HTTP4
组件实现此目的?
我最终实现了一个 Processor 如下:
public class FilenameHeaderMessageProcessor implements org.apache.camel.Processor {
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd-kkmm");
@Override
public void process(Exchange exchange) throws Exception {
Message in = exchange.getIn();
Map<String, Object> inHeaders = in.getHeaders();
log.debug("In headers: {}.", inHeaders);
Message out = exchange.getOut();
// Without this, out body is null
out.setBody(in.getBody());
Object filename = inHeaders.computeIfAbsent(FILE_NAME,
k -> Optional.ofNullable(inHeaders.get(KEY))
.orElse(defaultFilename())
);
out.setHeader(FILE_NAME, filename);
}
private final String defaultFilename() {
return DATE_TIME_FORMATTER.format(LocalDateTime.now()) + ".out";
}
}
我正在学习 Camel 并创建了如下路线:
from("timer:stream?period={{inbound.timer.period}}")
...
.setHeader(Exchange.HTTP_URI, simple(outboundUri()))
...
.multicast()
.to(
"stream:header",
"file://build?autoCreate=false",
outboundHttp
);
outboundUri()
方法 returns 路径中带有占位符的 URI,${header.CamelFileName}
。我想做的是使用某种 header 映射器解决这个问题,我可以在其中按优先顺序查看一些 headers,如果存在 none,则设置一个CamelFileName
.
如何使用 HTTP4
组件实现此目的?
我最终实现了一个 Processor 如下:
public class FilenameHeaderMessageProcessor implements org.apache.camel.Processor {
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd-kkmm");
@Override
public void process(Exchange exchange) throws Exception {
Message in = exchange.getIn();
Map<String, Object> inHeaders = in.getHeaders();
log.debug("In headers: {}.", inHeaders);
Message out = exchange.getOut();
// Without this, out body is null
out.setBody(in.getBody());
Object filename = inHeaders.computeIfAbsent(FILE_NAME,
k -> Optional.ofNullable(inHeaders.get(KEY))
.orElse(defaultFilename())
);
out.setHeader(FILE_NAME, filename);
}
private final String defaultFilename() {
return DATE_TIME_FORMATTER.format(LocalDateTime.now()) + ".out";
}
}