我在网络服务器上运行两个不同的服务。这两个服务都有一个名为“xyz”的操作,具有以下参数。
服务1:
Public String xyx(Student object) {}
服务2:
public String xyz(Employee object){}
现在我有一个客户端,它将根据收到的消息调用其中一项服务的操作。该消息将作为骆驼交换被接收。所以我需要识别消息的类型,然后调用适当的服务。
如何识别作为骆驼交换接收到的消息的原始类型。
谢谢。
或者你可以这样做:
from("foo:incommingroute")
.choice()
.when(simple("${body} is 'java.lang.String'"))
.to("webservice:Student")
.when(simple("${body} is 'foo.bar.Employee'"))
.to("webservice:Employee")
.otherwise()
.to("jms:Deadletter")
.end();
尝试exchange.getIn().getBody()实例学生
我会在标头中设置一个值来指示它是哪个服务,然后在骆驼路线上发送它。这种方法只是做到这一点的一种方法。 Christian Schneider 有另一个出色的解决方案,我可能会更多地使用它,因为我对 Camel 的了解比以往任何时候都多。然而,两者都会实现相同的目标,并且取决于你问的人,一个可能比另一个更清楚。
例如你可以这样做:
public void foo(Exchange exchange){
exchange.getIn().setHeader("MsgType", "Student");
}
然后,您可以在 Java DSL 甚至 Spring DSL 中过滤标头。
在 Java DSL 中你会做这样的事情(伪代码)
from("foo:incommingroute")
.choice()
.when(header("MsgType").equals("Student"))
.to("webservice:Student")
.when(header("MsgType").equals("Employee"))
.to("webservice:Employee")
.otherwise()
.to("jms:Deadletter")
.end();
在 Spring DSL 中你会做这样的事情(伪代码)
<route>
<from uri="foo:incommingroute"/>
<choice>
<when>
<simple>${header.MsgType} equals 'Student'</simple>
<to uri="webservice:Student"/>
</when>
<when>
<simple>${header.MsgType} equals 'Employee'</simple>
<to uri="webservice:Employee"/>
</when>
<otherwise>
<to uri="jms:badOrders"/>
<stop/>
</otherwise>
</choice>
<to uri="jms:Deadletter"/>
</route>
您还可以通过此链接查看丰富器模式http://camel.apache.org/content-enricher.html。基本上我建议的是遵循丰富模式。如果您能告诉我您如何向 Camel 发送消息,那么我可能可以提供更多帮助。
希望这能给您一些想法,如果代码中存在语法错误等,抱歉我在公交车站,没有时间检查它。
我更喜欢直接在路由定义中编写这种类型的逻辑,而不是在
Processor
中。这是 Camel DSL 方法,它使用 Predicate
来确定主体类类型。它假设您已经将 Exchange
主体反序列化为 Student
或 Employee
对象。
choice()
.when(body().isInstanceOf(Student.class))
.to(...)
.when(body().isInstanceOf(Employee.class))
.to(...)
.end()
如果您要在整个路线中对身体执行各种变换,从而在各个阶段产生各种
Student
或 Employee
对象类型(例如 Student
然后 StudentEntity
等),然后保存标头或属性中的类型作为路由开头的某个字符串常量可能是更简洁的方法。
// Note that this labelling could be bundled into a processor
choice()
.when(body().isInstanceOf(Student.class))
.setProperty("TYPE", "STUDENT")
.when(body().isInstanceOf(Employee.class))
.setProperty("TYPE", "EMPLOYEE")
.end()
// later after some body transformations
.choice()
.when(exchangeProperty("TYPE").isEqualTo("STUDENT"))
// process student
最后,您可能能够在处理器中完成所有操作,但我认为这种分支逻辑与服务调用相结合是 Camel 反模式。
class MyProcessor implements Processor {
@Override
public void process(Exchange exchange) {
Object body = exchange.getIn().getBody()
if (body instanceOf Student) {
// invoke StudentService
} else if (body instanceOf Employee) {
// invoke EmployeeService
}
}
}
// Route definition
from(...)
.process(myProcessor)