第 243 章 Netty4 HTTP 组件
从 Camel 版本 2.14 开始提供
netty4-http 组件是 Netty4 组件的扩展,它可通过 Netty4 进行 HTTP 传输。
此 camel 组件支持生成者和消费者端点。
Netty 是基于流的,这意味着它收到的输入作为流提交给 Camel。这意味着您只能够读取一次流的内容。
Netty4 HTTP 使用 io.netty.handler.codec.http.HttpObjectAggregator 将整个流读到内存中,以构建整个完整 http 消息。但是,生成的消息仍然是基于流的消息,该消息一次是可读的。
如果消息正文显示为空,或者您需要多次访问数据(例如:执行多播或重新发送错误处理)使用流缓存或将消息正文转换为 String,这会安全地重新读取多次。
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>
如果将 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);
}
});
}
243.1. URI 格式 复制链接链接已复制到粘贴板!
netty 组件的 URI 方案如下
netty4-http:http://0.0.0.0:8080[?options]
您可以在 URI 中附加查询选项,格式为 ?option=value&option=value&…
查询参数和端点选项.您可以了解 Camel 如何识别 URI 查询参数和端点选项。例如,您可以创建端点 URI,如下所示 - netty4-http:http/example.com?myParam=myValue&compression=true。在本例中,myParam 是 HTTP 参数,而 压缩 是 Camel 端点选项。在这种情况下,Camel 使用的策略是解决可用的端点选项并将其从 URI 中删除。这意味着,对于所讨论的示例,Netty HTTP producer 发送的 HTTP 请求将如下所示 - http//example.com?myParam=myValue,因为 压缩 端点选项将从目标 URL 解析并删除。请记住,您无法使用动态标头(如 CamelHttpQuery)指定端点选项。端点选项只能在端点 URI 定义级别(如 to 或 DSL 元素)指定。