在使用Mule ESB定义流程时,有时会使用自定义的Java Component,例如:
<flow name="testFlow">
<xx:inbound-endpoint doc name="xxx" />
<component class="xxx.xxx" doc:name="Java Component">
</component>
</flow>
默认情况下Mule引用自定义Component时,是request方式,即从inbound endpoint每推送一个Mule Message到Component节点时,创建一个Component instance去处理这条Message,处理完后instance被销毁。
正常情况下,request方式可以满足一般要求,但是如果Component中存在用于统计数据(例如处理时间,处理条数)等的属性时,每次新建一个instance都会重置这些属性,导致所有Mule Message处理完后无法统计这些数据。
针对这个问题,我们有以下两种解决方法:
1)将这些统计数据的属性设置为static。
2)将Java Component实例引用方式改为singleton方式。
第二种方法有两种设置方式:
- 直接在Mule流程文件中,设置引用的Java Component为singleton object
<flow name="testFlow">
<xx:inbound-endpoint doc name="xxx" />
<component doc:name="Java Component">
<singleton-object class="xxx.xxx"/>
</component>
</flow>
- 设置引用的Java Component为spring singleton object
<spring:beans>
<spring:bean id="xxId" name="xxName" class="xxx.xxx" scope="singleton" />
</spring:beans>
<flow name="testFlow">
<xx:inbound-endpoint doc name="xxx" />
<component doc:name="Java Component">
<spring-object bean="xxName"/>
</component>
</flow>
用这两种方式设置的singleton访问都可以保证数据正常被统计,当然,在统计完成后需要将这些属性归零。