table of contents - apache activemq · apache activemq artemis is an asynchronous messaging system,...

393
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 Table of Contents Introduction Legal Notice Preface Project Info Messaging Concepts Architecture Using the Server Using JMS Using Core Mapping JMS Concepts to the Core API The Client Classpath Examples Routing Messages With Wild Cards Understanding the Apache ActiveMQ Artemis Wildcard Syntax Filter Expressions Persistence Configuring Transports Configuration Reload Detecting Dead Connections Detecting Slow Consumers Resource Manager Configuration Flow Control Guarantees of sends and commits Message Redelivery and Undelivered Messages Message Expiry Large Messages Paging 1

Upload: others

Post on 24-Jul-2020

23 views

Category:

Documents


0 download

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

    MessagingConcepts

    Architecture

    UsingtheServer

    UsingJMS

    UsingCore

    MappingJMSConceptstotheCoreAPI

    TheClientClasspath

    Examples

    RoutingMessagesWithWildCards

    UnderstandingtheApacheActiveMQArtemisWildcardSyntax

    FilterExpressions

    Persistence

    ConfiguringTransports

    ConfigurationReload

    DetectingDeadConnections

    DetectingSlowConsumers

    ResourceManagerConfiguration

    FlowControl

    Guaranteesofsendsandcommits

    MessageRedeliveryandUndeliveredMessages

    MessageExpiry

    LargeMessages

    Paging

    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

    QueueAttributes

    ScheduledMessages

    Last-ValueQueues

    MessageGrouping

    ExtraAcknowledgeModes

    Management

    Security

    ResourceLimits

    TheJMSBridge

    ClientReconnectionandSessionReattachment

    DivertingandSplittingMessageFlows

    CoreBridges

    DuplicateMessageDetection

    Clusters

    HighAvailabilityandFailover

    GracefulServerShutdown

    LibaioNativeLibraries

    Threadmanagement

    Logging

    RESTInterface

    EmbeddingApacheActiveMQArtemis

    ApacheKaraf

    SpringIntegration

    AeroGearIntegration

    VertXIntegration

    CDIIntegration

    InterceptingOperations

    ProtocolsandInteroperability

    Tools

    MavenPlugin

    2

  • 1.58

    1.59

    1.60

    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.

    ForanswerstomorequestionsaboutwhatApacheActiveMQArtemisisandwhatitisn'tpleasevisittheFAQswikipage.

    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,runitinintegratedinyourfavouriteJEEapplicationserver,orrunitembeddedinsideyourownproduct.It'suptoyou.

    Seamlesshighavailability.WeprovideaHAsolutionwithautomaticclientfailoversoyoucanguaranteezeromessagelossorduplicationineventofserverfailure.

    Hugelyflexibleclustering.Createclustersofserversthatknowhowtoloadbalancemessages.Linkgeographicallydistributedclustersoverunreliableconnectionstoformaglobalnetwork.Configureroutingofmessagesinahighlyflexibleway.

    Preface

    6

  • Preface

    7

  • ProjectInformationTheofficialApacheActiveMQArtemisprojectpageishttp://activemq.apache.org/artemis/.

    SoftwareDownloadThesoftwarecanbedownloadfromtheDownloadpage:http://activemq.apache.org/download.html

    ProjectInformationIfyouhaveanyuserquestionspleaseuseouruserforum

    Ifyouhavedevelopmentrelatedquestions,pleaseuseourdeveloperforum

    PopinandchattousinourIRCchannel

    ApacheActiveMQArtemisGitrepositoryishttps://github.com/apache/activemq-artemis

    Allreleasetagsareavailablefromhttps://github.com/apache/activemq-artemis/releases

    Andmanythankstoallourcontributors,botholdandnewwhohelpedcreateApacheActiveMQArtemis.

    ProjectInfo

    8

    http://activemq.apache.org/artemis/http://activemq.apache.org/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

  • MessagingConceptsApacheActiveMQArtemisisanasynchronousmessagingsystem,anexampleofMessageOrientedMiddleware,we'lljustcallthemmessagingsystemsintheremainderofthisbook.

    We'llfirstpresentabriefoverviewofwhatkindofthingsmessagingsystemsdo,wherethey'reusefulandthekindofconceptsyou'llhearaboutinthemessagingworld.

    Ifyou'realreadyfamiliarwithwhatamessagingsystemisandwhatit'scapableof,thenyoucanskipthischapter.

    MessagingConceptsMessagingsystemsallowyoutolooselycoupleheterogeneoussystemstogether,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

    9

    http://en.wikipedia.org/wiki/Message_oriented_middlewarehttp://en.wikipedia.org/wiki/Remote_procedure_callhttp://en.wikipedia.org/wiki/Enterprise_service_bus

  • canallowthesystemtogrowandadaptmoreeasily.Italsoallowsmoreflexibilitytoaddnewsystemsorretireoldonessincetheydon'thavebrittledependenciesoneachother.

    MessagingstylesMessagingsystemsnormallysupporttwomainstylesofasynchronousmessaging:messagequeuemessaging(alsoknownaspoint-to-pointmessaging)andpublishsubscribemessaging.We'llsummarisethembrieflyhere:

    TheMessageQueuePattern

    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

    10

    http://en.wikipedia.org/wiki/Message_queuehttp://en.wikipedia.org/wiki/Publish_subscribe

  • Asanorderprocessorreceivesamessage,itfulfillstheorder,sendsorderinformationtothewarehousesystemandthenupdatestheorderdatabasewiththeorderdetails.Onceit'sdonethatitacknowledgesthemessagetotelltheserverthattheorderhasbeenprocessedandcanbeforgottenabout.Oftenthesendtothewarehousesystem,updateindatabaseandacknowledgementwillbecompletedinasingletransactiontoensureACIDproperties.

    ThePublish-SubscribePattern

    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

    11

    http://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'sJEEspecification.It'saJavaAPIthatencapsulatesbothmessagequeueandpublish-subscribemessagingpatterns.JMSisalowestcommondenominatorspecification-i.e.itwascreatedtoencapsulatecommonfunctionalityofthealreadyexistingmessagingsystemsthatwereavailableatthetimeofitscreation.

    MessagingConcepts

    12

    http://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.

    STOMP

    Stompisaverysimpletextprotocolforinteroperatingwithmessagingsystems.Itdefinesawireformat,sotheoreticallyanyStompclientcanworkwithanymessagingsystemthatsupportsStomp.Stompclientsareavailableinmanydifferentprogramminglanguages.

    MessagingConcepts

    13

    http://en.wikipedia.org/wiki/Representational_State_Transferhttp://stomp.github.io/

  • PleaseseeStompforusingSTOMPwithApacheActiveMQArtemis.

    AMQP

    AMQPisaspecificationforinteroperablemessaging.Italsodefinesawireformat,soanyAMQPclientcanworkwithanymessagingsystemthatsupportsAMQP.AMQPclientsareavailableinmanydifferentprogramminglanguages.

    ApacheActiveMQArtemisimplementstheAMQP1.0specification.Anyclientthatsupportsthe1.0specificationwillbeabletointeractwithApacheActiveMQArtemis.

    HighAvailabilityHighAvailability(HA)meansthatthesystemshouldremainoperationalafterfailureofoneormoreoftheservers.ThedegreeofsupportforHAvariesbetweenvariousmessagingsystems.

    ApacheActiveMQArtemisprovidesautomaticfailoverwhereyoursessionsareautomaticallyreconnectedtothebackupserveroneventofliveserverfailure.

    FormoreinformationonHA,pleaseseeHighAvailabilityandFailover.

    ClustersManymessagingsystemsallowyoutocreategroupsofmessagingserverscalledclusters.Clustersallowtheloadofsendingandconsumingmessagestobespreadovermanyservers.Thisallowsyoursystemtoscalehorizontallybyaddingnewserverstothecluster.

    Degreesofsupportforclustersvariesbetweenmessagingsystems,withsomesystemshavingfairlybasicclusterswiththeclustermembersbeinghardlyawareofeachother.

    ApacheActiveMQArtemisprovidesveryconfigurablestate-of-the-artclusteringmodelwheremessagescanbeintelligentlyloadbalancedbetweentheserversinthecluster,accordingtothenumberofconsumersoneachnode,andwhethertheyarereadyformessages.

    ApacheActiveMQArtemisalsohastheabilitytoautomaticallyredistributemessagesbetweennodesofaclustertopreventstarvationonanyparticularnode.

    MessagingConcepts

    14

    http://en.wikipedia.org/wiki/AMQPhttps://www.oasis-open.org/committees/tc_home.php?wg_abbrev=amqp

  • Forfulldetailsonclustering,pleaseseeClusters.

    BridgesandroutingSomemessagingsystemsallowisolatedclustersorsinglenodestobebridgedtogether,typicallyoverunreliableconnectionslikeawideareanetwork(WAN),ortheinternet.

    Abridgenormallyconsumesfromaqueueononeserverandforwardsmessagestoanotherqueueonadifferentserver.Bridgescopewithunreliableconnections,automaticallyreconnectingwhentheconnectionsbecomesavailableagain.

    ApacheActiveMQArtemisbridgescanbeconfiguredwithfilterexpressionstoonlyforwardcertainmessages,andtransformationcanalsobehookedin.

    ApacheActiveMQArtemisalsoallowsroutingbetweenqueuestobeconfiguredinserversideconfiguration.Thisallowscomplexroutingnetworkstobesetupforwardingorcopyingmessagesfromonedestinationtoanother,formingaglobalnetworkofinterconnectedbrokers.

    FormoreinformationpleaseseeCoreBridgesandDivertingandSplittingMessageFlows.

    MessagingConcepts

    15

  • ArchitectureInthissectionwewillgiveanoverviewoftheApacheActiveMQArtemishighlevelarchitecture.

    CoreArchitectureApacheActiveMQArtemiscoreisdesignedsimplyassetofPlainOldJavaObjects(POJOs)-wehopeyoulikeitsclean-cutdesign.

    We'vealsodesignedittohaveasfewdependenciesonexternaljarsaspossible.Infact,ApacheActiveMQArtemiscorehasonlyonejardependency,netty.jar,otherthanthestandardJDKclasses!Thisisbecauseweusesomeofthenettybufferclassesinternally.

    ThisallowsApacheActiveMQArtemistobeeasilyembeddedinyourownproject,orinstantiatedinanydependencyinjectionframeworksuchasSpringorGoogleGuice.

    EachApacheActiveMQArtemisserverhasitsownultrahighperformancepersistentjournal,whichitusesformessageandotherpersistence.

    Usingahighperformancejournalallowsoutrageouspersistencemessageperformance,somethingnotachievablewhenusingarelationaldatabaseforpersistence.

    ApacheActiveMQArtemisclients,potentiallyondifferentphysicalmachinesinteractwiththeApacheActiveMQArtemisserver.ApacheActiveMQArtemiscurrentlyprovidestwoAPIsformessagingattheclientside:

    1. CoreclientAPI.ThisisasimpleintuitiveJavaAPIthatallowsthefullsetofmessagingfunctionalitywithoutsomeofthecomplexitiesofJMS.

    2. JMSclientAPI.ThestandardJMSAPIisavailableattheclientside.

    ApacheActiveMQArtemisalsoprovidesdifferentprotocolimplementationsontheserversoyoucanuserespectiveclientsfortheseprotocols:

    1. Stomp2. OpenWire3. AMQP

    Architecture

    16

  • JMSsemanticsareimplementedbyaJMSfacadelayerontheclientside.

    TheApacheActiveMQArtemisserverdoesnotspeakJMSandinfactdoesnotknowanythingaboutJMS,itisaprotocolagnosticmessagingserverdesignedtobeusedwithmultipledifferentprotocols.

    WhenauserusestheJMSAPIontheclientside,allJMSinteractionsaretranslatedintooperationsontheApacheActiveMQArtemiscoreclientAPIbeforebeingtransferredoverthewireusingtheApacheActiveMQArtemiswireformat.

    TheserveralwaysjustdealswithcoreAPIinteractions.

    Aschematicillustratingthisrelationshipisshowninfigure3.1below:

    Architecture

    17

  • Architecture

    18

  • Figure3.1showstwouserapplicationsinteractingwithanApacheActiveMQArtemisserver.UserApplication1isusingtheJMSAPI,whileUserApplication2isusingthecoreclientAPIdirectly.

    YoucanseefromthediagramthattheJMSAPIisimplementedbyathinfacadelayerontheclientside.

    ApacheActiveMQArtemisembeddedinyourownapplicationApacheActiveMQArtemiscoreisdesignedasasetofsimplePOJOssoifyouhaveanapplicationthatrequiresmessagingfunctionalityinternallybutyoudon'twanttoexposethatasanApacheActiveMQArtemisserveryoucandirectlyinstantiateandembedApacheActiveMQArtemisserversinyourownapplication.

    FormoreinformationonembeddingApacheActiveMQArtemis,seeEmbeddingApacheActiveMQArtemis.

    ApacheActiveMQArtemisintegratedwithaJavaEEapplicationserverApacheActiveMQArtemisprovidesitsownfullyfunctionalJavaConnectorArchitecture(JCA)adaptorwhichenablesittobeintegratedeasilyintoanyJavaEEcompliantapplicationserverorservletengine.

    JavaEEapplicationserversprovideMessageDrivenBeans(MDBs),whichareaspecialtypeofEnterpriseJavaBeans(EJBs)thatcanprocessmessagesfromsourcessuchasJMSsystemsormailsystems.

    ProbablythemostcommonuseofanMDBistoconsumemessagesfromaJMSmessagingsystem.

    AccordingtotheJavaEEspecification,aJavaEEapplicationserverusesaJCAadaptertointegratewithaJMSmessagingsystemsoitcanconsumemessagesforMDBs.

    However,theJCAadapterisnotonlyusedbytheJavaEEapplicationserverforconsumingmessagesviaMDBs,itisalsousedwhensendingmessagetotheJMSmessagingsysteme.g.frominsideanEJBorservlet.

    Architecture

    19

  • WhenintegratingwithaJMSmessagingsystemfrominsideaJavaEEapplicationserveritisalwaysrecommendedthatthisisdoneviaaJCAadaptor.Infact,communicatingwithaJMSmessagingsystemdirectly,withoutusingJCAwouldbeillegalaccordingtotheJavaEEspecification.

    Theapplicationserver'sJCAserviceprovidesextrafunctionalitysuchasconnectionpoolingandautomatictransactionenlistment,whicharedesirablewhenusingmessaging,say,frominsideanEJB.ItispossibletotalktoaJMSmessagingsystemdirectlyfromanEJB,MDBorservletwithoutgoingthroughaJCAadapter,butthisisnotrecommendedsinceyouwillnotbeabletotakeadvantageoftheJCAfeatures,suchascachingofJMSsessions,whichcanresultinpoorperformance.

    Figure3.2belowshowsaJavaEEapplicationserverintegratingwithaApacheActiveMQArtemisserverviatheApacheActiveMQArtemisJCAadaptor.NotethatallcommunicationbetweenEJBsessionsorentitybeansandMessageDrivenbeansgothroughtheadaptorandnotdirectlytoApacheActiveMQArtemis.

    ThelargearrowwiththeprohibitedsignshowsanEJBsessionbeantalkingdirectlytotheApacheActiveMQArtemisserver.Thisisnotrecommendedasyou'llmostlikelyendupcreatinganewconnectionandsessioneverytimeyouwanttointeractfromtheEJB,whichisananti-pattern.

    Architecture

    20

  • FormoreinformationonusingtheJCAadaptor,pleaseseeApplicationServerIntegrationandJavaEE.

    Architecture

    21

  • ApacheActiveMQArtemisstand-aloneserverApacheActiveMQArtemiscanalsobedeployedasastand-aloneserver.ThismeansafullyindependentmessagingservernotdependentonaJavaEEapplicationserver.

    Thestandardstand-alonemessagingserverconfigurationcomprisesacoremessagingserverandaJMSservice.

    TheroleoftheJMSServiceistodeployanyJMSQueue,TopicandConnectionFactoryinstancesfromanyserversideJMSconfiguration.ItalsoprovidesasimplemanagementAPIforcreatinganddestroyingQueuesandTopicswhichcanbeaccessedviaJMXortheconnection.ItisaseparateservicetotheActiveMQArtemiscoreserver,sincethecoreserverisJMSagnostic.Ifyoudon'twanttodeployanyJMSQueueorTopicviaserversideXMLconfigurationanddon'trequireaJMSmanagementAPIontheserversidethenyoucandisablethisservice.

    Thestand-aloneserverconfigurationusesAirlineforbootstrappingtheBroker.

    Thestand-aloneserverarchitectureisshowninfigure3.3below:

    Architecture

    22

    https://github.com/airlift/airline

  • FormoreinformationonserverconfigurationfilesseeServerConfiguration

    Architecture

    23

  • Architecture

    24

  • UsingtheServerThischapterwillfamiliariseyouwithhowtousetheApacheActiveMQArtemisserver.

    We'llshowwhereitis,howtostartandstopit,andwe'lldescribethedirectorylayoutandwhatallthefilesareandwhattheydo.

    FortheremainderofthischapterwhenwetalkabouttheApacheActiveMQArtemisserverwemeantheApacheActiveMQArtemisstandaloneserver,initsdefaultconfigurationwithaJMSServiceenabled.

    ThisdocumentwillrefertothefullpathofthedirectorywheretheActiveMQdistributionhasbeenextractedtoas${ARTEMIS_HOME}directory.

    InstallationAfterdownloadingthedistribution,thefollowinghighlightssomeimportantfoldersonthedistribution:

    |___bin||___web||___user-manual||___api||___examples||___core||___javaee||___jms||___lib||___schema

    bin--binariesandscriptsneededtorunActiveMQArtemis.

    web--ThefolderwherethewebcontextisloadedwhenActiveMQArtemisruns.

    user-manual--Theusermanualisplacedunderthewebfolder.

    api--Theapidocumentationisplacedunderthewebfolder

    UsingtheServer

    25

  • examples--JMSandJavaEEexamples.Pleaserefertothe'runningexamples'chapterfordetailsonhowtorunthem.

    lib--jarsandlibrariesneededtorunActiveMQArtemis

    licenses--licensesforActiveMQArtemis

    schemas--XMLSchemasusedtovalidateActiveMQArtemisconfigurationfiles

    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

    26

  • $./artemishelpcreateNAMEartemiscreate-createsanewbrokerinstance

    SYNOPSISartemiscreate[--allow-anonymous][--cluster-password][--cluster-user][--clustered][--data][--encoding][--force][--home][--host][--java-options][--password][--port-offset][--replicated][--role][--shared-store][--silent][--user][--]

    OPTIONS--allow-anonymousEnablesanonymousconfigurationonsecurity(Default:input)

    --cluster-passwordTheclusterpasswordtouseforclustering.(Default:input)

    --cluster-userTheclusterusertouseforclustering.(Default:input)

    --clusteredEnableclustering

    --dataDirectorywhereActiveMQDataisused.Patharerelativetoartemis.instance/bin

    --encodingTheencodingthattextfilesshoulduse

    --forceOverwriteconfigurationatdestinationdirectory

    --homeDirectorywhereActiveMQArtemisisinstalled

    --hostThehostnameofthebroker(Default:0.0.0.0orinputifclustered)

    --java-optionsExtrajavaoptionstobepassedtotheprofile

    --passwordTheuser'spassword(Default:input)

    --port-offset

    UsingtheServer

    27

  • Offsetsthedefaultports

    --replicatedEnablebrokerreplication

    --roleThenamefortherolecreated(Default:amq)

    --shared-storeEnablebrokersharedstore

    --silentItwilldisablealltheinputs,anditwouldmakeabestguessforanyrequiredinput

    --userTheusername(Default:input)

    --Thisoptioncanbeusedtoseparatecommand-lineoptionsfromthelistofargument,(usefulwhenargumentsmightbemistakenforcommand-lineoptions

    Theinstancedirectorytoholdthebroker'sconfigurationanddata

    Someofthesepropertiesmaybemandatoryincertainconfigurationsandthesystemmayaskyouforadditionalinput.

    UsingtheServer

    28

  • ./artemiscreate/usr/serverCreatingActiveMQArtemisinstanceat:/user/server

    --user:ismandatorywiththisconfiguration:Pleaseprovidethedefaultusername:admin

    --password:ismandatorywiththisconfiguration:Pleaseprovidethedefaultpassword:

    --allow-anonymous:ismandatorywiththisconfiguration:Allowanonymousaccess?(Y/N):y

    Youcannowstartthebrokerbyexecuting:

    "/user/server/bin/artemis"run

    Oryoucanrunthebrokerinthebackgroundusing:

    "/user/server/bin/artemis-service"start

    StartingandStoppingaBrokerInstance

    Assumingyoucreatedthebrokerinstanceunder/var/lib/mybrokerallyouneedtodostartrunningthebrokerinstanceisexecute:

    /var/lib/mybroker/bin/artemisrun

    Nowthatthebrokerisrunning,youcanoptionallyrunsomeoftheincludedexamplestoverifythethebrokerisrunningproperly.

    TostoptheApacheActiveMQArtemisinstanceyouwillusethesameartemisscript,butwiththestopargument.Example:

    /var/lib/mybroker/bin/artemisstop

    PleasenotethatApacheActiveMQArtemisrequiresaJava7orlaterruntimetorun.

    Bydefaulttheetc/bootstrap.xmlconfigurationisused.Theconfigurationcanbechangede.g.byrunning./artemisrun--xml:path/to/bootstrap.xmloranotherconfigofyourchoosing.

    UsingtheServer

    29

  • Environmentvariablesareusedtoprovideeaseofchangingports,hostsanddatadirectoriesusedandcanbefoundinetc/artemis.profileonlinuxandetc\artemis.profile.cmdonWindows.

    ServerJVMsettingsTherunscriptssetsomeJVMsettingsfortuningthegarbagecollectionpolicyandheapsize.WerecommendusingaparallelgarbagecollectionalgorithmtosmoothoutlatencyandminimiselargeGCpauses.

    BydefaultApacheActiveMQArtemisrunsinamaximumof1GiBofRAM.Toincreasethememorysettingschangethe-Xmsand-XmxmemorysettingsasyouwouldforanyJavaprogram.

    IfyouwishtoaddanymoreJVMargumentsortunetheexistingones,therunscriptsaretheplacetodoit.

    Pre-configuredOptionsThedistributioncontainsseveralstandardconfigurationsetsforrunning:

    Nonclusteredstand-alone.

    Clusteredstand-alone

    Replicatedstand-alone

    Shared-storestand-alone

    Youcanofcoursecreateyourownconfigurationandspecifyanyconfigurationwhenrunningtherunscript.

    LibraryPathIfyou'reusingtheAsynchronousIOJournalonLinux,youneedtospecifyjava.library.pathasapropertyonyourJavaoptions.Thisisdoneautomaticallyinthescripts.

    Ifyoudon'tspecifyjava.library.pathatyourJavaoptionsthentheJVMwillusetheenvironmentvariableLD_LIBRARY_PATH.

    UsingtheServer

    30

  • YouwillneedtomakesurelibaioisinstalledonLinux.FormoreinformationrefertothelibaiochapteratRuntimeDependencies

    SystempropertiesApacheActiveMQArtemiscantakeasystempropertyonthecommandlineforconfiguringlogging.

    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.

    BootstrapFileThestand-aloneserverisbasicallyasetofPOJOswhichareinstantiatedbyAirlinecommands.

    Thebootstrapfileisverysimple.Let'stakealookatanexample:

    UsingtheServer

    31

  • core-Instantiatesacoreserverusingtheconfigurationfilefromtheconfigurationattribute.ThisisthemainbrokerPOJOnecessarytodoalltherealmessagingwork.InadditionallJMSobjectssuchas:Queues,TopicsandConnectionFactoryinstancesareconfiguredhere.

    Themainconfigurationfile.TheconfigurationfortheApacheActiveMQArtemiscoreserveriscontainedinbroker.xml.ThisiswhattheFileConfigurationbeanusestoconfigurethemessagingserver.

    TherearemanyattributeswhichyoucanconfigureApacheActiveMQArtemis.Inmostcasesthedefaultswilldofine,infacteveryattributecanbedefaultedwhichmeansafilewithasingleemptyconfigurationelementisavalidconfigurationfile.Thedifferentconfigurationwillbeexplainedthroughoutthemanualoryoucanrefertotheconfigurationreferencehere.

    WindowsServerOnwindowsyouwillhavetheoptiontorunActiveMQArtemisasaservice.Justusethefollowingcommandtoinstallit:

    $./artemis-service.exeinstall

    Thecreateprocessshouldgiveyouahintoftheavailablecommandsavailablefortheartemis-service.exe

    UsingtheServer

    32

  • UsingtheServer

    33

  • 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.

    JNDIConfiguration

    UsingJMS

    34

    http://docs.oracle.com/javaee/7/tutorial/partmessaging.htm

  • TheJMSspecificationestablishestheconventionthatadministeredobjects(i.e.JMSqueue,topicandconnectionfactoryinstances)aremadeavailableviatheJNDIAPI.BrokersarefreetoimplementJNDIastheyseefitassumingtheimplementationfitstheAPI.ApacheActiveMQArtemisdoesnothaveaJNDIserver.Rather,itusesaclient-sideJNDIimplementationthatreliesonspecialpropertiessetintheenvironmenttoconstructtheappropriateJMSobjects.Inotherwords,noobjectsarestoredinJNDIontheApacheActiveMQArtemisserver,insteadtheyaresimplyinstantiatedontheclientbasedontheprovidedconfiguration.Let'slookatthedifferentkindsofadministeredobjectsandhowtoconfigurethem.

    Note

    ThefollowingconfigurationpropertiesarestrictlyrequiredwhenApacheActiveMQArtemisisrunninginstand-alonemode.WhenApacheActiveMQArtemisisintegratedtoanapplicationserver(e.g.Wildfly)theapplicationserveritselfwillalmostcertainlyprovideaJNDIclientwithitsownproperties.

    ConnectionFactoryJNDIAJMSconnectionfactoryisusedbytheclienttomakeconnectionstotheserver.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:

    UsingJMS

    35

  • java.naming.factory.initial=org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactoryconnectionFactory.invmConnectionFactory0=vm://0connectionFactory.invmConnectionFactory1=vm://1connectionFactory.invmConnectionFactory2=vm://2

    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.

    UsingJMS

    36

  • Noteifyouareusingthetcpschemeandmultipleaddressesthenaquerycanbeappliedtoalltheurl'sorjusttoanindividualconnector,sowhereyouhave

    (tcp://remote-host1:5445?httpEnabled=true,remote-host2:5445?httpEnabled=true)?

    clientID=1234

    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.

    UsingJMS

    37

  • TherefreshTimeoutanddiscoveryInitialWaitTimeoutpropertiesaresupportedjustlikewithudp.

    Thedefaulttypeforthedefaultconnectionfactoryisoftypejavax.jms.ConnectionFactory.Thiscanbechangedbysettingthetypelikeso

    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:

    UsingJMS

    38

  • java.naming.factory.initial=org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactoryjava.naming.provider.url=tcp://myhost:5445queue.queues/OrderQueue=OrderQueue

    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

    39

  • 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

    40

  • Warning

    PleasenotethatJMSconnections,sessions,producersandconsumersaredesignedtobere-used.

    Itisananti-patterntocreatenewconnections,sessions,producersandconsumersforeachmessageyouproduceorconsume.Ifyoudothis,yourapplicationwillperformverypoorly.ThisisdiscussedfurtherinthesectiononperformancetuningPerformanceTuning.

    DirectlyinstantiatingJMSResourceswithoutusingJNDI

    AlthoughitisaverycommonJMSusagepatterntolookupJMSAdministeredObjects(that'sJMSQueue,TopicandConnectionFactoryinstances)fromJNDI,insomecasesyoujustthink"WhydoIneedJNDI?Whycan'tIjustinstantiatetheseobjectsdirectly?"

    WithApacheActiveMQArtemisyoucandoexactlythat.ApacheActiveMQArtemissupportsthedirectinstantiationofJMSQueue,TopicandConnectionFactoryinstances,soyoudon'thavetouseJNDIatall.

    Forafullworkingexampleofdirectinstantiationpleaselookatthe"InstantiateJMSObjectsDirectly"exampleundertheJMSsectionoftheexamples.SeetheExamplessectionformoreinfo.

    Here'soursimpleexample,rewrittentonotuseJNDIatall:

    WecreatetheJMSConnectionFactoryobjectviatheActiveMQJMSClientUtilityclass,noteweneedtoprovideconnectionparametersandspecifywhichtransportweareusing,formoreinformationonconnectorspleaseseeConfiguringtheTransport.

    UsingJMS

    41

  • 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

    ThisrepresentstheclientidforaJMSclientandisneededforcreatingdurablesubscriptions.ItispossibletoconfigurethisontheconnectionfactoryandcanbesetviatheclientIdelement.Anyconnectioncreatedbythisconnectionfactorywillhavethis

    UsingJMS

    42

  • setasitsclientid.

    SettingTheBatchSizeforDUPS_OK

    WhentheJMSacknowledgemodeissettoDUPS_OKitispossibletoconfiguretheconsumersothatitsendsacknowledgementsinbatchesratherthatoneatatime,savingvaluablebandwidth.ThiscanbeconfiguredviatheconnectionfactoryviathedupsOkBatchSizeelementandissetinbytes.Thedefaultis1024*1024bytes=1MiB.

    SettingTheTransactionBatchSize

    Whenreceivingmessagesinatransactionitispossibletoconfiguretheconsumertosendacknowledgementsinbatchesratherthanindividuallysavingvaluablebandwidth.ThiscanbeconfiguredontheconnectionfactoryviathetransactionBatchSizeelementandissetinbytes.Thedefaultis1024*1024.

    UsingJMS

    43

  • UsingCoreApacheActiveMQArtemiscoreisacompletelyJMS-agnosticmessagingsystemwithitsownnon-JMSAPI.WecallthisthecoreAPI.

    Ifyoudon'twanttouseJMSyoucanusethecoreAPIdirectly.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

    44

  • 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

    45

  • 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

    46

    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

    47

  • 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

    48

  • MappingJMSConceptstotheCoreAPIThischapterdescribeshowJMSdestinationsaremappedtoApacheActiveMQArtemisaddresses.

    ApacheActiveMQArtemiscoreisJMS-agnostic.ItdoesnothaveanyconceptofaJMStopic.AJMStopicisimplementedincoreasanaddress(thetopicname)withzeroormorequeuesboundtoit.Eachqueueboundtothataddressrepresentsatopicsubscription.Likewise,aJMSqueueisimplementedasanaddress(theJMSqueuename)withonesinglequeueboundtoitwhichrepresentstheJMSqueue.

    Byconvention,allJMSqueuesmaptocorequeueswherethecorequeuenamehasthestringjms.queue.prependedtoit.E.g.theJMSqueuewiththename"orders.europe"wouldmaptothecorequeuewiththename"jms.queue.orders.europe".Theaddressatwhichthecorequeueisboundisalsogivenbythecorequeuename.

    ForJMStopicstheaddressatwhichthequeuesthatrepresentthesubscriptionsareboundisgivenbyprependingthestring"jms.topic."tothenameoftheJMStopic.E.g.theJMStopicwithname"news.europe"wouldmaptothecoreaddress"jms.topic.news.europe"

    InotherwordsifyousendaJMSmessagetoaJMSqueuewithname"orders.europe"itwillgetroutedontheservertoanycorequeuesboundtotheaddress"jms.queue.orders.europe".IfyousendaJMSmessagetoaJMStopicwithname"news.europe"itwillgetroutedontheservertoanycorequeuesboundtotheaddress"jms.topic.news.europe".

    IfyouwanttoconfiguresettingsforaJMSQueuewiththename"orders.europe",youneedtoconfigurethecorrespondingcorequeue"jms.queue.orders.europe":

    jms.queue.expiry.europe...

    MappingJMSConceptstotheCoreAPI

    49

  • TheClientClasspathApacheActiveMQArtemisrequiresseveraljarsontheClientClasspathdependingonwhethertheclientusesApacheActiveMQArtemisCoreAPI,JMS,andJNDI.

    Warning

    AllthejarsmentionedherecanbefoundinthelibdirectoryoftheApacheActiveMQArtemisdistribution.Besureyouonlyusethejarsfromthecorrectversionoftherelease,youmustnotmixandmatchversionsofjarsfromdifferentApacheActiveMQArtemisversions.Mixingandmatchingdifferentjarversionsmaycausesubtleerrorsandfailurestooccur.

    ApacheActiveMQArtemisCoreClientIfyouareusingjustapureApacheActiveMQArtemisCoreclient(i.e.noJMS)thenyouneedactivemq-core-client.jar,activemq-commons.jar,andnetty.jaronyourclientclasspath.

    JMSClientIfyouareusingJMSontheclientside,thenyouwillalsoneedtoincludeactivemq-jms-client.jarandgeronimo-jms_2.0_spec.jar.

    Note

    geronimo-jms_2.0_spec.jarjustcontainsJavaEEAPIinterfaceclassesneededforthejavax.jms.*classes.Ifyoualreadyhaveajarwiththeseinterfaceclassesonyourclasspath,youwillnotneedit.

    TheClientClasspath

    50

  • ExamplesTheApacheActiveMQArtemisdistributioncomeswithover90runout-of-the-boxexamplesdemonstratingmanyofthefeatures.

    Theexamplesareavailableinboththebinaryandsourcedistributionundertheexamplesdirectory.Examplesaresplitbythefollowingsourcetree:

    features-Examplescontainingbrokerspecificfeatures.ha-examplesshowingfailoverandreconnectioncapabilities.clustered-examplesshowingloadbalancinganddistributioncapabilities.perf-examplesallowingyoutorunafewperformancetestsontheserversub-modules-examplesofintegratedexternalmodules.

    protocols-Protocolspecificexamplesopenwiremqttstompamqp

    AsetofJavaEEexamplesarealsoprovidedwhichneedWildFlyinstalledtobeabletorun.

    RunnningtheExamplesTorunanyexample,simplycdintotheappropriateexampledirectoryandtypemvnverifyormvninstall(Fordetailspleasereadthereadme.htmlineachexampledirectory).

    Youcanusetheprofile-Pexamplestorunmultipleexamplesunderanyexampletree.

    Foreachserver,youwillhaveacreatedserverunder./target/server0(someexamplesusemorethanoneserver).

    Youhavetheoptiontopreventtheexamplefromstartingtheserver(e.g.ifyouwanttostarttheservermanually)bysimplyspecifyingthe-PnoServerprofile,e.g.:

    #runninganexamplewithoutrunningtheservermvnverify-PnoServer

    Examples

    51

  • Alsounder./targettherewillbeascriptrepeatingthecommandstocreateeachserver.Hereisthecreate-server0.shgeneratedbytheQueueexample.Thisisusefultoseeexactlywhatcommand(s)arerequiredtoconfiguretheserver(s).

    #Thesearethecommandsusedtocreateserver0/myInstallDirectory/apache-artemis-1.1.0/bin/artemiscreate--allow-anonymous--silent--force--no-web--userguest--passwordguest--roleguest--port-offset0--data./data--allow-anonymous--no-autotune--verbose/myInstallDirectory/apache-artemis-1.1.0/examples/features/standard/queue/target/server0

    SeveralexamplesuseUDPclusteringwhichmaynotworkinyourenvironmentbydefault.Onlinuxthecommandwouldbe:

    routeadd-net224.0.0.0netmask240.0.0.0devlo

    Thiscommandshouldberunasroot.Thiswillredirectanytrafficdirectedto224.0.0.0totheloopbackinterface.OnMacOSX,thecommandisslightlydifferent:

    sudorouteadd224.0.0.0127.0.0.1-netmask240.0.0.0

    AlltheexamplesusetheMavenplugin,whichcanbeusefulforrunningyourtestserversaswell.

    Thisisthecommonoutputwhenrunninganexample.OnthiscasetakenfromtheQueueexample:

    [INFO]Scanningforprojects...[INFO][INFO]------------------------------------------------------------------------[INFO]BuildingActiveMQArtemisJMSQueueExample1.1.0[INFO]------------------------------------------------------------------------[INFO][INFO]---maven-enforcer-plugin:1.4:enforce(enforce-java)@queue---[INFO][INFO]---maven-remote-resources-plugin:1.5:process(default)@queue---[INFO][INFO]---maven-resources-plugin:2.6:resources(default-resources)@queue---[INFO]Using'UTF-8'encodingtocopyfilteredresources.[INFO]Copying1resource[INFO]Copying3resources[INFO][INFO]---maven-compiler-plugin:3.1:compile(default-compile)@queue---[INFO]Changesdetected-recompilingthemodule![INFO]Compiling1sourcefileto/work/apache-artemis-1.1.0/examples/features/sta

    Examples

    52

  • ndard/queue/target/classes[INFO][INFO]---maven-checkstyle-plugin:2.16:check(default)@queue---[INFO][INFO]---apache-rat-plugin:0.11:check(default)@queue---[INFO]RATwillnotexecutesinceitisconfiguredtobeskippedviasystemproperty'rat.skip'.[INFO][INFO]---maven-resources-plugin:2.6:testResources(default-testResources)@queue---[INFO]Using'UTF-8'encodingtocopyfilteredresources.[INFO]skipnonexistingresourceDirectory/work/apache-artemis-1.1.0/examples/features/standard/queue/src/test/resources[INFO]Copying3resources[INFO][INFO]---maven-compiler-plugin:3.1:testCompile(default-testCompile)@queue---[INFO]Nosourcestocompile[INFO][INFO]---maven-surefire-plugin:2.18.1:test(default-test)@queue---[INFO][INFO]---maven-jar-plugin:2.4:jar(default-jar)@queue---[INFO]Buildingjar:/work/apache-artemis-1.1.0/examples/features/standard/queue/target/queue-1.1.0.jar[INFO][INFO]---maven-site-plugin:3.3:attach-descriptor(attach-descriptor)@queue---[INFO][INFO]>>>maven-source-plugin:2.2.1:jar(attach-sources)>generate-sources@queue>>>[INFO][INFO]---maven-enforcer-plugin:1.4:enforce(enforce-java)@queue---[INFO][INFO]generate-sources@queue>>>[INFO][INFO]---maven-enforcer-plugin:1.4:enforce(enforce-java)@queue---[INFO][INFO]always]

    Examples

    53

  • [INFO]Entries.size2[INFO]...key=project=MavenProject:org.apache.activemq.examples.broker:queue:1.1.0@/work/apache-artemis-1.1.0/examples/features/standard/queue/pom.xml[INFO]...key=pluginDescriptor=ComponentDescriptor:role:'org.apache.maven.plugin.Mojo',implementation:'org.apache.activemq.artemis.maven.ArtemisCLIPlugin',rolehint:'org.apache.activemq:artemis-maven-plugin:1.1.0:cli'role:'org.apache.maven.plugin.Mojo',implementation:'org.apache.activemq.artemis.maven.ArtemisCreatePlugin',rolehint:'org.apache.activemq:artemis-maven-plugin:1.1.0:create'role:'org.apache.maven.plugin.Mojo',implementation:'org.apache.activemq.artemis.maven.ArtemisClientPlugin',rolehint:'org.apache.activemq:artemis-maven-plugin:1.1.0:runClient'---Executingorg.apache.activemq.artemis.cli.commands.Createcreate--allow-anonymous--silent--force--no-web--userguest--passwordguest--roleguest--port-offset0--data./data--allow-anonymous--no-autotune--verbose/work/apache-artemis-1.1.0/examples/features/standard/queue/target/server0Home::/work/apache-artemis-1.1.0/examples/features/standard/queue/../../../..,Instance::.CreatingActiveMQArtemisinstanceat:/work/apache-artemis-1.1.0/examples/features/standard/queue/target/server0

    Youcannowstartthebrokerbyexecuting:

    "/work/apache-artemis-1.1.0/examples/features/standard/queue/target/server0/bin/artemis"run

    Oryoucanrunthebrokerinthebackgroundusing:

    "/work/apache-artemis-1.1.0/examples/features/standard/queue/target/server0/bin/artemis-service"start

    [INFO]###################################################################################################[INFO]create-server0.shcreatedwithcommandstoreproduceserver0[INFO]under/work/apache-artemis-1.1.0/examples/features/standard/queue/target[INFO]###################################################################################################[INFO][INFO]---artemis-maven-plugin:1.1.0:cli(start)@queue---[INFO]awaitingservertostart[INFO]awaitingservertostartserver-out:___server-out:/\____||________(_)_____server-out:/_\|_\__|/_\\/||/__/server-out:/___\|\/|_/__/|\/|||\___\server-out:/_/\_\|\__\____|_||_|_|/___/server-out:ApacheActiveMQArtemis1.1.0server-out:server-out:server-out:17:30:25,091INFO[org.apache.activemq.artemis.integration.bootstrap]

    Examples

    54

  • AMQ101000:StartingActiveMQArtemisServerserver-out:17:30:25,120INFO[org.apache.activemq.artemis.core.server]AMQ221000:liveMessageBrokerisstartingwithconfigurationBrokerConfiguration(clustered=false,journalDirectory=./data/journal,bindingsDirectory=./data/bindings,largeMessagesDirectory=./data/large-messages,pagingDirectory=./data/paging)server-out:17:30:25,152INFO[org.apache.activemq.artemis.core.server]AMQ221013:UsingNIOJournalserver-out:17:30:25,195INFO[org.apache.activemq.artemis.core.server]AMQ221043:Protocolmodulefound:[artemis-server].Addingprotocolsupportfor:COREserver-out:17:30:25,199INFO[org.apache.activemq.artemis.core.server]AMQ221043:Protocolmodulefound:[artemis-amqp-protocol].Addingprotocolsupportfor:AMQPserver-out:17:30:25,209INFO[org.apache.activemq.artemis.core.server]AMQ221043:Protocolmodulefound:[artemis-hornetq-protocol].Addingprotocolsupportfor:HORNETQserver-out:17:30:25,211INFO[org.apache.activemq.artemis.core.server]AMQ221043:Protocolmodulefound:[artemis-mqtt-protocol].Addingprotocolsupportfor:MQTTserver-out:17:30:25,214INFO[org.apache.activemq.artemis.core.server]AMQ221043:Protocolmodulefound:[artemis-openwire-protocol].Addingprotocolsupportfor:OPENWIREserver-out:17:30:25,335INFO[org.apache.activemq.artemis.core.server]AMQ221043:Protocolmodulefound:[artemis-stomp-protocol].Addingprotocolsupportfor:STOMP[INFO]awaitingservertostartserver-out:17:30:25,781INFO[org.apache.activemq.artemis.core.server]AMQ221003:tryingtodeployqueuejms.queue.DLQserver-out:17:30:25,835INFO[org.apache.activemq.artemis.core.server]AMQ221003:tryingtodeployqueuejms.queue.ExpiryQueueserver-out:17:30:25,933INFO[org.apache.activemq.artemis.core.server]AMQ221020:StartedAcceptorat0.0.0.0:61616forprotocols[CORE,MQTT,AMQP,HORNETQ,STOMP,OPENWIRE]server-out:17:30:25,936INFO[org.apache.activemq.artemis.core.server]AMQ221020:StartedAcceptorat0.0.0.0:5445forprotocols[HORNETQ,STOMP]server-out:17:30:25,939INFO[org.apache.activemq.artemis.core.server]AMQ221020:StartedAcceptorat0.0.0.0:5672forprotocols[AMQP]server-out:17:30:25,944INFO[org.apache.activemq.artemis.core.server]AMQ221020:StartedAcceptorat0.0.0.0:1883forprotocols[MQTT]server-out:17:30:25,948INFO[org.apache.activemq.artemis.core.server]AMQ221020:StartedAcceptorat0.0.0.0:61613forprotocols[STOMP]server-out:17:30:25,949INFO[org.apache.activemq.artemis.core.server]AMQ221007:Serverisnowliveserver-out:17:30:25,949INFO[org.apache.activemq.artemis.core.server]AMQ221001:ApacheActiveMQArtemisMessageBrokerversion1.1.0[nodeID=a855176b-50f0-11e5-937e-2fe9bb000966][INFO]Serverstarted[INFO][INFO]---artemis-maven-plugin:1.1.0:runClient(runClient)@queue---Sentmessage:ThisisatextmessageReceivedmessage:Thisisatextmessage[INFO][INFO]---artemis-maven-plugin:1.1.0:cli(stop)@queue---server-out:17:30:27,476INFO[org.apache.activemq.artemis.core.server]AMQ221002:ApacheActiveMQArtemisMessageBrokerversion1.0.1-SNA

    Examples

    55

  • [INFO]------------------------------------------------------------------------[INFO]BUILDSUCCESS[INFO]------------------------------------------------------------------------[INFO]Totaltime:7.840s[INFO]Finishedat:2015-09-01T17:30:27-04:00[INFO]FinalMemory:42M/508M[INFO]------------------------------------------------------------------------

    ListThisincludesapreviewlistofafewexamplesthatwedistributewithArtemis.Pleaserefertothedistributionforamoreaccuratelist.

    AppletThisexampleshowsyouhowtosendandreceiveJMSmessagesfromanApplet.

    Application-LayerFailoverApacheActiveMQArtemisalsosupportsApplication-Layerfailover,usefulinthecasethatreplicationisnotenabledontheserverside.

    WithApplication-Layerfailover,it'suptotheapplicationtoregisteraJMSExceptionListenerwithApacheActiveMQArtemiswhichwillbecalledbyApacheActiveMQArtemisintheeventthatconnectionfailureisdetected.

    ThecodeintheExceptionListenerthenrecreatestheJMSconnection,session,etconanothernodeandtheapplicationcancontinue.

    Application-layerfailoverisanalternativeapproachtoHighAvailability(HA).Application-layerfailoverdiffersfromautomaticfailoverinthatsomeclientsidecodingisrequiredinordertoimplementthis.Also,withApplication-layerfailover,sincetheoldsessionobjectdiesandanewoneiscreated,anyuncommittedworkintheoldsessionwillbelost,andanyunacknowledgedmessagesmightberedelivered.

    CoreBridgeExample

    Examples

    56

  • Thebridgeexampledemonstratesacorebridgedeployedononeserver,whichconsumesmessagesfromalocalqueueandforwardsthemtoanaddressonasecondserver.

    CorebridgesareusedtocreatemessageflowsbetweenanytwoApacheActiveMQArtemisserverswhichareremotelyseparated.Corebridgesareresilientandwillcopewithtemporaryconnectionfailureallowingthemtobeanidealchoiceforforwardingoverunreliableconnections,e.g.aWAN.

    BrowserThebrowserexampleshowsyouhowtouseaJMSQueueBrowserwithApacheActiveMQArtemis.

    QueuesareastandardpartofJMS,pleaseconsulttheJMS1.1specificationforfulldetails.

    AQueueBrowserisusedtolookatmessagesonthequeuewithoutremovingthem.Itcanscantheentirecontentofaqueueoronlymessagesmatchingamessageselector.

    ClientKickoffTheclient-kickoffexampleshowshowtoterminateclientconnectionsgivenanIPaddressusingtheJMXmanagementAPI.

    ClientsidefailoverlistenerTheclient-side-failoverlistenerexampleshowshowtoregisteralistenertomonitorfailoverevents

    Client-SideLoad-BalancingTheclient-side-load-balancingexampledemonstrateshowsessionscreatedfromasingleJMSConnectioncanbecreatedtodifferentnodesofthecluster.InotherwordsitdemonstrateshowApacheActiveMQArtemisdoesclient-sideload-balancingofsessionsacrossthecluster.

    Examples

    57

  • ClusteredDurableSubscriptionThisexampledemonstratesaclusteredJMSdurablesubscription

    ClusteredGroupingThisissimilartothemessagegroupingexampleexceptthatitdemonstratesitworkingoveracluster.Messagessenttodifferentnodeswiththesamegroupidwillbesenttothesamenodeandthesameconsumer.

    ClusteredQueueTheclustered-queueexampledemonstratesaJMSqueuedeployedontwodifferentnodes.Thetwonodesareconfiguredtoformacluster.Wethencreateaconsumerforthequeueoneachnode,andwecreateaproducerononlyoneofthenodes.Wethensendsomemessagesviatheproducer,andweverifythatbothconsumersreceivethesentmessagesinaround-robinfashion.

    ClusteringwithJGroupsTheclustered-jgroupsexampledemonstrateshowtoformatwonodeclusterusingJGroupsasitsunderlyingtopologydiscoverytechnique,ratherthanthedefaultUDPbroadcasting.Wethencreateaconsumerforthequeueoneachnode,andwecreateaproducerononlyoneofthenodes.Wethensendsomemessagesviatheproducer,andweverifythatbothconsumersreceivethesentmessagesinaround-robinfashion.

    ClusteredStandaloneTheclustered-standaloneexampledemonstrateshowtoconfigureandstarts3clusternodesonthesamemachinetoformacluster.AsubscriberforaJMStopiciscreatedoneachnode,andwecreateaproducerononlyoneofthenodes.Wethensendsomemessagesviatheproducer,andweverifythatthe3subscribersreceiveallthesentmessages.

    Examples

    58

  • ClusteredStaticDiscoveryThisexampledemonstrateshowtoconfigureaclusterusingalistofconnectorsratherthanUDPfordiscovery

    ClusteredStaticClusterOneWayThisexampledemonstrateshowtosetupaclusterwhereclusterconnectionsareoneway,i.e.serverA->ServerB->ServerC

    ClusteredTopicTheclustered-topicexampledemonstratesaJMStopicdeployedontwodifferentnodes.Thetwonodesareconfiguredtoformacluster.Wethencreateasubscriberonthetopiconeachnode,andwecreateaproducerononlyoneofthenodes.Wethensendsomemessagesviatheproducer,andweverifythatbothsubscribersreceiveallthesentmessages.

    MessageConsumerRateLimitingWithApacheActiveMQArtemisyoucanspecifyamaximumconsumerateatwhichaJMSMessageConsumerwillconsumemessages.Thiscanbespecifiedwhencreatingordeployingtheconnectionfactory.

    IfthisvalueisspecifiedthenApacheActiveMQArtemiswillensurethatmessagesareneverconsumedataratehigherthanthespecifiedrate.Thisisaformofconsumerthrottling.

    DeadLetterThedead-letterexampleshowsyouhowtodefineanddealwithdeadlettermessages.Messagescanbedeliveredunsuccessfully(e.g.ifthetransactedsessionusedtoconsumethemisrolledback).

    Examples

    59

  • SuchamessagegoesbacktotheJMSdestinationreadytoberedelivered.However,thismeansitispossibleforamessagetobedeliveredagainandagainwithoutanysuccessandremaininthedestination,cloggingthesystem.

    Topreventthis,messagingsystemsdefinedeadlettermessages:afteraspecifiedunsuccessfuldeliveryattempts,themessageisremovedfromthedestinationandputinsteadinadeadletterdestinationwheretheycanbeconsumedforfurtherinvestigation.

    DelayedRedeliveryThedelayed-redeliveryexampledemonstrateshowApacheActiveMQArtemiscanbeconfiguredtoprovideadelayedredeliveryinthecaseamessageneedstoberedelivered.

    Delayingredeliverycanoftenbeusefulinthecasethatclientsregularlyfailorroll-back.Withoutadelayedredelivery,thesystemcangetintoa"thrashing"state,withdeliverybeingattempted,theclientrollingback,anddeliverybeingre-attemptedinquicksuccession,usingupvaluableCPUandnetworkresources.

    DivertApacheActiveMQArtemisdivertsallowmessagestobetransparently"diverted"orcopiedfromoneaddresstoanotherwithjustsomesimpleconfigurationdefinedontheserverside.

    DurableSubscriptionThedurable-subscriptionexampleshowsyouhowtouseadurablesubscriptionwithApacheActiveMQArtemis.DurablesubscriptionsareastandardpartofJMS,pleaseconsulttheJMS1.1specificationforfulldetails.

    Unlikenon-durablesubscriptions,thekeyfunctionofdurablesubscriptionsisthatthemessagescontainedinthempersistlongerthanthelifetimeofthesubscriber-i.e.theywillaccumulatemessagessenttothetopicevenifthereisnoactivesubscriberonthem.Theywillalsosurviveserverrestartsorcrashes.Notethatforthemessagestobepersisted,themessagessenttothemmustbemarkedasdurablemessages.

    Examples

    60

  • EmbeddedTheembeddedexampleshowshowtoembedJMSwithinyourowncodeusingPOJOinstantiationandnoconfigfiles.

    EmbeddedSimpleTheembeddedexampleshowshowtoembedJMSwithinyourowncodeusingregularApacheActiveMQArtemisXMLfiles.

    MessageExpirationTheexpiryexampleshowsyouhowtodefineanddealwithmessageexpiration.Messagescanberetainedinthemessagingsystemforalimitedperiodoftimebeforebeingremoved.JMSspecificationstatesthatclientsshouldnotreceivemessagesthathavebeenexpired(butitdoesnotguaranteethiswillnothappen).

    ApacheActiveMQArtemiscanassignanexpiryaddresstoagivenqueuesothatwhenmessagesareexpired,theyareremovedfromthequeueandsenttotheexpiryaddress.These"expired"messagescanlaterbeconsumedfromtheexpiryaddressforfurtherinspection.

    ApacheActiveMQArtemisResourceAdapterexampleThisexamplesshowshowtobuildtheactivemqresourceadaptersararfordeploymentinotherApplicationServer's

    HTTPTransportThehttp-transportexampleshowsyouhowtoconfigureApacheActiveMQArtemistousetheHTTPprotocolasitstransportlayer.

    InstantiateJMSObjectsDirectly

    Examples

    61

  • Usually,JMSObjectssuchasConnectionFactory,QueueandTopicinstancesarelookedupfromJNDIbeforebeingusedbytheclientcode.Thisobjectsarecalled"administeredobjects"inJMSterminology.

    However,insomecasesaJNDIservermaynotbeavailableordesired.TocometotherescueApacheActiveMQArtemisalsosupportsthedirectinstantiationoftheseadministeredobjectsontheclientsidesoyoudon'thavetouseJNDIforJMS.

    InterceptorApacheActiveMQArtemisallowsanapplicationtouseaninterceptortohookintothemessagingsystem.InterceptorsallowyoutohandlevariousmessageeventsinApacheActiveMQArtemis.

    JAASThejaasexampleshowsyouhowtoconfigureApacheActiveMQArtemistouseJAASforsecurity.ApacheActiveMQArtemiscanleverageJAAStodelegateuserauthenticationandauthorizationtoexistingsecurityinfrastructure.

    JMSAutoClosableThejms-auto-closeableexampleshowshowJMSresources,suchasconnections,sessionsandconsumers,inJMS2canbeautomaticallyclosedonerror.

    JMSCompletionListenerThejms-completion-listenerexampleshowshowtosendamessageasynchronouslytoApacheActiveMQArtemisanduseaCompletionListenertobenotifiedoftheBrokerreceivingit.

    JMSBridgeThejms-brigdeexampleshowshowtosetupabridgebetweentwostandaloneApacheActiveMQArtemisservers.

    Examples

    62

  • JMSContextThejms-contextexampleshowshowtosendandreceiveamessagetoaJMSQueueusingApacheActiveMQArtemisbyusingaJMSContext.

    AJMSContextispartofJMS2.0andcombinestheJMSConnectionandSessionObjectsintoasimpleInterface.

    JMSSharedConsumerThejms-shared-consumerexampleshowsyouhowcanusesharedconsumerstoshareasubscriptiononatopic.InJMS1.1thiswasnotallowedandsocausedascalabilityissue.InJMS2thisrestrictionhasbeenliftedsoyoucansharetheloadacrossdifferentthreadsandconnections.

    JMXManagementThejmxexampleshowshowtomanageApacheActiveMQArtemisusingJMX.

    LargeMessageThelarge-messageexampleshowsyouhowtosendandreceiveverylargemessageswithApacheActiveMQArtemis.ApacheActiveMQArtemissupportsthesendingandreceivingofhugemessages,muchlargerthancanfitinavailableRAMontheclientorserver.Effectivelytheonlylimittomessagesizeistheamountofdiskspaceyouhaveontheserver.

    Largemessagesarepersistedontheserversotheycansurviveaserverrestart.InotherwordsApacheActiveMQArtemisdoesn'tjustdoasimplesocketstreamfromthesendertotheconsumer.

    Last-ValueQueueThelast-value-queueexampleshowsyouhowtodefineanddealwithlast-valuequeues.Last-valuequeuesarespecialqueueswhichdiscardanymessageswhenanewermessagewiththesamevalueforawell-definedlast-valuepropertyisputinthe

    Examples

    63

  • queue.Inotherwords,alast-valuequeueonlyretainsthelastvalue.

    Atypicalexampleforlast-valuequeueisforstockprices,whereyouareonlyinterestedbythelatestpriceforaparticularstock.

    ManagementThemanagementexampleshowshowtomanageApacheActiveMQArtemisusingJMSMessagestoinvokemanagementoperationsontheserver.

    ManagementNotificationThemanagement-notificationexampleshowshowtoreceivemanagementnotificationsfromApacheActiveMQArtemisusingJMSmessages.ApacheActiveMQArtemisserversemitmanagementnotificationswheneventsofinterestoccur(consumersarecreatedorclosed,addressesarecreatedordeleted,securityauthenticationfails,etc.).

    MessageCounterThemessage-countersexampleshowsyouhowtousemessagecounterstoobtainmessageinformationforaJMSqueue.

    MessageGroupThemessage-groupexampleshowsyouhowtoconfigureandusemessagegroupswithApacheActiveMQArtemis.Messagegroupsallowyoutopinmessagessotheyareonlyconsumedbyasingleconsumer.Messagegroupsaresetsofmessagesthathasthefollowingcharacteristics:

    Messagesinamessagegroupsharethesamegroupid,i.e.theyhavesameJMSXGroupIDstringpropertyvalues

    Theconsumerthatreceivesthefirstmessageofagroupwillreceiveallthemessagesthatbelongstothegroup

    MessageGroup

    Examples

    64

  • Themessage-group2exampleshowsyouhowtoconfigureandusemessagegroupswithApacheActiveMQArtemisviaaconnectionfactory.

    MessagePriorityMessagePrioritycanbeusedtoinfluencethedeliveryorderformessages.

    Itcanberetrievedbythemessage'sstandardheaderfield'JMSPriority'asdefinedinJMSspecificationversion1.1.

    Thevalueisoftypeinteger,rangingfrom0(thelowest)to9(thehighest).Whenmessagesarebeingdelivered,theirprioritieswilleffecttheirorderofdelivery.Messagesofhigherprioritieswilllikelybedeliveredbeforethoseoflowerpriorities.

    Messagesofequalprioritiesaredeliveredinthenaturalorderoftheirarrivalattheirdestinations.PleaseconsulttheJMS1.1specificationforfulldetails.

    MultipleFailoverThisexampledemonstrateshowtosetupaliveserverwithmultiplebackups

    MultipleFailoverFailbackThisexampledemonstrateshowtosetupaliveserverwithmultiplebackupsbutforcingfailoverbacktotheoriginalliveserver

    NoConsumerBufferingBydefault,ApacheActiveMQArtemisconsumersbuffermessagesfromtheserverinaclientsidebufferbeforeyouactuallyreceivethemontheclientside.Thisimprovesperformancesinceotherwiseeverytimeyoucalledreceive()orhadprocessedthelastmessageinaMessageListeneronMessage()method,theApacheActiveMQArtemisclientwouldhavetogotheservertorequestthenextmessage,whichwouldthengetsenttotheclientside,ifonewasavailable.

    Examples

    65

  • Thiswouldinvolveanetworkroundtripforeverymessageandreduceperformance.Therefore,bydefault,ApacheActiveMQArtemispre-fetchesmessagesintoabufferoneachconsumer.

    Insomecasebufferingisnotdesirable,andApacheActiveMQArtemisallowsittobeswitchedoff.Thisexampledemonstratesthat.

    Non-TransactionFailoverWithServerDataReplicationThenon-transaction-failoverexampledemonstratestwoserverscoupledasalive-backuppairforhighavailability(HA),andaclientusinganon-transactedJMSsessionfailingoverfromlivetobackupwhentheliveserveriscrashed.

    ApacheActiveMQArtemisimplementsfailoverofclientconnectionsbetweenliveandbackupservers.Thisisimplementedbythereplicationofstatebetweenliveandbackupnodes.Whenreplicationisconfiguredandalivenodecrashes,theclientconnectionscancarryandcontinuetosendandconsumemessages.Whennon-transactedsessionsareused,onceandonlyoncemessagedeliveryisnotguaranteedanditispossiblethatsomemessageswillbelostordeliveredtwice.

    OpenWireTheOpenwireexampleshowshowtoconfigureanApacheActiveMQArtemisservertocommunicatewithanApacheActiveMQArtemisJMSclientthatusesopen-wireprotocol.

    Youwillfindthequeueexampleforopenwire,andthechatexample.

    PagingThepagingexampleshowshowApacheActiveMQArtemiscansupporthugequeuesevenwhentheserverisrunninginlimitedRAM.Itdoesthisbytransparentlypagingmessagestodisk,anddepagingthemwhentheyarerequired.

    Pre-Acknowledge

    Examples

    66

  • StandardJMSsupportsthreeacknowledgementmodes:AUTO_ACKNOWLEDGE,CLIENT_ACKNOWLEDGE,andDUPS_OK_ACKNOWLEDGE.ForafulldescriptiononthesemodespleaseconsulttheJMSspecification,oranyJMStutorial.

    Allofthesestandardmodesinvolvesendingacknowledgementsfromtheclienttotheserver.Howeverinsomecases,youreallydon'tmindlosingmessagesineventoffailure,soitwouldmakesensetoacknowledgethemessageontheserverbeforedeliveringittotheclient.ThisexampledemonstrateshowApacheActiveMQArtemisallowsthiswithanextraacknowledgementmode.

    MessageProducerRateLimitingTheproducer-rte-limitexampledemonstrateshow,withApacheActiveMQArtemis,youcanspecifyamaximumsendrateatwhichaJMSmessageproducerwillsendmessages.

    QueueAsimpleexampledemonstratingaJMSqueue.

    MessageRedistributionThequeue-message-redistributionexampledemonstratesmessageredistributionbetweenqueueswiththesamenamedeployedindifferentnodesofacluster.

    QueueRequestorAsimpleexampledemonstratingaJMSqueuerequestor.

    QueuewithMessageSelectorThequeue-selectorexampleshowsyouhowtoselectivelyconsumemessagesusingmessageselectorswithqueueconsumers.

    Examples

    67

  • ReattachNodeexampleTheReattachNodeexampleshowshowaclientcantrytoreconnecttothesameserverinsteadoffailingtheconnectionimmediatelyandnotifyinganyuserExceptionListenerobjects.ApacheActiveMQArtemiscanbeconfiguredtoautomaticallyretrytheconnection,andreattachtotheserverwhenitbecomesavailableagainacrossthenetwork.

    ReplicatedFailbackexampleAnexampleshowinghowfailbackworkswhenusingreplication,InthisexamplealiveserverwillreplicateallitsJournaltoabackupserverasitupdatesit.Whentheliveservercrashesthebackuptakesoverfromtheliveserverandtheclientreconnectsandcarriesonfromwhereitleftoff.

    ReplicatedFailbackstaticexampleAnexampleshowinghowfailbackworkswhenusingreplication,butthistimewithstaticconnectors

    ReplicatedmultiplefailoverexampleAnexampleshowinghowtoconfiguremultiplebackupswhenusingreplication

    ReplicatedFailovertransactionexampleAnexampleshowinghowfailoverworkswithatransactionwhenusingreplication

    Request-ReplyexampleAsimpleexampleshowingtheJMSrequest-responsepattern.

    ScheduledMessage

    Examples

    68

  • Thescheduled-messageexampleshowsyouhowtosendascheduledmessagetoaJMSQueuewithApacheActiveMQArtemis.Scheduledmessageswon'tgetdelivereduntilaspecifiedtimeinthefuture.

    SecurityThesecurityexampleshowsyouhowconfigureanduserolebasedqueuesecuritywithApacheActiveMQArtemis.

    SendAcknowledgementsThesend-acknowledgementsexampleshowsyouhowtouseApacheActiveMQArtemis'sadvancedasynchronoussendacknowledgementsfeaturetoobtainacknowledgementfromtheserverthatsendshavebeenreceivedandprocessedinaseparatestreamtothesentmessages.

    SpringIntegrationThisexampleshowshowtouseembeddedJMSusingApacheActiveMQArtemis'sSpringintegration.

    SSLTransportThessl-enabledshowsyouhowtoconfigureSSLwithApacheActiveMQArtemistosendandreceivemessage.

    StaticMessageSelectorThestatic-selectorexampleshowsyouhowtoconfigureanApacheActiveMQArtemiscorequeuewithstaticmessageselectors(filters).

    StaticMessageSelectorUsingJMS

    Examples

    69

  • Thestatic-selector-jmsexampleshowsyouhowtoconfigureanApacheActiveMQArtemisqueuewithstaticmessageselectors(filters)usingJMS.

    StompThestompexampleshowsyouhowtoconfigureanApacheActiveMQArtemisservertosendandreceiveStompmessages.

    Stomp1.1ThestompexampleshowsyouhowtoconfigureanApacheActiveMQArtemisservertosendandreceiveStompmessagesviaaStomp1.1connection.

    Stomp1.2ThestompexampleshowsyouhowtoconfigureanApacheActiveMQArtemisservertosendandreceiveStompmessagesviaaStomp1.2connection.

    StompOverWebSocketsThestomp-websocketsexampleshowsyouhowtoconfigureanApacheActiveMQArtemisservertosendandreceiveStompmessagesdirectlyfromWebbrowsers(providedtheysupportWebSockets).

    SymmetricClusterThesymmetric-clusterexampledemonstratesasymmetricclusterset-upwithApacheActiveMQArtemis.

    ApacheActiveMQArtemishasextremelyflexibleclusteringwhichallowsyoutoset-upserversinmanydifferenttopologies.Themostcommontopologythatyou'llperhapsbefamiliarwithifyouareusedtoapplicationserverclusteringisasymmetriccluster.

    Examples

    70

  • Withasymmetriccluster,theclusterishomogeneous,i.e.eachnodeisconfiguredthesameaseveryothernode,andeverynodeisconnectedtoeveryothernodeinthecluster.

    TemporaryQueueAsimpleexampledemonstratinghowtouseaJMStemporaryqueue.

    TopicAsimpleexampledemonstratingaJMStopic.

    TopicHierarchyApacheActiveMQArtemissupportstopichierarchies.Withatopichierarchyyoucanregisterasubscriberwithawild-cardandthatsubscriberwillreceiveanymessagessenttoanaddressthatmatchesthewildcard.

    TopicSelector1Thetopic-selector-example1exampleshowsyouhowtosendmessagetoaJMSTopic,andsubscribethemusingselectorswithApacheActiveMQArtemis.

    TopicSelector2Thetopic-selector-example2exampleshowsyouhowtoselectivelyconsumemessagesusingmessageselectorswithtopicconsumers.

    TransactionFailoverThetransaction-failoverexampledemonstratestwoserverscoupledasalive-backuppairforhighavailability(HA),andaclientusingatransactedJMSsessionfailingoverfromlivetobackupwhentheliveserveriscrashed.

    Examples

    71

  • ApacheActiveMQArtemisimplementsfailoverofclientconnectionsbetweenliveandbackupservers.Thisisimplementedbythesharingofajournalbetweentheservers.Whenalivenodecrashes,theclientconnectionscancarryandcontinuetosendandconsumemessages.Whentransactedsessionsareused,onceandonlyoncemessagedeliveryisguaranteed.

    FailoverWithoutTransactionsThestop-server-failoverexampledemonstratesfailoveroftheJMSconnectionfromonenodetoanotherwhentheliveservercrashesusingaJMSnon-transactedsession.

    TransactionalSessionThetransactionalexampleshowsyouhowtouseatransactionalSessionwithApacheActiveMQArtemis.

    XAHeuristicThexa-heuristicexampleshowsyouhowtomakeanXAheuristicdecisionthroughApacheActiveMQArtemisManagementInterface.AheuristicdecisionisaunilateraldecisiontocommitorrollbackanXAtransactionbranchafterithasbeenprepared.

    XAReceiveThexa-receiveexampleshowsyouhowmessagereceivingbehavesinanXAtransactioninApacheActiveMQArtemis.

    XASendThexa-sendexampleshowsyouhowmessagesendingbehavesinanXAtransactioninApacheActiveMQArtemis.

    CoreAPIExamples

    Examples

    72

  • Torunacoreexample,simplycdintotheappropriateexampledirectoryandtypeant

    EmbeddedTheembeddedexampleshowshowtoembedtheApacheActiveMQArtemisserverwithinyourowncode.

    Examples

    73

  • RoutingMessagesWithWildCardsApacheActiveMQArtemisallowstheroutingofmessagesviawildcardaddresses.

    Ifaqueueiscreatedwithanaddressofsayqueue.news.#thenitwillreceiveanymessagessenttoaddressesthatmatchthis,forinstancequeue.news.europeorqueue.news.usaorqueue.news.usa.sport.Ifyoucreateaconsumeronthisqueue,thisallowsaconsumertoconsumemessageswhicharesenttoahierarchyofaddresses.

    Note

    InJMSterminologythisallows"topichierarchies"tobecreated.

    Toenablethisfunctionalitysetthepropertywild-card-routing-enabledinthebroker.xmlfiletotrue.Thisistruebydefault.

    Formoreinformationonthewildcardsyntaxtakealookatwildcardsyntaxchapter,alsoseethetopichierarchyexampleintheexamples.

    RoutingMessagesWithWildCards

    74

  • UnderstandingtheApacheActiveMQArtemisWildcardSyntaxApacheActiveMQArtemisusesaspecificsyntaxforrepresentingwildcardsinsecuritysettings,addresssettingsandwhencreatingconsumers.

    ThesyntaxissimilartothatusedbyAMQP.

    AnApacheActiveMQArtemiswildcardexpressioncontainswordsdelimitedbythecharacter'.'(fullstop).

    Thespecialcharacters'#'and'*'alsohavespecialmeaningandcantaketheplaceofaword.

    Thecharacter'#'means'matchanysequenceofzeroormorewords'.

    Thecharacter'*'means'matchasingleword'.

    Sothewildcard'news.europe.#'wouldmatch'news.europe','news.europe.sport','news.europe.politics',and'news.europe.politics.regional'butwouldnotmatch'news.usa','news.usa.sport'nor'entertainment'.

    Thewildcard'news.*'wouldmatch'news.europe',butnot'news.europe.sport'.

    Thewildcard'news.*.sport'wouldmatch'news.europe.sport'andalso'news.usa.spo