ACTIVEMQ研究和分析.docx
《ACTIVEMQ研究和分析.docx》由会员分享,可在线阅读,更多相关《ACTIVEMQ研究和分析.docx(54页珍藏版)》请在冰豆网上搜索。
ACTIVEMQ研究和分析
研究目标
Ø熟悉activemq的原理和开发接口
⏹特点
Thenewfeaturesandenhancementsinthisreleaseinclude:
∙Additionaladvisorymessagesformessagesdelivered/consumedfastproducers/slowconsumers,Usagelimits,Slavesbecomemastersetc.
∙Enhancedsslcontextconfigurationthroughspring/xbean
∙Newindividualacknowledgemodeformessageconsumption
∙Abilitytoconfiguretheautomaticdiscardingoftheitemsbeingsenttothedeadletterqueue
∙AbilitytolimitthemaximumnumberofconnectionstoaBroker
∙Abilitytoconfigureseparatelock
DatasourceforJDBCMasterslave.
∙activemq-camelandactivemq-connection-poolnowhavetheirownmodules,nolongerinactivemq-core
∙ThedefaultActiveMQConnectionFactory
brokerUrlnowusesthefailovertransport.
∙UsesApacheCamel1.5
.
⏹Amq启动过程分析
采用spring
org.apache.activemq.xbeanXBeanBrokerService
org.apache.activemq.broker.BrokerService
org.apache.activemq.xbean.BrokerFactoryBean
org.apache.camel.spring.CamelContextFactoryBean
org.apache.activemq.util.MemoryPropertyEditor
⏹数据格式
CamelsupportsapluggableDataFormat
toallowmessagestobemarshalledtoandfrombinaryortextformatstosupportakindofMessageTranslator.
Thefollowingdataformatsarecurrentlysupported
∙ArtixDataServices
∙Bindy
∙CSV
∙EDI
∙FlatpackDataFormat
∙HL7DataFormat
∙JAXB
∙JSON
∙Serialization
∙String
∙TidyMarkup
∙XmlBeans
∙XMLSecurityDataFormat
∙XStream
∙ZipDataFormat
Unmarshalling
IfyoureceiveamessagefromoneoftheCamelComponentssuchasFile,HTTPorJMSyouoftenwanttounmarshalthepayloadintosomebeansothatyoucanprocessitusingsomeBeanIntegrationorperformPredicateevaluationandsoforth.TodothisusetheunmarshalwordintheDSLinJavaortheXmlConfiguration.
Forexample
DataFormatjaxb=newJaxbDataFormat("com.acme.model");
from("activemq:
My.Queue").
unmarshal(jaxb).
to("mqseries:
Another.Queue");
TheaboveusesanamedDataFormatofjaxbwhichisconfiguredwithanumberofJavapackagenames.YoucanifyoupreferuseanamedreferencetoadataformatwhichcanthenbedefinedinyourRegistrysuchasviayourSpringXMLfile.
YoucanalsousetheDSLitselftodefinethedataformatasyouuseit.ForexamplethefollowingusesJavaserializationtounmarshalabinaryfilethensenditasanObjectMessagetoActiveMQ
from("file:
//foo/bar").
unmarshal().serialization().
to("activemq:
Some.Queue");
Marshalling
Marshallingistheoppositeofunmarshalling,whereabeanismarshalledintosomebinaryortextualformatfortransmissionoversometransportviaaCamelComponent.Marshallingisusedinthesamewayasunmarshallingabove;intheDSLyoucanuseaDataFormatinstance,youcanconfiguretheDataFormatdynamicallyusingtheDSLoryoucanrefertoanamedinstanceoftheformatintheRegistry.
ThefollowingexampleunmarshalsviaserializationthenmarshalsusinganamedJAXBdataformattoperformakindofMessageTranslator
from("file:
//foo/bar").
unmarshal().serialization().
marshal("jaxb").
to("activemq:
Some.Queue");
⏹事务模型
⏹点对点传输模式
⏹发布订阅模式
UsingRoutingLogic
Anotheroptionistoexplicitlylistthepublish-subscriberelationshipinyourroutinglogic;thiskeepstheproducerandconsumerdecoupledbutletsyoucontrolthefinegrainedroutingconfigurationusingtheDSLorXmlConfiguration.
UsingtheFluentBuilders
RouteBuilderbuilder=newRouteBuilder(){
publicvoidconfigure(){
from("seda:
a").multicast().to("seda:
b","seda:
c","seda:
d");
}
};
⏹请求响应模式
ForexamplewhenusingJMSwithInOutthecomponentwillbydefaultperformtheseactions
∙createbydefaultatemporaryinboundqueue
∙settheJMSReplyTodestinationontherequestmessage
∙settheJMSCorrelationIDontherequestmessage
∙sendtherequestmessage
∙consumetheresponseandassociatetheinboundmessagetotherequestusingtheJMSCorrelationID(asyoumaybeperformingmanyconcurrentrequest/responses).
⏹消息群发
静态群发
Thefollowingexampleshowshowtoroutearequestfromaninputqueue:
aendpointtoastaticlistofdestinations
RouteBuilderbuilder=newRouteBuilder(){
publicvoidconfigure(){
from("seda:
a").multicast().to("seda:
b","seda:
c","seda:
d");
}
};
动态群发
UsuallyoneofthemainreasonsforusingtheRecipientList
patternisthatthelistofrecipientsisdynamicandcalculatedatruntime.ThefollowingexampledemonstrateshowtocreateadynamicrecipientlistusinganExpression(whichinthiscaseitextractsanamedheadervaluedynamically)tocalculatethelistofendpointswhichareeitheroftypeEndpoint
orareconvertedtoaStringandthenresolvedusingtheendpointURIs.
UsingtheFluentBuilders
RouteBuilderbuilder=newRouteBuilder(){
publicvoidconfigure(){
from("seda:
a").recipientList(header("foo"));
}
};
TheaboveassumesthattheheadercontainsalistofendpointURIs.Thefollowingtakesasinglestringheaderandtokenizesit
from("direct:
a").recipientList(
header("recipientListHeader").tokenize(","));
Iteratablevalue
Thedynamiclistofrecipientsthataredefinedintheheadermustbeiteratablesuchas:
▪java.util.Collection
▪java.util.Iterator
▪arrays
▪org.w3c.dom.NodeList
▪Camel1.5.1:
asingleStringwithvaluesseparatedwithcomma
▪anyothertypewillberegardedasasinglevalue
UsingtheSpringXMLExtensions
//camel.apache.org/schema/spring">
a"/>
$foo
Forfurtherexamplesofthispatterninuseyoucouldlookatoneofthejunittestcase
UsingdelimiterinSpringXML
AvailableasofCamel1.5.1
InSpringDSLyoucansetthedelimiterattributeforsettingadelimitertobeusediftheheadervalueisasingleStringwithmultipleseparatedendpoints.
a"/>
--usecommaasadelimiterforStringbasedvalues-->
SoifmyHeadercontainsaStringwiththevalue"activemq:
queue:
foo,activemq:
topic:
hello,log:
bar"thenCamelwillsplittheStringusingthedelimitergivenintheXMLthatwascomma,resultinginto3endpointstosendto.YoucanusespacesbetweentheendpointsasCamelwilltrimthevaluewhenitlookuptheendpointtosendto.
Note:
InJavaDSLyouusethetokenizertoarchivethesame.TherouteaboveinJavaDSL:
from("direct:
a").recipientList(header("myHeader").tokenize(","));
消息路由
TheMessageRouter
fromtheEIPpatternsallowsyoutoconsumefromaninputdestination,evaluatesomepredicatethenchoosetherightoutputdestination.
Thefollowingexampleshowshowtoroutearequestfromaninputqueue:
aendpointtoeitherqueue:
b,queue:
corqueue:
ddependingontheevaluationofvariousPredicateexpressions
UsingtheFluentBuilders
RouteBuilderbuilder=newRouteBuilder(){
publicvoidconfigure(){
from("seda:
a").choice().when(header("foo").isEqualTo("bar")).to("seda:
b")
.when(header("foo").isEqualTo("cheese")).to("seda:
c").otherwise().to("seda:
d");
}
};
Choicewithoutotherwise
Ifyouuseachoicewithoutaddinganotherwise,anyunmatchedexchangeswillbedroppedbydefault.Ifyouprefertohaveanexceptionforanunmatchedexchange,youcanaddathrowFaulttotheotherwise.
....otherwise().throwFault("Nomatchingwhenclausefoundonchoiceblock");
动态路由
publicclassRouterBean2{
@RecipientList
publicStringroute(@Header("customerID")StringcustIDStringbody){
if(custID==null)returnnull;
return"activemq:
Customers.Orders."+custID;
}
}
publicclassMyRouteBuilderextendsRouteBuilder{
protectedvoidconfigure(){
from("activemq:
Orders.Incoming").beanRef("myRouterBean","route");
}
}
⏹可靠传输
CamelsupportstheGuaranteedDelivery
fromtheEIPpatternsusingthefollowingcomponents
∙Fileforusingfilesystemsasapersistentstoreofmessages
∙JMSwhenusingpersistentdelivery(thedefault)forworkingwithJMSQueuesandTopicsforhighperformance,clusteringandloadbalancing
∙JPAforusingadatabaseasapersistencelayer
⏹消息转换
from("activemq:
SomeQueue").
beanRef("myTransformerBean","myMethodName").
to("mqseries:
AnotherQueue");
Wherethe"myTransformerBean"wouldbedefinedinaSpringXMLfileordefinedinJNDIetc.YoucanomitthemethodnameparameterfrombeanRef()andtheBeanIntegrationwilltrytodeducethemethodtoinvokefromthemessageexchange.
oryoucanaddyourownexplicitProcessortodothetransformation
from("direct:
start").process(newProcessor(){
publicvoidprocess(Exchangeexchange){
Messagein=exchange.getIn();
in.setBody(in.getBody(String.class)+"World!
");
}
}).to("mock:
result");
oryoucanusetheDSLtoexplicitlyconfigurethetransformation
from("direct:
start").transform(body().append("World!
")).to("mock:
result");
⏹消息过滤
ThefollowingexampleshowshowtocreateaMessageFilterrouteconsumingmessagesfromanendpointcalledqueue:
awhichifthePredicateistruewillbedispatchedtoqueue:
b
UsingtheFluentBuilders
RouteBuilderbuilder=newRouteBuilder(){
publicvoidconfigure(){
from("seda:
a").filter(header("foo").isEqualTo("bar")).to("seda:
b");
}
};
YoucanofcourseusemanydifferentPredicatelanguagessuchasXPath,XQuery,SQLorvariousScriptingLanguages.HereisanXPathexample
from("direct:
start").
filter().xpath("/person[@name='James']").
to("mock:
result");
UsingtheSpringXMLExtensions
//camel.apache.org/schema/spring">
a"/>
$foo='bar'
b"/>
⏹消