我在Web服务器上运行了两种不同的服务。这两个服务都有一个名为'xyz'的操作,带有以下参数。
服务1:
Public String xyx(Student object) {}
服务2:
public String xyz(Employee object){}
现在我有一个客户端,它将根据收到的消息调用其中一个服务的操作。该消息将作为骆驼交换机收到。所以我需要确定消息的类型,然后调用适当的服务。
如何识别作为camel exchange接收的消息的原始类型。
感谢。
答案 0 :(得分:6)
我会在标题中设置一个值来指示它是哪个服务,然后在驼峰路由上发送它。这种方法只是一种方法。 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发送消息,那么我可能会提供更多帮助。
希望这会给你一些想法,如果代码中有语法错误等,抱歉我在公共汽车站,没时间检查。
答案 1 :(得分:6)
或者你可以这样做:
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();
答案 2 :(得分:5)
尝试使用exchange.getIn()。getBody()instanceof Student
答案 3 :(得分:0)
我更喜欢直接在路由定义中而不是在Processor
中编写这种类型的逻辑。这是使用Predicate
来确定主体类类型的Camel DSL方法。假定您已经将Exchange
主体反序列化为Student
或Employee
对象。
choice()
.when(body().isInstanceOf(Student::class))
.to(...)
.when(body().isInstanceOf(Employee::class))
.to(...)
.end()
如果您要在整个路线上对人体执行各种变换,从而在各个阶段产生各种Student
或Employee
对象类型(例如Student
,则StudentEntity
等),然后将类型保存在标头或属性中,因为在路由开始时使用一些String常量可能是更干净的方法。
// 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
最后,您也许可以在处理器中完成所有操作,但是我认为将这种分支逻辑与服务调用结合起来是一种骆驼式反模式。
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)