Apache Camel - how to use InputStream as source?

与世无争的帅哥 提交于 2019-12-11 12:06:28

问题


What I'm trying to do seems simple enough, or at least a common task. The fact that I'm unable to find any examples, however, tells me I'm going about this the wrong way.

I have an InputStream I need to use as a source. The InputStream provides lines of text that I need to route to one or more destination endpoints. The source of the InputStream is a bit of a black box - it's not from a file or a URL. I have the most basic of stream examples working...using System.in and System.out:

public class InOutRoute extends RouteBuilder
{
    @Override
    public void configure() throws Exception
    {
        from("stream:in")
                .to("stream:out");
    }

}

All I'm trying to do right now is replace stream:in with the InputStream I've been given. I thought this would be a common operation but clearly I'm thinking about this the wrong way.

(Edit) More information about the stream: This "black box" I have to work with performs actions and then provides status updates about those actions via an InputStream. When the black box has completed its actions I discard the reference to the InputStream. One potential complication: I will likely have to handle multiple InputStreams at the same time.


回答1:


So you want to route from an input stream? You can use the bean component for that, to call a method on a bean that returns your input stream.

public InputStream giveItToMe() {
   ...
}


from("bean:myBean?method=giveItToMe")
  .to("stream:out");

Notice that when the route is complete, Camel calls the method on the bean again (in endless loop). So if you have no stream, then either block the call, or return null, and then you would need to filter that in the route, as then the InputStream would be null.

You can also just use a ProducerTemplate and call a Camel route with the stream, from where you have the stream when you want to route it in Camel

public void someBusinessLogic() {
   while (!done) {
     InputStream is = ...
     template.sendBody("direct:routeMe", is);

     ...
     // logic to know if we should continue or break out
   }
}

from("direct:routeMe")
  .to("stream:out");

More details at

  • http://camel.apache.org/bean
  • http://camel.apache.org/direct
  • http://camel.apache.org/producertemplate.html


来源:https://stackoverflow.com/questions/22420333/apache-camel-how-to-use-inputstream-as-source

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!