第 242 章 Netty4 HTTP Component
作为 Camel 版本 2.14 可用
netty4-http 组件是对 Netty4 组件的一个扩展,通过 Netty4 分离 HTTP 传输。
此 camel 组件支持制作者和消费者端点。
INFO: 流.Netty 基于流,这意味着其接收的输入被提交到 Camel 作为流。这意味着,一次只能读取流的内容 。如果发现消息正文显示为空的情况,或者您需要多次访问数据(例如:执行多播或重新传送错误处理),您应该使用 Stream 缓存或将消息正文转换为可安全地重新读取多次的 String。注意 Netty4 HTTP 使用 io.netty.handler.codec.http.HttpObjectAggregator 将整个流读取到内存中,以构建完整的 http 消息。但是生成的消息仍是一个基于流的消息,它可以被读取一次。
Maven 用户需要将以下依赖项添加到其 pom.xml 中:
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-netty4-http</artifactId>
<version>x.x.x</version>
<!-- use the same version as your Camel core version -->
</dependency>
INFO: 输入Stream.如果将 InputStream 用作消息正文,并且您想要写入或读取大型数据流(如 > 2 GB),则必须通过将 disableStreamCache 参数设置为 true 来使用流传输支持。
示例 1:将大型数据流上传到服务器
// Upload a large data stream to the server
from("direct:upstream-call")
.bean(Helper.class, "prepareStream")
.to("netty-http:http://localhost:{{port}}/upstream?disableStreamCache=true")
.log("get ${body}");
// Read a large data stream from the client
from("netty-http:http://0.0.0.0:{{port}}/upstream?disableStreamCache=true")
.bean(Helper.class, "processStream")
.to("mock:stream-size");示例 2:从服务器下载大型数据流
// Download a large data stream from the server
from("direct:download-call")
.to("netty-http:http://localhost:{{port}}/downstream?disableStreamCache=true")
.bean(Helper.class, "asyncProcessStream")
.log("get ${body}");
// Write a large data stream to the client
from("netty-http:http://0.0.0.0:{{port}}/downstream?disableStreamCache=true")
.bean(Helper.class, "prepareStream");
在下载示例中,您必须从其他线程的 InputStream 中读取以避免阻断底层流处理程序(请参阅 asyncProcessStream)。
public static void processStream(Exchange exchange) throws Exception {
InputStream is = exchange.getIn().getBody(InputStream.class);
byte[] buffer = new byte[1024];
long read = 0;
long total = 0;
while ((read = is.read(buffer, 0, buffer.length)) != -1) {
total += read;
}
exchange.getIn().setBody(new Long(total));
}
public static CompletableFuture<Void> asyncProcessStream(Exchange exchange) {
return CompletableFuture.runAsync(() -> {
try {
processStream(exchange);
} catch (Exception e) {
exchange.setException(e);
}
});
}242.1. URI 格式
netty 组件的 URI 方案如下
netty4-http:http://0.0.0.0:8080[?options]
您可以使用以下格式在 URI 中附加查询选项 ?option=value&option=value&…
INFO: 查询参数与端点选项。您可以了解 Camel 如何识别 URI 查询参数和端点选项。例如,您可以按照如下所示创建端点 URI - netty4-http:http//example.com?myParam=myValue&compression=true。在本例中,myParam 是 HTTP 参数,而 compression 是 Camel 端点选项。在这种情况下,Camel 使用的策略是解析可用的端点选项,并将它们从 URI 中删除。这意味着,对于所讨论的示例,由 Netty HTTP producer 发送的 HTTP 请求将如下所示: http//example.com?myParam=myValue,因为 压缩 端点选项将从目标 URL 中解析并删除。请记住,您不能使用动态标头(如 CamelHttpQuery)指定端点选项。端点选项只能在端点 URI 定义级别上指定(如 到 DSL 元素)。