我是 Camel 的新手。我一直在尝试将数据(文件中的 Json)提交到网络服务。这是我的代码:
public static void main(String args[]) throws Exception {
// create CamelContext
CamelContext context = new DefaultCamelContext();
// add our route to the CamelContext
context.addRoutes(new RouteBuilder() {
@Ghi đè
public void configure() {
from("file:data/inbox?noop=true")
.marshal()
.string()
.setHeader(Exchange.CONTENT_TYPE,constant("application/json"))
.to("http://www.a-service.com");
}
});
// start the route and let it do its work
context.start();
Thread.sleep(10000);
// stop the CamelContext
context.stop();
}
然后 web 服务将以 Json 响应,这可以是 {结果:好的} 或者 {结果:失败}
现在,如果响应的 responseCode 为 200,Camel 将视为成功。
我的问题是,我如何才能对响应的 JSON 进行验证,如果失败,Camel 不应将其视为成功?
解决方案 感谢@Namphibian:
通过添加处理器和结束。此代码已经过测试:
from("file:data/inbox?noop=true")
.marshal()
.string("UTF-8")
.setHeader(Exchange.CONTENT_TYPE,constant("application/json"))
.to("http://monrif-test.userspike.com/monrif/rss/monrif_-all-global")
.process(new Processor() {
@Ghi đè
public void process(Exchange exchange) throws Exception {
Message in = exchange.getIn();
String msg = in.getBody(String.class);
System.out.println("Response: " + msg);
if(msg.contains("OK")){
// go to party
}khác{
throw new Exception("test exception");
}
}
});
您可以使用两种广泛的策略来实现这一目标。
基于处理器:
将处理器添加到路由的末尾。在此处理器中,检查网络服务是否以真值或假值响应。
处理器看起来像这样:
package com.example;
import java.util.Map;
import org.apache.camel.Body;
import org.apache.camel.Exchange;
import org.apache.camel.Handler;
import org.apache.camel.Headers;
import org.apache.camel.Message;
public class GeneralProcessor {
@Handler
public void PrepapreErrorImportReport
(
@Headers Map hdr
, Exchange exch
)
{
//todo: Get the message as a string;
Message in = exch.getIn();
String msg = (String)in.getBody();
// Now check if body contains failed or ok.
if(msg.contains("OK")){
//todo: go party the message was OK
}
else{
//todo: Oh Oh! Houston we have a problem
}
}
}
然后您可以修改您的路由以使用此处理器。
简单表达式语言
这是一种方式,另一种方式是使用简单的表达语言。请参阅下面的示例,了解如何使用它。
from("file:data/inbox?noop=true")
.marshal()
.string()
.setHeader(Exchange.CONTENT_TYPE,constant("application/json"))
.to("http://www.a-service.com")
.choice()
.when(simple("${body} contains 'OK'")).to("activemq:okqueue")
.otherwise().to("activemq:queue:other");
Để ý simple("${body} contains 'OK'")
代码段。这就是简单的力量。
这两种方法都有用途。
Tôi là một lập trình viên xuất sắc, rất giỏi!