spring boot - Apache Camel - from jms to http



我有一个使用ApacheCamel的春季启动项目。我想从包含文件的activemq队列中读取一条消息,并将其发送到web服务器。

我正在努力寻找合适的方法来做这件事。

我相信我能做出这样的东西:

from("activemq:queue").bean(MyBean.class, "process")

手动构建一个http请求,但我忍不住想可能有更好的方法

from("activemq:queue").bean(MyBean.class, "process")
  .setHeader(Exchange.HTTP_METHOD,constant("POST"))
  .to("http://localhost:8080/test");

但我不知道如何操作"exchange"以获得有效的http消息。

MyBean接收一个包含JmsMessage的Exchange对象。我看到还有一个HTTPMessage,但我认为我不应该手动构建它。(它需要HTTPRequest和Response对象,我不确定如何获取。)

有人能阐明这个问题吗?

更新我要用豆子溶液。

from("activemq:queue").bean(MyBean.class, "sendMultipart");

public void sendMultipart(Exchange exchange) {
    ByteArrayInputStream in = new ByteArrayInputStream((byte[]) exchange.getIn().getBody());
    InputStreamBody contentBody = new InputStreamBody(in, ContentType.create("application/octet-stream"), "filename");
    HttpEntity entity = MultipartEntityBuilder
            .create()
            .addPart("file", contentBody)
            .build();
    HttpPost httpPost = new HttpPost("http://localhost:8080/upload/");
    httpPost.setEntity(entity);
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {
        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
        System.out.println(httpResponse);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

更新后的帖子

我发现了这个http://hilton.org.uk/blog/camel-multipart-form-data.它允许您利用camelhttp组件。

"jms:queue/SomeQ" ==> {
    process(toMultipart)
    setHeader(Exchange.CONTENT_TYPE, "multipart/form-data")
    process((e: Exchange) => e.getIn.setHeader(Exchange.HTTP_URI,"http://localhost:8111/foo"))
    to ("http:DUMMY")
}
def toMultipart(exchange: Exchange): Unit = {
  val data = exchange.in[java.io.File]
  val entity = MultipartEntityBuilder.create()
  entity.addBinaryBody("file", data)
  entity.addTextBody("name", "sample-data")
  // Set multipart entity as the outgoing message’s body…
  exchange.in = entity.build
}

附带说明:这将是一个很好的用例来尝试反应流。

原始帖子

我在理解你的实际问题上仍然有一些问题。也许一些代码可能会有所帮助:

我现在假设您正在接收一些字符编码的字节,并希望将其发送到动态建立的http端点。

下面是你正在寻找的东西吗(代码在camel的scala-dsl中)

"jms:queue/SomeQ" ==> {
    convertBodyTo(classOf[String],"UTF-32" )
    process((e: Exchange) => e.in = e.in[String].toUpperCase + "!")
    process((e: Exchange) => e.getIn.setHeader(Exchange.HTTP_URI,"http://localhost:8111/foo"))
    to ("http:DUMMY")
}

它将作为HTTPPOST发送,因为正文不是null。

我在我创建的另一个端点上收到了它,以确保上面的代码是正确的:

"jetty:http://localhost:8111/foo" ==> {
  log("received on http 8111 endpoint ${body}")
 }

最新更新