table of contents - apache activemq1.25 1.26 1.27 table of contents introduction legal notice...
TRANSCRIPT
-
1.1
1.2
1.3
1.4
1.5
1.6
1.7
1.8
1.9
1.10
1.11
1.12
1.13
1.14
1.15
1.16
1.17
1.18
1.19
1.20
1.21
1.22
1.23
1.24
1.25
1.26
1.27
TableofContentsIntroduction
LegalNotice
Preface
ProjectInfo
Versions
MessagingConcepts
Architecture
UsingtheServer
Upgrading
AddressModel
UsingJMS
UsingCore
UsingAMQP
MappingJMSConceptstotheCoreAPI
TheClientClasspath
Examples
RoutingMessagesWithWildCards
UnderstandingtheApacheActiveMQArtemisWildcardSyntax
FilterExpressions
Persistence
ConfiguringTransports
ConfigurationReload
DetectingDeadConnections
DetectingSlowConsumers
AvoidingNetworkIsolation
DetectingBrokerIssues(CriticalAnalysis)
ResourceManagerConfiguration
1
-
1.28
1.29
1.30
1.31
1.32
1.33
1.34
1.35
1.36
1.37
1.38
1.39
1.40
1.41
1.42
1.43
1.44
1.45
1.46
1.47
1.48
1.49
1.50
1.51
1.52
1.53
1.54
1.55
1.56
1.57
FlowControl
Guaranteesofsendsandcommits
MessageRedeliveryandUndeliveredMessages
MessageExpiry
LargeMessages
Paging
ScheduledMessages
Last-ValueQueues
ExclusiveQueues
MessageGrouping
ExtraAcknowledgeModes
Management
ManagementConsole
Security
MaskingPasswords
BrokerPlugins
ResourceLimits
TheJMSBridge
ClientReconnectionandSessionReattachment
DivertingandSplittingMessageFlows
CoreBridges
DuplicateMessageDetection
Clusters
HighAvailabilityandFailover
GracefulServerShutdown
LibaioNativeLibraries
Threadmanagement
Logging
RESTInterface
EmbeddingApacheActiveMQArtemis
2
-
1.58
1.59
1.60
1.61
1.62
1.63
1.64
1.65
1.66
1.67
1.68
ApacheKaraf
ApacheTomcat
SpringIntegration
CDIIntegration
InterceptingOperations
ProtocolsandInteroperability
Tools
MavenPlugin
UnitTesting
TroubleshootingandPerformanceTuning
ConfigurationReference
3
-
ApacheActiveMQArtemisUserManualTheUsermanualisanindepthmanualonallaspectsofApacheActiveMQArtemis
Introduction
4
-
LegalNoticeLicensedtotheApacheSoftwareFoundation(ASF)underoneormorecontributorlicenseagreements.SeetheNOTICEfiledistributedwiththisworkforadditionalinformationregardingcopyrightownership.TheASFlicensesthisfiletoYouundertheApacheLicense,Version2.0(the"License");youmaynotusethisfileexceptincompliancewiththeLicense.YoumayobtainacopyoftheLicenseat
http://www.apache.org/licenses/LICENSE-2.0
Unlessrequiredbyapplicablelaworagreedtoinwriting,softwaredistributedundertheLicenseisdistributedonan"ASIS"BASIS,WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.SeetheLicenseforthespecificlanguagegoverningpermissionsandlimitationsundertheLicense.
LegalNotice
5
http://www.apache.org/licenses/LICENSE-2.0
-
PrefaceWhatisApacheActiveMQArtemis?
ApacheActiveMQArtemisisanopensourceprojecttobuildamulti-protocol,embeddable,veryhighperformance,clustered,asynchronousmessagingsystem.
ApacheActiveMQArtemisisanexampleofMessageOrientedMiddleware(MoM).ForadescriptionofMoMsandothermessagingconceptspleaseseetheMessagingConcepts.
WhyuseApacheActiveMQArtemis?Herearejustafewofthereasons:
100%opensourcesoftware.ApacheActiveMQArtemisislicensedusingtheApacheSoftwareLicensev2.0tominimisebarrierstoadoption.
ApacheActiveMQArtemisisdesignedwithusabilityinmind.
WritteninJava.RunsonanyplatformwithaJava8+runtime,that'severythingfromWindowsdesktopstoIBMmainframes.
Amazingperformance.Ourground-breakinghighperformancejournalprovidespersistentmessagingperformanceatratesnormallyseenfornon-persistentmessaging,ournon-persistentmessagingperformancerockstheboattoo.
Fullfeatureset.Allthefeaturesyou'dexpectinanyseriousmessagingsystem,andothersyouwon'tfindanywhereelse.
Elegant,clean-cutdesignwithminimalthirdpartydependencies.RunActiveMQArtemisstand-alone,runitinintegratedinyourfavouriteJavaEEapplicationserver,orrunitembeddedinsideyourownproduct.It'suptoyou.
Seamlesshighavailability.WeprovideaHAsolutionwithautomaticclientfailoversoyoucanguaranteezeromessagelossorduplicationineventofserverfailure.
Hugelyflexibleclustering.Createclustersofserversthatknowhowtoloadbalancemessages.Linkgeographicallydistributedclustersoverunreliableconnectionstoformaglobalnetwork.Configureroutingofmessagesinahighlyflexibleway.
Preface
6
-
ProjectInformationTheofficialApacheActiveMQArtemisprojectpageishttp://activemq.apache.org/artemis/.
SoftwareDownloadThesoftwarecanbedownloadfromtheDownloadpage:http://activemq.apache.org/artemis/download.html
ProjectInformationIfyouhaveanyuserquestionspleaseuseouruserforum
Ifyouhavedevelopmentrelatedquestions,pleaseuseourdeveloperforum
PopinandchattousinourIRCchannel
ApacheActiveMQArtemisGitrepositoryishttps://github.com/apache/activemq-artemis
Allreleasetagsareavailablefromhttps://github.com/apache/activemq-artemis/releases
Andmanythankstoallourcontributors,botholdandnewwhohelpedcreateApacheActiveMQArtemis.
ProjectInfo
7
http://activemq.apache.org/artemis/http://activemq.apache.org/artemis/download.htmlhttp://activemq.2283324.n4.nabble.com/ActiveMQ-User-f2341805.htmlhttp://activemq.2283324.n4.nabble.com/ActiveMQ-Dev-f2368404.htmlirc://irc.freenode.net:6667/apache-activemqhttps://github.com/apache/activemq-artemishttps://github.com/apache/activemq-artemis/releases
-
VersionsThischapterprovidestheinformationforeachrelease:
Alinktothefullreleasenoteswhichincludesallissuesresolvedintherelease.Abrieflistof"highlights."Ifnecessary,specificstepsrequiredwhenupgradingfromthepreviousversion.
NOTE:Iftheupgradespansmultipleversionsthenthestepsfromeachversionneedtobefollowedinorder.NOTE:FollowthegeneralupgradeprocedureoutlinedintheUpgradingtheBrokerchapterinadditiontoanyversion-specificupgradeinstructions.
2.5.0Fullreleasenotes.
Highlights:
Exclusiveconsumers.EquivalentActiveMQ5.xVirtualTopicnamingabilities.SSLCertificaterevocationlist.Last-valuequeuesupportforOpenWire.Supportmaskedpasswordsinbootstrap.xmandlogin.configConfigurablebrokerpluginimplementationforloggingvariousbrokerevents(i.e.LoggingActiveMQServerPlugin).OptiontouseOpenSSLproviderforNettyviathesslProviderURLparameter.Enablesplittingofbroker.xmlintomultiplefiles.Enhancedmessagecountandsizemetricsforqueues.
Upgradingfrom2.4.0
1. DuetochangesfromARTEMIS-1644anyacceptorthatneedstobecompatiblewithHornetQand/orArtemis1.xclientsneedstohaveanycastPrefix=jms.queue.;multicastPrefix=jms.topic.intheacceptorurl.Thisprefixusedtobeconfiguredautomaticallybehindthesceneswhenthebrokerdetectedtheseoldtypesofclients,butthatbrokecertainuse-caseswithnopossiblework-around.SeeARTEMIS-1644formoredetails.
Versions
8
https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12342127https://issues.apache.org/jira/browse/ARTEMIS-1644https://issues.apache.org/jira/browse/ARTEMIS-1644
-
2.4.0Fullreleasenotes.
Highlights:
JMXconfigurationviaXMLratherthanhavingtousesystempropertiesviacommandlineorstartscript.ConfigurationofmaxframepayloadlengthforSTOMPweb-socket.AbilitytoconfigureHAusingJDBCpersistence.Implementrole-basedaccesscontrolformanagementobjects.
Upgradingfrom2.3.0
1. Create/etc/management.xml.Attheveryleast,thefilemustcontainthis:
ThisconfiguresrolebasedauthorisationforJMX.ReadmoreintheManagementdocumentation.
2. Ifconfigured,removetheJolokiawarfilefromthewebelementin/etc/bootstrap.xml:
ThisisnolongerrequiredastheJolokiaRESTinterfaceisnowintegratedintotheconsolewebapplication.
Ifthefollowingisabsentandyoudesiretodeploythewebconsolethenadd:
NOTE:theJolokiaRESTinterfaceURLwillnowbeathttp://:/console/jolokia
2.3.0Fullreleasenotes.
Versions
9
https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12341540https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12341247
-
Highlights:
Webadminconsole!CriticalAnalysisanddeadlockdetectiononbrokerSupportNettynativekqueueonMac.Last-valuequeueforAMQP
Upgradingfrom2.2.0
1. Ifyoudesiretodeploythewebconsolethenaddthefollowingtothewebelementin/etc/bootstrap.xml:
2.2.0Fullreleasenotes.
Highlights:
ScheduledmessageswiththeSTOMPprotocol.SupportforJNDIReferenceFactoryandJNDIStorable.Abilitytodeletequeuesandaddresseswhenbroker.xmlchanges.ClientauthenticationviaKerberosTLSCipherSuites(RFC2712).
2.1.0Fullreleasenotes.
Highlights:
Brokerpluginsupport.SupportNettynativeepollonLinux.Abilitytoconfigurearbitrarysecurityrolemappings.AMQPperformanceimprovements.
2.0.0Fullreleasenotes.
Versions
10
https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12340541https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12339963https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12338813
-
Highlights:
Hugeupdateinvolvingasignificantrefactoringoftheaddressingmodelyieldingthefollowingbenefits:
SimplerandmoreflexibleXMLconfiguration.Supportforadditionalmessaginguse-cases.EliminatesconfusingJMS-specificqueuenamingconventions(i.e."jms.queue."&"jms.topic."prefixes).
PureencodingofmessagessoprotocolslikeAMQPdon'tneedtoconvertmessagesto"core"formatunlessabsolutelynecessary."MAPPED"journaltypeforincreasedperformanceincertainuse-cases.
1.5.6Fullreleasenotes.
Highlights:
Bugfixes.
1.5.5Fullreleasenotes.
Highlights:
Bugfixes.
1.5.4Fullreleasenotes.
Highlights:
SupportOracle12CforJDBCpersistence.Bugfixes.
1.5.3
Versions
11
https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12340547https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12339947https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12339158
-
Fullreleasenotes.
Highlights:
Support"bytenotation"(e.g."K","KB","Gb",etc.)inbrokerXMLconfiguration.CLIcommandtorecalculatedisksynctimes.Bugfixes.
1.5.2Fullreleasenotes.
Highlights:
SupportforpagingusingJDBC.Bugfixes.
1.5.1Fullreleasenotes.
Highlights:
SupportoutgoingconnectionsforAMQP.Bugfixes.
1.5.0Fullreleasenotes.
Highlights:
AMQPperformanceimprovements.JUnitruleimplementationsomessagingresourceslikebrokerscanbeeasilyconfiguredintests.BasicCDIintegration.Storeuser'spasswordinhashformbydefault.
1.4.0
Versions
12
https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12339575https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12338833https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12338661https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12338118
-
Fullreleasenotes.
Highlights:
"Global"limitfordiskusage.DetectandreloadcertainXMLconfigurationchangesatruntime.MQTTinterceptors.Supportadding/deletingqueuesviaCLI.New"browse"securitypermissionforclientswhoonlywishtolookatmessages.OptiontopopulateJMSXUserID."Dualauthentication"supporttoauthenticateSSL-basedandnon-SSL-basedclientsdifferently.
1.3.0Fullreleasenotes.
Highlights:
BettersupportofOpenWirefeatures(e.g.reconnect,producerflow-control,optimizedacknowledgements)SSLkeystorereloadatruntime.InitialsupportforJDBCpersistence.Supportscheduledmessagesonlast-valuequeue.
1.2.0Fullreleasenotes.
Highlights:
ImprovementsaroundperformanceOSGisupport.Supportfunctionalityequivalenttoall5.xJAASloginmodulesincluding:
PropertiesfileLDAPSSLcertificate"Guest"
Versions
13
https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12336052https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12328978https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12333274
-
1.1.0Fullreleasenotes.
Highlights:
MQTTsupport.TheexamplesnowusetheCLIprogrammaticallytocreate,start,stop,etc.serversreflectingrealcasesusedinproduction.CLIimprovements.Therearenewtoolstocompactthejournalandadditionalimprovementstotheuserexperience.Configurableresourcelimits.Abilitytodisableserver-sidemessageload-balancing.
1.0.0Fullreleasenotes.
Highlights:
Firstreleaseofthedonatedcode-baseasActiveMQArtemis!LotsoffeaturesforparitywithActiveMQ5.xincluding:
OpenWiresupportAMQP1.0supportURLbasedconnectionsAuto-createaddresses/queuesJolokiaintegration
Versions
14
https://issues.apache.org/jira/secure/ReleaseNote.jspa?version=12332642&projectId=12315920https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12328953http://mail-archives.apache.org/mod_mbox/activemq-dev/201407.mbox/%3cCAKF+bsovr7Hvn-rMYkb3pF6hoGjx7nuJWzT_Nh8MyC4usRBX9A@mail.gmail.com%3e
-
MessagingConceptsApacheActiveMQArtemisisanasynchronousmessagingsystem,anexampleofMessageOrientedMiddleware,we'lljustcallthemmessagingsystemsintheremainderofthisbook.
We'llfirstpresentabriefoverviewofwhatkindofthingsmessagingsystemsdo,wherethey'reusefulandthekindofconceptsyou'llhearaboutinthemessagingworld.
Ifyou'realreadyfamiliarwithwhatamessagingsystemisandwhatit'scapableof,thenyoucanskipthischapter.
GeneralConceptsMessagingsystemsallowyoutolooselycoupleheterogeneoussystemstogether,whilsttypicallyprovidingreliability,transactionsandmanyotherfeatures.
UnlikesystemsbasedonaRemoteProcedureCall(RPC)pattern,messagingsystemsprimarilyuseanasynchronousmessagepassingpatternwithnotightrelationshipbetweenrequestsandresponses.Mostmessagingsystemsalsosupportarequest-responsemodebutthisisnotaprimaryfeatureofmessagingsystems.
Designingsystemstobeasynchronousfromend-to-endallowsyoutoreallytakeadvantageofyourhardwareresources,minimizingtheamountofthreadsblockingonIOoperations,andtouseyournetworkbandwidthtoitsfullcapacity.WithanRPCapproachyouhavetowaitforaresponseforeachrequestyoumakesoarelimitedbythenetworkroundtriptime,orlatencyofyournetwork.Withanasynchronoussystemyoucanpipelineflowsofmessagesindifferentdirections,soarelimitedbythenetworkbandwidthnotthelatency.Thistypicallyallowsyoutocreatemuchhigherperformanceapplications.
Messagingsystemsdecouplethesendersofmessagesfromtheconsumersofmessages.Thesendersandconsumersofmessagesarecompletelyindependentandknownothingofeachother.Thisallowsyoutocreateflexible,looselycoupledsystems.
Often,largeenterprisesuseamessagingsystemtoimplementamessagebuswhichlooselycouplesheterogeneoussystemstogether.MessagebusesoftenformthecoreofanEnterpriseServiceBus.(ESB).Usingamessagebustode-coupledisparatesystems
MessagingConcepts
15
https://en.wikipedia.org/wiki/Message-oriented_middlewarehttps://en.wikipedia.org/wiki/Remote_procedure_callhttps://en.wikipedia.org/wiki/Enterprise_service_bus
-
canallowthesystemtogrowandadaptmoreeasily.Italsoallowsmoreflexibilitytoaddnewsystemsorretireoldonessincetheydon'thavebrittledependenciesoneachother.
MessagingstylesMessagingsystemsnormallysupporttwomainstylesofasynchronousmessaging:messagequeuemessaging(alsoknownaspoint-to-pointmessaging)andpublishsubscribemessaging.We'llsummarisethembrieflyhere:
Point-to-Point
Withthistypeofmessagingyousendamessagetoaqueue.Themessageisthentypicallypersistedtoprovideaguaranteeofdelivery,thensometimelaterthemessagingsystemdeliversthemessagetoaconsumer.Theconsumerthenprocessesthemessageandwhenitisdone,itacknowledgesthemessage.Oncethemessageisacknowledgeditdisappearsfromthequeueandisnotavailabletobedeliveredagain.Ifthesystemcrashesbeforethemessagingserverreceivesanacknowledgementfromtheconsumer,thenonrecovery,themessagewillbeavailabletobedeliveredtoaconsumeragain.
Withpoint-to-pointmessaging,therecanbemanyconsumersonthequeuebutaparticularmessagewillonlyeverbeconsumedbyamaximumofoneofthem.Senders(alsoknownasproducers)tothequeuearecompletelydecoupledfromreceivers(alsoknownasconsumers)ofthequeue-theydonotknowofeachother'sexistence.
Aclassicexampleofpointtopointmessagingwouldbeanorderqueueinacompany'sbookorderingsystem.Eachorderisrepresentedasamessagewhichissenttotheorderqueue.Let'simaginetherearemanyfrontendorderingsystemswhichsendorderstotheorderqueue.Whenamessagearrivesonthequeueitispersisted-thisensuresthatiftheservercrashestheorderisnotlost.Let'salsoimaginetherearemanyconsumersontheorderqueue-eachrepresentinganinstanceofanorderprocessingcomponent-thesecanbeondifferentphysicalmachinesbutconsumingfromthesamequeue.Themessagingsystemdeliverseachmessagetooneandonlyoneoftheorderingprocessingcomponents.Differentmessagescanbeprocessedbydifferentorderprocessors,butasingleorderisonlyprocessedbyoneorderprocessor-thisensuresordersaren'tprocessedtwice.
MessagingConcepts
16
https://en.wikipedia.org/wiki/Message_queuehttps://en.wikipedia.org/wiki/Publish_subscribe
-
Asanorderprocessorreceivesamessage,itfulfillstheorder,sendsorderinformationtothewarehousesystemandthenupdatestheorderdatabasewiththeorderdetails.Onceit'sdonethatitacknowledgesthemessagetotelltheserverthattheorderhasbeenprocessedandcanbeforgottenabout.Oftenthesendtothewarehousesystem,updateindatabaseandacknowledgementwillbecompletedinasingletransactiontoensureACIDproperties.
Publish-Subscribe
Withpublish-subscribemessagingmanysenderscansendmessagestoanentityontheserver,oftencalledatopic(e.g.intheJMSworld).
Therecanbemanysubscriptionsonatopic,asubscriptionisjustanotherwordforaconsumerofatopic.Eachsubscriptionreceivesacopyofeachmessagesenttothetopic.Thisdiffersfromthemessagequeuepatternwhereeachmessageisonlyconsumedbyasingleconsumer.
Subscriptionscanoptionallybedurablewhichmeanstheyretainacopyofeachmessagesenttothetopicuntilthesubscriberconsumesthem-eveniftheservercrashesorisrestartedinbetween.Non-durablesubscriptionsonlylastamaximumofthelifetimeoftheconnectionthatcreatedthem.
Anexampleofpublish-subscribemessagingwouldbeanewsfeed.Asnewsarticlesarecreatedbydifferenteditorsaroundtheworldtheyaresenttoanewsfeedtopic.Therearemanysubscribersaroundtheworldwhoareinterestedinreceivingnewsitems-eachonecreatesasubscriptionandthemessagingsystemensuresthatacopyofeachnewsmessageisdeliveredtoeachsubscription.
DeliveryguaranteesAkeyfeatureofmostmessagingsystemsisreliablemessaging.Withreliablemessagingtheservergivesaguaranteethatthemessagewillbedeliveredonceandonlyoncetoeachconsumerofaqueueoreachdurablesubscriptionofatopic,evenintheeventofsystemfailure.Thisiscrucialformanybusinesses;e.g.youdon'twantyourordersfulfilledmorethanonceoranyofyourorderstobelost.
Inothercasesyoumaynotcareaboutaonceandonlyoncedeliveryguaranteeandarehappytocopewithduplicatedeliveriesorlostmessages-anexampleofthismightbetransientstockpriceupdates-whicharequicklysupersededbythenextupdateonthe
MessagingConcepts
17
https://en.wikipedia.org/wiki/ACID
-
samestock.Themessagingsystemallowsyoutoconfigurewhichdeliveryguaranteesyourequire.
TransactionsMessagingsystemstypicallysupportthesendingandacknowledgementofmultiplemessagesinasinglelocaltransaction.ApacheActiveMQArtemisalsosupportsthesendingandacknowledgementofmessageaspartofalargeglobaltransaction-usingtheJavamappingofXA:JTA.
DurabilityMessagesareeitherdurableornondurable.Durablemessageswillbepersistedinpermanentstorageandwillsurviveserverfailureorrestart.Nondurablemessageswillnotsurviveserverfailureorrestart.Examplesofdurablemessagesmightbeordersortrades,wheretheycannotbelost.Anexampleofanondurablemessagemightbeastockpriceupdatewhichistransitoryanddoesn'tneedtosurvivearestart.
MessagingAPIsandprotocolsHowdoclientapplicationsinteractwithmessagingsystemsinordertosendandconsumemessages?
SeveralmessagingsystemsprovidetheirownproprietaryAPIswithwhichtheclientcommunicateswiththemessagingsystem.
Therearealsosomestandardwaysofoperatingwithmessagingsystemsandsomeemergingstandardsinthisspace.
Let'stakeabrieflookatthese:
JavaMessageService(JMS)
JMSispartofOracle'sJavaEEspecification.It'saJavaAPIthatencapsulatesbothmessagequeueandpublish-subscribemessagingpatterns.JMSisalowestcommondenominatorspecification-i.e.itwascreatedtoencapsulatecommonfunctionalityofthealreadyexistingmessagingsystemsthatwereavailableatthetimeofitscreation.
MessagingConcepts
18
https://en.wikipedia.org/wiki/Java_Message_Service
-
JMSisaverypopularAPIandisimplementedbymostmessagingsystems.JMSisonlyavailabletoclientsrunningJava.
JMSdoesnotdefineastandardwireformat-itonlydefinesaprogrammaticAPIsoJMSclientsandserversfromdifferentvendorscannotdirectlyinteroperatesinceeachwillusethevendor'sowninternalwireprotocol.
ApacheActiveMQArtemisprovidesafullycompliantJMS1.1andJMS2.0API.
SystemspecificAPIs
ManysystemsprovidetheirownprogrammaticAPIforwhichtointeractwiththemessagingsystem.Theadvantageofthisitallowsthefullsetofsystemfunctionalitytobeexposedtotheclientapplication.API'slikeJMSarenotnormallyrichenoughtoexposealltheextrafeaturesthatmostmessagingsystemsprovide.
ApacheActiveMQArtemisprovidesitsowncoreclientAPIforclientstouseiftheywishtohaveaccesstofunctionalityoverandabovethataccessibleviatheJMSAPI.
RESTfulAPI
RESTapproachestomessagingareshowingalotinterestrecently.
ItseemsplausiblethatAPIstandardsforcloudcomputingmayconvergeonaRESTstylesetofinterfacesandconsequentlyaRESTmessagingapproachisaverystrongcontenderforbecomingthede-factomethodformessaginginteroperability.
WithaRESTapproachmessagingresourcesaremanipulatedasresourcesdefinedbyaURIandtypicallyusingasimplesetofoperationsonthoseresources,e.g.PUT,POST,GETetc.RESTapproachestomessagingoftenuseHTTPastheirunderlyingprotocol.
TheadvantageofaRESTapproachwithHTTPisinitssimplicityandthefacttheinternetisalreadytunedtodealwithHTTPoptimally.
PleaseseeRestInterfaceforusingApacheActiveMQArtemis'sRESTfulinterface.
AMQP
AMQPisaspecificationforinteroperablemessaging.Italsodefinesawireformat,soanyAMQPclientcanworkwithanymessagingsystemthatsupportsAMQP.AMQPclientsareavailableinmanydifferentprogramminglanguages.
MessagingConcepts
19
https://en.wikipedia.org/wiki/Representational_State_Transferhttps://en.wikipedia.org/wiki/AMQP
-
ApacheActiveMQArtemisimplementstheAMQP1.0specification.Anyclientthatsupportsthe1.0specificationwillbeabletointeractwithApacheActiveMQArtemis.
MQTT
MQTTisalightweightconnectivityprotocol.Itisdesignedtoruninenvironmentswheredeviceandnetworksareconstrained.OutoftheboxApacheActiveMQArtemissupportsversionMQTT3.1.1.AnyclientsupportingthisversionoftheprotocolwillworkagainstApacheActiveMQArtemis.
STOMP
Stompisaverysimpletextprotocolforinteroperatingwithmessagingsystems.Itdefinesawireformat,sotheoreticallyanyStompclientcanworkwithanymessagingsystemthatsupportsStomp.Stompclientsareavailableinmanydifferentprogramminglanguages.
PleaseseeStompforusingSTOMPwithApacheActiveMQArtemis.
OPENWIRE
ActiveMQ5.xdefinesit'sownwireProtocol"OPENWIRE".InordertosupportActiveMQ5.xclients,ApacheActiveMQArtemissupportsOPENWIRE.AnyActiveMQ5.12.xorhighercanbeusedwithApacheActiveMQArtemis.
HighAvailabilityHighAvailability(HA)meansthatthesystemshouldremainoperationalafterfailureofoneormoreoftheservers.ThedegreeofsupportforHAvariesbetweenvariousmessagingsystems.
ApacheActiveMQArtemisprovidesautomaticfailoverwhereyoursessionsareautomaticallyreconnectedtothebackupserveroneventofliveserverfailure.
FormoreinformationonHA,pleaseseeHighAvailabilityandFailover.
Clusters
MessagingConcepts
20
https://www.oasis-open.org/committees/tc_home.php?wg_abbrev=amqphttps://mqtt.org/https://stomp.github.io/
-
Manymessagingsystemsallowyoutocreategroupsofmessagingserverscalledclusters.Clustersallowtheloadofsendingandconsumingmessagestobespreadovermanyservers.Thisallowsyoursystemtoscalehorizontallybyaddingnewserverstothecluster.
Degreesofsupportforclustersvariesbetweenmessagingsystems,withsomesystemshavingfairlybasicclusterswiththeclustermembersbeinghardlyawareofeachother.
ApacheActiveMQArtemisprovidesveryconfigurablestate-of-the-artclusteringmodelwheremessagescanbeintelligentlyloadbalancedbetweentheserversinthecluster,accordingtothenumberofconsumersoneachnode,andwhethertheyarereadyformessages.
ApacheActiveMQArtemisalsohastheabilitytoautomaticallyredistributemessagesbetweennodesofaclustertopreventstarvationonanyparticularnode.
Forfulldetailsonclustering,pleaseseeClusters.
BridgesandroutingSomemessagingsystemsallowisolatedclustersorsinglenodestobebridgedtogether,typicallyoverunreliableconnectionslikeawideareanetwork(WAN),ortheinternet.
Abridgenormallyconsumesfromaqueueononeserverandforwardsmessagestoanotherqueueonadifferentserver.Bridgescopewithunreliableconnections,automaticallyreconnectingwhentheconnectionsbecomesavailableagain.
ApacheActiveMQArtemisbridgescanbeconfiguredwithfilterexpressionstoonlyforwardcertainmessages,andtransformationcanalsobehookedin.
ApacheActiveMQArtemisalsoallowsroutingbetweenqueuestobeconfiguredinserversideconfiguration.Thisallowscomplexroutingnetworkstobesetupforwardingorcopyingmessagesfromonedestinationtoanother,formingaglobalnetworkofinterconnectedbrokers.
FormoreinformationpleaseseeCoreBridgesandDivertingandSplittingMessageFlows.
MessagingConcepts
21
-
CoreArchitectureApacheActiveMQArtemiscoreisdesignedsimplyassetofPlainOldJavaObjects(POJOs)-wehopeyoulikeitsclean-cutdesign.
EachApacheActiveMQArtemisserverhasitsownultrahighperformancepersistentjournal,whichitusesformessageandotherpersistence.
Usingahighperformancejournalallowsoutrageouspersistencemessageperformance,somethingnotachievablewhenusingarelationaldatabaseforpersistence.
ApacheActiveMQArtemisclients,potentiallyondifferentphysicalmachinesinteractwiththeApacheActiveMQArtemisserver.ApacheActiveMQArtemiscurrentlyprovidestwoAPIsformessagingattheclientside:
1. CoreclientAPI.ThisisasimpleintuitiveJavaAPIthatisalignedwiththeArtemisinternalCore.Allowingmorecontrolofbrokerobjects,likeforexample,directcreationofaddressesandqueues.TheCoreAPIalsooffersafullsetofmessagingfunctionalitywithoutsomeofthecomplexitiesofJMS.
2. JMSclientAPI.ThestandardJMSAPIisavailableattheclientside.
ApacheActiveMQArtemisalsoprovidesdifferentprotocolimplementationsontheserversoyoucanuserespectiveclientsfortheseprotocols:
1. AMQP2. OpenWire3. MQTT4. STOMP5. HornetQ(forusewithHornetQclients).6. CORE(ArtemisCOREprotocol)
JMSsemanticsareimplementedbyaJMSfacadelayerontheclientside.
TheApacheActiveMQArtemisserverdoesnotspeakJMSandinfactdoesnotknowanythingaboutJMS,itisaprotocolagnosticmessagingserverdesignedtobeusedwithmultipledifferentprotocols.
WhenauserusestheJMSAPIontheclientside,allJMSinteractionsaretranslatedintooperationsontheApacheActiveMQArtemiscoreclientAPIbeforebeingtransferredoverthewireusingtheApacheActiveMQArtemiswireformat.
Architecture
22
-
TheserveralwaysjustdealswithcoreAPIinteractions.
Aschematicillustratingthisrelationshipisshowninfigure3.1below:
Architecture
23
-
Figure3.1showstwouserapplicationsinteractingwithanApacheActiveMQArtemisserver.UserApplication1isusingtheJMSAPI,whileUserApplication2isusingthecoreclientAPIdirectly.
YoucanseefromthediagramthattheJMSAPIisimplementedbyathinfacadelayerontheclientside.
Stand-aloneBrokerThenormalstand-alonemessagingbrokerconfigurationcomprisesacoremessagingbrokerandanumberofprotocolmanagersthatprovidesupportforthevariousprotocolmentionedearlier.Protocolmanagersarepluggableifyou
Thestand-alonebrokerconfigurationusesAirlineforbootstrappingtheBroker.
Thestand-alonebrokerarchitectureisshowninfigure3.3below:
Architecture
24
https://github.com/airlift/airline
-
FormoreinformationonserverconfigurationfilesseeServerConfiguration
Architecture
25
-
EmbeddedBrokerApacheActiveMQArtemiscoreisdesignedasasetofsimplePOJOssoifyouhaveanapplicationthatrequiresmessagingfunctionalityinternallybutyoudon'twanttoexposethatasanApacheActiveMQArtemisbrokeryoucandirectlyinstantiateandembedApacheActiveMQArtemisbrokersinyourownapplication.
FormoreinformationonembeddingApacheActiveMQArtemis,seeEmbeddingApacheActiveMQArtemis.
IntegratedwithaJavaEEapplicationserverApacheActiveMQArtemisprovidesitsownfullyfunctionalJavaConnectorArchitecture(JCA)adaptorwhichenablesittobeintegratedeasilyintoanyJavaEEcompliantapplicationserverorservletengine.
JavaEEapplicationserversprovideMessageDrivenBeans(MDBs),whichareaspecialtypeofEnterpriseJavaBeans(EJBs)thatcanprocessmessagesfromsourcessuchasJMSsystemsormailsystems.
ProbablythemostcommonuseofanMDBistoconsumemessagesfromaJMSmessagingsystem.
AccordingtotheJavaEEspecification,aJavaEEapplicationserverusesaJCAadaptertointegratewithaJMSmessagingsystemsoitcanconsumemessagesforMDBs.
However,theJCAadapterisnotonlyusedbytheJavaEEapplicationserverforconsumingmessagesviaMDBs,itisalsousedwhensendingmessagetotheJMSmessagingsysteme.g.frominsideanEJBorservlet.
WhenintegratingwithaJMSmessagingsystemfrominsideaJavaEEapplicationserveritisalwaysrecommendedthatthisisdoneviaaJCAadaptor.Infact,communicatingwithaJMSmessagingsystemdirectly,withoutusingJCAwouldbeillegalaccordingtotheJavaEEspecification.
Theapplicationserver'sJCAserviceprovidesextrafunctionalitysuchasconnectionpoolingandautomatictransactionenlistment,whicharedesirablewhenusingmessaging,say,frominsideanEJB.ItispossibletotalktoaJMSmessagingsystem
Architecture
26
-
directlyfromanEJB,MDBorservletwithoutgoingthroughaJCAadapter,butthisisnotrecommendedsinceyouwillnotbeabletotakeadvantageoftheJCAfeatures,suchascachingofJMSsessions,whichcanresultinpoorperformance.
Figure3.2belowshowsaJavaEEapplicationserverintegratingwithaApacheActiveMQArtemisserverviatheApacheActiveMQArtemisJCAadaptor.NotethatallcommunicationbetweenEJBsessionsorentitybeansandMessageDrivenbeansgothroughtheadaptorandnotdirectlytoApacheActiveMQArtemis.
ThelargearrowwiththeprohibitedsignshowsanEJBsessionbeantalkingdirectlytotheApacheActiveMQArtemisserver.Thisisnotrecommendedasyou'llmostlikelyendupcreatinganewconnectionandsessioneverytimeyouwanttointeractfromtheEJB,whichisananti-pattern.
Architecture
27
-
Architecture
28
-
Architecture
29
-
UsingtheServerThischapterwillfamiliariseyouwithhowtousetheApacheActiveMQArtemisserver.
We'llshowwhereitis,howtostartandstopit,andwe'lldescribethedirectorylayoutandwhatallthefilesareandwhattheydo.
FortheremainderofthischapterwhenwetalkabouttheApacheActiveMQArtemisserverwemeantheApacheActiveMQArtemisstandaloneserver,initsdefaultconfigurationwithaJMSServiceenabled.
ThisdocumentwillrefertothefullpathofthedirectorywheretheActiveMQdistributionhasbeenextractedtoas${ARTEMIS_HOME}directory.
InstallationAfterdownloadingthedistribution,thefollowinghighlightssomeimportantfoldersonthedistribution:
|___bin||___examples||___common||___features||___perf||___protocols||___lib||___client||___schema||___web|___api|___hacking-guide|___migration-guide|___user-manual
bin-binariesandscriptsneededtorunActiveMQArtemis.
examples-Allmannerofexamples.Pleaserefertotheexampleschapterfordetailsonhowtorunthem.
UsingtheServer
30
-
lib-jarsandlibrariesneededtorunActiveMQArtemis
schema-XMLSchemasusedtovalidateActiveMQArtemisconfigurationfiles
web-Thefolderwherethewebcontextisloadedwhenthebrokerruns.
api-Theapidocumentationisplacedunderthewebfolder.
user-manual-Theusermanualisplacedunderthewebfolder.
CreatingaBrokerInstanceAbrokerinstanceisthedirectorycontainingalltheconfigurationandruntimedata,suchaslogsanddatafiles,associatedwithabrokerprocess.Itisrecommendedthatyoudonotcreatetheinstancedirectoryunder${ARTEMIS_HOME}.ThisseparationisencouragedsothatyoucanmoreeasilyupgradewhenthenextversionofActiveMQArtemisisreleased.
OnUnixsystems,itisacommonconventiontostorethiskindofruntimedataunderthe/var/libdirectory.Forexample,tocreateaninstanceat'/var/lib/mybroker',runthefollowingcommandsinyourcommandlineshell:
cd/var/lib${ARTEMIS_HOME}/bin/artemiscreatemybroker
Abrokerinstancedirectorywillcontainthefollowingsubdirectories:
bin:holdsexecutionscriptsassociatedwiththisinstance.etc:holdtheinstanceconfigurationfilesdata:holdsthedatafilesusedforstoringpersistentmessageslog:holdsrotatinglogfilestmp:holdstemporaryfilesthataresafetodeletebetweenbrokerruns
Atthispointyoumaywanttoadjustthedefaultconfigurationlocatedintheetcdirectory.
Options
Thereareseveraloptionsyoucanusewhencreatinganinstance.
Forafulllistofupdatedpropertiesalwaysuse:
UsingtheServer
31
-
$./artemishelpcreateNAMEartemiscreate-createsanewbrokerinstance
SYNOPSISartemiscreate[--addresses][--aio][--allow-anonymous][--autocreate][--blocking][--cluster-password][--cluster-user][--clustered][--data][--default-port][--disable-persistence][--encoding][--etc][--failover-on-shutdown][--force][--global-max-size][--home][--host][--http-host][--http-port][--java-options][--mapped][--max-hops][--message-load-balancing][--name][--nio][--no-amqp-acceptor][--no-autocreate][--no-autotune][--no-fsync][--no-hornetq-acceptor][--no-mqtt-acceptor][--no-stomp-acceptor][--no-web][--paging][--password][--ping][--port-offset][--queues][--replicated][--require-login][--role][--shared-store][--silent][--slave][--ssl-key][--ssl-key-password][--ssl-trust][--ssl-trust-password][--use-client-auth][--user][--verbose][--]
OPTIONS--addressesCommaseparatedlistofaddresses
--aioSetsthejournalasasyncio.
--allow-anonymousEnablesanonymousconfigurationonsecurity,oppositeof--require-login(Default:input)
--autocreateAutocreateaddresses.(default:true)
--blockingBlockproducerswhenaddressbecomesfull,oppositeof--paging(Default:false)
--cluster-passwordTheclusterpasswordtouseforclustering.(Default:input)
--cluster-userTheclusterusertouseforclustering.(Default:input)
UsingtheServer
32
-
--clusteredEnableclustering
--dataDirectorywhereActiveMQdataarestored.Pathscanbeabsoluteorrelativetoartemis.instancedirectory('data'bydefault)
--default-portTheportnumbertouseforthemain'artemis'acceptor(Default:61616)
--disable-persistenceDisablemessagepersistencetothejournal
--encodingTheencodingthattextfilesshoulduse
--etcDirectorywhereActiveMQconfigurationislocated.Pathscanbeabsoluteorrelativetoartemis.instancedirectory('etc'bydefault)
--failover-on-shutdownValidforsharedstore:willshutdowntriggerafailover?(Default:false)
--forceOverwriteconfigurationatdestinationdirectory
--global-max-sizeMaximumamountofmemorywhichmessagedatamayconsume(Default:Undefined,halfofthesystem'smemory)
--homeDirectorywhereActiveMQArtemisisinstalled
--hostThehostnameofthebroker(Default:0.0.0.0orinputifclustered)
--http-hostThehostnametouseforembeddedwebserver(Default:localhost)
--http-portTheportnumbertouseforembeddedwebserver(Default:8161)
--java-optionsExtrajavaoptionstobepassedtotheprofile
--mappedSetsthejournalasmapped.
--max-hops
UsingtheServer
33
-
Numberofhopsontheclusterconfiguration
--message-load-balancingLoadbalancingpolicyoncluster.[ON_DEMAND(default)|STRICT|OFF]
--nameThenameofthebroker(Default:sameashost)
--nioSetsthejournalasnio.
--no-amqp-acceptorDisabletheAMQPspecificacceptor.
--no-autocreateDisableAutocreateaddresses.
--no-autotuneDisableautotuningonthejournal.
--no-fsyncDisableusageoffdatasync(channel.force(false)fromjavanio)onthejournal
--no-hornetq-acceptorDisabletheHornetQspecificacceptor.
--no-mqtt-acceptorDisabletheMQTTspecificacceptor.
--no-stomp-acceptorDisabletheSTOMPspecificacceptor.
--no-webRemovetheweb-serverdefinitionfrombootstrap.xml
--pagingPagemessagestodiskwhenaddressbecomesfull,oppositeof--blocking(Default:true)
--passwordTheuser'spassword(Default:input)
--pingAcommaseparatedstringtobepassedontothebrokerconfigasnetwork-check-list.Thebrokerwillshutdownwhenalltheseaddressesareunreachable.
--port-offsetOffsetstheportsofeveryacceptor
UsingtheServer
34
-
--queuesCommaseparatedlistofqueues.
--replicatedEnablebrokerreplication
--require-loginThiswillconfiguresecuritytorequireuser/password,oppositeof--allow-anonymous
--roleThenamefortherolecreated(Default:amq)
--shared-storeEnablebrokersharedstore
--silentItwilldisablealltheinputs,anditwouldmakeabestguessforanyrequiredinput
--slaveValidforsharedstoreorreplication:thisisaslaveserver?
--ssl-keyThekeystorepathforembeddedwebserver
--ssl-key-passwordThekeystorepassword
--ssl-trustThetruststorepathincaseofclientauthentication
--ssl-trust-passwordThetruststorepassword
--use-client-authIftheembeddedserverrequiresclientauthentication
--userTheusername(Default:input)
--verboseAddsmoreinformationontheexecution
--Thisoptioncanbeusedtoseparatecommand-lineoptionsfromthelistofargument,(usefulwhenargumentsmightbemistakenforcommand-lineoptions
Theinstancedirectorytoholdthebroker'sconfigurationanddata.Pathmustbewritable.
UsingtheServer
35
-
Someofthesepropertiesmaybemandatoryincertainconfigurationsandthesystemmayaskyouforadditionalinput.
./artemiscreate/usr/serverCreatingActiveMQArtemisinstanceat:/user/server
--user:isamandatoryproperty!Pleaseprovidethedefaultusername:admin
--password:ismandatorywiththisconfiguration:Pleaseprovidethedefaultpassword:
--allow-anonymous|--require-login:isamandatoryproperty!Allowanonymousaccess?,validvaluesareY,N,True,Falsey
Autotuningjournal...done!Yoursystemcanmake0.34writespermillisecond,yourjournal-buffer-timeoutwillbe2956000
Youcannowstartthebrokerbyexecuting:
"/user/server/bin/artemis"run
Oryoucanrunthebrokerinthebackgroundusing:
"/user/server/bin/artemis-service"start
StartingandStoppingaBrokerInstanceAssumingyoucreatedthebrokerinstanceunder/var/lib/mybrokerallyouneedtodostartrunningthebrokerinstanceisexecute:
/var/lib/mybroker/bin/artemisrun
Nowthatthebrokerisrunning,youcanoptionallyrunsomeoftheincludedexamplestoverifythethebrokerisrunningproperly.
TostoptheApacheActiveMQArtemisinstanceyouwillusethesameartemisscript,butwiththestopargument.Example:
UsingtheServer
36
-
/var/lib/mybroker/bin/artemisstop
PleasenotethatApacheActiveMQArtemisrequiresaJava7orlaterruntimetorun.
Bydefaulttheetc/bootstrap.xmlconfigurationisused.Theconfigurationcanbechangede.g.byrunning./artemisrun--xml:path/to/bootstrap.xmloranotherconfigofyourchoosing.
Environmentvariablesareusedtoprovideeaseofchangingports,hostsanddatadirectoriesusedandcanbefoundinetc/artemis.profileonlinuxandetc\artemis.profile.cmdonWindows.
ServerJVMsettingsTherunscriptssetsomeJVMsettingsfortuningthegarbagecollectionpolicyandheapsize.WerecommendusingaparallelgarbagecollectionalgorithmtosmoothoutlatencyandminimiselargeGCpauses.
BydefaultApacheActiveMQArtemisrunsinamaximumof1GiBofRAM.Toincreasethememorysettingschangethe-Xmsand-XmxmemorysettingsasyouwouldforanyJavaprogram.
IfyouwishtoaddanymoreJVMargumentsortunetheexistingones,therunscriptsaretheplacetodoit.
LibraryPathIfyou'reusingtheAsynchronousIOJournalonLinux,youneedtospecifyjava.library.pathasapropertyonyourJavaoptions.Thisisdoneautomaticallyinthescripts.
Ifyoudon'tspecifyjava.library.pathatyourJavaoptionsthentheJVMwillusetheenvironmentvariableLD_LIBRARY_PATH.
YouwillneedtomakesurelibaioisinstalledonLinux.FormoreinformationrefertothelibaiochapteratRuntimeDependencies
Systemproperties
UsingtheServer
37
-
ApacheActiveMQArtemiscantakeasystempropertyonthecommandlineforconfiguringlogging.
Formoreinformationonconfiguringlogging,pleaseseethesectiononLogging.
ConfigurationfilesTheconfigurationfileusedtobootstraptheserver(e.g.bootstrap.xmlbydefault)referencesthespecificbrokerconfigurationfiles.
broker.xml.ThisisthemainActiveMQconfigurationfile.Alltheparametersinthisfilearedescribedhere
Itisalsopossibletousesystempropertysubstitutioninalltheconfigurationfiles.byreplacingavaluewiththenameofasystemproperty.Hereisanexampleofthiswithaconnectorconfiguration:
tcp://${activemq.remoting.netty.host:localhost}:${activemq.remoting.netty.port:61616}
Hereyoucanseewehavereplaced2valueswithsystempropertiesactivemq.remoting.netty.hostandactivemq.remoting.netty.port.Thesevalueswillbereplacedbythevaluefoundinthesystempropertyifthereisone,ifnottheydefaultbacktolocalhostor61616respectively.Itisalsopossibletonotsupplyadefault.i.e.${activemq.remoting.netty.host},howeverthesystempropertymustbesuppliedinthatcase.
Bootstrapconfigurationfile
Thestand-aloneserverisbasicallyasetofPOJOswhichareinstantiatedbyAirlinecommands.
Thebootstrapfileisverysimple.Let'stakealookatanexample:
UsingtheServer
38
-
server-Instantiatesacoreserverusingtheconfigurationfilefromtheconfigurationattribute.ThisisthemainbrokerPOJOnecessarytodoalltherealmessagingwork.
jaas-security-Configuressecurityfortheserver.Thedomainattributereferstotherelevantloginmoduleentryinlogin.config.
web-ConfiguresanembeddedJettyinstancetoservewebapplicationsliketheadminconsole.
Brokerconfigurationfile
TheconfigurationfortheApacheActiveMQArtemiscoreserveriscontainedinbroker.xml.ThisiswhattheFileConfigurationbeanusestoconfigurethemessagingserver.
TherearemanyattributeswhichyoucanconfigureApacheActiveMQArtemis.Inmostcasesthedefaultswilldofine,infacteveryattributecanbedefaultedwhichmeansafilewithasingleemptyconfigurationelementisavalidconfigurationfile.Thedifferentconfigurationwillbeexplainedthroughoutthemanualoryoucanrefertotheconfigurationreferencehere.
WindowsServerOnwindowsyouwillhavetheoptiontorunActiveMQArtemisasaservice.Justusethefollowingcommandtoinstallit:
$./artemis-service.exeinstall
UsingtheServer
39
-
Thecreateprocessshouldgiveyouahintoftheavailablecommandsavailablefortheartemis-service.exe
AddingRuntimeDependenciesRuntimedependencieslikediverts,transformers,brokerplugins,JDBCdrivers,passworddecoders,etc.mustbeaccessiblebythebrokeratruntime.Packagethedependencyinajar,andputitonthebroker'sclasspath.Thiscanbedonebyplacingthejarfileinthelibdirectoryofthebrokerdistributionitselforinthelibdirectoryofthebrokerinstance.Abrokerinstancedoesnothavealibdirectorybydefaultsoitmayneedtobecreated.Itshouldbeonthe"top"levelwiththebin,data,log,etc.directories.
UsingtheServer
40
-
UpgradingtheBrokerApacheActiveMQ5.x(andpreviousversions)isrunnableoutoftheboxbyexecutingthecommand:./bin/activemqrun.TheActiveMQArtemisbrokerfollowsadifferentparadigmwheretheprojectdistributionservesasthebroker"home"andoneormorebroker"instances"arecreatedwhichreferencethe"home"forresources(e.g.jarfiles)whichcanbesafelysharedbetweenbrokerinstances.Therefore,aninstanceofthebrokermustbecreatedbeforeitcanberun.Thismayseemslikeanoverheadatfirstglance,butitbecomesverypracticalwhenupdatingtoanewArtemisversionforexample.
TocreateanArtemisbrokerinstancenavigateintotheArtemishomefolderandrun:./bin/artemiscreate/path/to/myBrokerInstanceonthecommandline.
Note
It'srecommendedtochooseafolderdifferentthantheonwhereApacheArtemiswasdownloaded.ThisseparationallowsyourunmultiplebrokerinstanceswiththesameArtemis"home"forexample.ItalsosimplifiesupdatingtonewerversionsofArtemis.
Becauseofthisseparationit'sveryeasytoupgradeArtemisinmostcases.
GeneralUpgradeProcedureUpgradingmayrequiresomespecificstepsnotedintheversions,butthegeneralprocessisasfollows:
1. Navigatetotheetcfolderofthebrokerinstancethat'sbeingupgraded2. Openartemis.profile(artemis.profile.cmdonWindows).Itcontainsaproperty
whichisrelevantfortheupgrade:
ARTEMIS_HOME='/path/to/apache-artemis-version'
TheARTEMIS_HOMEpropertyisusedtolinktheinstancewiththehome.Inmostcasestheinstancecanbeupgradedtoanewerversionsimplybychangingthevalueofthispropertytothelocationofthenewbrokerhome.Pleaserefertotheaforementionedversionsdocumentforadditionalupgradesteps(ifrequired).
Upgrading
41
-
Upgrading
42
-
AddressingModelApacheActiveMQArtemishasauniqueaddressingmodelthatisbothpowerfulandflexibleandthatoffersgreatperformance.Theaddressingmodelcomprisesthreemainconcepts:addresses,queuesandroutingtypes.
Anaddressrepresentsamessagingendpoint.Withintheconfiguration,atypicaladdressisgivenauniquename,0ormorequeues,andaroutingtype.
Aqueueisassociatedwithanaddress.Therecanbemultiplequeuesperaddress.Onceanincomingmessageismatchedtoanaddress,themessagewillbesentontooneormoreofitsqueues,dependingontheroutingtypeconfigured.Queuescanbeconfiguredtobeautomaticallycreatedanddeleted.
Aroutingtypedetermineshowmessagesaresenttothequeuesassociatedwithanaddress.AnApacheActiveMQArtemisaddresscanbeconfiguredwithtwodifferentroutingtypes.
Table1.RoutingTypes
Ifyouwantyourmessagesroutedto… Usethisroutingtype…
Asinglequeuewithinthematchingaddress,inapoint-to-pointmanner. Anycast
Everyqueuewithinthematchingaddress,inapublish-subscribemanner. Multicast
Note:Itispossibletodefinemorethanoneroutingtypeperaddress,butthistypicallyresultsinananti-patternandisthereforenotrecommended.Ifanaddressdoesusebothroutingtypes,however,andtheclientdoesnotshowapreferenceforeitherone,thebrokertypicallydefaultstotheanycastroutingtype.TheoneexceptioniswhentheclientusestheMQTTprotocol.Inthatcase,thedefaultroutingtypeismulticast.|
BasicAddressConfiguration
AddressModel
43
-
Thefollowingexamplesshowhowtoconfigurebasicpointtopointandpublishsubscribeaddresses.
Point-to-PointMessaging
Point-to-pointmessagingisacommonscenarioinwhichamessagesentbyaproducerhasonlyoneconsumer.AMQPandJMSmessageproducersandconsumerscanmakeuseofpoint-to-pointmessagingqueues,forexample.Defineananycastroutingtypeforanaddresssothatitsqueuesreceivemessagesinapoint-to-pointmanner.
Whenamessageisreceivedonanaddressusinganycast,ApacheActiveMQArtemislocatesthequeueassociatedwiththeaddressandroutesthemessagetoit.Whenconsumersrequesttoconsumefromtheaddress,thebrokerlocatestherelevantqueueandassociatesthisqueuewiththeappropriateconsumers.Ifmultipleconsumersareconnectedtothesamequeue,messagesaredistributedamongsteachconsumerequally,providingtheconsumersareequallyabletohandlethem.
Figure1.PointtoPointMessaging
UsingtheAnycastRoutingType
Openthefile/etc/broker.xmlforediting.
Addanaddressconfigurationelementanditsassociatedqueueiftheydonotexistalready.
NoteFornormalPointtoPointsemantics,thequeuenameMUSTmatchtheaddressname.
AddressModel
44
-
...
Publish-SubscribeMessaging
Inapublish-subscribescenario,messagesaresenttoeveryconsumersubscribedtoanaddress.JMStopicsandMQTTsubscriptionsaretwoexamplesofpublish-subscribemessaging.
Toconfigureanaddresswithpublish-subscribesemantics,createanaddresswiththemulticastroutingtype.
Figure2.Publish-Subscribe
UsingtheMulticastRoutingType
Openthefile/etc/broker.xmlforediting.
Addanaddressconfigurationelementwithmulticastroutingtype.
AddressModel
45
-
...
Whenclientsconnecttoanaddresswiththemulticastelement,asubscriptionqueuefortheclientwillbeautomaticallycreatedfortheclient.Itisalsopossibletopre-configuresubscriptionqueuesandconnecttothemdirectlyusingthequeue'sFullyQualifiedQueuenames.
Optionallyaddoneormorequeueelementstotheaddressandwrapthemulticastelementaroundthem.Thisstepistypicallynotneededsincethebrokerwillautomaticallycreateaqueueforeachsubscriptionrequestedbyaclient.
...
Figure3.Point-to-PointwithTwoQueues
Point-to-PointAddressmultipleQueues
Itisactuallypossibletodefinemorethanonequeueonanaddresswithananycastroutingtype.Whenmessagesarereceivedonsuchanaddress,theyarefirstlydistributedevenlyacrossallthedefinedqueues.UsingFullyQualifiedQueuenames,clientsareabletoselectthequeuethattheywouldliketosubscribeto.Shouldmorethanoneconsumerconnectdirecttoasinglequeue,ApacheActiveMQArtemiswilltakecareofdistributingmessagesbetweenthem,asintheexampleabove.
AddressModel
46
-
Figure3.Point-to-PointwithTwoQueues
Note:ThisishowApacheActiveMQArtemishandlesloadbalancingofqueuesacrossmultiplenodesinacluster.ConfiguringaPoint-to-PointAddresswithtwoqueues,openthefile/etc/broker.xmlforediting.
AddanaddressconfigurationwithAnycastroutingtypeelementanditsassociatedqueues.
...
Point-to-PointandPublish-SubscribeAddresses
Itispossibletodefineanaddresswithbothpoint-to-pointandpublish-subscribesemanticsenabled.Whilenottypicallyrecommend,thiscanbeusefulwhenyouwant,forexample,aJMSQueuesayordersandaJMSTopicnamedorders.Thedifferentroutingtypesmaketheaddressesappeartobedistinct.
UsinganexampleofJMSClients,themessagessentbyaJMSmessageproducerwillberoutedusingtheanycastroutingtype.MessagessentbyaJMStopicproducerwillusethemulticastroutingtype.InadditionwhenaJMStopicconsumerattaches,itwillbe
AddressModel
47
-
attachedtoit’sownsubscriptionqueue.JMSqueueconsumerwillbeattachedtotheanycastqueue.
Figure4.[Point-to-PointandPublish-Subscribe
Note:Thebehaviorinthisscenarioisdependentontheprotocolbeingused.ForJMSthereisacleardistinctionbetweentopicandqueueproducersandconsumers,whichmakethelogicstraightforward.OtherprotocolslikeAMQPdonotmakethisdistinction.AmessagebeingsentviaAMQPwillberoutedbybothanycastandmulticastandconsumerswilldefaulttoanycast.Formoreinformation,pleasecheckthebehaviorofeachprotocolinthesectionsonprotocols.
TheXMLsnippetbelowisanexampleofwhattheconfigurationforanaddressusingbothanycastandmulticastwouldlooklikein/etc/broker.xml.Notethatsubscriptionqueuesaretypicallycreatedondemand,sothereisnoneedtolistspecificqueueelementsinsidethemulticastroutingtype.
...
Howtofiltermessages
AddressModel
48
-
ApacheActiveMQArtemissupportstheabilitytofiltermessagesusingApacheArtemisFilterExpressions.
Filterscanbeappliedintwoplaces,onaqueueandonaconsumer.
QueueFilter
Whenafilterisappliedtoaqueue,messagesarefilterbeforetheysenttothequeue.Toaddaqueuefilterusethefilterelementwhenconfiguringaqueue.Openupthebroker.xmlandaddanaddresswithaqueue,usingthefilterelementtoconfigureafilteronthisqueue.
Thefilterdefinedaboveensuresthatonlymessageswithanattribute"color='red'"issenttothisqueue.
ConsumerFilters
ConsumerfiltersareappliedaftermessageshavereachedaqueueandaredefinedusingtheappropriateclientAPIs.ThefollowJMSexampleshowshowtoconsumerfilterswork.
1. Defineanaddresswithasinglequeue,withnofilterapplied.
AddressModel
49
-
...//Sendsomemessagesfor(inti=0;i<3;i++){TextMessageredMessage=senderSession.createTextMessage("Red");redMessage.setStringProperty("color","red");producer.send(redMessage)
TextMessagegreenMessage=senderSession.createTextMessage("Green");greenMessage.setStringProperty("color","green");producer.send(greenMessage)}
Atthispointthequeuewouldhave6messages:red,green,red,green,red,green
MessageConsumerredConsumer=redSession.createConsumer(queue,"color='red'");
TheredConsumerhasafilterthatonlymatches"red"messages.TheredConsumerwillreceive3messages.
red,red,red
Theresultingqueuewouldnowbe
green,green,green
AutomaticAddress/QueueManagementYoucanconfigureApacheActiveMQArtemistoautomaticallycreateaddressesandqueues,andthendeletethemwhentheyarenolongerinuse.Thissavesyoufromhavingtopreconfigureeachaddressandqueuebeforeaclientcanconnecttoit.Automaticcreationanddeletionisconfiguredonaperaddressbasisandiscontrolledbyfollowing:
AddressModel
50
-
Parameter Description
auto-create-addresses
Whensettotrue,thebrokerwillcreatetheaddressrequestedbytheclientifitdoesnotexistalready.Thedefaultistrue.
auto-delete-addresses
Whensettotrue,thebrokerwillbedeleteanyauto-createdadddressonceallofit’squeueshavebeendeleted.Thedefaultistrue
default-address-routing-type
Theroutingtypetouseiftheclientdoesnotspecifyone.PossiblevaluesareMULTICASTandANYCAST.Seeearlierinthischapterformoreinformationaboutroutingtypes.ThedefaultvalueisMULTICAST.
AutoAddressCreation
Editthefile/etc/broker.xmlandaddtheauto-create-addresseselementtotheaddress-settingyouwantthebrokertoautomaticallycreate.
(Optional)Addtheaddress-settingifitdoesnotexits.Usethematchparameterandthewildcardsyntaxtomatchmorethanonespecificaddress.
Setauto-create-addressestotrue
(Optional)AssignMULTICASTorANYCASTasthedefaultroutingtypefortheaddress.
Theexamplebelowconfiguresanaddress-settingtobeautomaticallycreatedbythebroker.ThedefaultroutingtypetobeusedifnotspecifiedbytheclientisMULTICAST.Notethatwildcardsyntaxisused.Anyaddressstartingwith/news/politics/willbeautomaticallycreatedbythebroker.
...trueMULTICAST...
AddressModel
51
-
AutoAddressDeletion
Editthefile/etc/broker.xmlandaddtheauto-delete-addresseselementtotheaddress-settingyouwantthebrokertoautomaticallycreate.
(Optional)Addtheaddress-settingifitdoesnotexits.Usethematchparameterandthewildcardsyntaxtomatchmorethanonespecificaddress.
Setauto-delete-addressestotrue
Theexamplebelowconfiguresanaddress-settingtobeautomaticallydeletedbythebroker.Notethatwildcardsyntaxisused.Anyaddressrequestbytheclientthatstartswith/news/politics/isconfiguredtobeautomaticallydeletedbythebroker.
...trueMULTICAST...
"FullyQualified"QueueNamesInternallythebrokermapsaclient’srequestforanaddresstospecificqueues.Thebrokerdecidesonbehalfoftheclientwhichqueuestosendmessagestoorfromwhichqueuetoreceivemessages.However,moreadvancedusecasesmightrequirethattheclientspecifyaqueuedirectly.Inthesesituationstheclientanduseafullyqualifiedqueuename,byspecifyingboththeaddressnameandthequeuename,separatedbya::.
CurrentlyArtemissupportsfullyqualifiedqueuenamesonCore,AMQP,JMS,OpenWire,MQTTandStompprotocolsforreceivingmessagesonly.
SpecifyingaFullyQualifiedQueueName
AddressModel
52
-
Inthisexample,theaddressfooisconfiguredwithtwoqueuesq1,q2asshownintheconfigurationbelow.
...
Intheclientcode,useboththeaddressnameandthequeuenamewhenrequestingaconnectionfromthebroker.Remembertousetwocolons,::,toseparatethenames,asintheexampleJavacodebelow.
StringFQQN="foo::q1";Queueq1session.createQueue(FQQN);MessageConsumerconsumer=session.createConsumer(q1);
UsingPrefixestoDetermineRoutingTypeNormally,ifthebrokerreceivesamessagesenttoaparticularaddress,thathasbothANYCASTandMULTICASTroutingtypesenable,itwillrouteacopyofthemessagetooneoftheANYCASTqueuesandtoalloftheMULTICASTqueues.
However,clientscanspecifyaspecialprefixwhenconnectingtoanaddresstoindicatewhichkindofroutingtypetouse.TheprefixesarecustomvaluesthataredesignatedusingtheanycastPrefixandmulticastPrefixparameterswithintheURLofanacceptor.
ConfiguringanAnycastPrefix
In/etc/broker.xml,addtheanycastPrefixtotheURLofthedesiredacceptor.Intheexamplebelow,theacceptorisconfiguredtouseanycast://fortheanycastPrefix.Clientcodecanspecifyanycast://foo/iftheclientneedstosendamessagetoonlyoneoftheANYCASTqueues.
AddressModel
53
-
...tcp://0.0.0.0:61616?protocols=AMQP;anycastPrefix=anycast://...
ConfiguringaMulticastPrefix
In/etc/broker.xml,addthemulticastPrefixtotheURLofthedesiredacceptor.Intheexamplebelow,theacceptorisconfiguredtousemulticast://forthemulticastPrefix.Clientcodecanspecifymulticast://foo/iftheclientneedstosendamessagetoonlyoneoftheMULTICASTqueues.
...tcp://0.0.0.0:61616?protocols=AMQP;multicastPrefix=multicast://...
AdvancedAddressConfiguration
StaticSubscriptionQueues
Inmostcasesit’snotnecessarytostaticallyconfiguresubscriptionqueues.Therelevantprotocolmanagerstakecareofdynamicallycreatingsubscriptionqueueswhenclientsrequesttosubscribetoanaddress.Thetypeofsubscriptionqueuecreateddependsonwhatpropertiestheclientrequest.Forexample,durable,non-shared,sharedetc.Protocolmanagersusespecialqueuenamingconventionstoidentifywhichqueuesbelongtowhichconsumersandusersneednotworryaboutthedetails.
AddressModel
54
-
However,therearescenarioswhereausermaywanttousebrokersideconfigurationtostaticallyconfigureasubscriptionandlaterconnecttothatqueuedirectlyusingaFullyQualifiedQueuename.Theexamplesbelowshowhowtousebrokersideconfigurationtostaticallyconfigureaqueuewithpublishsubscribebehaviorforshared,non-shared,durableandnon-durablesubscriptionbehavior.
Shared,DurableSubscriptionQueueusingmax-consumers
Thedefaultbehaviorforqueuesistonotlimitthenumberconnectedqueueconsumers.Themax-consumersparameterofthequeueelementcanbeusedtolimitthenumberofconnectedconsumersallowedatanyonetime.
Openthefile/etc/broker.xmlforediting.
...true
Non-shared,DurableSubscriptionQueue
Thebrokercanbeconfiguredtopreventmorethanoneconsumerfromconnectingtoaqueueatanyonetime.Thesubscriptionstoqueuesconfiguredthiswayaretherefore"non-shared".Todothissimplysetthemax-consumersparameterto"1"
AddressModel
55
-
...true
Non-durableSubscriptionQueue
Non-durablesubscriptionsareagainusuallymanagedbytherelevantprotocolmanager,bycreatinganddeletingtemporaryqueues.
Ifauserrequirestopre-createaqueuethatbehaveslikeanon-durablesubscriptionqueuethepurge-on-no-consumersflagcanbeenabledonthequeue.Whenpurge-on-no-consumersissettotrue.Thequeuewillnotstartreceivingmessagesuntilaconsumerisattached.Whenthelastconsumerisdetachedfromthequeue.Thequeueispurged(it'smessagesareremoved)andwillnotreceiveanymoremessagesuntilanewconsumerisattached.
Openthefile/etc/broker.xmlforediting.
...
ExclusiveConsumerQueue
Ifauserrequirestostaticallyconfigureaqueuethatroutesexclusivelytooneactiveconsumertheexclusiveflagcanbeenabledonthequeue.
AddressModel
56
-
Whenexclusiveissettotruethequeuewillroutemessagestotheasingleactiveconsumer.Whentheactiveconsumerthatisbeingroutedtoisdetachedfromthequeue,ifanotheractiveconsumerexist,onewillbechosenandroutingwillnowbeexclusivetoit.
SeeExclusiveQueueforfurtherinformation.
Openthefile/etc/broker.xmlforediting.
...
ProtocolManagersA"protocolmanager"mapsprotocol-specificconceptsdowntothecoreaddressingmodel(usingaddresses,queuesandroutingtypes).Forexample,whenaclientsendsaMQTTsubscriptionpacketwiththeaddresses:
/house/room1/lights/house/room2/lights
TheMQTTprotocolmanagerunderstandsthatthetwoaddressesrequireMULTICASTsemantics.TheprotocolmanagerwillthereforefirstlooktoensurethatMULTICASTisenabledforbothaddresses.Ifnot,itwillattempttodynamicallycreatethem.Ifsuccessful,theprotocolmanagerwillthencreatespecialsubscriptionqueueswithspecialnames,foreachsubscriptionrequestedbytheclient.
Thespecialnameallowstheprotocolmanagertoquicklyidentifytherequiredclientsubscriptionqueuesshouldtheclientdisconnectandreconnectatalaterdate.Ifthesubscriptionistemporarytheprotocolmanagerwilldeletethequeueoncetheclientdisconnects.
AddressModel
57
-
Whenaclientrequeststosubscribetoapointtopointaddress.Theprotocolmanagerwilllookupthequeueassociatedwiththepointtopointaddress.Thisqueueshouldhavethesamenameastheaddresss.
Note:Ifthequeueisautocreated,itwillbeautodeletedoncetherearenoconsumersandnomessagesinit.FormoreinformationonautocreateseethenextsectionConfiguringAddressesandQueuesviaAddressSettings
ConfiguringAddressesandQueuesviaAddressSettingsTherearesomeattributesthataredefinedagainstanaddresswildcardratherthanaspecificaddress/queue.Hereanexampleofanaddress-settingentrythatwouldbefoundinthebroker.xmlfile.
DLA35000ExpiryQueuetrue100000200000truePAGE-1NOTIFY5
Theideawithaddresssettings,isyoucanprovideablockofsettingswhichwillbeappliedagainstanyaddressesthatmatchthestringinthematchattribute.Intheaboveexamplethesettingswouldonlybeappliedtotheaddress"order.foo"addressbutyoucanalsousewildcardstoapplysettings.See:Thechapteronthewildcardsyntax.
Forexample,ifyouusedthematchstringqueue.#thesettingswouldbeappliedtoalladdresseswhichstartwithqueue.
AddressModel
58
-
Themeaningofthespecificsettingsareexplainedfullythroughouttheusermanual,howeverhereisabriefdescriptionwithalinktotheappropriatechapterifavailable.
max-delivery-attemptsdefineshowmanytimeacancelledmessagecanberedeliveredbeforesendingtothedead-letter-address.Afullexplanationcanbefoundhere.
redelivery-delaydefineshowlongtowaitbeforeattemptingredeliveryofacancelledmessage.seehere.
expiry-addressdefineswheretosendamessagethathasexpired.seehere.
expiry-delaydefinestheexpirationtimethatwillbeusedformessageswhichareusingthedefaultexpirationtime(i.e.0).Forexample,ifexpiry-delayissetto"10"andamessagewhichisusingthedefaultexpirationtime(i.e.0)arrivesthenitsexpirationtimeof"0"willbechangedto"10."However,ifamessagewhichisusinganexpirationtimeof"20"arrivesthenitsexpirationtimewillremainunchanged.Settingexpiry-delayto"-1"willdisablethisfeature.Thedefaultis"-1".
last-value-queuedefineswhetheraqueueonlyuseslastvaluesornot.seehere.
max-size-bytesandpage-size-bytesareusedtosetpagingonanaddress.Thisisexplainedhere.
redistribution-delaydefineshowlongtowaitwhenthelastconsumerisclosedonaqueuebeforeredistributinganymessages.seehere.
send-to-dla-on-no-route.Ifamessageissenttoanaddress,buttheserverdoesnotrouteittoanyqueues,forexample,theremightbenoqueuesboundtothataddress,ornoneofthequeueshavefiltersthatmatch,thennormallythatmessagewouldbediscarded.Howeverifthisparameterissettotrueforthataddress,ifthemessageisnotroutedtoanyqueuesitwillinsteadbesenttothedeadletteraddress(DLA)forthataddress,ifitexists.
address-full-policy.Thisattributecanhaveoneofthefollowingvalues:PAGE,DROP,FAILorBLOCKanddetermineswhathappenswhenanaddresswheremax-size-bytesisspecifiedbecomesfull.ThedefaultvalueisPAGE.IfthevalueisPAGEthenfurthermessageswillbepagedtodisk.IfthevalueisDROPthenfurthermessageswillbesilentlydropped.IfthevalueisFAILthenfurthermessageswillbedroppedandanexceptionwillbethrownontheclient-side.IfthevalueisBLOCKthenclientmessageproducerswillblockwhentheytryandsendfurthermessages.SeethefollowingchaptersformoreinfoFlowControl,Paging.
AddressModel
59
-
slow-consumer-threshold.Theminimumrateofmessageconsumptionallowedbeforeaconsumerisconsidered"slow."Measuredinmessages-per-second.Defaultis-1(i.e.disabled);anyothervalidvaluemustbegreaterthan0.
slow-consumer-policy.Whatshouldhappenwhenaslowconsumerisdetected.KILLwillkilltheconsumer'sconnection(whichwillobviouslyimpactanyotherclientthreadsusingthatsameconnection).NOTIFYwillsendaCONSUMER_SLOWmanagementnotificationwhichanapplicationcouldreceiveandtakeactionwith.Seeslowconsumersformoredetailsonthisnotification.
slow-consumer-check-period.Howoftentocheckforslowconsumersonaparticularqueue.Measuredinseconds.Defaultis5.Seeslowconsumersformoreinformationaboutslowconsumerdetection.
auto-create-jms-queues.WhetherornotthebrokershouldautomaticallycreateaJMSqueuewhenaJMSmessageissenttoaqueuewhosenamefitstheaddressmatch(remember,aJMSqueueisjustacorequeuewhichhasthesameaddressandqueuename)oraJMSconsumertriestoconnecttoaqueuewhosenamefitstheaddressmatch.Queueswhichareauto-createdaredurable,non-temporary,andnon-transient.Defaultistrue.ThisisDEPRECATED.Seeauto-create-queues.
auto-delete-jms-queues.Whetherornotthebrokershouldautomaticallydeleteauto-createdJMSqueueswhentheyhaveboth0consumersand0messages.Defaultistrue.ThisisDEPRECATED.Seeauto-delete-queues.
auto-create-jms-topics.WhetherornotthebrokershouldautomaticallycreateaJMStopicwhenaJMSmessageissenttoatopicwhosenamefitstheaddressmatch(remember,aJMStopicisjustacoreaddresswhichhasoneormorecorequeuesmappedtoit)oraJMSconsumertriestosubscribetoatopicwhosenamefitstheaddressmatch.Defaultistrue.ThisisDEPRECATED.Seeauto-create-addresses.
auto-delete-jms-topics.Whetherornotthebrokershouldautomaticallydeleteauto-createdJMStopicsoncethelastsubscriptiononthetopichasbeenclosed.Defaultistrue.ThisisDEPRECATED.Seeauto-delete-addresses.
auto-create-queues.Whetherornotthebrokershouldautomaticallycreateaqueuewhenamessageissentoraconsumertriestoconnecttoaqueuewhosenamefitstheaddressmatch.Queueswhichareauto-createdaredurable,non-temporary,andnon-transient.Defaultistrue.
auto-delete-queues.Whetherornotthebrokershouldautomaticallydeleteauto-createdqueueswhentheyhaveboth0consumersand0messages.Defaultistrue.
AddressModel
60
-
config-delete-queues.Howthebrokershouldhandlequeuesdeletedonconfigreload,bydeletepolicy:OFForFORCE.Seeconfig-reloadformoredetails.DefaultisOFF.
auto-create-addresses.Whetherornotthebrokershouldautomaticallycreateanaddresswhenamessageissenttooraconsumertriestoconsumefromaqueuewhichismappedtoanaddresswhosenamefitstheaddressmatch.Defaultistrue.
auto-delete-addresses.Whetherornotthebrokershouldautomaticallydeleteauto-createdaddressesoncetheaddressnolongerhasanyqueues.Defaultistrue.
config-delete-addresses.Howthebrokershouldhandleaddressesdeletedonconfigreload,bydeletepolicy:OFForFORCE.Seeconfig-reloadformoredetails.DefaultisOFF.
AddressModel
61
-
UsingJMSAlthoughApacheActiveMQArtemisprovidesaJMSagnosticmessagingAPI,manyuserswillbemorecomfortableusingJMS.
JMSisaverypopularAPIstandardformessaging,andmostmessagingsystemsprovideaJMSAPI.IfyouarecompletelynewtoJMSwesuggestyoufollowtheOracleJMStutorial-afullJMStutorialisoutofscopeforthisguide.
ApacheActiveMQArtemisalsoshipswithawiderangeofexamples,manyofwhichdemonstrateJMSAPIusage.AgoodplacetostartwouldbetoplayaroundwiththesimpleJMSQueueandTopicexample,butwealsoprovideexamplesformanyotherpartsoftheJMSAPI.AfulldescriptionoftheexamplesisavailableinExamples.
Inthissectionwe'llgothroughthemainstepsinconfiguringtheserverforJMSandcreatingasimpleJMSprogram.We'llalsoshowhowtoconfigureanduseJNDI,andalsohowtouseJMSwithApacheActiveMQArtemiswithoutusinganyJNDI.
AsimpleorderingsystemForthischapterwe'regoingtouseaverysimpleorderingsystemasourexample.Itisasomewhatcontrivedexamplebecauseofitsextremesimplicity,butitservestodemonstratetheverybasicsofsettingupandusingJMS.
WewillhaveasingleJMSQueuecalledOrderQueue,andwewillhaveasingleMessageProducersendinganordermessagetothequeueandasingleMessageConsumerconsumingtheordermessagefromthequeue.
Thequeuewillbeadurablequeue,i.e.itwillsurviveaserverrestartorcrash.Wealsowanttopre-deploythequeue,i.e.specifythequeueintheserverconfigurationsoitiscreatedautomaticallywithoutushavingtoexplicitlycreateitfromtheclient.
JNDIConfigurationTheJMSspecificationestablishestheconventionthatadministeredobjects(i.e.JMSqueue,topicandconnectionfactoryinstances)aremadeavailableviatheJNDIAPI.BrokersarefreetoimplementJNDIastheyseefitassumingtheimplementationfitsthe
UsingJMS
62
https://docs.oracle.com/javaee/7/tutorial/partmessaging.htm
-
API.ApacheActiveMQArtemisdoesnothaveaJNDIserver.Rather,itusesaclient-sideJNDIimplementationthatreliesonspecialpropertiessetintheenvironmenttoconstructtheappropriateJMSobjects.Inotherwords,noobjectsarestoredinJNDIontheApacheActiveMQArtemisserver,insteadtheyaresimplyinstantiatedontheclientbasedontheprovidedconfiguration.Let'slookatthedifferentkindsofadministeredobjectsandhowtoconfigurethem.
Note
ThefollowingconfigurationpropertiesarestrictlyrequiredwhenApacheActiveMQArtemisisrunninginstand-alonemode.WhenApacheActiveMQArtemisisintegratedtoanapplicationserver(e.g.Wildfly)theapplicationserveritselfwillalmostcertainlyprovideaJNDIclientwithitsownproperties.
ConnectionFactoryJNDI
AJMSconnectionfactoryisusedbytheclienttomakeconnectionstotheserver.Itknowsthelocationoftheserveritisconnectingto,aswellasmanyotherconfigurationparameters.
Here'sasimpleexampleoftheJNDIcontextenvironmentforaclientlookingupaconnectionfactorytoaccessanembeddedinstanceofApacheActiveMQArtemis:
java.naming.factory.initial=org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactoryconnectionFactory.invmConnectionFactory=vm://0
InthisinstancewehavecreatedaconnectionfactorythatisboundtoinvmConnectionFactory,anyentrywithprefixconnectionFactory.willcreateaconnectionfactory.
IncertainsituationstherecouldbemultipleserverinstancesrunningwithinaparticularJVM.InthatsituationeachserverwouldtypicallyhaveanInVMacceptorwithauniqueserver-ID.AclientusingJMSandJNDIcanaccountforthisbyspecifyingaconnctionfactoryforeachserver,likeso:
java.naming.factory.initial=org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactoryconnectionFactory.invmConnectionFactory0=vm://0connectionFactory.invmConnectionFactory1=vm://1connectionFactory.invmConnectionFactory2=vm://2
UsingJMS
63
-
HereisalistofallthesupportedURLschemes:
vm
tcp
udp
jgroups
Mostclientswon'tbeconnectingtoanembeddedbroker.Clientswillmostcommonlyconnectacrossanetworkaremotebroker.Here'sasimpleexampleofaclientconfiguringaconnectionfactorytoconnecttoaremotebrokerrunningonmyhost:5445:
java.naming.factory.initial=org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactoryconnectionFactory.ConnectionFactory=tcp://myhost:5445
IntheexampleabovetheclientisusingthetcpschemefortheproviderURL.Aclientmayalsospecifymultiplecomma-delimitedhost:portcombinationsintheURL(e.g.(tcp://remote-host1:5445,remote-host2:5445)).Whetherthereisoneormanyhost:portcombinationsintheURLtheyaretreatedastheinitialconnector(s)fortheunderlyingconnection.
Theudpschemeisalsosupportedwhichshoulduseahost:portcombinationthatmatchesthegroup-addressandgroup-portfromthecorrespondingbroadcast-groupconfiguredontheActiveMQArtemisserver(s).
EachschemehasaspecificsetofpropertieswhichcanbesetusingthetraditionalURLquerystringformat(e.g.scheme://host:port?key1=value1&key2=value2)tocustomizetheunderlyingtransportmechanism.Forexample,ifaclientwantedtoconnecttoaremoteserverusingTCPandSSLitwouldcreateaconnectionfactorylikeso,tcp://remote-host:5445?ssl-enabled=true.
AllthepropertiesavailableforthetcpschemearedescribedinthedocumentationregardingtheNettytransport.
Noteifyouareusingthetcpschemeandmultipleaddressesthenaquerycanbeappliedtoalltheurl'sorjusttoanindividualconnector,sowhereyouhave
(tcp://remote-host1:5445?httpEnabled=true,remote-host2:5445?httpEnabled=true)?
clientID=1234
UsingJMS
64
-
thenthehttpEnabledpropertyisonlysetontheindividualconnectorswhereastheclientIdissetontheactualconnectionfactory.AnyconnectorspecificpropertiessetonthewholeURIwillbeappliedtoalltheconnectors.
Theudpschemesupports4properties:
localAddress-Ifyouarerunningwithmultiplenetworkinterfacesonthesamemachine,youmaywanttospecifythatthediscoverygrouplistensonlyonlyaspecificinterface.Todothisyoucanspecifytheinterfaceaddresswiththisparameter.
localPort-Ifyouwanttospecifyalocalporttowhichthedatagramsocketisboundyoucanspecifyithere.Normallyyouwouldjustusethedefaultvalueof-1whichsignifiesthatananonymousportshouldbeused.ThisparameterisalwaysspecifiedinconjunctionwithlocalAddress.
refreshTimeout-Thisistheperiodthediscoverygroupwaitsafterreceivingthelastbroadcastfromaparticularserverbeforeremovingthatserversconnectorpairentryfromitslist.Youwouldnormallysetthistoavaluesignificantlyhigherthanthebroadcast-periodonthebroadcastgroupotherwiseserversmightintermittentlydisappearfromthelisteventhoughtheyarestillbroadcastingduetoslightdifferencesintiming.Thisparameterisoptional,thedefaultvalueis10000milliseconds(10seconds).
discoveryInitialWaitTimeout-Iftheconnectionfactoryisusedimmediatelyaftercreationthenitmaynothavehadenoughtimetoreceivedbroadcastsfromallthenodesinthecluster.Onfirstusage,theconnectionfactorywillmakesureitwaitsthislongsincecreationbeforecreatingthefirstconnection.Thedefaultvalueforthisparameteris10000milliseconds.
Lastly,thejgroupsschemeissupportedwhichprovidesanalternativetotheudpschemeforserverdiscovery.TheURLpatterniseitherjgroups://channelName?file=jgroups-xml-conf-filenamewherejgroups-xml-conf-filenamereferstoanXMLfileontheclasspaththatcontainstheJGroupsconfigurationoritcanbejgroups://channelName?properties=some-jgroups-properties.InbothinstancethechannelNameisthenamegiventothejgroupschannelcreated.
TherefreshTimeoutanddiscoveryInitialWaitTimeoutpropertiesaresupportedjustlikewithudp.
Thedefaulttypeforthedefaultconnectionfactoryisoftypejavax.jms.ConnectionFactory.Thiscanbechangedbysettingthetypelikeso
UsingJMS
65
-
java.naming.factory.initial=org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactoryjava.naming.provider.url=tcp://localhost:5445?type=CF
Inthisexampleitisstillsettothedefault,belowshowsalistoftypesthatcanbeset.
ConfigurationforConnectionFactoryTypes
type interface
CF(default) javax.jms.ConnectionFactory
XA_CF javax.jms.XAConnectionFactory
QUEUE_CF javax.jms.QueueConnectionFactory
QUEUE_XA_CF javax.jms.XAQueueConnectionFactory
TOPIC_CF javax.jms.TopicConnectionFactory
TOPIC_XA_CF javax.jms.XATopicConnectionFactory
DestinationJNDI
JMSdestinationsarealsotypicallylookedupviaJNDI.Aswithconnectionfactories,destinationscanbeconfiguredusingspecialpropertiesintheJNDIcontextenvironment.Thepropertynameshouldfollowthepattern:queue.ortopic..ThepropertyvalueshouldbethenameofthequeuehostedbytheApacheActiveMQArtemisserver.Forexample,iftheserverhadaJMSqueueconfiguredlikeso:
Andiftheclientwantedtobindthisqueueto"queues/OrderQueue"thentheJNDIpropertieswouldbeconfiguredlikeso:
java.naming.factory.initial=org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactoryjava.naming.provider.url=tcp://myhost:5445queue.queues/OrderQueue=OrderQueue
UsingJMS
66
-
Itisalsopossibletolook-upJMSdestinationswhichhaven'tbeenconfiguredexplicitlyintheJNDIcontextenvironment.ThisispossibleusingdynamicQueues/ordynamicTopics/inthelook-upstring.Forexample,iftheclientwantedtolook-uptheaforementioned"OrderQueue"itcoulddososimplybyusingthestring"dynamicQueues/OrderQueue".Note,thetextthatfollowsdynamicQueues/ordynamicTopics/mustcorrespondexactlytothenameofthedestinationontheserver.
Thecode
Here'sthecodefortheexample:
Firstwe'llcreateaJNDIinitialcontextfromwhichtolookupourJMSobjects.Iftheabovepropertiesaresetinjndi.propertiesanditisontheclasspaththenanynew,emptyInitialContextwillbeinitializedusingthoseproperties:
UsingJMS
67
-
InitialContextic=newInitialContext();
//Nowwe'lllookuptheconnectionfactoryfromwhichwecancreate//connectionstomyhost:5445:
ConnectionFactorycf=(ConnectionFactory)ic.lookup("ConnectionFactory");
//AndlookuptheQueue:
QueueorderQueue=(Queue)ic.lookup("queues/OrderQueue");
//NextwecreateaJMSconnectionusingtheconnectionfactory:
Connectionconnection=cf.createConnection();
//AndwecreateanontransactedJMSSession,withAUTO\_ACKNOWLEDGE//acknowledgemode:
Sessionsession=connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
//WecreateaMessageProducerthatwillsendorderstothequeue:
MessageProducerproducer=session.createProducer(orderQueue);
//AndwecreateaMessageConsumerwhichwillconsumeordersfromthe//queue:
MessageConsumerconsumer=session.createConsumer(orderQueue);
//Wemakesurewestarttheconnection,ordeliverywon'toccuronit:
connection.start();
//WecreateasimpleTextMessageandsendit:
TextMessagemessage=session.createTextMessage("Thisisanorder");producer.send(message);
//Andweconsumethemessage:
TextMessagereceivedMessage=(TextMessage)consumer.receive();System.out.println("Gotorder:"+receivedMessage.getText());
Itisassimpleasthat.ForawiderangeofworkingJMSexamplespleaseseetheexamplesdirectoryinthedistribution.
UsingJMS
68
-
Warning
PleasenotethatJMSconnections,sessions,producersandconsumersaredesignedtobere-used.
Itisananti-patterntocreatenewconnections,sessions,producersandconsumersforeachmessageyouproduceorconsume.Ifyoudothis,yourapplicationwillperformverypoorly.ThisisdiscussedfurtherinthesectiononperformancetuningPerformanceTuning.
DirectlyinstantiatingJMSResourceswithoutusingJNDIAlthoughitisaverycommonJMSusagepatterntolookupJMSAdministeredObjects(that'sJMSQueue,TopicandConnectionFactoryinstances)fromJNDI,insomecasesyoujustthink"WhydoIneedJNDI?Whycan'tIjustinstantiatetheseobjectsdirectly?"
WithApacheActiveMQArtemisyoucandoexactlythat.ApacheActiveMQArtemissupportsthedirectinstantiationofJMSQueue,TopicandConnectionFactoryinstances,soyoudon'thavetouseJNDIatall.
Forafullworkingexampleofdirectinstantiationpleaselookatthe"InstantiateJMSObjectsDirectly"exampleundertheJMSsectionoftheexamples.SeetheExamplessectionformoreinfo.
Here'soursimpleexample,rewrittentonotuseJNDIatall:
WecreatetheJMSConnectionFactoryobjectviatheActiveMQJMSClientUtilityclass,noteweneedtoprovideconnectionparametersandspecifywhichtransportweareusing,formoreinformationonconnectorspleaseseeConfiguringtheTransport.
UsingJMS
69
-
TransportConfigurationtransportConfiguration=newTransportConfiguration(NettyConnectorFactory.class.getName());
ConnectionFactorycf=ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF,transportConfiguration);
//WealsocreatetheJMSQueueobjectviatheActiveMQJMSClientUtility//class:
QueueorderQueue=ActiveMQJMSClient.createQueue("OrderQueue");
//NextwecreateaJMSconnectionusingtheconnectionfactory:
Connectionconnection=cf.createConnection();
//AndwecreateanontransactedJMSSession,withAUTO\_ACKNOWLEDGE//acknowledgemode:
Sessionsession=connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
//WecreateaMessageProducerthatwillsendorderstothequeue:
MessageProducerproducer=session.createProducer(orderQueue);
//AndwecreateaMessageConsumerwhichwillconsumeordersfromthe//queue:
MessageConsumerconsumer=session.createConsumer(orderQueue);
//Wemakesurewestarttheconnection,ordeliverywon'toccuronit:
connection.start();
//WecreateasimpleTextMessageandsendit:
TextMessagemessage=session.createTextMessage("Thisisanorder");producer.send(message);
//Andweconsumethemessage:
TextMessagereceivedMessage=(TextMessage)consumer.receive();System.out.println("Gotorder:"+receivedMessage.getText());
SettingTheClientID
UsingJMS
70
-
ThisrepresentstheclientidforaJMSclientandisneededforcreatingdurablesubscriptions.ItispossibletoconfigurethisontheconnectionfactoryandcanbesetviatheclientIdelement.Anyconnectioncreatedbythisconnectionfactorywillhavethissetasitsclientid.
SettingTheBatchSizeforDUPS_OKWhentheJMSacknowledgemodeissettoDUPS_OKitispossibletoconfiguretheconsumersothatitsendsacknowledgementsinbatchesratherthatoneatatime,savingvaluablebandwidth.ThiscanbeconfiguredviatheconnectionfactoryviathedupsOkBatchSizeelementandissetinbytes.Thedefaultis1024*1024bytes=1MiB.
SettingTheTransactionBatchSizeWhenreceivingmessagesinatransactionitispossibletoconfiguretheconsumertosendacknowledgementsinbatchesratherthanindividuallysavingvaluablebandwidth.ThiscanbeconfiguredontheconnectionfactoryviathetransactionBatchSizeelementandissetinbytes.Thedefaultis1024*1024.
SettingTheDestinationCacheManyframeworkssuchasSpringresolvethedestinationbynameoneveryoperation,thiscancauseaperformanceissueandextracallstothebroker,inascenariowheredestinations(addresses)arepermanentbrokerside,suchastheyaremanagedbyaplatformoroperationsteam.usingdestinationCacheelement,youcantoggleonthedestinationcachetoimprovetheperformanceandreducethecallstothebroker.Thisshouldnotbeusedifdestinations(addresses)arenotpermanentbrokerside,asindynamiccreation/deletion.
UsingJMS
71
-
UsingCoreApacheActiveMQArtemiscoreisacompletelyJMS-agnosticmessagingsystemwithitsownAPI.WecallthisthecoreAPI.
Ifyoudon'twanttouseJMSorotherprotocolsyoucanusethecoreAPIdirectly.ThecoreAPIprovidesallthefunctionalityofJMSbutwithoutmuchofthecomplexity.ItalsoprovidesfeaturesthatarenotavailableusingJMS.
CoreMessagingConceptsSomeofthecoremessagingconceptsaresimilartoJMSconcepts,butcoremessagingconceptsdifferinsomeways.IngeneralthecoremessagingAPIissimplerthantheJMSAPI,sinceweremovedistinctionsbetweenqueues,topicsandsubscriptions.We'lldiscusseachofthemajorcoremessagingconceptsinturn,buttoseetheAPIindetail,pleaseconsulttheJavadoc.
Message
Amessageistheunitofdatawhichissentbetweenclientsandservers.
Amessagehasabodywhichisabuffercontainingconvenientmethodsforreadingandwritingdataintoit.
Amessagehasasetofpropertieswhicharekey-valuepairs.Eachpropertykeyisastringandpropertyvaluescanbeoftypeinteger,long,short,byte,byte[],String,double,floatorboolean.
Amessagehasanaddressitisbeingsentto.Whenthemessagearrivesontheserveritisroutedtoanyqueuesthatareboundtotheaddress-ifthequeuesareboundwithanyfilter,themessagewillonlyberoutedtothatqueueifthefiltermatches.Anaddressmayhavemanyqueuesboundtoitorevennone.Theremayalsobeentitiesotherthanqueues,likedivertsboundtoaddresses.
Messagescanbeeitherdurableornondurable.Durablemessagesinadurablequeuewillsurviveaservercrashorrestart.Nondurablemessageswillneversurviveaservercrashorrestart.
UsingCore
72
-
Messagescanbespecifiedwithapriorityvaluebetween0and9.0representsthelowestpriorityand9representsthehighest.ApacheActiveMQArtemiswillattempttodeliverhigherprioritymessagesbeforelowerpriorityones.
Messagescanbespecifiedwithanoptionalexpirytime.ApacheActiveMQArtemiswillnotdelivermessagesafteritsexpirytimehasbeenexceeded.
Messagesalsohaveanoptionaltimestampwhichrepresentsthetimethemessagewassent.
ApacheActiveMQArtemisalsosupportsthesending/consumingofverylargemessagesmuchlargerthancanfitinavailableRAMatanyonetime.
Address
Aservermaintainsamappingbetweenanaddressandasetofqueues.Zeroormorequeuescanbeboundtoasingleaddress.Eachqueuecanbeboundwithanoptionalmessagefilter.Whenamessageisrouted,itisroutedtothesetofqueuesboundtothemessage'saddress.Ifanyofthequeuesareboundwithafilterexpression,thenthemessagewillonlyberoutedtothesubsetofboundqueueswhichmatchthatfilterexpression.
Otherentities,suchasdivertscanalsobeboundtoanaddressandmessageswillalsoberoutedthere.
Note
Incore,thereisnoconceptofaTopic,TopicisaJMSonlyterm.Instead,incore,wejustdealwithaddressesandqueues.
Forexample,aJMStopicwouldbeimplementedbyasingleaddresstowhichmanyqueuesarebound.Eachqueuerepresentsasubscriptionofthetopic.AJMSQueuewouldbeimplementedasasingleaddresstowhichonequeueisbound-thatqueuerepresentstheJMSqueue.
Queue
Queuescanbedurable,meaningthemessagestheycontainsurviveaservercrashorrestart,aslongasthemessagesinthemaredurable.Nondurablequeuesdonotsurviveaserverrestartorcrashevenifthemessagestheycontainaredurable.
UsingCore
73
-
Queuescanalsobetemporary,meaningtheyareautomaticallydeletedwhentheclientconnectionisclosed,iftheyarenotexplicitlydeletedbeforethat.
Queuescanbeboundwithanoptionalfilterexpression.Ifafilterexpressionissuppliedthentheserverwillonlyroutemessagesthatmatchthatfilterexpressiontoanyqueuesboundtotheaddress.
Manyqueuescanbeboundtoasingleaddress.Aparticularqueueisonlyboundtoamaximumofoneaddress.
ServerLocator
ClientsuseServerLocatorinstancestocreateClientSessionFactoryinstances.ServerLocatorinstancesareusedtolocateserversandcreateconnectionstothem.
InJMStermsthinkofaServerLocatorinthesamewayyouwouldaJMSConnectionFactory.
ServerLocatorinstancesarecreatedusingtheActiveMQClientfactoryclass.
ClientSessionFactory
ClientsuseClientSessionFactoryinstancestocreateClientSessioninstances.ClientSessionFactoryinstancesarebasicallytheconnectiontoaserver
InJMStermsthinkofthemasJMSConnections.
ClientSessionFactoryinstancesarecreatedusingtheServerLocatorclass.
ClientSession
AclientusesaClientSessionforconsumingandproducingmessagesandforgroupingthemintransactions.ClientSessioninstancescansupportbothtransactionalandnontransactionalsemanticsandalsoprovideanXAResourceinterfacesomessagingoperationscanbeperformedaspartofaJTAtransaction.
ClientSessioninstancesgroupClientConsumersandClientProducers.
ClientSessioninstancescanberegisteredwithanoptionalSendAcknowledgementHandler.Thisallowsyourclientcodetobenotifiedasynchronouslywhensentmessageshavesuccessfullyreachedtheserver.ThisuniqueApacheActiveMQArtemisfeature,allowsyoutohavefullguaranteesthatsentmessageshavereachedtheserverwithouthaving
UsingCore
74
http://www.oracle.com/technetwork/java/javaee/tech/jta-138684.html
-
toblockoneachmessagesentuntilaresponseisreceived.Blockingoneachmessagessentiscostlysinceitrequiresanetworkroundtripforeachmessagesent.BynotblockingandreceivingsendacknowledgementsasynchronouslyyoucancreatetrueendtoendasynchronoussystemswhichisnotpossibleusingthestandardJMSAPI.FormoreinformationonthisadvancedfeaturepleaseseethesectionGuaranteesofsendsandcommits.
ClientConsumer
ClientsuseClientConsumerinstancestoconsumemessagesfromaqueue.CoreMessagingsupportsbothsynchronousandasynchronousmessageconsumptionsemantics.ClientConsumerinstancescanbeconfiguredwithanoptionalfilterexpressionandwillonlyconsumemessageswhichmatchthatexpression.
ClientProducer
ClientscreateClientProducerinstancesonClientSessioninstancessotheycansendmessages.ClientProducerinstancescanspecifyanaddresstowhichallsentmessagesarerouted,ortheycanhavenospecifiedaddress,andtheaddressisspecifiedatsendtimeforthemessage.
Warning
PleasenotethatClientSession,ClientProducerandClientConsumerinstancesaredesignedtobere-used.
It'sananti-patterntocreatenewClientSession,ClientProducerandClientConsumerinstancesforeachmessageyouproduceorconsume.Ifyoudothis,yourapplicationwillperformverypoorly.ThisisdiscussedfurtherinthesectiononperformancetuningPerformanceTuning.
AsimpleexampleofusingCoreHere'saverysimpleprogramusingthecoremessagingAPItosendandreceiveamessage.Logicallyit'scomprisedoftwosections:firstlysettinguptheproducertowriteamessagetoanaddresss,andsecondly,creatingaqueuefortheconsumer,creatingtheconsumerandstartingit.
UsingCore
75
-
ServerLocatorlocator=ActiveMQClient.createServerLocatorWithoutHA(newTransportConfiguration(InVMConnectorFactory.class.getName()));
//Inthissimpleexample,wejustuseonesessionforbothproducingandreceiving
ClientSessionFactoryfactory=locator.createClientSessionFactory();ClientSessionsession=factory.createSession();
//Aproducerisassociatedwithanaddress...
ClientProducerproducer=session.createProducer("example");ClientMessagemessage=session.createMessage(true);message.getBodyBuffer().writeString("Hello");
//Weneedaqueueattachedtotheaddress...
session.createQueue("example","example",true);
//Andaconsumerattachedtothequeue...
ClientConsumerconsumer=session.createConsumer("example");
//Oncewehaveaqueue,wecansendthemessage...
producer.send(message);
//Weneedtostartthesessionbeforewecan-receive-messages...
session.start();ClientMessagemsgReceived=consumer.receive();
System.out.println("message="+msgReceived.getBodyBuffer().readString());
session.close();
UsingCore
76
-
UsingAMQPApacheActiveMQArtemisisalsoapureAMQP1.0broker,withahighperformantandfeaturecompleteprotocolmanagerforAMQP.
YoucanuseanyAMQP1.0compatibleclients.
Ashortlistincludes:
qpidclientsattheqpidproject.NETClientsJavascriptNodeJSJavaScriptRHEA
...andmanyothers.
MessageConversionsThebrokerwillnotperformanymessageconversiontoanyotherprotocolswhensendingAMQPandreceivingAMQP.
HoweverifyouintendyourmessagetobereceivedonaAMQPJMSCl