Table of Contents - Apache ActiveMQ · 2020. 7. 29. · Using JMS 9. Using Core 10. Mapping JMS...

234
1. Introduction 2. Legal Notice 3. Preface 4. Project Info 5. Messaging Concepts 6. Architecture 7. Using the Server 8. Using JMS 9. Using Core 10. Mapping JMS Concepts to the Core API 11. The Client Classpath 12. Examples 13. Routing Messages With Wild Cards 14. Understanding the Apache ActiveMQ Artemis Wildcard Syntax 15. Filter Expressions 16. Persistence 17. Configuring Transports 18. Detecting Dead Connections 19. Detecting Slow Consumers 20. Resource Manager Configuration 21. Flow Control 22. Guarantees of sends and commits 23. Message Redeliveryand Undelivered Messages 24. Message Expiry 25. Large Messages 26. Paging 27. Queue Attributes 28. Scheduled Messages 29. Last-Value Queues 30. Message Grouping 31. Extra Acknowledge Modes 32. Management 33. Security 34. Resource Limits 35. The JMS Bridge 36. Client Reconnection and Session Reattachment 37. Diverting and Splitting Message Flows 38. Core Bridges 39. Duplicate Message Detection 40. Clusters 41. High Availabilityand Failover 42. Graceful Server Shutdown 43. Libaio Native Libraries 44. Thread management 45. Logging 46. REST Interface 47. Embedding Apache ActiveMQ Artemis 48. Spring Integration 49. AeroGear Integration Table of Contents ActiveMQ Artemis Documentation 1

Transcript of Table of Contents - Apache ActiveMQ · 2020. 7. 29. · Using JMS 9. Using Core 10. Mapping JMS...

  • 1. Introduction

    2. LegalNotice

    3. Preface

    4. ProjectInfo

    5. MessagingConcepts

    6. Architecture

    7. UsingtheServer

    8. UsingJMS

    9. UsingCore

    10. MappingJMSConceptstotheCoreAPI

    11. TheClientClasspath

    12. Examples

    13. RoutingMessagesWithWildCards

    14. UnderstandingtheApacheActiveMQArtemisWildcardSyntax

    15. FilterExpressions

    16. Persistence

    17. ConfiguringTransports

    18. DetectingDeadConnections

    19. DetectingSlowConsumers

    20. ResourceManagerConfiguration

    21. FlowControl

    22. Guaranteesofsendsandcommits

    23. MessageRedeliveryandUndeliveredMessages

    24. MessageExpiry

    25. LargeMessages

    26. Paging

    27. QueueAttributes

    28. ScheduledMessages

    29. Last-ValueQueues

    30. MessageGrouping

    31. ExtraAcknowledgeModes

    32. Management

    33. Security

    34. ResourceLimits

    35. TheJMSBridge

    36. ClientReconnectionandSessionReattachment

    37. DivertingandSplittingMessageFlows

    38. CoreBridges

    39. DuplicateMessageDetection

    40. Clusters

    41. HighAvailabilityandFailover

    42. GracefulServerShutdown

    43. LibaioNativeLibraries

    44. Threadmanagement

    45. Logging

    46. RESTInterface

    47. EmbeddingApacheActiveMQArtemis

    48. SpringIntegration

    49. AeroGearIntegration

    TableofContents

    ActiveMQArtemisDocumentation

    1

  • 50. VertXIntegration

    51. InterceptingOperations

    52. ProtocolsandInteroperability

    53. Tools

    54. MavenPlugin

    55. TroubleshootingandPerformanceTuning

    56. ConfigurationReference

    ActiveMQArtemisDocumentation

    2

  • TheUsermanualisanindepthmanualonallaspectsofApacheActiveMQArtemis

    ApacheActiveMQArtemisUserManual

    ActiveMQArtemisDocumentation

    3Introduction

  • LicensedtotheApacheSoftwareFoundation(ASF)underoneormorecontributorlicenseagreements.SeetheNOTICE

    filedistributedwiththisworkforadditionalinformationregardingcopyrightownership.TheASFlicensesthisfiletoYou

    undertheApacheLicense,Version2.0(the"License");youmaynotusethisfileexceptincompliancewiththeLicense.

    YoumayobtainacopyoftheLicenseat

    http://www.apache.org/licenses/LICENSE-2.0

    Unlessrequiredbyapplicablelaworagreedtoinwriting,softwaredistributedundertheLicenseisdistributedonan"AS

    IS"BASIS,WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.SeetheLicenseforthe

    specificlanguagegoverningpermissionsandlimitationsundertheLicense.

    LegalNotice

    ActiveMQArtemisDocumentation

    4LegalNotice

    http://www.apache.org/licenses/LICENSE-2.0

  • WhatisApacheActiveMQArtemis?

    ApacheActiveMQArtemisisanopensourceprojecttobuildamulti-protocol,embeddable,veryhighperformance,

    clustered,asynchronousmessagingsystem.

    ApacheActiveMQArtemisisanexampleofMessageOrientedMiddleware(MoM).ForadescriptionofMoMsand

    othermessagingconceptspleaseseetheMessagingConcepts.

    ForanswerstomorequestionsaboutwhatApacheActiveMQArtemisisandwhatitisn'tpleasevisittheFAQswiki

    page.

    WhyuseApacheActiveMQArtemis?Herearejustafewofthereasons:

    100%opensourcesoftware.ApacheActiveMQArtemisislicensedusingtheApacheSoftwareLicensev2.0to

    minimisebarrierstoadoption.

    ApacheActiveMQArtemisisdesignedwithusabilityinmind.

    WritteninJava.RunsonanyplatformwithaJava8+runtime,that'severythingfromWindowsdesktopstoIBM

    mainframes.

    Amazingperformance.Ourground-breakinghighperformancejournalprovidespersistentmessagingperformance

    atratesnormallyseenfornon-persistentmessaging,ournon-persistentmessagingperformancerockstheboat

    too.

    Fullfeatureset.Allthefeaturesyou'dexpectinanyseriousmessagingsystem,andothersyouwon'tfindanywhere

    else.

    Elegant,clean-cutdesignwithminimalthirdpartydependencies.RunActiveMQArtemisstand-alone,runitin

    integratedinyourfavouriteJEEapplicationserver,orrunitembeddedinsideyourownproduct.It'suptoyou.

    Seamlesshighavailability.WeprovideaHAsolutionwithautomaticclientfailoversoyoucanguaranteezero

    messagelossorduplicationineventofserverfailure.

    Hugelyflexibleclustering.Createclustersofserversthatknowhowtoloadbalancemessages.Linkgeographically

    distributedclustersoverunreliableconnectionstoformaglobalnetwork.Configureroutingofmessagesinahighly

    flexibleway.

    Preface

    ActiveMQArtemisDocumentation

    5Preface

  • TheofficialApacheActiveMQArtemisprojectpageishttp://activemq.apache.org//.

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

    Ifyouhaveanyuserquestionspleaseuseouruserforum

    Ifyouhavedevelopmentrelatedquestions,pleaseuseourdeveloperforum

    PopinandchattousinourIRCchannel

    Followusontwitter

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

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

    Andmanythankstoallourcontributors,botholdandnewwhohelpedcreateApacheActiveMQArtemis.

    ProjectInformation

    SoftwareDownload

    ProjectInformation

    ActiveMQArtemisDocumentation

    6ProjectInfo

    http://activemq.apache.org//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/activemqhttps://twitter.com/activemqhttps://github.com/apache/activemq-artemishttps://github.com/apache/activemq-artemis/releases

  • ApacheActiveMQArtemisisanasynchronousmessagingsystem,anexampleofMessageOrientedMiddleware,we'll

    justcallthemmessagingsystemsintheremainderofthisbook.

    We'llfirstpresentabriefoverviewofwhatkindofthingsmessagingsystemsdo,wherethey'reusefulandthekindof

    conceptsyou'llhearaboutinthemessagingworld.

    Ifyou'realreadyfamiliarwithwhatamessagingsystemisandwhatit'scapableof,thenyoucanskipthischapter.

    Messagingsystemsallowyoutolooselycoupleheterogeneoussystemstogether,whilsttypicallyprovidingreliability,

    transactionsandmanyotherfeatures.

    UnlikesystemsbasedonaRemoteProcedureCall(RPC)pattern,messagingsystemsprimarilyuseanasynchronous

    messagepassingpatternwithnotightrelationshipbetweenrequestsandresponses.Mostmessagingsystemsalso

    supportarequest-responsemodebutthisisnotaprimaryfeatureofmessagingsystems.

    Designingsystemstobeasynchronousfromend-to-endallowsyoutoreallytakeadvantageofyourhardware

    resources,minimizingtheamountofthreadsblockingonIOoperations,andtouseyournetworkbandwidthtoitsfull

    capacity.WithanRPCapproachyouhavetowaitforaresponseforeachrequestyoumakesoarelimitedbythenetwork

    roundtriptime,orlatencyofyournetwork.Withanasynchronoussystemyoucanpipelineflowsofmessagesindifferentdirections,soarelimitedbythenetworkbandwidthnotthelatency.Thistypicallyallowsyoutocreatemuchhigherperformanceapplications.

    Messagingsystemsdecouplethesendersofmessagesfromtheconsumersofmessages.Thesendersand

    consumersofmessagesarecompletelyindependentandknownothingofeachother.Thisallowsyoutocreateflexible,

    looselycoupledsystems.

    Often,largeenterprisesuseamessagingsystemtoimplementamessagebuswhichlooselycouplesheterogeneous

    systemstogether.MessagebusesoftenformthecoreofanEnterpriseServiceBus.(ESB).Usingamessagebustode-

    coupledisparatesystemscanallowthesystemtogrowandadaptmoreeasily.Italsoallowsmoreflexibilitytoaddnew

    systemsorretireoldonessincetheydon'thavebrittledependenciesoneachother.

    Messagingsystemsnormallysupporttwomainstylesofasynchronousmessaging:messagequeuemessaging(also

    knownaspoint-to-pointmessaging)andpublishsubscribemessaging.We'llsummarisethembrieflyhere:

    Withthistypeofmessagingyousendamessagetoaqueue.Themessageisthentypicallypersistedtoprovidea

    guaranteeofdelivery,thensometimelaterthemessagingsystemdeliversthemessagetoaconsumer.Theconsumer

    thenprocessesthemessageandwhenitisdone,itacknowledgesthemessage.Oncethemessageisacknowledged

    itdisappearsfromthequeueandisnotavailabletobedeliveredagain.Ifthesystemcrashesbeforethemessaging

    serverreceivesanacknowledgementfromtheconsumer,thenonrecovery,themessagewillbeavailabletobe

    deliveredtoaconsumeragain.

    Withpoint-to-pointmessaging,therecanbemanyconsumersonthequeuebutaparticularmessagewillonlyeverbe

    MessagingConcepts

    MessagingConcepts

    Messagingstyles

    TheMessageQueuePattern

    ActiveMQArtemisDocumentation

    7MessagingConcepts

    http://en.wikipedia.org/wiki/Message_oriented_middlewarehttp://en.wikipedia.org/wiki/Remote_procedure_callhttp://en.wikipedia.org/wiki/Enterprise_service_bushttp://en.wikipedia.org/wiki/Message_queuehttp://en.wikipedia.org/wiki/Publish_subscribe

  • consumedbyamaximumofoneofthem.Senders(alsoknownasproducers)tothequeuearecompletelydecoupledfromreceivers(alsoknownasconsumers)ofthequeue-theydonotknowofeachother'sexistence.

    Aclassicexampleofpointtopointmessagingwouldbeanorderqueueinacompany'sbookorderingsystem.Each

    orderisrepresentedasamessagewhichissenttotheorderqueue.Let'simaginetherearemanyfrontendordering

    systemswhichsendorderstotheorderqueue.Whenamessagearrivesonthequeueitispersisted-thisensuresthat

    iftheservercrashestheorderisnotlost.Let'salsoimaginetherearemanyconsumersontheorderqueue-each

    representinganinstanceofanorderprocessingcomponent-thesecanbeondifferentphysicalmachinesbut

    consumingfromthesamequeue.Themessagingsystemdeliverseachmessagetooneandonlyoneoftheordering

    processingcomponents.Differentmessagescanbeprocessedbydifferentorderprocessors,butasingleorderisonly

    processedbyoneorderprocessor-thisensuresordersaren'tprocessedtwice.

    Asanorderprocessorreceivesamessage,itfulfillstheorder,sendsorderinformationtothewarehousesystemand

    thenupdatestheorderdatabasewiththeorderdetails.Onceit'sdonethatitacknowledgesthemessagetotellthe

    serverthattheorderhasbeenprocessedandcanbeforgottenabout.Oftenthesendtothewarehousesystem,update

    indatabaseandacknowledgementwillbecompletedinasingletransactiontoensureACIDproperties.

    Withpublish-subscribemessagingmanysenderscansendmessagestoanentityontheserver,oftencalledatopic(e.g.intheJMSworld).

    Therecanbemanysubscriptionsonatopic,asubscriptionisjustanotherwordforaconsumerofatopic.Eachsubscriptionreceivesacopyofeachmessagesenttothetopic.Thisdiffersfromthemessagequeuepatternwhereeachmessageisonlyconsumedbyasingleconsumer.

    Subscriptionscanoptionallybedurablewhichmeanstheyretainacopyofeachmessagesenttothetopicuntilthesubscriberconsumesthem-eveniftheservercrashesorisrestartedinbetween.Non-durablesubscriptionsonlylasta

    maximumofthelifetimeoftheconnectionthatcreatedthem.

    Anexampleofpublish-subscribemessagingwouldbeanewsfeed.Asnewsarticlesarecreatedbydifferenteditors

    aroundtheworldtheyaresenttoanewsfeedtopic.Therearemanysubscribersaroundtheworldwhoareinterestedin

    receivingnewsitems-eachonecreatesasubscriptionandthemessagingsystemensuresthatacopyofeachnews

    messageisdeliveredtoeachsubscription.

    Akeyfeatureofmostmessagingsystemsisreliab lemessaging.Withreliablemessagingtheservergivesaguaranteethatthemessagewillbedeliveredonceandonlyoncetoeachconsumerofaqueueoreachdurablesubscriptionofa

    topic,evenintheeventofsystemfailure.Thisiscrucialformanybusinesses;e.g.youdon'twantyourordersfulfilled

    morethanonceoranyofyourorderstobelost.

    Inothercasesyoumaynotcareaboutaonceandonlyoncedeliveryguaranteeandarehappytocopewithduplicate

    deliveriesorlostmessages-anexampleofthismightbetransientstockpriceupdates-whicharequicklysuperseded

    bythenextupdateonthesamestock.Themessagingsystemallowsyoutoconfigurewhichdeliveryguaranteesyou

    require.

    Messagingsystemstypicallysupportthesendingandacknowledgementofmultiplemessagesinasinglelocal

    transaction.ApacheActiveMQArtemisalsosupportsthesendingandacknowledgementofmessageaspartofalarge

    globaltransaction-usingtheJavamappingofXA:JTA.

    ThePublish-SubscribePattern

    Deliveryguarantees

    Transactions

    ActiveMQArtemisDocumentation

    8MessagingConcepts

    http://en.wikipedia.org/wiki/ACID

  • Messagesareeitherdurableornondurable.Durablemessageswillbepersistedinpermanentstorageandwillsurvive

    serverfailureorrestart.Nondurablemessageswillnotsurviveserverfailureorrestart.Examplesofdurablemessages

    mightbeordersortrades,wheretheycannotbelost.Anexampleofanondurablemessagemightbeastockprice

    updatewhichistransitoryanddoesn'tneedtosurvivearestart.

    Howdoclientapplicationsinteractwithmessagingsystemsinordertosendandconsumemessages?

    SeveralmessagingsystemsprovidetheirownproprietaryAPIswithwhichtheclientcommunicateswiththemessaging

    system.

    Therearealsosomestandardwaysofoperatingwithmessagingsystemsandsomeemergingstandardsinthis

    space.

    Let'stakeabrieflookatthese:

    JMSispartofOracle'sJEEspecification.It'saJavaAPIthatencapsulatesbothmessagequeueandpublish-subscribe

    messagingpatterns.JMSisalowestcommondenominatorspecification-i.e.itwascreatedtoencapsulatecommon

    functionalityofthealreadyexistingmessagingsystemsthatwereavailableatthetimeofitscreation.

    JMSisaverypopularAPIandisimplementedbymostmessagingsystems.JMSisonlyavailabletoclientsrunning

    Java.

    JMSdoesnotdefineastandardwireformat-itonlydefinesaprogrammaticAPIsoJMSclientsandserversfrom

    differentvendorscannotdirectlyinteroperatesinceeachwillusethevendor'sowninternalwireprotocol.

    ApacheActiveMQArtemisprovidesafullycompliantJMS1.1andJMS2.0API.

    ManysystemsprovidetheirownprogrammaticAPIforwhichtointeractwiththemessagingsystem.Theadvantageof

    thisitallowsthefullsetofsystemfunctionalitytobeexposedtotheclientapplication.API'slikeJMSarenotnormallyrich

    enoughtoexposealltheextrafeaturesthatmostmessagingsystemsprovide.

    ApacheActiveMQArtemisprovidesitsowncoreclientAPIforclientstouseiftheywishtohaveaccesstofunctionality

    overandabovethataccessibleviatheJMSAPI.

    RESTapproachestomessagingareshowingalotinterestrecently.

    ItseemsplausiblethatAPIstandardsforcloudcomputingmayconvergeonaRESTstylesetofinterfacesand

    consequentlyaRESTmessagingapproachisaverystrongcontenderforbecomingthede-factomethodformessaging

    interoperability.

    WithaRESTapproachmessagingresourcesaremanipulatedasresourcesdefinedbyaURIandtypicallyusinga

    simplesetofoperationsonthoseresources,e.g.PUT,POST,GETetc.RESTapproachestomessagingoftenuseHTTP

    astheirunderlyingprotocol.

    Durability

    MessagingAPIsandprotocols

    JavaMessageService(JMS)

    SystemspecificAPIs

    RESTfulAPI

    ActiveMQArtemisDocumentation

    9MessagingConcepts

    http://en.wikipedia.org/wiki/Java_Message_Servicehttp://en.wikipedia.org/wiki/Representational_State_Transfer

  • TheadvantageofaRESTapproachwithHTTPisinitssimplicityandthefacttheinternetisalreadytunedtodealwith

    HTTPoptimally.

    PleaseseeRestInterfaceforusingApacheActiveMQArtemis'sRESTfulinterface.

    Stompisaverysimpletextprotocolforinteroperatingwithmessagingsystems.Itdefinesawireformat,sotheoretically

    anyStompclientcanworkwithanymessagingsystemthatsupportsStomp.Stompclientsareavailableinmany

    differentprogramminglanguages.

    PleaseseeStompforusingSTOMPwithApacheActiveMQArtemis.

    AMQPisaspecificationforinteroperablemessaging.Italsodefinesawireformat,soanyAMQPclientcanworkwithany

    messagingsystemthatsupportsAMQP.AMQPclientsareavailableinmanydifferentprogramminglanguages.

    ApacheActiveMQArtemisimplementstheAMQP1.0specification.Anyclientthatsupportsthe1.0specificationwillbe

    abletointeractwithApacheActiveMQArtemis.

    HighAvailability(HA)meansthatthesystemshouldremainoperationalafterfailureofoneormoreoftheservers.The

    degreeofsupportforHAvariesbetweenvariousmessagingsystems.

    ApacheActiveMQArtemisprovidesautomaticfailoverwhereyoursessionsareautomaticallyreconnectedtothebackup

    serveroneventofliveserverfailure.

    FormoreinformationonHA,pleaseseeHighAvailabilityandFailover.

    Manymessagingsystemsallowyoutocreategroupsofmessagingserverscalledclusters.Clustersallowtheloadofsendingandconsumingmessagestobespreadovermanyservers.Thisallowsyoursystemtoscalehorizontallyby

    addingnewserverstothecluster.

    Degreesofsupportforclustersvariesbetweenmessagingsystems,withsomesystemshavingfairlybasicclusters

    withtheclustermembersbeinghardlyawareofeachother.

    ApacheActiveMQArtemisprovidesveryconfigurablestate-of-the-artclusteringmodelwheremessagescanbe

    intelligentlyloadbalancedbetweentheserversinthecluster,accordingtothenumberofconsumersoneachnode,and

    whethertheyarereadyformessages.

    ApacheActiveMQArtemisalsohastheabilitytoautomaticallyredistributemessagesbetweennodesofaclusterto

    preventstarvationonanyparticularnode.

    Forfulldetailsonclustering,pleaseseeClusters.

    Somemessagingsystemsallowisolatedclustersorsinglenodestobebridgedtogether,typicallyoverunreliable

    STOMP

    AMQP

    HighAvailability

    Clusters

    Bridgesandrouting

    ActiveMQArtemisDocumentation

    10MessagingConcepts

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

  • connectionslikeawideareanetwork(WAN),ortheinternet.

    Abridgenormallyconsumesfromaqueueononeserverandforwardsmessagestoanotherqueueonadifferent

    server.Bridgescopewithunreliableconnections,automaticallyreconnectingwhentheconnectionsbecomesavailable

    again.

    ApacheActiveMQArtemisbridgescanbeconfiguredwithfilterexpressionstoonlyforwardcertainmessages,and

    transformationcanalsobehookedin.

    ApacheActiveMQArtemisalsoallowsroutingbetweenqueuestobeconfiguredinserversideconfiguration.Thisallows

    complexroutingnetworkstobesetupforwardingorcopyingmessagesfromonedestinationtoanother,forminga

    globalnetworkofinterconnectedbrokers.

    FormoreinformationpleaseseeCoreBridgesandDivertingandSplittingMessageFlows.

    ActiveMQArtemisDocumentation

    11MessagingConcepts

  • InthissectionwewillgiveanoverviewoftheApacheActiveMQArtemishighlevelarchitecture.

    ApacheActiveMQArtemiscoreisdesignedsimplyassetofPlainOldJavaObjects(POJOs)-wehopeyoulikeitsclean-

    cutdesign.

    We'vealsodesignedittohaveasfewdependenciesonexternaljarsaspossible.Infact,ApacheActiveMQArtemiscore

    hasonlyonejardependency,netty.jar,otherthanthestandardJDKclasses!Thisisbecauseweusesomeofthenetty

    bufferclassesinternally.

    ThisallowsApacheActiveMQArtemistobeeasilyembeddedinyourownproject,orinstantiatedinanydependency

    injectionframeworksuchasSpringorGoogleGuice.

    EachApacheActiveMQArtemisserverhasitsownultrahighperformancepersistentjournal,whichitusesformessage

    andotherpersistence.

    Usingahighperformancejournalallowsoutrageouspersistencemessageperformance,somethingnotachievable

    whenusingarelationaldatabaseforpersistence.

    ApacheActiveMQArtemisclients,potentiallyondifferentphysicalmachinesinteractwiththeApacheActiveMQArtemis

    server.ApacheActiveMQArtemiscurrentlyprovidestwoAPIsformessagingattheclientside:

    1. CoreclientAPI.ThisisasimpleintuitiveJavaAPIthatallowsthefullsetofmessagingfunctionalitywithoutsomeof

    thecomplexitiesofJMS.

    2. JMSclientAPI.ThestandardJMSAPIisavailableattheclientside.

    ApacheActiveMQArtemisalsoprovidesdifferentprotocolimplementationsontheserversoyoucanuserespective

    clientsfortheseprotocols:

    1. Stomp

    2. OpenWire

    3. AMQP

    JMSsemanticsareimplementedbyaJMSfacadelayerontheclientside.

    TheApacheActiveMQArtemisserverdoesnotspeakJMSandinfactdoesnotknowanythingaboutJMS,itisaprotocol

    agnosticmessagingserverdesignedtobeusedwithmultipledifferentprotocols.

    WhenauserusestheJMSAPIontheclientside,allJMSinteractionsaretranslatedintooperationsontheApache

    ActiveMQArtemiscoreclientAPIbeforebeingtransferredoverthewireusingtheApacheActiveMQArtemiswireformat.

    TheserveralwaysjustdealswithcoreAPIinteractions.

    Aschematicillustratingthisrelationshipisshowninfigure3.1below:

    Architecture

    CoreArchitecture

    ActiveMQArtemisDocumentation

    12Architecture

  • Figure3.1showstwouserapplicationsinteractingwithanApacheActiveMQArtemisserver.UserApplication1isusing

    theJMSAPI,whileUserApplication2isusingthecoreclientAPIdirectly.

    YoucanseefromthediagramthattheJMSAPIisimplementedbyathinfacadelayerontheclientside.

    ActiveMQArtemisDocumentation

    13Architecture

  • ApacheActiveMQArtemiscoreisdesignedasasetofsimplePOJOssoifyouhaveanapplicationthatrequires

    messagingfunctionalityinternallybutyoudon'twanttoexposethatasanApacheActiveMQArtemisserveryoucan

    directlyinstantiateandembedApacheActiveMQArtemisserversinyourownapplication.

    FormoreinformationonembeddingApacheActiveMQArtemis,seeEmbeddingApacheActiveMQArtemis.

    ApacheActiveMQArtemisprovidesitsownfullyfunctionalJavaConnectorArchitecture(JCA)adaptorwhichenablesitto

    beintegratedeasilyintoanyJavaEEcompliantapplicationserverorservletengine.

    JavaEEapplicationserversprovideMessageDrivenBeans(MDBs),whichareaspecialtypeofEnterpriseJavaBeans

    (EJBs)thatcanprocessmessagesfromsourcessuchasJMSsystemsormailsystems.

    ProbablythemostcommonuseofanMDBistoconsumemessagesfromaJMSmessagingsystem.

    AccordingtotheJavaEEspecification,aJavaEEapplicationserverusesaJCAadaptertointegratewithaJMS

    messagingsystemsoitcanconsumemessagesforMDBs.

    However,theJCAadapterisnotonlyusedbytheJavaEEapplicationserverforconsumingmessagesviaMDBs,itisalsousedwhensendingmessagetotheJMSmessagingsysteme.g.frominsideanEJBorservlet.

    WhenintegratingwithaJMSmessagingsystemfrominsideaJavaEEapplicationserveritisalwaysrecommendedthat

    thisisdoneviaaJCAadaptor.Infact,communicatingwithaJMSmessagingsystemdirectly,withoutusingJCAwould

    beillegalaccordingtotheJavaEEspecification.

    Theapplicationserver'sJCAserviceprovidesextrafunctionalitysuchasconnectionpoolingandautomatictransaction

    enlistment,whicharedesirablewhenusingmessaging,say,frominsideanEJB.ItispossibletotalktoaJMS

    messagingsystemdirectlyfromanEJB,MDBorservletwithoutgoingthroughaJCAadapter,butthisisnot

    recommendedsinceyouwillnotbeabletotakeadvantageoftheJCAfeatures,suchascachingofJMSsessions,which

    canresultinpoorperformance.

    Figure3.2belowshowsaJavaEEapplicationserverintegratingwithaApacheActiveMQArtemisserverviatheApache

    ActiveMQArtemisJCAadaptor.NotethatallcommunicationbetweenEJBsessionsorentitybeansandMessageDriven

    beansgothroughtheadaptorandnotdirectlytoApacheActiveMQArtemis.

    ThelargearrowwiththeprohibitedsignshowsanEJBsessionbeantalkingdirectlytotheApacheActiveMQArtemis

    server.Thisisnotrecommendedasyou'llmostlikelyendupcreatinganewconnectionandsessioneverytimeyou

    wanttointeractfromtheEJB,whichisananti-pattern.

    ApacheActiveMQArtemisembeddedinyourownapplication

    ApacheActiveMQArtemisintegratedwithaJavaEEapplicationserver

    ActiveMQArtemisDocumentation

    14Architecture

  • FormoreinformationonusingtheJCAadaptor,pleaseseeApplicationServerIntegrationandJavaEE.

    ApacheActiveMQArtemisstand-aloneserver

    ActiveMQArtemisDocumentation

    15Architecture

  • ApacheActiveMQArtemiscanalsobedeployedasastand-aloneserver.Thismeansafullyindependentmessaging

    servernotdependentonaJavaEEapplicationserver.

    Thestandardstand-alonemessagingserverconfigurationcomprisesacoremessagingserverandaJMSservice.

    TheroleoftheJMSServiceistodeployanyJMSQueue,TopicandConnectionFactoryinstancesfromanyserverside

    JMSconfiguration.ItalsoprovidesasimplemanagementAPIforcreatinganddestroyingQueuesandTopicswhichcan

    beaccessedviaJMXortheconnection.ItisaseparateservicetotheActiveMQArtemiscoreserver,sincethecoreserver

    isJMSagnostic.Ifyoudon'twanttodeployanyJMSQueueorTopicviaserversideXMLconfigurationanddon'trequirea

    JMSmanagementAPIontheserversidethenyoucandisablethisservice.

    Thestand-aloneserverconfigurationusesAirlineforbootstrappingtheBroker.

    Thestand-aloneserverarchitectureisshowninfigure3.3below:

    ActiveMQArtemisDocumentation

    16Architecture

    https://github.com/airlift/airline

  • FormoreinformationonserverconfigurationfilesseeServerConfiguration

    ActiveMQArtemisDocumentation

    17Architecture

  • ThischapterwillfamiliariseyouwithhowtousetheApacheActiveMQArtemisserver.

    We'llshowwhereitis,howtostartandstopit,andwe'lldescribethedirectorylayoutandwhatallthefilesareandwhat

    theydo.

    FortheremainderofthischapterwhenwetalkabouttheApacheActiveMQArtemisserverwemeantheApacheActiveMQ

    Artemisstandaloneserver,initsdefaultconfigurationwithaJMSServiceenabled.

    ThisdocumentwillrefertothefullpathofthedirectorywheretheActiveMQdistributionhasbeenextractedtoas

    ${ARTEMIS_HOME}directory.

    Afterdownloadingthedistribution,thefollowinghighlightssomeimportantfoldersonthedistribution:

    |___bin

    |

    |___web

    ||___user-manual

    ||___api

    |

    |___examples

    ||___core

    ||___javaee

    ||___jms

    |

    |___lib

    |

    |___schema

    bin--binariesandscriptsneededtorunActiveMQArtemis.

    web--ThefolderwherethewebcontextisloadedwhenActiveMQArtemisruns.

    user-manual--Theusermanualisplacedunderthewebfolder.

    api--Theapidocumentationisplacedunderthewebfolder

    examples--JMSandJavaEEexamples.Pleaserefertothe'runningexamples'chapterfordetailsonhowtorun

    them.

    lib--jarsandlibrariesneededtorunActiveMQArtemis

    licenses--licensesforActiveMQArtemis

    schemas--XMLSchemasusedtovalidateActiveMQArtemisconfigurationfiles

    Abrokerinstanceisthedirectorycontainingalltheconfigurationandruntimedata,suchaslogsanddatafiles,

    associatedwithabrokerprocess.Itisrecommendedthatyoudonotcreatetheinstancedirectoryunder${ARTEMIS_HOME}.ThisseparationisencouragedsothatyoucanmoreeasilyupgradewhenthenextversionofActiveMQArtemisis

    UsingtheServer

    Installation

    CreatingaBrokerInstance

    ActiveMQArtemisDocumentation

    18UsingtheServer

  • released.

    OnUnixsystems,itisacommonconventiontostorethiskindofruntimedataunderthe/var/libdirectory.Forexample,

    tocreateaninstanceat'/var/lib/mybroker',runthefollowingcommandsinyourcommandlineshell:

    cd/var/lib

    ${ARTEMIS_HOME}/bin/activemqcreatemybroker

    Abrokerinstancedirectorywillcontainthefollowingsubdirectories:

    bin:holdsexecutionscriptsassociatedwiththisinstance.

    etc:holdtheinstanceconfigurationfiles

    data:holdsthedatafilesusedforstoringpersistentmessages

    log:holdsrotatinglogfiles

    tmp:holdstemporaryfilesthataresafetodeletebetweenbrokerruns

    Atthispointyoumaywanttoadjustthedefaultconfigurationlocatedintheetcdirectory.

    Thereareseveraloptionsyoucanusewhencreatinganinstance.

    Forafulllistofupdatedpropertiesalwaysuse:

    $./artemishelpcreate

    NAME

    artemiscreate-createsanewbrokerinstance

    SYNOPSIS

    artemiscreate[--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-anonymous

    Enablesanonymousconfigurationonsecurity(Default:input)

    --cluster-password

    Theclusterpasswordtouseforclustering.(Default:input)

    --cluster-user

    Theclusterusertouseforclustering.(Default:input)

    --clustered

    Enableclustering

    --data

    DirectorywhereActiveMQDataisused.Patharerelativeto

    artemis.instance/bin

    --encoding

    Theencodingthattextfilesshoulduse

    --force

    Overwriteconfigurationatdestinationdirectory

    --home

    DirectorywhereActiveMQArtemisisinstalled

    --host

    Thehostnameofthebroker(Default:0.0.0.0orinputifclustered)

    Options

    ActiveMQArtemisDocumentation

    19UsingtheServer

  • --java-options

    Extrajavaoptionstobepassedtotheprofile

    --password

    Theuser'spassword(Default:input)

    --port-offset

    Offsetsthedefaultports

    --replicated

    Enablebrokerreplication

    --role

    Thenamefortherolecreated(Default:amq)

    --shared-store

    Enablebrokersharedstore

    --silent

    Itwilldisablealltheinputs,anditwouldmakeabestguessfor

    anyrequiredinput

    --user

    Theusername(Default:input)

    --

    Thisoptioncanbeusedtoseparatecommand-lineoptionsfromthe

    listofargument,(usefulwhenargumentsmightbemistakenfor

    command-lineoptions

    Theinstancedirectorytoholdthebroker'sconfigurationanddata

    Someofthesepropertiesmaybemandatoryincertainconfigurationsandthesystemmayaskyouforadditionalinput.

    ./artemiscreate/usr/server

    CreatingActiveMQArtemisinstanceat:/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

    Assumingyoucreatedthebrokerinstanceunder/var/lib/mybrokerallyouneedtodostartrunningthebrokerinstanceis

    execute:

    /var/lib/mybroker/bin/activemqrun

    Nowthatthebrokerisrunning,youcanoptionallyrunsomeoftheincludedexamplestoverifythethebrokerisrunning

    StartingandStoppingaBrokerInstance

    ActiveMQArtemisDocumentation

    20UsingtheServer

  • properly.

    TostoptheApacheActiveMQArtemisinstanceyouwillusethesameactivemqscript,butwiththestopargument.Example:

    /var/lib/mybroker/bin/activemqstop

    PleasenotethatApacheActiveMQArtemisrequiresaJava7orlaterruntimetorun.

    Bydefaulttheetc/bootstrap.xmlconfigurationisused.Theconfigurationcanbechangede.g.byrunning./activemqrun--

    xml:path/to/bootstrap.xmloranotherconfigofyourchoosing.

    Environmentvariablesareusedtoprovideeaseofchangingports,hostsanddatadirectoriesusedandcanbefoundin

    etc/activemq.profileonlinuxandetc\activemq.profile.cmdonWindows.

    TherunscriptssetsomeJVMsettingsfortuningthegarbagecollectionpolicyandheapsize.Werecommendusinga

    parallelgarbagecollectionalgorithmtosmoothoutlatencyandminimiselargeGCpauses.

    BydefaultApacheActiveMQArtemisrunsinamaximumof1GiBofRAM.Toincreasethememorysettingschangethe-

    Xmsand-XmxmemorysettingsasyouwouldforanyJavaprogram.

    IfyouwishtoaddanymoreJVMargumentsortunetheexistingones,therunscriptsaretheplacetodoit.

    Thedistributioncontainsseveralstandardconfigurationsetsforrunning:

    Nonclusteredstand-alone.

    Clusteredstand-alone

    Replicatedstand-alone

    Shared-storestand-alone

    Youcanofcoursecreateyourownconfigurationandspecifyanyconfigurationwhenrunningtherunscript.

    Ifyou'reusingtheAsynchronousIOJournalonLinux,youneedtospecifyjava.library.pathasapropertyonyourJava

    options.Thisisdoneautomaticallyinthescripts.

    Ifyoudon'tspecifyjava.library.pathatyourJavaoptionsthentheJVMwillusetheenvironmentvariableLD_LIBRARY_PATH.

    YouwillneedtomakesurelibaioisinstalledonLinux.FormoreinformationrefertothelibaiochapteratRuntime

    Dependencies

    ApacheActiveMQArtemiscantakeasystempropertyonthecommandlineforconfiguringlogging.

    ServerJVMsettings

    Pre-configuredOptions

    LibraryPath

    Systemproperties

    ActiveMQArtemisDocumentation

    21UsingtheServer

  • Formoreinformationonconfiguringlogging,pleaseseethesectiononLogging.

    Theconfigurationfileusedtobootstraptheserver(e.g.bootstrap.xmlbydefault)referencesthespecificbroker

    configurationfiles.

    broker.xml.ThisisthemainActiveMQconfigurationfile.Alltheparametersinthisfilearedescribedhere

    Itisalsopossibletousesystempropertysubstitutioninalltheconfigurationfiles.byreplacingavaluewiththenameof

    asystemproperty.Hereisanexampleofthiswithaconnectorconfiguration:

    tcp://${activemq.remoting.netty.host:localhost}:${activemq.remoting.netty.port:61616}

    Hereyoucanseewehavereplaced2valueswithsystempropertiesactivemq.remoting.netty.hostand

    activemq.remoting.netty.port.Thesevalueswillbereplacedbythevaluefoundinthesystempropertyifthereisone,ifnot

    theydefaultbacktolocalhostor61616respectively.Itisalsopossibletonotsupplyadefault.i.e.

    ${activemq.remoting.netty.host},howeverthesystempropertymustbesuppliedinthatcase.

    Thestand-aloneserverisbasicallyasetofPOJOswhichareinstantiatedbyAirlinecommands.

    Thebootstrapfileisverysimple.Let'stakealookatanexample:

    core-Instantiatesacoreserverusingtheconfigurationfilefromtheconfigurationattribute.Thisisthemainbroker

    POJOnecessarytodoalltherealmessagingwork.InadditionallJMSobjectssuchas:Queues,Topicsand

    ConnectionFactoryinstancesareconfiguredhere.

    TheconfigurationfortheApacheActiveMQArtemiscoreserveriscontainedinbroker.xml.Thisiswhatthe

    FileConfigurationbeanusestoconfigurethemessagingserver.

    TherearemanyattributeswhichyoucanconfigureApacheActiveMQArtemis.Inmostcasesthedefaultswilldofine,in

    facteveryattributecanbedefaultedwhichmeansafilewithasingleemptyconfigurationelementisavalidconfiguration

    file.Thedifferentconfigurationwillbeexplainedthroughoutthemanualoryoucanrefertotheconfigurationreference

    here.

    OnwindowsyouwillhavetheoptiontorunActiveMQArtemisasaservice.Justusethefollowingcommandtoinstallit:

    Configurationfiles

    BootstrapFile

    Themainconfigurationfile.

    WindowsServer

    ActiveMQArtemisDocumentation

    22UsingtheServer

  • $./artemis-service.exeinstall

    Thecreateprocessshouldgiveyouahintoftheavailablecommandsavailablefortheartemis-service.exe

    ActiveMQArtemisDocumentation

    23UsingtheServer

  • AlthoughApacheActiveMQArtemisprovidesaJMSagnosticmessagingAPI,manyuserswillbemorecomfortableusing

    JMS.

    JMSisaverypopularAPIstandardformessaging,andmostmessagingsystemsprovideaJMSAPI.Ifyouare

    completelynewtoJMSwesuggestyoufollowtheOracleJMStutorial-afullJMStutorialisoutofscopeforthisguide.

    ApacheActiveMQArtemisalsoshipswithawiderangeofexamples,manyofwhichdemonstrateJMSAPIusage.Agood

    placetostartwouldbetoplayaroundwiththesimpleJMSQueueandTopicexample,butwealsoprovideexamplesfor

    manyotherpartsoftheJMSAPI.AfulldescriptionoftheexamplesisavailableinExamples.

    Inthissectionwe'llgothroughthemainstepsinconfiguringtheserverforJMSandcreatingasimpleJMSprogram.

    We'llalsoshowhowtoconfigureanduseJNDI,andalsohowtouseJMSwithApacheActiveMQArtemiswithoutusing

    anyJNDI.

    Forthischapterwe'regoingtouseaverysimpleorderingsystemasourexample.Itisasomewhatcontrivedexample

    becauseofitsextremesimplicity,butitservestodemonstratetheverybasicsofsettingupandusingJMS.

    WewillhaveasingleJMSQueuecalledOrderQueue,andwewillhaveasingleMessageProducersendinganorder

    messagetothequeueandasingleMessageConsumerconsumingtheordermessagefromthequeue.

    Thequeuewillbeadurablequeue,i.e.itwillsurviveaserverrestartorcrash.Wealsowanttopre-deploythequeue,i.e.

    specifythequeueintheserverconfigurationsoitiscreatedautomaticallywithoutushavingtoexplicitlycreateitfromthe

    client.

    TheJMSspecificationestablishestheconventionthatadministeredobjects(i.e.JMSqueue,topicandconnectionfactoryinstances)aremadeavailableviatheJNDIAPI.BrokersarefreetoimplementJNDIastheyseefitassumingthe

    implementationfitstheAPI.ApacheActiveMQArtemisdoesnothaveaJNDIserver.Rather,itusesaclient-sideJNDI

    implementationthatreliesonspecialpropertiessetintheenvironmenttoconstructtheappropriateJMSobjects.Inother

    words,noobjectsarestoredinJNDIontheApacheActiveMQArtemisserver,insteadtheyaresimplyinstantiatedonthe

    clientbasedontheprovidedconfiguration.Let'slookatthedifferentkindsofadministeredobjectsandhowtoconfigure

    them.

    Note

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

    AJMSconnectionfactoryisusedbytheclienttomakeconnectionstotheserver.Itknowsthelocationoftheserveritis

    connectingto,aswellasmanyotherconfigurationparameters.

    UsingJMS

    Asimpleorderingsystem

    JNDIConfiguration

    ConnectionFactoryJNDI

    ActiveMQArtemisDocumentation

    24UsingJMS

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

  • Here'sasimpleexampleoftheJNDIcontextenvironmentforaclientlookingupaconnectionfactorytoaccessan

    embeddedinstanceofApacheActiveMQArtemis:

    java.naming.factory.initial=org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactory

    connectionFactory.invmConnectionFactory=vm://0

    InthisinstancewehavecreatedaconnectionfactorythatisboundtoinvmConnectionFactory,anyentrywithprefix

    connectionFactory.willcreateaconnectionfactory.

    IncertainsituationstherecouldbemultipleserverinstancesrunningwithinaparticularJVM.Inthatsituationeachserver

    wouldtypicallyhaveanInVMacceptorwithauniqueserver-ID.AclientusingJMSandJNDIcanaccountforthisby

    specifyingaconnctionfactoryforeachserver,likeso:

    java.naming.factory.initial=org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactory

    connectionFactory.invmConnectionFactory0=vm://0

    connectionFactory.invmConnectionFactory1=vm://1

    connectionFactory.invmConnectionFactory2=vm://2

    HereisalistofallthesupportedURLschemes:

    vm

    tcp

    udp

    jgroups

    Mostclientswon'tbeconnectingtoanembeddedbroker.Clientswillmostcommonlyconnectacrossanetworka

    remotebroker.Here'sasimpleexampleofaclientconfiguringaconnectionfactorytoconnecttoaremotebroker

    runningonmyhost:5445:

    java.naming.factory.initial=org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactory

    connectionFactory.ConnectionFactory=tcp://myhost:5445

    IntheexampleabovetheclientisusingthetcpschemefortheproviderURL.Aclientmayalsospecifymultiplecomma-

    delimitedhost:portcombinationsintheURL(e.g.(tcp://remote-host1:5445,remote-host2:5445)).Whetherthereisoneor

    manyhost:portcombinationsintheURLtheyaretreatedastheinitialconnector(s)fortheunderlyingconnection.

    Theudpschemeisalsosupportedwhichshoulduseahost:portcombinationthatmatchesthegroup-addressandgroup-

    portfromthecorrespondingbroadcast-groupconfiguredontheActiveMQArtemisserver(s).

    EachschemehasaspecificsetofpropertieswhichcanbesetusingthetraditionalURLquerystringformat(e.g.

    scheme://host:port?key1=value1&key2=value2)tocustomizetheunderlyingtransportmechanism.Forexample,ifaclient

    wantedtoconnecttoaremoteserverusingTCPandSSLitwouldcreateaconnectionfactorylikeso,tcp://remote-

    host:5445?ssl-enabled=true.

    AllthepropertiesavailableforthetcpschemearedescribedinthedocumentationregardingtheNettytransport.

    Noteifyouareusingthetcpschemeandmultipleaddressesthenaquerycanbeappliedtoalltheurl'sorjusttoan

    individualconnector,sowhereyouhave

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

    ActiveMQArtemisDocumentation

    25UsingJMS

  • thenthehttpEnabledpropertyisonlysetontheindividualconnectorswhereastheclientIdissetontheactual

    connectionfactory.AnyconnectorspecificpropertiessetonthewholeURIwillbeappliedtoalltheconnectors.

    Theudpschemesupports4properties:

    localAddress-Ifyouarerunningwithmultiplenetworkinterfacesonthesamemachine,youmaywanttospecifythat

    thediscoverygrouplistensonlyonlyaspecificinterface.Todothisyoucanspecifytheinterfaceaddresswiththis

    parameter.

    localPort-Ifyouwanttospecifyalocalporttowhichthedatagramsocketisboundyoucanspecifyithere.Normally

    youwouldjustusethedefaultvalueof-1whichsignifiesthatananonymousportshouldbeused.Thisparameteris

    alwaysspecifiedinconjunctionwithlocalAddress.

    refreshTimeout-Thisistheperiodthediscoverygroupwaitsafterreceivingthelastbroadcastfromaparticular

    serverbeforeremovingthatserversconnectorpairentryfromitslist.Youwouldnormallysetthistoavalue

    significantlyhigherthanthebroadcast-periodonthebroadcastgroupotherwiseserversmightintermittently

    disappearfromthelisteventhoughtheyarestillbroadcastingduetoslightdifferencesintiming.Thisparameteris

    optional,thedefaultvalueis10000milliseconds(10seconds).

    discoveryInitialWaitTimeout-Iftheconnectionfactoryisusedimmediatelyaftercreationthenitmaynothavehad

    enoughtimetoreceivedbroadcastsfromallthenodesinthecluster.Onfirstusage,theconnectionfactorywill

    makesureitwaitsthislongsincecreationbeforecreatingthefirstconnection.Thedefaultvalueforthisparameter

    is10000milliseconds.

    Lastly,thejgroupsschemeissupportedwhichprovidesanalternativetotheudpschemeforserverdiscovery.TheURL

    patterniseitherjgroups://channelName?file=jgroups-xml-conf-filenamewherejgroups-xml-conf-filenamereferstoanXMLfileon

    theclasspaththatcontainstheJGroupsconfigurationoritcanbejgroups://channelName?properties=some-jgroups-properties.

    InbothinstancethechannelNameisthenamegiventothejgroupschannelcreated.

    TherefreshTimeoutanddiscoveryInitialWaitTimeoutpropertiesaresupportedjustlikewithudp.

    Thedefaulttypeforthedefaultconnectionfactoryisoftypejavax.jms.ConnectionFactory.Thiscanbechangedbysetting

    thetypelikeso

    java.naming.factory.initial=org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactory

    java.naming.provider.url=tcp://localhost:5445?type=CF

    Inthisexampleitisstillsettothedefault,belowshowsalistoftypesthatcanbeset.

    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

    ConfigurationforConnectionFactoryTypes

    DestinationJNDI

    ActiveMQArtemisDocumentation

    26UsingJMS

  • JMSdestinationsarealsotypicallylookedupviaJNDI.Aswithconnectionfactories,destinationscanbeconfigured

    usingspecialpropertiesintheJNDIcontextenvironment.Thepropertynameshouldfollowthepattern:queue.ortopic..ThepropertyvalueshouldbethenameofthequeuehostedbytheApacheActiveMQArtemisserver.Forexample,iftheserverhadaJMSqueueconfiguredlikeso:

    Andiftheclientwantedtobindthisqueueto"queues/OrderQueue"thentheJNDIpropertieswouldbeconfiguredlikeso:

    java.naming.factory.initial=org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactory

    java.naming.provider.url=tcp://myhost:5445

    queue.queues/OrderQueue=OrderQueue

    Itisalsopossibletolook-upJMSdestinationswhichhaven'tbeenconfiguredexplicitlyintheJNDIcontextenvironment.

    ThisispossibleusingdynamicQueues/ordynamicTopics/inthelook-upstring.Forexample,iftheclientwantedtolook-up

    theaforementioned"OrderQueue"itcoulddososimplybyusingthestring"dynamicQueues/OrderQueue".Note,thetext

    thatfollowsdynamicQueues/ordynamicTopics/mustcorrespondexactlytothenameofthedestinationontheserver.

    Here'sthecodefortheexample:

    Firstwe'llcreateaJNDIinitialcontextfromwhichtolookupourJMSobjects.Iftheabovepropertiesaresetin

    jndi.propertiesanditisontheclasspaththenanynew,emptyInitialContextwillbeinitializedusingthoseproperties:

    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);

    Thecode

    ActiveMQArtemisDocumentation

    27UsingJMS

  • //Andweconsumethemessage:

    TextMessagereceivedMessage=(TextMessage)consumer.receive();

    System.out.println("Gotorder:"+receivedMessage.getText());

    Itisassimpleasthat.ForawiderangeofworkingJMSexamplespleaseseetheexamplesdirectoryinthedistribution.

    Warning

    PleasenotethatJMSconnections,sessions,producersandconsumersaredesignedtobere-used.

    Itisananti-patterntocreatenewconnections,sessions,producersandconsumersforeachmessageyou

    produceorconsume.Ifyoudothis,yourapplicationwillperformverypoorly.Thisisdiscussedfurtherinthe

    sectiononperformancetuningPerformanceTuning.

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

    theseobjectsdirectly?"

    WithApacheActiveMQArtemisyoucandoexactlythat.ApacheActiveMQArtemissupportsthedirectinstantiationofJMS

    Queue,TopicandConnectionFactoryinstances,soyoudon'thavetouseJNDIatall.

    Forafullworkingexampleofdirectinstantiationpleaselookatthe"InstantiateJMSObjectsDirectly"example

    undertheJMSsectionoftheexamples.SeetheExamplessectionformoreinfo.

    Here'soursimpleexample,rewrittentonotuseJNDIatall:

    WecreatetheJMSConnectionFactoryobjectviatheActiveMQJMSClientUtilityclass,noteweneedtoprovideconnection

    parametersandspecifywhichtransportweareusing,formoreinformationonconnectorspleaseseeConfiguringthe

    Transport.

    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();

    DirectlyinstantiatingJMSResourceswithoutusingJNDI

    ActiveMQArtemisDocumentation

    28UsingJMS

  • //WecreateasimpleTextMessageandsendit:

    TextMessagemessage=session.createTextMessage("Thisisanorder");

    producer.send(message);

    //Andweconsumethemessage:

    TextMessagereceivedMessage=(TextMessage)consumer.receive();

    System.out.println("Gotorder:"+receivedMessage.getText());

    ThisrepresentstheclientidforaJMSclientandisneededforcreatingdurablesubscriptions.Itispossibletoconfigure

    thisontheconnectionfactoryandcanbesetviatheclientIdelement.Anyconnectioncreatedbythisconnectionfactory

    willhavethissetasitsclientid.

    WhentheJMSacknowledgemodeissettoDUPS_OKitispossibletoconfiguretheconsumersothatitsends

    acknowledgementsinbatchesratherthatoneatatime,savingvaluablebandwidth.Thiscanbeconfiguredviathe

    connectionfactoryviathedupsOkBatchSizeelementandissetinbytes.Thedefaultis1024*1024bytes=1MiB.

    Whenreceivingmessagesinatransactionitispossibletoconfiguretheconsumertosendacknowledgementsin

    batchesratherthanindividuallysavingvaluablebandwidth.Thiscanbeconfiguredontheconnectionfactoryviathe

    transactionBatchSizeelementandissetinbytes.Thedefaultis1024*1024.

    SettingTheClientID

    SettingTheBatchSizeforDUPS_OK

    SettingTheTransactionBatchSize

    ActiveMQArtemisDocumentation

    29UsingJMS

  • ApacheActiveMQArtemiscoreisacompletelyJMS-agnosticmessagingsystemwithitsownnon-JMSAPI.Wecallthis

    thecoreAPI.

    Ifyoudon'twanttouseJMSyoucanusethecoreAPIdirectly.ThecoreAPIprovidesallthefunctionalityofJMSbutwithout

    muchofthecomplexity.ItalsoprovidesfeaturesthatarenotavailableusingJMS.

    SomeofthecoremessagingconceptsaresimilartoJMSconcepts,butcoremessagingconceptsdifferinsomeways.

    IngeneralthecoremessagingAPIissimplerthantheJMSAPI,sinceweremovedistinctionsbetweenqueues,topics

    andsubscriptions.We'lldiscusseachofthemajorcoremessagingconceptsinturn,buttoseetheAPIindetail,please

    consulttheJavadoc.

    Amessageistheunitofdatawhichissentbetweenclientsandservers.

    Amessagehasabodywhichisabuffercontainingconvenientmethodsforreadingandwritingdataintoit.

    Amessagehasasetofpropertieswhicharekey-valuepairs.Eachpropertykeyisastringandpropertyvaluescan

    beoftypeinteger,long,short,byte,byte[],String,double,floatorboolean.

    Amessagehasanaddressitisbeingsentto.Whenthemessagearrivesontheserveritisroutedtoanyqueuesthatareboundtotheaddress-ifthequeuesareboundwithanyfilter,themessagewillonlyberoutedtothatqueue

    ifthefiltermatches.Anaddressmayhavemanyqueuesboundtoitorevennone.Theremayalsobeentitiesother

    thanqueues,likedivertsboundtoaddresses.

    Messagescanbeeitherdurableornondurable.Durablemessagesinadurablequeuewillsurviveaservercrash

    orrestart.Nondurablemessageswillneversurviveaservercrashorrestart.

    Messagescanbespecifiedwithapriorityvaluebetween0and9.0representsthelowestpriorityand9represents

    thehighest.ApacheActiveMQArtemiswillattempttodeliverhigherprioritymessagesbeforelowerpriorityones.

    Messagescanbespecifiedwithanoptionalexpirytime.ApacheActiveMQArtemiswillnotdelivermessagesafterits

    expirytimehasbeenexceeded.

    Messagesalsohaveanoptionaltimestampwhichrepresentsthetimethemessagewassent.

    ApacheActiveMQArtemisalsosupportsthesending/consumingofverylargemessagesmuchlargerthancanfitin

    availableRAMatanyonetime.

    Aservermaintainsamappingbetweenanaddressandasetofqueues.Zeroormorequeuescanbeboundtoasingle

    address.Eachqueuecanbeboundwithanoptionalmessagefilter.Whenamessageisrouted,itisroutedtothesetof

    queuesboundtothemessage'saddress.Ifanyofthequeuesareboundwithafilterexpression,thenthemessagewill

    onlyberoutedtothesubsetofboundqueueswhichmatchthatfilterexpression.

    Otherentities,suchasdivertscanalsobeboundtoanaddressandmessageswillalsoberoutedthere.

    UsingCore

    CoreMessagingConcepts

    Message

    Address

    ActiveMQArtemisDocumentation

    30UsingCore

  • Note

    Incore,thereisnoconceptofaTopic,TopicisaJMSonlyterm.Instead,incore,wejustdealwithaddressesandqueues.

    Forexample,aJMStopicwouldbeimplementedbyasingleaddresstowhichmanyqueuesarebound.Each

    queuerepresentsasubscriptionofthetopic.AJMSQueuewouldbeimplementedasasingleaddresstowhich

    onequeueisbound-thatqueuerepresentstheJMSqueue.

    Queuescanbedurable,meaningthemessagestheycontainsurviveaservercrashorrestart,aslongasthe

    messagesinthemaredurable.Nondurablequeuesdonotsurviveaserverrestartorcrashevenifthemessagesthey

    containaredurable.

    Queuescanalsobetemporary,meaningtheyareautomaticallydeletedwhentheclientconnectionisclosed,iftheyare

    notexplicitlydeletedbeforethat.

    Queuescanbeboundwithanoptionalfilterexpression.Ifafilterexpressionissuppliedthentheserverwillonlyroute

    messagesthatmatchthatfilterexpressiontoanyqueuesboundtotheaddress.

    Manyqueuescanbeboundtoasingleaddress.Aparticularqueueisonlyboundtoamaximumofoneaddress.

    ClientsuseServerLocatorinstancestocreateClientSessionFactoryinstances.ServerLocatorinstancesareusedtolocate

    serversandcreateconnectionstothem.

    InJMStermsthinkofaServerLocatorinthesamewayyouwouldaJMSConnectionFactory.

    ServerLocatorinstancesarecreatedusingtheActiveMQClientfactoryclass.

    ClientsuseClientSessionFactoryinstancestocreateClientSessioninstances.ClientSessionFactoryinstancesarebasically

    theconnectiontoaserver

    InJMStermsthinkofthemasJMSConnections.

    ClientSessionFactoryinstancesarecreatedusingtheServerLocatorclass.

    AclientusesaClientSessionforconsumingandproducingmessagesandforgroupingthemintransactions.

    ClientSessioninstancescansupportbothtransactionalandnontransactionalsemanticsandalsoprovidean

    XAResourceinterfacesomessagingoperationscanbeperformedaspartofaJTAtransaction.

    ClientSessioninstancesgroupClientConsumersandClientProducers.

    ClientSessioninstancescanberegisteredwithanoptionalSendAcknowledgementHandler.Thisallowsyourclientcodetobe

    notifiedasynchronouslywhensentmessageshavesuccessfullyreachedtheserver.ThisuniqueApacheActiveMQ

    Artemisfeature,allowsyoutohavefullguaranteesthatsentmessageshavereachedtheserverwithouthavingtoblock

    oneachmessagesentuntilaresponseisreceived.Blockingoneachmessagessentiscostlysinceitrequiresa

    networkroundtripforeachmessagesent.Bynotblockingandreceivingsendacknowledgementsasynchronouslyyou

    cancreatetrueendtoendasynchronoussystemswhichisnotpossibleusingthestandardJMSAPI.Formore

    Queue

    ServerLocator

    ClientSessionFactory

    ClientSession

    ActiveMQArtemisDocumentation

    31UsingCore

    http://www.oracle.com/technetwork/java/javaee/tech/jta-138684.html

  • informationonthisadvancedfeaturepleaseseethesection[Guaranteesofsendsandcommits]{send-guarantees.md).

    ClientsuseClientConsumerinstancestoconsumemessagesfromaqueue.CoreMessagingsupportsboth

    synchronousandasynchronousmessageconsumptionsemantics.ClientConsumerinstancescanbeconfiguredwithan

    optionalfilterexpressionandwillonlyconsumemessageswhichmatchthatexpression.

    ClientscreateClientProducerinstancesonClientSessioninstancessotheycansendmessages.ClientProducer

    instancescanspecifyanaddresstowhichallsentmessagesarerouted,ortheycanhavenospecifiedaddress,and

    theaddressisspecifiedatsendtimeforthemessage.

    Warning

    PleasenotethatClientSession,ClientProducerandClientConsumerinstancesaredesignedtobere-used.

    It'sananti-patterntocreatenewClientSession,ClientProducerandClientConsumerinstancesforeachmessage

    youproduceorconsume.Ifyoudothis,yourapplicationwillperformverypoorly.Thisisdiscussedfurtherinthe

    sectiononperformancetuningPerformanceTuning.

    Here'saverysimpleprogramusingthecoremessagingAPItosendandreceiveamessage.Logicallyit'scomprisedof

    twosections:firstlysettinguptheproducertowriteamessagetoanaddresss,andsecondly,creatingaqueuefortheconsumer,creatingtheconsumerandstartingit.

    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();

    ClientConsumer

    ClientProducer

    AsimpleexampleofusingCore

    ActiveMQArtemisDocumentation

    32UsingCore

  • ActiveMQArtemisDocumentation

    33UsingCore

  • ThischapterdescribeshowJMSdestinationsaremappedtoApacheActiveMQArtemisaddresses.

    ApacheActiveMQArtemiscoreisJMS-agnostic.ItdoesnothaveanyconceptofaJMStopic.AJMStopicisimplemented

    incoreasanaddress(thetopicname)withzeroormorequeuesboundtoit.Eachqueueboundtothataddress

    representsatopicsubscription.Likewise,aJMSqueueisimplementedasanaddress(theJMSqueuename)withone

    singlequeueboundtoitwhichrepresentstheJMSqueue.

    Byconvention,allJMSqueuesmaptocorequeueswherethecorequeuenamehasthestringjms.queue.prependedto

    it.E.g.theJMSqueuewiththename"orders.europe"wouldmaptothecorequeuewiththename

    "jms.queue.orders.europe".Theaddressatwhichthecorequeueisboundisalsogivenbythecorequeuename.

    ForJMStopicstheaddressatwhichthequeuesthatrepresentthesubscriptionsareboundisgivenbyprependingthe

    string"jms.topic."tothenameoftheJMStopic.E.g.theJMStopicwithname"news.europe"wouldmaptothecore

    address"jms.topic.news.europe"

    InotherwordsifyousendaJMSmessagetoaJMSqueuewithname"orders.europe"itwillgetroutedontheserverto

    anycorequeuesboundtotheaddress"jms.queue.orders.europe".IfyousendaJMSmessagetoaJMStopicwith

    name"news.europe"itwillgetroutedontheservertoanycorequeuesboundtotheaddress"jms.topic.news.europe".

    IfyouwanttoconfiguresettingsforaJMSQueuewiththename"orders.europe",youneedtoconfigurethe

    correspondingcorequeue"jms.queue.orders.europe":

    jms.queue.expiry.europe

    ...

    MappingJMSConceptstotheCoreAPI

    ActiveMQArtemisDocumentation

    34MappingJMSConceptstotheCoreAPI

  • ApacheActiveMQArtemisrequiresseveraljarsontheClientClasspathdependingonwhethertheclientusesApacheActiveMQArtemisCoreAPI,JMS,andJNDI.

    Warning

    AllthejarsmentionedherecanbefoundinthelibdirectoryoftheApacheActiveMQArtemisdistribution.Besure

    youonlyusethejarsfromthecorrectversionoftherelease,youmustnotmixandmatchversionsofjarsfromdifferentApacheActiveMQArtemisversions.Mixingandmatchingdifferentjarversionsmaycausesubtleerrors

    andfailurestooccur.

    IfyouareusingjustapureApacheActiveMQArtemisCoreclient(i.e.noJMS)thenyouneedactivemq-core-client.jar,

    activemq-commons.jar,andnetty.jaronyourclientclasspath.

    IfyouareusingJMSontheclientside,thenyouwillalsoneedtoincludeactivemq-jms-client.jarandgeronimo-

    jms_2.0_spec.jar.

    Note

    geronimo-jms_2.0_spec.jarjustcontainsJavaEEAPIinterfaceclassesneededforthejavax.jms.*classes.Ifyou

    alreadyhaveajarwiththeseinterfaceclassesonyourclasspath,youwillnotneedit.

    TheClientClasspath

    ApacheActiveMQArtemisCoreClient

    JMSClient

    ActiveMQArtemisDocumentation

    35TheClientClasspath

  • TheApacheActiveMQArtemisdistributioncomeswithover90runout-of-the-boxexamplesdemonstratingmanyofthe

    features.

    Theexamplesareavailableinboththebinaryandsourcedistributionundertheexamplesdirectory.Examplesaresplitby

    thefollowingsourcetree:

    features-Examplescontainingbrokerspecificfeatures.

    ha-examplesshowingfailoverandreconnectioncapabilities.

    clustered-examplesshowingloadbalancinganddistributioncapabilities.

    perf-examplesallowingyoutorunafewperformancetestsontheserver

    sub-modules-examplesofintegratedexternalmodules.

    protocols-Protocolspecificexamples

    openwire

    mqtt

    stomp

    amqp

    AsetofJavaEEexamplesarealsoprovidedwhichneedWildFlyinstalledtobeabletorun.

    Torunanyexample,simplycdintotheappropriateexampledirectoryandtypemvnverifyormvninstall(Fordetails

    pleasereadthereadme.htmlineachexampledirectory).

    Youcanusetheprofile-Pexamplestorunmultipleexamplesunderanyexampletree.

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

    Youhavetheoptiontodisabletheserverrunning(sayifyouwanttostarttheservermanually)bysimplyspecifyingthe-

    PnoServerprofile

    Thiswillruntheexamplewithoutaserver:

    #runninganexamplewithoutrunningtheserver

    mvnverify-PnoServer

    Alsounder./targettherewillbeascriptrepeatingthecommandstocreateeachserver:

    Examplethisiscreate-server0.shcreatedforthequeueexample.Itcouldbeusefultoseewhatwedoontheexample:

    #Thesearethecommandsusedtocreateserver0

    /myInstallDirectory/apache-artemis-1.1.0/bin/artemiscreate--allow-anonymous--silent--force--no-web--userguest--passwordguest--roleguest--port-offset

    TheseexamplesareallusingtheMavenplugin,whichcanbeusefulforrunningyourtestserversaswell.

    Thisisthecommonoutputwhenrunninganexample.OnthiscasetakenfromtheQueueexample:

    Examples

    Examples

    ActiveMQArtemisDocumentation

    36Examples

  • [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/standard/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]

    [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'

    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-offset

    Home::/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

    ActiveMQArtemisDocumentation

    37Examples

  • 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]awaitingservertostart

    server-out:___

    server-out:/\____||________(_)_____

    server-out:/_\|_\__|/_\\/||/__/

    server-out:/___\|\/|_/__/|\/|||\___\

    server-out:/_/\_\|\__\____|_||_|_|/___/

    server-out:ApacheActiveMQArtemis1.1.0

    server-out:

    server-out:

    server-out:17:30:25,091INFO[org.apache.activemq.artemis.integration.bootstrap]AMQ101000:StartingActiveMQArtemisServer

    server-out:17:30:25,120INFO[org.apache.activemq.artemis.core.server]AMQ221000:liveMessageBrokerisstartingwithconfigurationBrokerConfiguration(clustered=

    server-out:17:30:25,152INFO[org.apache.activemq.artemis.core.server]AMQ221013:UsingNIOJournal

    server-out:17:30:25,195INFO[org.apache.activemq.artemis.core.server]AMQ221043:Protocolmodulefound:[artemis-server].Addingprotocolsupport

    server-out:17:30:25,199INFO[org.apache.activemq.artemis.core.server]AMQ221043:Protocolmodulefound:[artemis-amqp-protocol].Addingprotocolsupport

    server-out:17:30:25,209INFO[org.apache.activemq.artemis.core.server]AMQ221043:Protocolmodulefound:[artemis-hornetq-protocol].Addingprotocolsupport

    server-out:17:30:25,211INFO[org.apache.activemq.artemis.core.server]AMQ221043:Protocolmodulefound:[artemis-mqtt-protocol].Addingprotocolsupport

    server-out:17:30:25,214INFO[org.apache.activemq.artemis.core.server]AMQ221043:Protocolmodulefound:[artemis-openwire-protocol].Addingprotocolsupport

    server-out:17:30:25,335INFO[org.apache.activemq.artemis.core.server]AMQ221043:Protocolmodulefound:[artemis-stomp-protocol].Addingprotocolsupport

    [INFO]awaitingservertostart

    server-out:17:30:25,781INFO[org.apache.activemq.artemis.core.server]AMQ221003:tryingtodeployqueuejms.queue.DLQ

    server-out:17:30:25,835INFO[org.apache.activemq.artemis.core.server]AMQ221003:tryingtodeployqueuejms.queue.ExpiryQueue

    server-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:Serverisnowlive

    server-out:17:30:25,949INFO[org.apache.activemq.artemis.core.server]AMQ221001:ApacheActiveMQArtemisMessageBrokerversion

    [INFO]Serverstarted

    [INFO]

    [INFO]---artemis-maven-plugin:1.1.0:runClient(runClient)@queue---

    Sentmessage:Thisisatextmessage

    Receivedmessage: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:ApacheActiveMQArtemisMessageBrokerversion

    [INFO]------------------------------------------------------------------------

    [INFO]BUILDSUCCESS

    [INFO]------------------------------------------------------------------------

    [INFO]Totaltime:7.840s

    [INFO]Finishedat:2015-09-01T17:30:27-04:00

    [INFO]FinalMemory:42M/508M

    [INFO]------------------------------------------------------------------------

    ThisexampleshowsyouhowtosendandreceiveJMSmessagesfromanApplet.

    ApacheActiveMQArtemisalsosupportsApplication-Layerfailover,usefulinthecasethatreplicationisnotenabledon

    theserverside.

    WithApplication-Layerfailover,it'suptotheapplicationtoregisteraJMSExceptionListenerwithApacheActiveMQArtemis

    whichwillbecalledbyApacheActiveMQArtemisintheeventthatconnectionfailureisdetected.

    Applet

    Application-LayerFailover

    ActiveMQArtemisDocumentation

    38Examples

  • ThecodeintheExceptionListenerthenrecreatestheJMSconnection,session,etconanothernodeandtheapplication

    cancontinue.

    Application-layerfailoverisanalternativeapproachtoHighAvailability(HA).Application-layerfailoverdiffersfrom

    automaticfailoverinthatsomeclientsidecodingisrequiredinordertoimplementthis.Also,withApplication-layer

    failover,sincetheoldsessionobjectdiesandanewoneiscreated,anyuncommittedworkintheoldsessionwillbe

    lost,andanyunacknowledgedmessagesmightberedelivered.

    Thebridgeexampledemonstratesacorebridgedeployedononeserver,whichconsumesmessagesfromalocal

    queueandforwardsthemtoanaddressonasecondserver.

    CorebridgesareusedtocreatemessageflowsbetweenanytwoApacheActiveMQArtemisserverswhichareremotely

    separated.Corebridgesareresilientandwillcopewithtemporaryconnectionfailureallowingthemtobeanideal

    choiceforforwardingoverunreliableconnections,e.g.aWAN.

    ThebrowserexampleshowsyouhowtouseaJMSQueueBrowserwithApacheActiveMQArtemis.

    QueuesareastandardpartofJMS,pleaseconsulttheJMS1.1specificationforfulldetails.

    AQueueBrowserisusedtolookatmessagesonthequeuewithoutremovingthem.Itcanscantheentirecontentofa

    queueoronlymessagesmatchingamessageselector.

    Theclient-kickoffexampleshowshowtoterminateclientconnectionsgivenanIPaddressusingtheJMXmanagement

    API.

    Theclient-side-failoverlistenerexampleshowshowtoregisteralistenertomonitorfailoverevents

    Theclient-side-load-balancingexampledemonstrateshowsessionscreatedfromasingleJMSConnectioncanbe

    createdtodifferentnodesofthecluster.InotherwordsitdemonstrateshowApacheActiveMQArtemisdoesclient-side

    load-balancingofsessionsacrossthecluster.

    ThisexampledemonstratesaclusteredJMSdurablesubscription

    Thisissimilartothemessagegroupingexampleexceptthatitdemonstratesitworkingoveracluster.Messagessentto

    CoreBridgeExample

    Browser

    ClientKickoff

    Clientsidefailoverlistener

    Client-SideLoad-Balancing

    ClusteredDurableSubscription

    ClusteredGrouping

    ActiveMQArtemisDocumentation

    39Examples

  • differentnodeswiththesamegroupidwillbesenttothesamenodeandthesameconsumer.

    Theclustered-queueexampledemonstratesaJMSqueuedeployedontwodifferentnodes.Thetwonodesare

    configuredtoformacluster.Wethencreateaconsumerforthequeueoneachnode,andwecreateaproducerononly

    oneofthenodes.Wethensendsomemessagesviatheproducer,andweverifythatbothconsumersreceivethesent

    messagesinaround-robinfashion.

    Theclustered-jgroupsexampledemonstrateshowtoformatwonodeclusterusingJGroupsasitsunderlyingtopology

    discoverytechnique,ratherthanthedefaultUDPbroadcasting.Wethencreateaconsumerforthequeueoneachnode,

    andwecreateaproducerononlyoneofthenodes.Wethensendsomemessagesviatheproducer,andweverifythat

    bothconsumersreceivethesentmessagesinaround-robinfashion.

    Theclustered-standaloneexampledemonstrateshowtoconfigureandstarts3clusternodesonthesamemachineto

    formacluster.AsubscriberforaJMStopiciscreatedoneachnode,andwecreateaproducerononlyoneofthenodes.

    Wethensendsomemessagesviatheproducer,andweverifythatthe3subscribersreceiveallthesentmessages.

    ThisexampledemonstrateshowtoconfigureaclusterusingalistofconnectorsratherthanUDPfordiscovery

    Thisexampledemonstrateshowtosetupaclusterwhereclusterconnectionsareoneway,i.e.serverA->ServerB->

    ServerC

    Theclustered-topicexampledemonstratesaJMStopicdeployedontwodifferentnodes.Thetwonodesareconfigured

    toformacluster.Wethencreateasubscriberonthetopiconeachnode,andwecreateaproducerononlyoneofthe

    nodes.Wethensendsomemessagesviatheproducer,andweverifythatbothsubscribersreceiveallthesent

    messages.

    WithApacheActiveMQArtemisyoucanspecifyamaximumconsumerateatwhichaJMSMessageConsumerwill

    consumemessages.Thiscanbespecifiedwhencreatingordeployingtheconnectionfactory.

    IfthisvalueisspecifiedthenApacheActiveMQArtemiswillensurethatmessagesareneverconsumedataratehigher

    thanthespecifiedrate.Thisisaformofconsumerthrottling.

    ClusteredQueue

    ClusteringwithJGroups

    ClusteredStandalone

    ClusteredStaticDiscovery

    ClusteredStaticClusterOneWay

    ClusteredTopic

    MessageConsumerRateLimiting

    DeadLetter

    ActiveMQArtemisDocumentation

    40Examples

  • Thedead-letterexampleshowsyouhowtodefineanddealwithdeadlettermessages.Messagescanbedelivered

    unsuccessfully(e.g.ifthetransactedsessionusedtoconsumethemisrolledback).

    SuchamessagegoesbacktotheJMSdestinationreadytoberedelivered.However,thismeansitispossiblefora

    messagetobedeliveredagainandagainwithoutanysuccessandremaininthedestination,cloggingthesystem.

    Topreventthis,messagingsystemsdefinedeadlettermessages:afteraspecifiedunsuccessfuldeliveryattempts,the

    messageisremovedfromthedestinationandputinsteadinadeadletterdestinationwheretheycanbeconsumedfor

    furtherinvestigation.

    Thedelayed-redeliveryexampledemonstrateshowApacheActiveMQArtemiscanbeconfiguredtoprovideadelayed

    redeliveryinthecaseamessageneedstoberedelivered.

    Delayingredeliverycanoftenbeusefulinthecasethatclientsregularlyfailorroll-back.Withoutadelayedredelivery,the

    systemcangetintoa"thrashing"state,withdeliverybeingattempted,theclientrollingback,anddeliverybeingre-

    attemptedinquicksuccession,usingupvaluableCPUandnetworkresources.

    ApacheActiveMQArtemisdivertsallowmessagestobetransparently"diverted"orcopiedfromoneaddresstoanother

    withjustsomesimpleconfigurationdefinedontheserverside.

    Thedurable-subscriptionexampleshowsyouhowtouseadurablesubscriptionwithApacheActiveMQArtemis.Durable

    subscriptionsareastandardpartofJMS,pleaseconsulttheJMS1.1specificationforfulldetails.

    Unlikenon-durablesubscriptions,thekeyfunctionofdurablesubscriptionsisthatthemessagescontainedinthem

    persistlongerthanthelifetimeofthesubscriber-i.e.theywillaccumulatemessagessenttothetopicevenifthereisno

    activesubscriberonthem.Theywillalsosurviveserverrestartsorcrashes.Notethatforthemessagestobepersisted,

    themessagessenttothemmustbemarkedasdurablemessages.

    TheembeddedexampleshowshowtoembedJMSwithinyourowncodeusingPOJOinstantiationandnoconfigfiles.

    TheembeddedexampleshowshowtoembedJMSwithinyourowncodeusingregularApacheActiveMQArtemisXML

    files.

    Theexpiryexampleshowsyouhowtodefineanddealwithmessageexpiration.Messagescanberetainedinthe

    messagingsystemforalimitedperiodoftimebeforebeingremoved.JMSspecificationstatesthatclientsshouldnot

    receivemessagesthathavebeenexpired(butitdoesnotguaranteethiswillnothappen).

    DelayedRedelivery

    Divert

    DurableSubscription

    Embedded

    EmbeddedSimple

    MessageExpiration

    ActiveMQArtemisDocumentation

    41Examples

  • ApacheActiveMQArtemiscanassignanexpiryaddresstoagivenqueuesothatwhenmessagesareexpired,theyare

    removedfromthequeueandsenttotheexpiryaddress.These"expired"messagescanlaterbeconsumedfromthe

    expiryaddressforfurtherinspection.

    ThisexamplesshowshowtobuildtheactivemqresourceadaptersararfordeploymentinotherApplicationServer's

    Thehttp-transportexampleshowsyouhowtoconfigureApacheActiveMQArtemistousetheHTTPprotocolasits

    transportlayer.

    Usually,JMSObjectssuchasConnectionFactory,QueueandTopicinstancesarelookedupfromJNDIbeforebeingused

    bytheclientcode.Thisobjectsarecalled"administeredobjects"inJMSterminology.

    However,insomecasesaJNDIservermaynotbeavailableordesired.TocometotherescueApacheActiveMQArtemis

    alsosupportsthedirectinstantiationoftheseadministeredobjectsontheclientsidesoyoudon'thavetouseJNDIfor

    JMS.

    ApacheActiveMQArtemisallowsanapplicationtouseaninterceptortohookintothemessagingsystem.Interceptors

    allowyoutohandlevariousmessageeventsinApacheActiveMQArtemis.

    ThejaasexampleshowsyouhowtoconfigureApacheActiveMQArtemistouseJAASforsecurity.ApacheActiveMQ

    ArtemiscanleverageJAAStodelegateuserauthenticationandauthorizationtoexistingsecurityinfrastructure.

    Thejms-auto-closeableexampleshowshowJMSresources,suchasconnections,sessionsandconsumers,inJMS2

    canbeautomaticallyclosedonerror.

    Thejms-completion-listenerexampleshowshowtosendamessageasynchronouslytoApacheActiveMQArtemisand

    useaCompletionListenertobenotifiedoftheBrokerreceivingit.

    Thejms-brigeexampleshowshowtosetupabridgebetweentwostandaloneApacheActiveMQArtemisservers.

    ApacheActiveMQArtemisResourceAdapterexample

    HTTPTransport

    InstantiateJMSObjectsDirectly

    Interceptor

    JAAS

    JMSAutoClosable

    JMSCompletionListener

    JMSBridge

    ActiveMQArtemisDocumentation

    42Examples

  • Thejms-contextexampleshowshowtosendandreceiveamessagetoaJMSQueueusingApacheActiveMQArtemis

    byusingaJMSContext.

    AJMSContextispartofJMS2.0andcombinestheJMSConnectionandSessionObjectsintoasimpleInterface.

    Thejms-shared-consumerexampleshowsyouhowcanusesharedconsumerstoshareasubscriptiononatopic.InJMS

    1.1thiswasnotallowedandsocausedascalabilityissue.InJMS2thisrestrictionhasbeenliftedsoyoucansharethe

    loadacrossdifferentthreadsandconnections.

    ThejmxexampleshowshowtomanageApacheActiveMQArtemisusingJMX.

    Thelarge-messageexampleshowsyouhowtosendandreceiveverylargemessageswithApacheActiveMQArtemis.

    ApacheActiveMQArtemissupportsthesendingandreceivingofhugemessages,muchlargerthancanfitinavailable

    RAMontheclientorserver.Effectivelytheonlylimittomessagesizeistheamountofdiskspaceyouhaveontheserver.

    Largemessagesarepersistedontheserversotheycansurviveaserverrestart.InotherwordsApacheActiveMQ

    Artemisdoesn'tjustdoasimplesocketstreamfromthesendertotheconsumer.

    Thelast-value-queueexampleshowsyouhowtodefineanddealwithlast-valuequeues.Last-valuequeuesarespecial

    queueswhichdiscardanymessageswhenanewermessagewiththesamevalueforawell-definedlast-valueproperty

    isputinthequeue.Inotherwords,alast-valuequeueonlyretainsthelastvalue.

    Atypicalexampleforlast-valuequeueisforstockprices,whereyouareonlyinterestedbythelatestpriceforaparticular

    stock.

    ThemanagementexampleshowshowtomanageApacheActiveMQArtemisusingJMSMessagestoinvokemanagement

    operationsontheserver.

    Themanagement-notificationexampleshowshowtoreceivemanagementnotificationsfromApacheActiveMQArtemis

    usingJMSmessages.ApacheActiveMQArtemisserversemitmanagementnotificationswheneventsofinterestoccur

    (consumersarecreatedorclosed,addressesarecreatedordeleted,securityauthenticationfails,etc.).

    JMSContext

    JMSSharedConsumer

    JMXManagement

    LargeMessage

    Last-ValueQueue

    Management

    ManagementNotification

    MessageCounter

    ActiveMQArtemisDocumentation

    43Examples

  • Themessage-countersexampleshowsyouhowtousemessagecounterstoobtainmessageinformationforaJMS

    queue.

    Themessage-groupexampleshowsyouhowtoconfigureandusemessagegroupswithApacheActiveMQArtemis.

    Messagegroupsallowyoutopinmessagessotheyareonlyconsumedbyasingleconsumer.Messagegroupsare

    setsofmessagesthathasthefollowingcharacteristics:

    Messagesinamessagegroupsharethesamegroupid,i.e.theyhavesameJMSXGroupIDstringpropertyvalues

    Theconsumerthatreceivesthefirstmessageofagroupwillreceiveallthemessagesthatbelongstothegroup

    Themessage-group2exampleshowsyouhowtoconfigureandusemessagegroupswithApacheActiveMQArtemisviaa

    connectionfactory.

    MessagePrioritycanbeusedtoinfluencethedeliveryorderformessages.

    Itcanberetrievedbythemessage'sstandardheaderfield'JMSPriority'asdefinedinJMSspecificationversion1.1.

    Thevalueisoftypeinteger,rangingfrom0(thelowest)to9(thehighest).Whenmessagesarebeingdelivered,their

    prioritieswilleffecttheirorderofdelivery.Messagesofhigherprioritieswilllikelybedeliveredbeforethoseoflower

    priorities.

    Messagesofequalprioritiesaredeliveredinthenaturalorderoftheirarrivalattheirdestinations.Pleaseconsultthe

    JMS1.1specificationforfulldetails.

    Thisexampledemonstrateshowtosetupaliveserverwithmultiplebackups

    Thisexampledemonstrateshowtosetupaliveserverwithmultiplebackupsbutforcingfailoverbacktotheoriginallive

    server

    Bydefault,ApacheActiveMQArtemisconsumersbuffermessagesfromtheserverinaclientsidebufferbeforeyou

    actuallyreceivethemontheclientside.Thisimprovesperformancesinceotherwiseeverytimeyoucalledreceive()or

    hadprocessedthelastmessageinaMessageListeneronMessage()method,theApacheActiveMQArtemisclientwould

    havetogotheservertorequestthenextmessage,whichwouldthengetsenttotheclientside,ifonewasavailable.

    Thiswouldinvolveanetworkroundtripforeverymessageandreduceperformance.Therefore,bydefault,Apache

    ActiveMQArtemispre-fetchesmessagesintoabufferoneachconsumer.

    MessageGroup

    MessageGroup

    MessagePriority

    MultipleFailover

    MultipleFailoverFailback

    NoConsumerBuffering

    ActiveMQArtemisDocumentation

    44Examples

  • Insomecasebufferingisnotdesirable,andApacheActiveMQArtemisallowsittobeswitchedoff.Thisexample

    demonstratesthat.

    Thenon-transaction-failoverexampledemonstratestwoserverscoupledasalive-backuppairforhighavailability(HA),

    andaclientusinganon-transactedJMSsessionfailingoverfromlivetobackupwhentheliveserveriscrashed.

    ApacheActiveMQArtemisimplementsfailoverofclientconnectionsbetweenliveandbackupservers.Thisis

    implementedbythereplicationofstatebetweenliveandbackupnodes.Whenreplicationisconfiguredandalivenode

    crashes,theclientconnectionscancarryandcontinuetosendandconsumemessages.Whennon-transacted

    sessionsareused,onceandonlyoncemessagedeliveryisnotguaranteedanditispossiblethatsomemessageswill

    belostordeliveredtwice.

    TheOpenwireexampleshowshowtoconfigureanApacheActiveMQArtemisservertocommunicatewithanApache

    ActiveMQArtemisJMSclientthatusesopen-wireprotocol.

    Youwillfindthequeueexampleforopenwire,andthechatexample.

    ThepagingexampleshowshowApacheActiveMQArtemiscansupporthugequeuesevenwhentheserverisrunningin

    limitedRAM.Itdoesthisbytransparentlypagingmessagestodisk,anddepagingthemwhentheyarerequired.

    StandardJMSsupportsthreeacknowledgementmodes:AUTO_ACKNOWLEDGE,CLIENT_ACKNOWLEDGE,andDUPS_OK_ACKNOWLEDGE.For

    afulldescriptiononthesemodespleaseconsulttheJMSspecification,oranyJMStutorial.

    Allofthesestandardmodesinvolvesendingacknowledgementsfromtheclienttotheserver.Howeverinsomecases,

    youreallydon'tmindlosingmessagesineventoffailure,soitwouldmakesensetoacknowledgethemessageonthe

    serverbeforedeliveringittotheclient.ThisexampledemonstrateshowApacheActiveMQArtemisallowsthiswithan

    extraacknowledgementmode.

    Theproducer-rte-limitexampledemonstrateshow,withApacheActiveMQArtemis,youcanspecifyamaximumsend

    rateatwhichaJMSmessageproducerwillsendmessages.

    ApacheActiveMQArtemiscanbeconfiguredtoacceptrequestsfromanyAMQPclientthatsupportsthe1.0versionofthe

    protocol.Thisproton-jexampleshowsasimplyqpidjava1.0clientexample.

    Non-TransactionFailoverWithServerDataReplication

    OpenWire

    Paging

    Pre-Acknowledge

    MessageProducerRateLimiting

    ProtonQpid

    ProtonRuby

    ActiveMQArtemisDocumentation

    45Examples

  • ApacheActiveMQArtemiscanbeconfiguredtoacceptrequestsfromanyAMQPclientthatsupportsthe1.0versionofthe

    protocol.Thisexampleshowsasimplyprotonrubyclientthatsendsandreceivesmessages

    AsimpleexampledemonstratingaJMSqueue.

    Thequeue-message-redistributionexampledemonstratesmessageredistributionbetweenqueueswiththesamename

    deployedindifferentnodesofacluster.

    AsimpleexampledemonstratingaJMSqueuerequestor.

    Thequeue-selectorexampleshowsyouhowtoselectivelyconsumemessagesusingmessageselectorswithqueue

    consumers.

    TheReattachNodeexampleshowshowaclientcantrytoreconnecttothesameserverinsteadoffailingtheconnection

    immediatelyandnotifyinganyuserExceptionListenerobjects.ApacheActiveMQArtemiscanbeconfiguredto

    automaticallyretrytheconnection,andreattachtotheserverwhenitbecomesavailableagainacrossthenetwork.

    Anexampleshowinghowfailbackworkswhenusingreplication,InthisexamplealiveserverwillreplicateallitsJournal

    toabackupserverasitupdatesit.Whentheliveservercrashesthebackuptakesoverfromtheliveserverandtheclient

    reconnectsandcarriesonfromwhereitleftoff.

    Anexampleshowinghowfailbackworkswhenusingreplication,butthistimewithstaticconnectors

    Anexampleshowinghowtoconfiguremultiplebackupswhenusingreplication

    Anexampleshowinghowfailoverworkswithatransactionwhenusingreplication

    Queue

    MessageRedistribution

    QueueRequestor

    QueuewithMessageSelector

    ReattachNodeexample

    ReplicatedFailbackexample

    ReplicatedFailbackstaticexample

    Replicatedmultiplefailoverexample

    ReplicatedFailovertransactionexample

    ActiveMQArtemisDocumentation

    46Examples

  • AsimpleexampleshowingtheJMSrequest-responsepattern.

    AnexampleshowinghowtousetheApacheActiveMQArtemisRestAPI

    Thescheduled-messageexampleshowsyouhowtosendascheduledmessagetoaJMSQueuewithApacheActiveMQ

    Artemis.Scheduledmessageswon'tgetdelivereduntilaspecifiedtimeinthefuture.

    ThesecurityexampleshowsyouhowconfigureanduserolebasedqueuesecuritywithApacheActiveMQArtemis.

    Thesend-acknowledgementsexampleshowsyouhowtouseApacheActiveMQArtemis'sadvancedasynchronoussendacknowledgementsfeaturetoobtainacknowledgementfromtheserverthatsendshavebeenreceivedandprocessedinaseparatestreamtothesentmessages.

    ThisexampleshowshowtouseembeddedJMSusingApacheActiveMQArtemis'sSpringintegration.

    Thessl-enabledshowsyouhowtoconfigureSSLwithApacheActiveMQArtemistosendandreceivemessage.

    Thestatic-selectorexampleshowsyouhowtoconfigureanApacheActiveMQArtemiscorequeuewithstaticmessage

    selectors(filters).

    Thestatic-selector-jmsexampleshowsyouhowtoconfigureanApacheActiveMQArtemisqueuewithstaticmessage

    selectors(filters)usingJMS.

    ThestompexampleshowsyouhowtoconfigureanApacheActiveMQArtemisservertosendandreceiveStomp

    messages.

    Request-Replyexample

    Restexample

    ScheduledMessage

    Security

    SendAcknowledgements

    SpringIntegration

    SSLTransport

    StaticMessageSelector

    StaticMessageSelectorUsingJMS

    Stomp

    ActiveMQArtemisDocumentation

    47Examples

  • ThestompexampleshowsyouhowtoconfigureanApacheActiveMQArtemisservertosendandreceiveStomp

    messagesviaaStomp1.1connection.

    ThestompexampleshowsyouhowtoconfigureanApacheActiveMQArtemisservertosendandreceiveStomp

    messagesviaaStomp1.2connection.

    Thestomp-websocketsexampleshowsyouhowtoconfigureanApacheActiveMQArtemisservertosendandreceive

    StompmessagesdirectlyfromWebbrowsers(providedtheysupportWebSockets).

    Thesymmetric-clusterexampledemonstratesasymmetricclusterset-upwithApacheActiveMQArtemis.

    ApacheActiveMQArtemishasextremelyflexibleclusteringwhichallowsyoutoset-upserversinmanydifferent

    topologies.Themostcommontopologythatyou'llperhapsbefamiliarwithifyouareusedtoapplicationserver

    clusteringisasymmetriccluster.

    Withasymmetriccluster,the