Camel从直接路由返回消息以便重用

时间:2016-08-30 07:49:28

标签: apache-camel

我很遗憾回归"身体"来自Camel的to()调用的子路由。根据我发现的直接路由,他们鼓励路由重用,并用于逻辑分裂过于复杂的路由。但我似乎失败了做一个最简单的"分裂":

    from("jms:createRequestQueue")
            .to("direct:createRequest")

            // here the processing of the message fails, see below

            .bean(processor)

            .to("...");

    from("direct:createRequest")
            .onException(Exception.class).bean(requestErrorHandler).stop()
            .unmarshal().json(JsonLibrary.Jackson, MyModelRequest.class);

处理器实例的类如下所示:

public class RequestProcessor {

    @Handler
    public void update(@Body MyModelRequest request) {
        // do stuff
    }

}

问题是解组请求的路由(第二路由)的结果不会传播回调用路由。抛出一个异常,说它无法将String(进入队列的JSON)转换为MyModelRequest类。所以似乎第一条路线中的JSON主体不会被解组路线的结果所取代。这似乎是我希望的一个很好的路由重用。

我偶然发现了InOut消息,但文档非常不清楚,我的实验也失败了。

我需要做些什么才能真正将部分路线提取到另一条路线以供重复使用?

2 个答案:

答案 0 :(得分:1)

所以问题出现在onException子句中(原来问题遗漏了,我认为这不是问题)。我将end()调用与stop()调用混淆,因此路由停止太快,在String中返回未解析的JSON。正确的是:

from("direct:createRequest")
        .onException(Exception.class).bean(requestErrorHandler).end()
        .unmarshal().json(JsonLibrary.Jackson, MyModelRequest.class);

答案 1 :(得分:0)

如果没有一个可重复执行错误的可运行示例,那么很难说出现了什么问题,但它应该(并且确实在2.17.2以及2.15.3上进行测试)工作:

@Component
public class DemoRouteBuilder extends RouteBuilder {   

  @Override
  public void configure() throws Exception {
    from("timer:sender?delay=10s&period=3s")
        .setBody(constant("{\"title\":\"Lord of the Rings\",\"author\":\"J.R.R. Tolkien\"}"))
        .to("direct:unmarshal")
        .bean(new RequestProcessor())
        .log("${body}!");

    from("direct:unmarshal")
        .unmarshal().json(JsonLibrary.Jackson, Book.class);
  }

  public static class RequestProcessor {

    @Handler
    public void update(@Body Book book) {
      System.out.println("Got " + book);
    }

  }

  public static class Book {
    private final String title;

    private final String author;

    private Book() {
      this(null, null);
    }

    public Book(String title, String author) {
      this.title = title;
      this.author = author;
    }

    public String getTitle() {
      return title;
    }

    public String getAuthor() {
      return author;
    }
    @Override
    public String toString() {
      return "title='" + title + "', author='" + author + '\'';
    }

  }
}

这是输出:

  

2016-08-30 13:48:34.337 INFO 16240 --- [main] com.example.DemoApplication:在5.859秒内启动DemoApplication(JVM运行6.587)

     

得到冠军='指环王',作者='J.R.R。托尔金'

     

2016-08-30 13:48:44.298 INFO 16240 --- [timer:// sender] route1:title ='指环王',作者='J.R.R。托尔金!

     

得到冠军='指环王',作者='J.R.R。托尔金'

     

2016-08-30 13:48:47.232 INFO 16240 --- [timer:// sender] route1:title ='指环王',作者='J.R.R。托尔金!