Table of Contents - Apache ActiveMQ...REST Interface 48. Embedding Apache ActiveMQ Artemis 49....

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

Transcript of Table of Contents - Apache ActiveMQ...REST Interface 48. Embedding Apache ActiveMQ Artemis 49....

  • 1. Introduction

    2. LegalNotice

    3. Preface

    4. ProjectInfo

    5. RunningtheServer

    6. MessagingConcepts

    7. Architecture

    8. UsingtheServer

    9. UsingJMS

    10. UsingCore

    11. MappingJMSConceptstotheCoreAPI

    12. TheClientClasspath

    13. Examples

    14. RoutingMessagesWithWildCards

    15. UnderstandingtheApacheActiveMQArtemisWildcardSyntax

    16. FilterExpressions

    17. Persistence

    18. ConfiguringTransports

    19. DetectingDeadConnections

    20. DetectingSlowConsumers

    21. ResourceManagerConfiguration

    22. FlowControl

    23. Guaranteesofsendsandcommits

    24. MessageRedeliveryandUndeliveredMessages

    25. MessageExpiry

    26. LargeMessages

    27. Paging

    28. QueueAttributes

    29. ScheduledMessages

    30. Last-ValueQueues

    31. MessageGrouping

    32. ExtraAcknowledgeModes

    33. Management

    34. Security

    35. ResourceLimits

    36. TheJMSBridge

    37. ClientReconnectionandSessionReattachment

    38. DivertingandSplittingMessageFlows

    39. CoreBridges

    40. DuplicateMessageDetection

    41. Clusters

    42. HighAvailabilityandFailover

    43. GracefulServerShutdown

    44. LibaioNativeLibraries

    45. Threadmanagement

    46. Logging

    47. RESTInterface

    48. EmbeddingApacheActiveMQArtemis

    49. SpringIntegration

    50. AeroGearIntegration

    51. VertXIntegration

    52. InterceptingOperations

    TableofContents

  • 53. Interoperability

    54. Tools

    55. PerformanceTuning

    56. ConfigurationReference

  • TheUsermanualisanindepthmanualonallaspectsofApacheActiveMQArtemis

    ApacheActiveMQArtemisUserManual

  • 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

    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

  • 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

    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

  • Note

    ActiveMQArtemisonlyrunsonJava7orlater.

    Bydefault,ActiveMQArtemisserverrunswith1GiBofmemory.Ifyourcomputerhaslessmemory,oryouwanttorunit

    withmoreavailableRAM,modifythevalueinbin/run.shaccordingly.

    IfyouareonLinuxyoumaywanttoenablelibaioForpersistence,ActiveMQArtemisusesitsownfastjournal,whichyou

    canconfiguretouselibaio(whichisthedefaultwhenrunningonLinux)orJavaNIO.Inordertousethelibaiomoduleon

    Linux,you'llneedtoinstalllibaio,ifit'snotalreadyinstalled.

    Ifyou'renotrunningonLinuxthenyoudon'tneedtoworryaboutthis.

    Youcaninstalllibaiousingthefollowingstepsastherootuser:

    Usingyum,(e.g.onFedoraorRedHatEnterpriseLinux):

    yuminstalllibaio

    Usingaptitude,(e.g.onUbuntuorDebiansystem):

    apt-getinstalllibaio

    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.

    Prerequisites

    Installation

  • lib--jarsandlibrariesneededtorunActiveMQArtemis

    licenses--licensesforActiveMQArtemis

    schemas--XMLSchemasusedtovalidateActiveMQArtemisconfigurationfiles

    Abrokerinstanceisthedirectorycontainingalltheconfigurationandruntimedata,suchaslogsanddatafiles,

    associatedwithabrokerprocess.Itisrecommendedthatyoudonotcreatetheinstancedirectoryunder${ARTEMIS_HOME}.ThisseparationisencouragedsothatyoucanmoreeasilyupgradewhenthenextversionofActiveMQArtemisis

    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.

    Environmentvariablesareusedtoprovideeaseofchangingports,hostsanddatadirectoriesusedandcanbefoundin

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

    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-input][--user][--]

    OPTIONS

    --allow-anonymous

    Enablesanonymousconfigurationonsecurity(Default:input)

    --cluster-password

    Theclusterpasswordtouseforclustering.(Default:input)

    --cluster-user

    Theclusterusertouseforclustering.(Default:input)

    CreatingaBrokerInstance

    Options

  • --clustered

    Enableclustering

    --data

    DirectorywhereActiveMQDataisused.Patharerelativeto

    artemis.instance/bin

    --encoding

    Theencodingthattextfilesshoulduse

    --force

    Overwriteconfigurationatdestinationdirectory

    --home

    DirectorywhereActiveMQArtemisisinstalled

    --host

    Thehostnameofthebroker(Default:0.0.0.0orinputifclustered)

    --java-options

    Extrajavaoptionstobepassedtotheprofile

    --password

    Theuser'spassword(Default:input)

    --port-offset

    Offsetsthedefaultports

    --replicated

    Enablebrokerreplication

    --role

    Thenamefortherolecreated(Default:amq)

    --shared-store

    Enablebrokersharedstore

    --silent-input

    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

    properly.

    TostoptheApacheActiveMQArtemisinstanceyouwillusethesameactivemqscript,butwiththestopargument.Example:

    /var/lib/mybroker/bin/activemqstop

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

    xml:path/to/bootstrap.xmloranotherconfigofyourchoosing.

    OnwindowsyouwillhavetheoptiontorunActiveMQArtemisasaservice.Justusethefollowingcommandtoinstallit:

    $./artemis-service.exeinstall

    Thecreateprocessshouldgiveyouahintoftheavailablecommandsavailablefortheartemis-service.exe

    StartingandStoppingaBrokerInstance

    WindowsServer

  • 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

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

    Aclassicexampleofpointtopointmessagingwouldbeanorderqueueinacompany'sbookorderingsystem.Each

    MessagingConcepts

    MessagingConcepts

    Messagingstyles

    TheMessageQueuePattern

    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

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

    Messagesareeitherdurableornondurable.Durablemessageswillbepersistedinpermanentstorageandwillsurvive

    serverfailureorrestart.Nondurablemessageswillnotsurviveserverfailureorrestart.Examplesofdurablemessages

    mightbeordersortrades,wheretheycannotbelost.Anexampleofanondurablemessagemightbeastockprice

    ThePublish-SubscribePattern

    Deliveryguarantees

    Transactions

    Durability

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

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

    TheadvantageofaRESTapproachwithHTTPisinitssimplicityandthefacttheinternetisalreadytunedtodealwith

    HTTPoptimally.

    PleaseseeRestInterfaceforusingApacheActiveMQArtemis'sRESTfulinterface.

    Stompisaverysimpletextprotocolforinteroperatingwithmessagingsystems.Itdefinesawireformat,sotheoretically

    MessagingAPIsandprotocols

    JavaMessageService(JMS)

    SystemspecificAPIs

    RESTfulAPI

    STOMP

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

  • 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

    connectionslikeawideareanetwork(WAN),ortheinternet.

    Abridgenormallyconsumesfromaqueueononeserverandforwardsmessagestoanotherqueueonadifferent

    server.Bridgescopewithunreliableconnections,automaticallyreconnectingwhentheconnectionsbecomesavailable

    again.

    ApacheActiveMQArtemisbridgescanbeconfiguredwithfilterexpressionstoonlyforwardcertainmessages,and

    transformationcanalsobehookedin.

    ApacheActiveMQArtemisalsoallowsroutingbetweenqueuestobeconfiguredinserversideconfiguration.Thisallows

    complexroutingnetworkstobesetupforwardingorcopyingmessagesfromonedestinationtoanother,forminga

    AMQP

    HighAvailability

    Clusters

    Bridgesandrouting

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

  • globalnetworkofinterconnectedbrokers.

    FormoreinformationpleaseseeCoreBridgesandDivertingandSplittingMessageFlows.

  • 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

  • Figure3.1showstwouserapplicationsinteractingwithanApacheActiveMQArtemisserver.UserApplication1isusing

    theJMSAPI,whileUserApplication2isusingthecoreclientAPIdirectly.

    YoucanseefromthediagramthattheJMSAPIisimplementedbyathinfacadelayerontheclientside.

    ApacheActiveMQArtemisembeddedinyourownapplication

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

    ApacheActiveMQArtemisintegratedwithaJavaEEapplicationserver

  • FormoreinformationonusingtheJCAadaptor,pleaseseeApplicationServerIntegrationandJavaEE.

    ApacheActiveMQArtemiscanalsobedeployedasastand-aloneserver.Thismeansafullyindependentmessaging

    servernotdependentonaJavaEEapplicationserver.

    ApacheActiveMQArtemisstand-aloneserver

  • Thestandardstand-alonemessagingserverconfigurationcomprisesacoremessagingserverandaJMSservice.

    TheroleoftheJMSServiceistodeployanyJMSQueue,TopicandConnectionFactoryinstancesfromanyserverside

    JMSconfiguration.ItalsoprovidesasimplemanagementAPIforcreatinganddestroyingQueuesandTopicswhichcan

    beaccessedviaJMXortheconnection.ItisaseparateservicetotheActiveMQArtemiscoreserver,sincethecoreserver

    isJMSagnostic.Ifyoudon'twanttodeployanyJMSQueueorTopicviaserversideXMLconfigurationanddon'trequirea

    JMSmanagementAPIontheserversidethenyoucandisablethisservice.

    Thestand-aloneserverconfigurationusesAirlineforbootstrappingtheBroker.

    Thestand-aloneserverarchitectureisshowninfigure3.3below:

    https://github.com/airlift/airline

  • FormoreinformationonserverconfigurationfilesseeServerConfiguration

  • ThischapterwillfamiliariseyouwithhowtousetheApacheActiveMQArtemisserver.

    We'llshowwhereitis,howtostartandstopit,andwe'lldescribethedirectorylayoutandwhatallthefilesareandwhat

    theydo.

    FortheremainderofthischapterwhenwetalkabouttheApacheActiveMQArtemisserverwemeantheApacheActiveMQ

    Artemisstandaloneserver,initsdefaultconfigurationwithaJMSServiceenabled.

    ThisdocumentwillrefertothefullpathofthedirectorywheretheActiveMQdistributionhasbeenextractedtoas

    ${ARTEMIS_HOME}directory.

    Abrokerinstanceisthedirectorycontainingalltheconfigurationandruntimedata,suchaslogsanddatafiles,

    associatedwithabrokerprocess.Itisrecommendedthatyoudonotcreatetheinstancedirectoryunder${ARTEMIS_HOME}.ThisseparationisencouragedsothatyoucanmoreeasilyupgradewhenthenextversionofActiveMQArtemisis

    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.

    Assumingyoucreatedthebrokerinstanceunder/var/lib/mybrokerallyouneedtodostartrunningthebrokerinstanceis

    execute:

    /var/lib/mybroker/bin/activemqrun

    Nowthatthebrokerisrunning,youcanoptionallyrunsomeoftheincludedexamplestoverifythethebrokerisrunning

    properly.

    TostoptheApacheActiveMQArtemisinstanceyouwillusethesameactivemqscript,butwiththestopargument.Example:

    /var/lib/mybroker/bin/activemqstop

    PleasenotethatApacheActiveMQArtemisrequiresaJava7orlaterruntimetorun.

    UsingtheServer

    CreatingaBrokerInstance

    StartingandStoppingaBrokerInstance

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

    ApacheActiveMQArtemiscantakeasystempropertyonthecommandlineforconfiguringlogging.

    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}

    ServerJVMsettings

    Pre-configuredOptions

    LibraryPath

    Systemproperties

    Configurationfiles

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

    BootstrapFile

    Themainconfigurationfile.

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

    Here'sasimpleexampleoftheJNDIcontextenvironmentforaclientlookingupaconnectionfactorytoaccessan

    embeddedinstanceofApacheActiveMQArtemis:

    UsingJMS

    Asimpleorderingsystem

    JNDIConfiguration

    ConnectionFactoryJNDI

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

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

    Theudpschemeisalsosupportedwhichshoulduseanhost:portcombinationthatmatchesthegroup-addressand

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

    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

    JMSdestinationsarealsotypicallylookedupviaJNDI.Aswithconnectionfactories,destinationscanbeconfigured

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

    ConfigurationforConnectionFactoryTypes

    DestinationJNDI

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

    //Andweconsumethemessage:

    TextMessagereceivedMessage=(TextMessage)consumer.receive();

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

    Itisassimpleasthat.ForawiderangeofworkingJMSexamplespleaseseetheexamplesdirectoryinthedistribution.

    Warning

    PleasenotethatJMSconnections,sessions,producersandconsumersaredesignedtobere-used.

    Itisananti-patterntocreatenewconnections,sessions,producersandconsumersforeachmessageyou

    Thecode

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

    //WecreateasimpleTextMessageandsendit:

    TextMessagemessage=session.createTextMessage("Thisisanorder");

    producer.send(message);

    //Andweconsumethemessage:

    TextMessagereceivedMessage=(TextMessage)consumer.receive();

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

    ThisrepresentstheclientidforaJMSclientandisneededforcreatingdurablesubscriptions.Itispossibletoconfigure

    thisontheconnectionfactoryandcanbesetviatheclientIdelement.Anyconnectioncreatedbythisconnectionfactory

    willhavethissetasitsclientid.

    DirectlyinstantiatingJMSResourceswithoutusingJNDI

    SettingTheClientID

  • WhentheJMSacknowledgemodeissettoDUPS_OKitispossibletoconfiguretheconsumersothatitsends

    acknowledgementsinbatchesratherthatoneatatime,savingvaluablebandwidth.Thiscanbeconfiguredviathe

    connectionfactoryviathedupsOkBatchSizeelementandissetinbytes.Thedefaultis1024*1024bytes=1MiB.

    Whenreceivingmessagesinatransactionitispossibletoconfiguretheconsumertosendacknowledgementsin

    batchesratherthanindividuallysavingvaluablebandwidth.Thiscanbeconfiguredontheconnectionfactoryviathe

    transactionBatchSizeelementandissetinbytes.Thedefaultis1024*1024.

    SettingTheBatchSizeforDUPS_OK

    SettingTheTransactionBatchSize

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

    Note

    Incore,thereisnoconceptofaTopic,TopicisaJMSonlyterm.Instead,incore,wejustdealwithaddressesand

    UsingCore

    CoreMessagingConcepts

    Message

    Address

  • queues.

    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

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

    ClientsuseClientConsumerinstancestoconsumemessagesfromaqueue.CoreMessagingsupportsboth

    Queue

    ServerLocator

    ClientSessionFactory

    ClientSession

    ClientConsumer

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

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

    ClientProducer

    AsimpleexampleofusingCore

  • 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

  • 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

  • TheApacheActiveMQArtemisdistributioncomeswithover90runout-of-the-boxexamplesdemonstratingmanyofthe

    features.

    Theexamplesareavailableinthedistribution,intheexamplesdirectory.ExamplesaresplitintoJMSandcoreexamples.

    JMSexamplesshowhowaparticularfeaturecanbeusedbyanormalJMSclient.Coreexamplesshowhowthe

    equivalentfeaturecanbeusedbyacoremessagingclient.

    AsetofJavaEEexamplesarealsoprovidedwhichneedWildFlyinstalledtobeabletorun.

    TorunaJMSexample,simplycdintotheappropriateexampledirectoryandtypemvnverify-Pexample(Fordetailsplease

    readthereadme.htmlineachexampledirectory).

    Here'salistingoftheexampleswithabriefdescription.

    ThisexampleshowshowyoucansendamessagetoamobiledevicebyleveragingAeroGearspushtechnologywhich

    providessupportfordifferentpushnotificationtechnologieslikeGoogleCloudMessaging,Apple'sAPNsorMozilla's

    SimplePush.

    ThisexampleshowsyouhowtosendandreceiveJMSmessagesfromanApplet.

    ApacheActiveMQArtemisalsosupportsApplication-Layerfailover,usefulinthecasethatreplicationisnotenabledon

    theserverside.

    WithApplication-Layerfailover,it'suptotheapplicationtoregisteraJMSExceptionListenerwithApacheActiveMQArtemis

    whichwillbecalledbyApacheActiveMQArtemisintheeventthatconnectionfailureisdetected.

    ThecodeintheExceptionListenerthenrecreatestheJMSconnection,session,etconanothernodeandtheapplication

    cancontinue.

    Application-layerfailoverisanalternativeapproachtoHighAvailability(HA).Application-layerfailoverdiffersfrom

    automaticfailoverinthatsomeclientsidecodingisrequiredinordertoimplementthis.Also,withApplication-layer

    failover,sincetheoldsessionobjectdiesandanewoneiscreated,anyuncommittedworkintheoldsessionwillbe

    lost,andanyunacknowledgedmessagesmightberedelivered.

    Thebridgeexampledemonstratesacorebridgedeployedononeserver,whichconsumesmessagesfromalocal

    queueandforwardsthemtoanaddressonasecondserver.

    CorebridgesareusedtocreatemessageflowsbetweenanytwoApacheActiveMQArtemisserverswhichareremotely

    separated.Corebridgesareresilientandwillcopewithtemporaryconnectionfailureallowingthemtobeanideal

    Examples

    JMSExamples

    JMSAeroGear

    Applet

    Application-LayerFailover

    CoreBridgeExample

  • 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

    differentnodeswiththesamegroupidwillbesenttothesamenodeandthesameconsumer.

    Theclustered-queueexampledemonstratesaJMSqueuedeployedontwodifferentnodes.Thetwonodesare

    configuredtoformacluster.Wethencreateaconsumerforthequeueoneachnode,andwecreateaproducerononly

    oneofthenodes.Wethensendsomemessagesviatheproducer,andweverifythatbothconsumersreceivethesent

    messagesinaround-robinfashion.

    Theclustered-jgroupsexampledemonstrateshowtoformatwonodeclusterusingJGroupsasitsunderlyingtopology

    discoverytechnique,ratherthanthedefaultUDPbroadcasting.Wethencreateaconsumerforthequeueoneachnode,

    andwecreateaproducerononlyoneofthenodes.Wethensendsomemessagesviatheproducer,andweverifythat

    bothconsumersreceivethesentmessagesinaround-robinfashion.

    Browser

    ClientKickoff

    Clientsidefailoverlistener

    Client-SideLoad-Balancing

    ClusteredDurableSubscription

    ClusteredGrouping

    ClusteredQueue

    ClusteringwithJGroups

    ClusteredStandalone

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

    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.

    ClusteredStaticDiscovery

    ClusteredStaticClusterOneWay

    ClusteredTopic

    MessageConsumerRateLimiting

    DeadLetter

    DelayedRedelivery

    Divert

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

    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.

    DurableSubscription

    Embedded

    EmbeddedSimple

    MessageExpiration

    ApacheActiveMQArtemisResourceAdapterexample

    HTTPTransport

    InstantiateJMSObjectsDirectly

  • ApacheActiveMQArtemisallowsanapplicationtouseaninterceptortohookintothemessagingsystem.Interceptors

    allowyoutohandlevariousmessageeventsinApacheActiveMQArtemis.

    ThejaasexampleshowsyouhowtoconfigureApacheActiveMQArtemistouseJAASforsecurity.ApacheActiveMQ

    ArtemiscanleverageJAAStodelegateuserauthenticationandauthorizationtoexistingsecurityinfrastructure.

    Thejms-auto-closeableexampleshowshowJMSresources,suchasconnections,sessionsandconsumers,inJMS2

    canbeautomaticallyclosedonerror.

    Thejms-completion-listenerexampleshowshowtosendamessageasynchronouslytoApacheActiveMQArtemisand

    useaCompletionListenertobenotifiedoftheBrokerreceivingit.

    Thejms-brigeexampleshowshowtosetupabridgebetweentwostandaloneApacheActiveMQArtemisservers.

    Thejms-contextexampleshowshowtosendandreceiveamessagetoaJMSQueueusingApacheActiveMQArtemis

    byusingaJMSContext.

    AJMSContextispartofJMS2.0andcombinestheJMSConnectionandSessionObjectsintoasimpleInterface.

    Thejms-shared-consumerexampleshowsyouhowcanusesharedconsumerstoshareasubscriptiononatopic.InJMS

    1.1thiswasnotallowedandsocausedascalabilityissue.InJMS2thisrestrictionhasbeenliftedsoyoucansharethe

    loadacrossdifferentthreadsandconnections.

    ThejmxexampleshowshowtomanageApacheActiveMQArtemisusingJMX.

    Thelarge-messageexampleshowsyouhowtosendandreceiveverylargemessageswithApacheActiveMQArtemis.

    ApacheActiveMQArtemissupportsthesendingandreceivingofhugemessages,muchlargerthancanfitinavailable

    RAMontheclientorserver.Effectivelytheonlylimittomessagesizeistheamountofdiskspaceyouhaveontheserver.

    Largemessagesarepersistedontheserversotheycansurviveaserverrestart.InotherwordsApacheActiveMQ

    Artemisdoesn'tjustdoasimplesocketstreamfromthesendertotheconsumer.

    Interceptor

    JAAS

    JMSAutoClosable

    JMSCompletionListener

    JMSBridge

    JMSContext

    JMSSharedConsumer

    JMXManagement

    LargeMessage

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

    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.

    Last-ValueQueue

    Management

    ManagementNotification

    MessageCounter

    MessageGroup

    MessageGroup

    MessagePriority

  • Thisexampledemonstrateshowtosetupaliveserverwithmultiplebackups

    Thisexampledemonstrateshowtosetupaliveserverwithmultiplebackupsbutforcingfailoverbacktotheoriginallive

    server

    Bydefault,ApacheActiveMQArtemisconsumersbuffermessagesfromtheserverinaclientsidebufferbeforeyou

    actuallyreceivethemontheclientside.Thisimprovesperformancesinceotherwiseeverytimeyoucalledreceive()or

    hadprocessedthelastmessageinaMessageListeneronMessage()method,theApacheActiveMQArtemisclientwould

    havetogotheservertorequestthenextmessage,whichwouldthengetsenttotheclientside,ifonewasavailable.

    Thiswouldinvolveanetworkroundtripforeverymessageandreduceperformance.Therefore,bydefault,Apache

    ActiveMQArtemispre-fetchesmessagesintoabufferoneachconsumer.

    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.

    ThepagingexampleshowshowApacheActiveMQArtemiscansupporthugequeuesevenwhentheserverisrunningin

    limitedRAM.Itdoesthisbytransparentlypagingmessagestodisk,anddepagingthemwhentheyarerequired.

    StandardJMSsupportsthreeacknowledgementmodes:AUTO_ACKNOWLEDGE,CLIENT_ACKNOWLEDGE,andDUPS_OK_ACKNOWLEDGE.For

    afulldescriptiononthesemodespleaseconsulttheJMSspecification,oranyJMStutorial.

    Allofthesestandardmodesinvolvesendingacknowledgementsfromtheclienttotheserver.Howeverinsomecases,

    youreallydon'tmindlosingmessagesineventoffailure,soitwouldmakesensetoacknowledgethemessageonthe

    serverbeforedeliveringittotheclient.ThisexampledemonstrateshowApacheActiveMQArtemisallowsthiswithan

    MultipleFailover

    MultipleFailoverFailback

    NoConsumerBuffering

    Non-TransactionFailoverWithServerDataReplication

    OpenWire

    Paging

    Pre-Acknowledge

  • extraacknowledgementmode.

    Theproducer-rte-limitexampledemonstrateshow,withApacheActiveMQArtemis,youcanspecifyamaximumsend

    rateatwhichaJMSmessageproducerwillsendmessages.

    ApacheActiveMQArtemiscanbeconfiguredtoacceptrequestsfromanyAMQPclientthatsupportsthe1.0versionofthe

    protocol.Thisproton-jexampleshowsasimplyqpidjava1.0clientexample.

    ApacheActiveMQArtemiscanbeconfiguredtoacceptrequestsfromanyAMQPclientthatsupportsthe1.0versionofthe

    protocol.Thisexampleshowsasimplyprotonrubyclientthatsendsandreceivesmessages

    AsimpleexampledemonstratingaJMSqueue.

    Thequeue-message-redistributionexampledemonstratesmessageredistributionbetweenqueueswiththesamename

    deployedindifferentnodesofacluster.

    AsimpleexampledemonstratingaJMSqueuerequestor.

    Thequeue-selectorexampleshowsyouhowtoselectivelyconsumemessagesusingmessageselectorswithqueue

    consumers.

    TheReattachNodeexampleshowshowaclientcantrytoreconnecttothesameserverinsteadoffailingtheconnection

    immediatelyandnotifyinganyuserExceptionListenerobjects.ApacheActiveMQArtemiscanbeconfiguredto

    automaticallyretrytheconnection,andreattachtotheserverwhenitbecomesavailableagainacrossthenetwork.

    Anexampleshowinghowfailbackworkswhenusingreplication,InthisexamplealiveserverwillreplicateallitsJournal

    toabackupserverasitupdatesit.Whentheliveservercrashesthebackuptakesoverfromtheliveserverandtheclient

    reconnectsandcarriesonfromwhereitleftoff.

    MessageProducerRateLimiting

    ProtonQpid

    ProtonRuby

    Queue

    MessageRedistribution

    QueueRequestor

    QueuewithMessageSelector

    ReattachNodeexample

    ReplicatedFailbackexample

    ReplicatedFailbackstaticexample

  • Anexampleshowinghowfailbackworkswhenusingreplication,butthistimewithstaticconnectors

    Anexampleshowinghowtoconfiguremultiplebackupswhenusingreplication

    Anexampleshowinghowfailoverworkswithatransactionwhenusingreplication

    AsimpleexampleshowingtheJMSrequest-responsepattern.

    AnexampleshowinghowtousetheApacheActiveMQArtemisRestAPI

    Thescheduled-messageexampleshowsyouhowtosendascheduledmessagetoaJMSQueuewithApacheActiveMQ

    Artemis.Scheduledmessageswon'tgetdelivereduntilaspecifiedtimeinthefuture.

    ThesecurityexampleshowsyouhowconfigureanduserolebasedqueuesecuritywithApacheActiveMQArtemis.

    Thesend-acknowledgementsexampleshowsyouhowtouseApacheActiveMQArtemis'sadvancedasynchronoussendacknowledgementsfeaturetoobtainacknowledgementfromtheserverthatsendshavebeenreceivedandprocessedinaseparatestreamtothesentmessages.

    ThisexampleshowshowtouseembeddedJMSusingApacheActiveMQArtemis'sSpringintegration.

    Thessl-enabledshowsyouhowtoconfigureSSLwithApacheActiveMQArtemistosendandreceivemessage.

    Thestatic-selectorexampleshowsyouhowtoconfigureanApacheActiveMQArtemiscorequeuewithstaticmessage

    selectors(filters).

    Replicatedmultiplefailoverexample

    ReplicatedFailovertransactionexample

    Request-Replyexample

    Restexample

    ScheduledMessage

    Security

    SendAcknowledgements

    SpringIntegration

    SSLTransport

    StaticMessageSelector

    StaticMessageSelectorUsingJMS

  • Thestatic-selector-jmsexampleshowsyouhowtoconfigureanApacheActiveMQArtemisqueuewithstaticmessage

    selectors(filters)usingJMS.

    ThestompexampleshowsyouhowtoconfigureanApacheActiveMQArtemisservertosendandreceiveStomp

    messages.

    ThestompexampleshowsyouhowtoconfigureanApacheActiveMQArtemisservertosendandreceiveStomp

    messagesviaaStomp1.1connection.

    ThestompexampleshowsyouhowtoconfigureanApacheActiveMQArtemisservertosendandreceiveStomp

    messagesviaaStomp1.2connection.

    Thestomp-websocketsexampleshowsyouhowtoconfigureanApacheActiveMQArtemisservertosendandreceive

    StompmessagesdirectlyfromWebbrowsers(providedtheysupportWebSockets).

    Thesymmetric-clusterexampledemonstratesasymmetricclusterset-upwithApacheActiveMQArtemis.

    ApacheActiveMQArtemishasextremelyflexibleclusteringwhichallowsyoutoset-upserversinmanydifferent

    topologies.Themostcommontopologythatyou'llperhapsbefamiliarwithifyouareusedtoapplicationserver

    clusteringisasymmetriccluster.

    Withasymmetriccluster,theclusterishomogeneous,i.e.eachnodeisconfiguredthesameaseveryothernode,and

    everynodeisconnectedtoeveryothernodeinthecluster.

    AsimpleexampledemonstratinghowtouseaJMStemporaryqueue.

    AsimpleexampledemonstratingaJMStopic.

    ApacheActiveMQArtemissupportstopichierarchies.Withatopichierarchyyoucanregisterasubscriberwithawild-

    cardandthatsubscriberwillreceiveanymessagessenttoanaddressthatmatchesthewildcard.

    Stomp

    Stomp1.1

    Stomp1.2

    StompOverWebSockets

    SymmetricCluster

    TemporaryQueue

    Topic

    TopicHierarchy

    TopicSelector1

  • Thetopic-selector-example1exampleshowsyouhowtosendmessagetoaJMSTopic,andsubscribethemusing

    selectorswithApacheActiveMQArtemis.

    Thetopic-selector-example2exampleshowsyouhowtoselectivelyconsumemessagesusingmessageselectorswith

    topicconsumers.

    Thetransaction-failoverexampledemonstratestwoserverscoupledasalive-backuppairforhighavailability(HA),and

    aclientusingatransactedJMSsessionfailingoverfromlivetobackupwhentheliveserveriscrashed.

    ApacheActiveMQArtemisimplementsfailoverofclientconnectionsbetweenliveandbackupservers.Thisis

    implementedbythesharingofajournalbetweentheservers.Whenalivenodecrashes,theclientconnectionscan

    carryandcontinuetosendandconsumemessages.Whentransactedsessionsareused,onceandonlyonce

    messagedeliveryisguaranteed.

    Thestop-server-failoverexampledemonstratesfailoveroftheJMSconnectionfromonenodetoanotherwhenthelive

    servercrashesusingaJMSnon-transactedsession.

    ThetransactionalexampleshowsyouhowtouseatransactionalSessionwithApacheActiveMQArtemis.

    Thexa-heuristicexampleshowsyouhowtomakeanXAheuristicdecisionthroughApacheActiveMQArtemis

    ManagementInterface.AheuristicdecisionisaunilateraldecisiontocommitorrollbackanXAtransactionbranchafterit

    hasbeenprepared.

    Thexa-receiveexampleshowsyouhowmessagereceivingbehavesinanXAtransactioninApacheActiveMQArtemis.

    Thexa-sendexampleshowsyouhowmessagesendingbehavesinanXAtransactioninApacheActiveMQArtemis.

    Torunacoreexample,simplycdintotheappropriateexampledirectoryandtypeant

    TheembeddedexampleshowshowtoembedtheApacheActiveMQArtemisserverwithinyourowncode.

    TopicSelector2

    TransactionFailover

    FailoverWithoutTransactions

    TransactionalSession

    XAHeuristic

    XAReceive

    XASend

    CoreAPIExamples

    Embedded

  • ApacheActiveMQArtemisallowstheroutingofmessagesviawildcardaddresses.

    Ifaqueueiscreatedwithanaddressofsayqueue.news.#thenitwillreceiveanymessagessenttoaddressesthatmatch

    this,forinstancequeue.news.europeorqueue.news.usaorqueue.news.usa.sport.Ifyoucreateaconsumeronthisqueue,this

    allowsaconsumertoconsumemessageswhicharesenttoahierarchyofaddresses.

    Note

    InJMSterminologythisallows"topichierarchies"tobecreated.

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

    Formoreinformationonthewildcardsyntaxtakealookatwildcardsyntaxchapter,alsoseethetopichierarchyexample

    intheexamples.

    RoutingMessagesWithWildCards

  • ApacheActiveMQArtemisusesaspecificsyntaxforrepresentingwildcardsinsecuritysettings,addresssettingsand

    whencreatingconsumers.

    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.sport',butnot'news.europe.politics'.

    UnderstandingtheApacheActiveMQArtemisWildcardSyntax

    http://www.amqp.org

  • ApacheActiveMQArtemisprovidesapowerfulfilterlanguagebasedonasubsetoftheSQL92expressionsyntax.

    ItisthesameasthesyntaxusedforJMSselectors,butthepredefinedidentifiersaredifferent.Fordocumentationon

    JMSselectorsyntaxpleasetheJMSjavadocforjavax.jms.Message.

    FilterexpressionsareusedinseveralplacesinApacheActiveMQArtemis

    PredefinedQueues.Whenpre-definingaqueue,inbroker.xmlineitherthecoreorjmsconfigurationafilter

    expressioncanbedefinedforaqueue.Onlymessagesthatmatchthefilterexpressionwillenterthequeue.

    Corebridgescanbedefinedwithanoptionalfilterexpression,onlymatchingmessageswillbebridged(seeCore

    Bridges).

    Divertscanbedefinedwithanoptionalfilterexpression,onlymatchingmessageswillbediverted(seeDiverts).

    Filterarealsousedprogrammaticallywhencreatingconsumers,queuesandinseveralplacesasdescribedin

    management.

    TherearesomedifferencesbetweenJMSselectorexpressionsandApacheActiveMQArtemiscorefilterexpressions.

    WhereasJMSselectorexpressionsoperateonaJMSmessage,ApacheActiveMQArtemiscorefilterexpressions

    operateonacoremessage.

    Thefollowingidentifierscanbeusedinacorefilterexpressionstorefertoattributesofthecoremessageinan

    expression:

    AMQPriority.Torefertothepriorityofamessage.Messageprioritiesareintegerswithvalidvaluesfrom0-9.0is

    thelowestpriorityand9isthehighest.E.g.AMQPriority=3ANDanimal='aardvark'

    AMQExpiration.Torefertotheexpirationtimeofamessage.Thevalueisalonginteger.

    AMQDurable.Torefertowhetheramessageisdurableornot.Thevalueisastringwithvalidvalues:DURABLEor

    NON_DURABLE.

    AMQTimestamp.Thetimestampofwhenthemessagewascreated.Thevalueisalonginteger.

    AMQSize.Thesizeofamessageinbytes.Thevalueisaninteger.

    Anyotheridentifiersusedincorefilterexpressionswillbeassumedtobepropertiesofthemessage.

    FilterExpressions

    http://docs.oracle.com/javaee/6/api/javax/jms/Message.html

  • InthischapterwewilldescribehowpersistenceworkswithApacheActiveMQArtemisandhowtoconfigureit.

    ApacheActiveMQArtemisshipswithahighperformancejournal.SinceApacheActiveMQArtemishandlesitsown

    persistence,ratherthanrelyingonadatabaseorother3rdpartypersistenceengineitisveryhighlyoptimisedforthe

    specificmessagingusecases.

    AnApacheActiveMQArtemisjournalisanappendonlyjournal.Itconsistsofasetoffilesondisk.Eachfileispre-createdtoafixedsizeandinitiallyfilledwithpadding.Asoperationsareperformedontheserver,e.g.addmessage,

    updatemessage,deletemessage,recordsareappendedtothejournal.Whenonejournalfileisfullwemovetothe

    nextone.

    Becauserecordsareonlyappended,i.e.addedtotheendofthejournalweminimisediskheadmovement,i.e.we

    minimiserandomaccessoperationswhichistypicallytheslowestoperationonadisk.

    Makingthefilesizeconfigurablemeansthatanoptimalsizecanbechosen,i.e.makingeachfilefitonadiskcylinder.

    Moderndisktopologiesarecomplexandwearenotincontroloverwhichcylinder(s)thefileismappedontosothisis

    notanexactscience.Butbyminimisingthenumberofdiskcylindersthefileisusing,wecanminimisetheamountof

    diskheadmovement,sinceanentirediskcylinderisaccessiblesimplybythediskrotating-theheaddoesnothaveto

    move.

    Asdeleterecordsareaddedtothejournal,ApacheActiveMQArtemishasasophisticatedfilegarbagecollection

    algorithmwhichcandetermineifaparticularjournalfileisneededanymore-i.e.hasallitsdatabeendeletedinthe

    sameorotherfiles.Ifso,thefilecanbereclaimedandre-used.

    ApacheActiveMQArtemisalsohasacompactionalgorithmwhichremovesdeadspacefromthejournaland

    compressesupthedatasoittakesuplessfilesondisk.

    Thejournalalsofullysupportstransactionaloperationifrequired,supportingbothlocalandXAtransactions.

    ThemajorityofthejournaliswritteninJava,howeverweabstractouttheinteractionwiththeactualfilesystemtoallow

    differentpluggableimplementations.ApacheActiveMQArtemisshipswithtwoimplementations:

    JavaNIO.

    ThefirstimplementationusesstandardJavaNIOtointerfacewiththefilesystem.Thisprovidesextremelygood

    performanceandrunsonanyplatformwherethere'saJava6+runtime.

    LinuxAsynchronousIO

    ThesecondimplementationusesathinnativecodewrappertotalktotheLinuxasynchronousIOlibrary(AIO).With

    AIO,ApacheActiveMQArtemiswillbecalledbackwhenthedatahasmadeittodisk,allowingustoavoidexplicit

    syncsaltogetherandsimplysendbackconfirmationofcompletionwhenAIOinformsusthatthedatahasbeen

    persisted.

    UsingAIOwilltypicallyprovideevenbetterperformancethanusingJavaNIO.

    TheAIOjournalisonlyavailablewhenrunningLinuxkernel2.6orlaterandafterhavinginstalledlibaio(ifit'snot