table of contents - apache activemq · 2019-10-08 · the publish-subscribe pattern with...

407
1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 1.10 1.11 1.12 1.13 1.14 1.15 1.16 1.17 1.18 1.19 1.20 1.21 1.22 1.23 1.24 1.25 1.26 1.27 Table of Contents Introduction Legal Notice Preface Project Info Messaging Concepts Architecture Using the Server Address Model Using JMS Using Core Using AMQP Mapping JMS Concepts to the Core API The Client Classpath Examples Routing Messages With Wild Cards Understanding the Apache ActiveMQ Artemis Wildcard Syntax Filter Expressions Persistence Configuring Transports Configuration Reload Detecting Dead Connections Detecting Slow Consumers Avoiding Network Isolation Resource Manager Configuration Flow Control Guarantees of sends and commits Message Redelivery and Undelivered Messages 1

Upload: others

Post on 24-Jul-2020

12 views

Category:

Documents


0 download

TRANSCRIPT

  • 1.1

    1.2

    1.3

    1.4

    1.5

    1.6

    1.7

    1.8

    1.9

    1.10

    1.11

    1.12

    1.13

    1.14

    1.15

    1.16

    1.17

    1.18

    1.19

    1.20

    1.21

    1.22

    1.23

    1.24

    1.25

    1.26

    1.27

    TableofContentsIntroduction

    LegalNotice

    Preface

    ProjectInfo

    MessagingConcepts

    Architecture

    UsingtheServer

    AddressModel

    UsingJMS

    UsingCore

    UsingAMQP

    MappingJMSConceptstotheCoreAPI

    TheClientClasspath

    Examples

    RoutingMessagesWithWildCards

    UnderstandingtheApacheActiveMQArtemisWildcardSyntax

    FilterExpressions

    Persistence

    ConfiguringTransports

    ConfigurationReload

    DetectingDeadConnections

    DetectingSlowConsumers

    AvoidingNetworkIsolation

    ResourceManagerConfiguration

    FlowControl

    Guaranteesofsendsandcommits

    MessageRedeliveryandUndeliveredMessages

    1

  • 1.28

    1.29

    1.30

    1.31

    1.32

    1.33

    1.34

    1.35

    1.36

    1.37

    1.38

    1.39

    1.40

    1.41

    1.42

    1.43

    1.44

    1.45

    1.46

    1.47

    1.48

    1.49

    1.50

    1.51

    1.52

    1.53

    1.54

    1.55

    1.56

    1.57

    MessageExpiry

    LargeMessages

    Paging

    QueueAttributes

    ScheduledMessages

    Last-ValueQueues

    MessageGrouping

    ExtraAcknowledgeModes

    Management

    Security

    BrokerPlugins

    ResourceLimits

    TheJMSBridge

    ClientReconnectionandSessionReattachment

    DivertingandSplittingMessageFlows

    CoreBridges

    DuplicateMessageDetection

    Clusters

    HighAvailabilityandFailover

    GracefulServerShutdown

    LibaioNativeLibraries

    Threadmanagement

    Logging

    RESTInterface

    EmbeddingApacheActiveMQArtemis

    ApacheKaraf

    SpringIntegration

    CDIIntegration

    InterceptingOperations

    ProtocolsandInteroperability

    2

  • 1.58

    1.59

    1.60

    1.61

    1.62

    1.63

    Tools

    MavenPlugin

    UnitTesting

    TroubleshootingandPerformanceTuning

    ConfigurationReference

    UpdatingArtemis

    3

  • ApacheActiveMQArtemisUserManualTheUsermanualisanindepthmanualonallaspectsofApacheActiveMQArtemis

    Introduction

    4

  • LegalNoticeLicensedtotheApacheSoftwareFoundation(ASF)underoneormorecontributorlicenseagreements.SeetheNOTICEfiledistributedwiththisworkforadditionalinformationregardingcopyrightownership.TheASFlicensesthisfiletoYouundertheApacheLicense,Version2.0(the"License");youmaynotusethisfileexceptincompliancewiththeLicense.YoumayobtainacopyoftheLicenseat

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

    Unlessrequiredbyapplicablelaworagreedtoinwriting,softwaredistributedundertheLicenseisdistributedonan"ASIS"BASIS,WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.SeetheLicenseforthespecificlanguagegoverningpermissionsandlimitationsundertheLicense.

    LegalNotice

    5

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

  • PrefaceWhatisApacheActiveMQArtemis?

    ApacheActiveMQArtemisisanopensourceprojecttobuildamulti-protocol,embeddable,veryhighperformance,clustered,asynchronousmessagingsystem.

    ApacheActiveMQArtemisisanexampleofMessageOrientedMiddleware(MoM).ForadescriptionofMoMsandothermessagingconceptspleaseseetheMessagingConcepts.

    WhyuseApacheActiveMQArtemis?Herearejustafewofthereasons:

    100%opensourcesoftware.ApacheActiveMQArtemisislicensedusingtheApacheSoftwareLicensev2.0tominimisebarrierstoadoption.

    ApacheActiveMQArtemisisdesignedwithusabilityinmind.

    WritteninJava.RunsonanyplatformwithaJava8+runtime,that'severythingfromWindowsdesktopstoIBMmainframes.

    Amazingperformance.Ourground-breakinghighperformancejournalprovidespersistentmessagingperformanceatratesnormallyseenfornon-persistentmessaging,ournon-persistentmessagingperformancerockstheboattoo.

    Fullfeatureset.Allthefeaturesyou'dexpectinanyseriousmessagingsystem,andothersyouwon'tfindanywhereelse.

    Elegant,clean-cutdesignwithminimalthirdpartydependencies.RunActiveMQArtemisstand-alone,runitinintegratedinyourfavouriteJEEapplicationserver,orrunitembeddedinsideyourownproduct.It'suptoyou.

    Seamlesshighavailability.WeprovideaHAsolutionwithautomaticclientfailoversoyoucanguaranteezeromessagelossorduplicationineventofserverfailure.

    Hugelyflexibleclustering.Createclustersofserversthatknowhowtoloadbalancemessages.Linkgeographicallydistributedclustersoverunreliableconnectionstoformaglobalnetwork.Configureroutingofmessagesinahighlyflexibleway.

    Preface

    6

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

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

    ProjectInformationIfyouhaveanyuserquestionspleaseuseouruserforum

    Ifyouhavedevelopmentrelatedquestions,pleaseuseourdeveloperforum

    PopinandchattousinourIRCchannel

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

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

    Andmanythankstoallourcontributors,botholdandnewwhohelpedcreateApacheActiveMQArtemis.

    ProjectInfo

    7

    http://activemq.apache.org/artemis/http://activemq.apache.org/download.htmlhttp://activemq.2283324.n4.nabble.com/ActiveMQ-User-f2341805.htmlhttp://activemq.2283324.n4.nabble.com/ActiveMQ-Dev-f2368404.htmlirc://irc.freenode.net:6667/apache-activemqhttps://github.com/apache/activemq-artemishttps://github.com/apache/activemq-artemis/releases

  • MessagingConceptsApacheActiveMQArtemisisanasynchronousmessagingsystem,anexampleofMessageOrientedMiddleware,we'lljustcallthemmessagingsystemsintheremainderofthisbook.

    We'llfirstpresentabriefoverviewofwhatkindofthingsmessagingsystemsdo,wherethey'reusefulandthekindofconceptsyou'llhearaboutinthemessagingworld.

    Ifyou'realreadyfamiliarwithwhatamessagingsystemisandwhatit'scapableof,thenyoucanskipthischapter.

    MessagingConceptsMessagingsystemsallowyoutolooselycoupleheterogeneoussystemstogether,whilsttypicallyprovidingreliability,transactionsandmanyotherfeatures.

    UnlikesystemsbasedonaRemoteProcedureCall(RPC)pattern,messagingsystemsprimarilyuseanasynchronousmessagepassingpatternwithnotightrelationshipbetweenrequestsandresponses.Mostmessagingsystemsalsosupportarequest-responsemodebutthisisnotaprimaryfeatureofmessagingsystems.

    Designingsystemstobeasynchronousfromend-to-endallowsyoutoreallytakeadvantageofyourhardwareresources,minimizingtheamountofthreadsblockingonIOoperations,andtouseyournetworkbandwidthtoitsfullcapacity.WithanRPCapproachyouhavetowaitforaresponseforeachrequestyoumakesoarelimitedbythenetworkroundtriptime,orlatencyofyournetwork.Withanasynchronoussystemyoucanpipelineflowsofmessagesindifferentdirections,soarelimitedbythenetworkbandwidthnotthelatency.Thistypicallyallowsyoutocreatemuchhigherperformanceapplications.

    Messagingsystemsdecouplethesendersofmessagesfromtheconsumersofmessages.Thesendersandconsumersofmessagesarecompletelyindependentandknownothingofeachother.Thisallowsyoutocreateflexible,looselycoupledsystems.

    Often,largeenterprisesuseamessagingsystemtoimplementamessagebuswhichlooselycouplesheterogeneoussystemstogether.MessagebusesoftenformthecoreofanEnterpriseServiceBus.(ESB).Usingamessagebustode-coupledisparatesystems

    MessagingConcepts

    8

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

  • canallowthesystemtogrowandadaptmoreeasily.Italsoallowsmoreflexibilitytoaddnewsystemsorretireoldonessincetheydon'thavebrittledependenciesoneachother.

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

    TheMessageQueuePattern

    Withthistypeofmessagingyousendamessagetoaqueue.Themessageisthentypicallypersistedtoprovideaguaranteeofdelivery,thensometimelaterthemessagingsystemdeliversthemessagetoaconsumer.Theconsumerthenprocessesthemessageandwhenitisdone,itacknowledgesthemessage.Oncethemessageisacknowledgeditdisappearsfromthequeueandisnotavailabletobedeliveredagain.Ifthesystemcrashesbeforethemessagingserverreceivesanacknowledgementfromtheconsumer,thenonrecovery,themessagewillbeavailabletobedeliveredtoaconsumeragain.

    Withpoint-to-pointmessaging,therecanbemanyconsumersonthequeuebutaparticularmessagewillonlyeverbeconsumedbyamaximumofoneofthem.Senders(alsoknownasproducers)tothequeuearecompletelydecoupledfromreceivers(alsoknownasconsumers)ofthequeue-theydonotknowofeachother'sexistence.

    Aclassicexampleofpointtopointmessagingwouldbeanorderqueueinacompany'sbookorderingsystem.Eachorderisrepresentedasamessagewhichissenttotheorderqueue.Let'simaginetherearemanyfrontendorderingsystemswhichsendorderstotheorderqueue.Whenamessagearrivesonthequeueitispersisted-thisensuresthatiftheservercrashestheorderisnotlost.Let'salsoimaginetherearemanyconsumersontheorderqueue-eachrepresentinganinstanceofanorderprocessingcomponent-thesecanbeondifferentphysicalmachinesbutconsumingfromthesamequeue.Themessagingsystemdeliverseachmessagetooneandonlyoneoftheorderingprocessingcomponents.Differentmessagescanbeprocessedbydifferentorderprocessors,butasingleorderisonlyprocessedbyoneorderprocessor-thisensuresordersaren'tprocessedtwice.

    MessagingConcepts

    9

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

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

    ThePublish-SubscribePattern

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

    Therecanbemanysubscriptionsonatopic,asubscriptionisjustanotherwordforaconsumerofatopic.Eachsubscriptionreceivesacopyofeachmessagesenttothetopic.Thisdiffersfromthemessagequeuepatternwhereeachmessageisonlyconsumedbyasingleconsumer.

    Subscriptionscanoptionallybedurablewhichmeanstheyretainacopyofeachmessagesenttothetopicuntilthesubscriberconsumesthem-eveniftheservercrashesorisrestartedinbetween.Non-durablesubscriptionsonlylastamaximumofthelifetimeoftheconnectionthatcreatedthem.

    Anexampleofpublish-subscribemessagingwouldbeanewsfeed.Asnewsarticlesarecreatedbydifferenteditorsaroundtheworldtheyaresenttoanewsfeedtopic.Therearemanysubscribersaroundtheworldwhoareinterestedinreceivingnewsitems-eachonecreatesasubscriptionandthemessagingsystemensuresthatacopyofeachnewsmessageisdeliveredtoeachsubscription.

    DeliveryguaranteesAkeyfeatureofmostmessagingsystemsisreliablemessaging.Withreliablemessagingtheservergivesaguaranteethatthemessagewillbedeliveredonceandonlyoncetoeachconsumerofaqueueoreachdurablesubscriptionofatopic,evenintheeventofsystemfailure.Thisiscrucialformanybusinesses;e.g.youdon'twantyourordersfulfilledmorethanonceoranyofyourorderstobelost.

    Inothercasesyoumaynotcareaboutaonceandonlyoncedeliveryguaranteeandarehappytocopewithduplicatedeliveriesorlostmessages-anexampleofthismightbetransientstockpriceupdates-whicharequicklysupersededbythenextupdateonthe

    MessagingConcepts

    10

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

  • samestock.Themessagingsystemallowsyoutoconfigurewhichdeliveryguaranteesyourequire.

    TransactionsMessagingsystemstypicallysupportthesendingandacknowledgementofmultiplemessagesinasinglelocaltransaction.ApacheActiveMQArtemisalsosupportsthesendingandacknowledgementofmessageaspartofalargeglobaltransaction-usingtheJavamappingofXA:JTA.

    DurabilityMessagesareeitherdurableornondurable.Durablemessageswillbepersistedinpermanentstorageandwillsurviveserverfailureorrestart.Nondurablemessageswillnotsurviveserverfailureorrestart.Examplesofdurablemessagesmightbeordersortrades,wheretheycannotbelost.Anexampleofanondurablemessagemightbeastockpriceupdatewhichistransitoryanddoesn'tneedtosurvivearestart.

    MessagingAPIsandprotocolsHowdoclientapplicationsinteractwithmessagingsystemsinordertosendandconsumemessages?

    SeveralmessagingsystemsprovidetheirownproprietaryAPIswithwhichtheclientcommunicateswiththemessagingsystem.

    Therearealsosomestandardwaysofoperatingwithmessagingsystemsandsomeemergingstandardsinthisspace.

    Let'stakeabrieflookatthese:

    JavaMessageService(JMS)

    JMSispartofOracle'sJEEspecification.It'saJavaAPIthatencapsulatesbothmessagequeueandpublish-subscribemessagingpatterns.JMSisalowestcommondenominatorspecification-i.e.itwascreatedtoencapsulatecommonfunctionalityofthealreadyexistingmessagingsystemsthatwereavailableatthetimeofitscreation.

    MessagingConcepts

    11

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

  • JMSisaverypopularAPIandisimplementedbymostmessagingsystems.JMSisonlyavailabletoclientsrunningJava.

    JMSdoesnotdefineastandardwireformat-itonlydefinesaprogrammaticAPIsoJMSclientsandserversfromdifferentvendorscannotdirectlyinteroperatesinceeachwillusethevendor'sowninternalwireprotocol.

    ApacheActiveMQArtemisprovidesafullycompliantJMS1.1andJMS2.0API.

    SystemspecificAPIs

    ManysystemsprovidetheirownprogrammaticAPIforwhichtointeractwiththemessagingsystem.Theadvantageofthisitallowsthefullsetofsystemfunctionalitytobeexposedtotheclientapplication.API'slikeJMSarenotnormallyrichenoughtoexposealltheextrafeaturesthatmostmessagingsystemsprovide.

    ApacheActiveMQArtemisprovidesitsowncoreclientAPIforclientstouseiftheywishtohaveaccesstofunctionalityoverandabovethataccessibleviatheJMSAPI.

    RESTfulAPI

    RESTapproachestomessagingareshowingalotinterestrecently.

    ItseemsplausiblethatAPIstandardsforcloudcomputingmayconvergeonaRESTstylesetofinterfacesandconsequentlyaRESTmessagingapproachisaverystrongcontenderforbecomingthede-factomethodformessaginginteroperability.

    WithaRESTapproachmessagingresourcesaremanipulatedasresourcesdefinedbyaURIandtypicallyusingasimplesetofoperationsonthoseresources,e.g.PUT,POST,GETetc.RESTapproachestomessagingoftenuseHTTPastheirunderlyingprotocol.

    TheadvantageofaRESTapproachwithHTTPisinitssimplicityandthefacttheinternetisalreadytunedtodealwithHTTPoptimally.

    PleaseseeRestInterfaceforusingApacheActiveMQArtemis'sRESTfulinterface.

    AMQP

    AMQPisaspecificationforinteroperablemessaging.Italsodefinesawireformat,soanyAMQPclientcanworkwithanymessagingsystemthatsupportsAMQP.AMQPclientsareavailableinmanydifferentprogramminglanguages.

    MessagingConcepts

    12

    http://en.wikipedia.org/wiki/Representational_State_Transferhttp://en.wikipedia.org/wiki/AMQP

  • ApacheActiveMQArtemisimplementstheAMQP1.0specification.Anyclientthatsupportsthe1.0specificationwillbeabletointeractwithApacheActiveMQArtemis.

    MQTT

    MQTTisalightweightconnectivityprotocol.Itisdesignedtoruninenvironmentswheredeviceandnetworksareconstrained.OutoftheboxApacheActiveMQArtemissupportsversionMQTT3.1.1.AnyclientsupportingthisversionoftheprotocolwillworkagainstApacheActiveMQArtemis.

    STOMP

    Stompisaverysimpletextprotocolforinteroperatingwithmessagingsystems.Itdefinesawireformat,sotheoreticallyanyStompclientcanworkwithanymessagingsystemthatsupportsStomp.Stompclientsareavailableinmanydifferentprogramminglanguages.

    PleaseseeStompforusingSTOMPwithApacheActiveMQArtemis.

    OPENWIRE

    ActiveMQ5.xdefinesit'sownwireProtocol"OPENWIRE".InordertosupportActiveMQ5.xclients,ApacheActiveMQArtemissupportsOPENWIRE.AnyActiveMQ5.12.xorhighercanbeusedwithApacheActiveMQArtemis.

    HighAvailabilityHighAvailability(HA)meansthatthesystemshouldremainoperationalafterfailureofoneormoreoftheservers.ThedegreeofsupportforHAvariesbetweenvariousmessagingsystems.

    ApacheActiveMQArtemisprovidesautomaticfailoverwhereyoursessionsareautomaticallyreconnectedtothebackupserveroneventofliveserverfailure.

    FormoreinformationonHA,pleaseseeHighAvailabilityandFailover.

    Clusters

    MessagingConcepts

    13

    https://www.oasis-open.org/committees/tc_home.php?wg_abbrev=amqphttp://mqtt.org/http://stomp.github.io/

  • Manymessagingsystemsallowyoutocreategroupsofmessagingserverscalledclusters.Clustersallowtheloadofsendingandconsumingmessagestobespreadovermanyservers.Thisallowsyoursystemtoscalehorizontallybyaddingnewserverstothecluster.

    Degreesofsupportforclustersvariesbetweenmessagingsystems,withsomesystemshavingfairlybasicclusterswiththeclustermembersbeinghardlyawareofeachother.

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

    ApacheActiveMQArtemisalsohastheabilitytoautomaticallyredistributemessagesbetweennodesofaclustertopreventstarvationonanyparticularnode.

    Forfulldetailsonclustering,pleaseseeClusters.

    BridgesandroutingSomemessagingsystemsallowisolatedclustersorsinglenodestobebridgedtogether,typicallyoverunreliableconnectionslikeawideareanetwork(WAN),ortheinternet.

    Abridgenormallyconsumesfromaqueueononeserverandforwardsmessagestoanotherqueueonadifferentserver.Bridgescopewithunreliableconnections,automaticallyreconnectingwhentheconnectionsbecomesavailableagain.

    ApacheActiveMQArtemisbridgescanbeconfiguredwithfilterexpressionstoonlyforwardcertainmessages,andtransformationcanalsobehookedin.

    ApacheActiveMQArtemisalsoallowsroutingbetweenqueuestobeconfiguredinserversideconfiguration.Thisallowscomplexroutingnetworkstobesetupforwardingorcopyingmessagesfromonedestinationtoanother,formingaglobalnetworkofinterconnectedbrokers.

    FormoreinformationpleaseseeCoreBridgesandDivertingandSplittingMessageFlows.

    MessagingConcepts

    14

  • ArchitectureInthissectionwewillgiveanoverviewoftheApacheActiveMQArtemishighlevelarchitecture.

    CoreArchitectureApacheActiveMQArtemiscoreisdesignedsimplyassetofPlainOldJavaObjects(POJOs)-wehopeyoulikeitsclean-cutdesign.

    EachApacheActiveMQArtemisserverhasitsownultrahighperformancepersistentjournal,whichitusesformessageandotherpersistence.

    Usingahighperformancejournalallowsoutrageouspersistencemessageperformance,somethingnotachievablewhenusingarelationaldatabaseforpersistence.

    ApacheActiveMQArtemisclients,potentiallyondifferentphysicalmachinesinteractwiththeApacheActiveMQArtemisserver.ApacheActiveMQArtemiscurrentlyprovidestwoAPIsformessagingattheclientside:

    1. CoreclientAPI.ThisisasimpleintuitiveJavaAPIthatisalignedwiththeArtemisinternalCore.Allowingmorecontrolofbrokerobjects,likeforexample,directcreationofaddressesandqueues.TheCoreAPIalsooffersafullsetofmessagingfunctionalitywithoutsomeofthecomplexitiesofJMS.

    2. JMSclientAPI.ThestandardJMSAPIisavailableattheclientside.

    ApacheActiveMQArtemisalsoprovidesdifferentprotocolimplementationsontheserversoyoucanuserespectiveclientsfortheseprotocols:

    1. AMQP2. OpenWire3. MQTT4. STOMP5. HornetQ(forusewithHornetQclients).6. CORE(ArtemisCOREprotocol)

    JMSsemanticsareimplementedbyaJMSfacadelayerontheclientside.

    Architecture

    15

  • TheApacheActiveMQArtemisserverdoesnotspeakJMSandinfactdoesnotknowanythingaboutJMS,itisaprotocolagnosticmessagingserverdesignedtobeusedwithmultipledifferentprotocols.

    WhenauserusestheJMSAPIontheclientside,allJMSinteractionsaretranslatedintooperationsontheApacheActiveMQArtemiscoreclientAPIbeforebeingtransferredoverthewireusingtheApacheActiveMQArtemiswireformat.

    TheserveralwaysjustdealswithcoreAPIinteractions.

    Aschematicillustratingthisrelationshipisshowninfigure3.1below:

    Architecture

    16

  • Architecture

    17

  • Figure3.1showstwouserapplicationsinteractingwithanApacheActiveMQArtemisserver.UserApplication1isusingtheJMSAPI,whileUserApplication2isusingthecoreclientAPIdirectly.

    YoucanseefromthediagramthattheJMSAPIisimplementedbyathinfacadelayerontheclientside.

    ApacheActiveMQArtemisstand-aloneserverThestandardstand-alonemessagingserverconfigurationcomprisesacoremessagingserverandanumberofprotocolmanagersthatprovidesupportforthevariousprotocolmentionedearlier.Protocolmanagersareplugableifyou

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

    Thestand-aloneserverconfigurationusesAirlineforbootstrappingtheBroker.

    Thestand-aloneserverarchitectureisshowninfigure3.3below:

    Architecture

    18

    https://github.com/airlift/airline

  • FormoreinformationonserverconfigurationfilesseeServerConfiguration

    Architecture

    19

  • ApacheActiveMQArtemisembeddedinyourownapplicationApacheActiveMQArtemiscoreisdesignedasasetofsimplePOJOssoifyouhaveanapplicationthatrequiresmessagingfunctionalityinternallybutyoudon'twanttoexposethatasanApacheActiveMQArtemisserveryoucandirectlyinstantiateandembedApacheActiveMQArtemisserversinyourownapplication.

    FormoreinformationonembeddingApacheActiveMQArtemis,seeEmbeddingApacheActiveMQArtemis.

    ApacheActiveMQArtemisintegratedwithaJavaEEapplicationserverApacheActiveMQArtemisprovidesitsownfullyfunctionalJavaConnectorArchitecture(JCA)adaptorwhichenablesittobeintegratedeasilyintoanyJavaEEcompliantapplicationserverorservletengine.

    JavaEEapplicationserversprovideMessageDrivenBeans(MDBs),whichareaspecialtypeofEnterpriseJavaBeans(EJBs)thatcanprocessmessagesfromsourcessuchasJMSsystemsormailsystems.

    ProbablythemostcommonuseofanMDBistoconsumemessagesfromaJMSmessagingsystem.

    AccordingtotheJavaEEspecification,aJavaEEapplicationserverusesaJCAadaptertointegratewithaJMSmessagingsystemsoitcanconsumemessagesforMDBs.

    However,theJCAadapterisnotonlyusedbytheJavaEEapplicationserverforconsumingmessagesviaMDBs,itisalsousedwhensendingmessagetotheJMSmessagingsysteme.g.frominsideanEJBorservlet.

    WhenintegratingwithaJMSmessagingsystemfrominsideaJavaEEapplicationserveritisalwaysrecommendedthatthisisdoneviaaJCAadaptor.Infact,communicatingwithaJMSmessagingsystemdirectly,withoutusingJCAwouldbeillegalaccordingtotheJavaEEspecification.

    Architecture

    20

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

    Figure3.2belowshowsaJavaEEapplicationserverintegratingwithaApacheActiveMQArtemisserverviatheApacheActiveMQArtemisJCAadaptor.NotethatallcommunicationbetweenEJBsessionsorentitybeansandMessageDrivenbeansgothroughtheadaptorandnotdirectlytoApacheActiveMQArtemis.

    ThelargearrowwiththeprohibitedsignshowsanEJBsessionbeantalkingdirectlytotheApacheActiveMQArtemisserver.Thisisnotrecommendedasyou'llmostlikelyendupcreatinganewconnectionandsessioneverytimeyouwanttointeractfromtheEJB,whichisananti-pattern.

    Architecture

    21

  • Architecture

    22

  • Architecture

    23

  • UsingtheServerThischapterwillfamiliariseyouwithhowtousetheApacheActiveMQArtemisserver.

    We'llshowwhereitis,howtostartandstopit,andwe'lldescribethedirectorylayoutandwhatallthefilesareandwhattheydo.

    FortheremainderofthischapterwhenwetalkabouttheApacheActiveMQArtemisserverwemeantheApacheActiveMQArtemisstandaloneserver,initsdefaultconfigurationwithaJMSServiceenabled.

    ThisdocumentwillrefertothefullpathofthedirectorywheretheActiveMQdistributionhasbeenextractedtoas${ARTEMIS_HOME}directory.

    InstallationAfterdownloadingthedistribution,thefollowinghighlightssomeimportantfoldersonthedistribution:

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

    bin--binariesandscriptsneededtorunActiveMQArtemis.

    web--ThefolderwherethewebcontextisloadedwhenActiveMQArtemisruns.

    user-manual--Theusermanualisplacedunderthewebfolder.

    api--Theapidocumentationisplacedunderthewebfolder

    UsingtheServer

    24

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

    lib--jarsandlibrariesneededtorunActiveMQArtemis

    licenses--licensesforActiveMQArtemis

    schemas--XMLSchemasusedtovalidateActiveMQArtemisconfigurationfiles

    CreatingaBrokerInstanceAbrokerinstanceisthedirectorycontainingalltheconfigurationandruntimedata,suchaslogsanddatafiles,associatedwithabrokerprocess.Itisrecommendedthatyoudonotcreatetheinstancedirectoryunder${ARTEMIS_HOME}.ThisseparationisencouragedsothatyoucanmoreeasilyupgradewhenthenextversionofActiveMQArtemisisreleased.

    OnUnixsystems,itisacommonconventiontostorethiskindofruntimedataunderthe/var/libdirectory.Forexample,tocreateaninstanceat'/var/lib/mybroker',runthefollowingcommandsinyourcommandlineshell:

    cd/var/lib${ARTEMIS_HOME}/bin/artemiscreatemybroker

    Abrokerinstancedirectorywillcontainthefollowingsubdirectories:

    bin:holdsexecutionscriptsassociatedwiththisinstance.etc:holdtheinstanceconfigurationfilesdata:holdsthedatafilesusedforstoringpersistentmessageslog:holdsrotatinglogfilestmp:holdstemporaryfilesthataresafetodeletebetweenbrokerruns

    Atthispointyoumaywanttoadjustthedefaultconfigurationlocatedintheetcdirectory.

    Options

    Thereareseveraloptionsyoucanusewhencreatinganinstance.

    Forafulllistofupdatedpropertiesalwaysuse:

    UsingtheServer

    25

  • $./artemishelpcreateNAMEartemiscreate-createsanewbrokerinstance

    SYNOPSISartemiscreate[--addresses][--aio][--allow-anonymous][--autocreate][--blocking][--cluster-password][--cluster-user][--clustered][--data][--default-port][--disable-persistence][--encoding][--failover-on-shutdown][--force][--global-max-size][--home][--host][--http-host][--http-port][--java-options][--mapped][--max-hops][--message-load-balancing][--name][--nio][--no-amqp-acceptor][--no-autocreate][--no-autotune][--no-fsync][--no-hornetq-acceptor][--no-mqtt-acceptor][--no-stomp-acceptor][--no-web][--paging][--password][--ping][--port-offset][--queues][--replicated][--require-login][--role][--shared-store][--silent][--slave][--ssl-key][--ssl-key-password][--ssl-trust][--ssl-trust-password][--use-client-auth][--user][--verbose][--]

    OPTIONS--addressesCommaseparatedlistofaddresses

    --aioSetsthejournalasasyncio.

    --allow-anonymousEnablesanonymousconfigurationonsecurity,oppositeof--require-login(Default:input)

    --autocreateAutocreateaddresses.(default:true)

    --blockingBlockproducerswhenaddressbecomesfull,oppositeof--paging(Default:false)

    --cluster-passwordTheclusterpasswordtouseforclustering.(Default:input)

    --cluster-userTheclusterusertouseforclustering.(Default:input)

    --clustered

    UsingtheServer

    26

  • Enableclustering

    --dataDirectorywhereActiveMQDataisused.Pathsarerelativetoartemis.instance

    --default-portTheportnumbertouseforthemain'artemis'acceptor(Default:61616)

    --disable-persistenceDisablemessagepersistencetothejournal

    --encodingTheencodingthattextfilesshoulduse

    --failover-on-shutdownValidforsharedstore:willshutdowntriggerafailover?(Default:false)

    --forceOverwriteconfigurationatdestinationdirectory

    --global-max-sizeMaximumamountofmemorywhichmessagedatamayconsume(Default:Undefined,halfofthesystem'smemory)

    --homeDirectorywhereActiveMQArtemisisinstalled

    --hostThehostnameofthebroker(Default:0.0.0.0orinputifclustered)

    --http-hostThehostnametouseforembeddedwebserver(Default:localhost)

    --http-portTheportnumbertouseforembeddedwebserver(Default:8161)

    --java-optionsExtrajavaoptionstobepassedtotheprofile

    --mappedSetsthejournalasmapped.

    --max-hopsNumberofhopsontheclusterconfiguration

    --message-load-balancingLoadbalancingpolicyoncluster.[ON_DEMAND(default)|STRICT|OFF]

    UsingtheServer

    27

  • --nameThenameofthebroker(Default:sameashost)

    --nioSetsthejournalasnio.

    --no-amqp-acceptorDisabletheAMQPspecificacceptor.

    --no-autocreateDisableAutocreateaddresses.

    --no-autotuneDisableautotuningonthejournal.

    --no-fsyncDisableusageoffdatasync(channel.force(false)fromjavanio)onthejournal

    --no-hornetq-acceptorDisabletheHornetQspecificacceptor.

    --no-mqtt-acceptorDisabletheMQTTspecificacceptor.

    --no-stomp-acceptorDisabletheSTOMPspecificacceptor.

    --no-webRemovetheweb-serverdefinitionfrombootstrap.xml

    --pagingPagemessagestodiskwhenaddressbecomesfull,oppositeof--blocking(Default:true)

    --passwordTheuser'spassword(Default:input)

    --pingAcommaseparatedstringtobepassedontothebrokerconfigasnetwork-check-list.Thebrokerwillshutdownwhenalltheseaddressesareunreachable.

    --port-offsetOffsetstheportsofeveryacceptor

    --queuesCommaseparatedlistofqueues.

    --replicatedEnablebrokerreplication

    UsingtheServer

    28

  • --require-loginThiswillconfiguresecuritytorequireuser/password,oppositeof--allow-anonymous

    --roleThenamefortherolecreated(Default:amq)

    --shared-storeEnablebrokersharedstore

    --silentItwilldisablealltheinputs,anditwouldmakeabestguessforanyrequiredinput

    --slaveValidforsharedstoreorreplication:thisisaslaveserver?

    --ssl-keyThekeystorepathforembeddedwebserver

    --ssl-key-passwordThekeystorepassword

    --ssl-trustThetruststorepathincaseofclientauthentication

    --ssl-trust-passwordThetruststorepassword

    --use-client-authIftheembeddedserverrequiresclientauthentication

    --userTheusername(Default:input)

    --verboseAddsmoreinformationontheexecution

    --Thisoptioncanbeusedtoseparatecommand-lineoptionsfromthelistofargument,(usefulwhenargumentsmightbemistakenforcommand-lineoptions

    Theinstancedirectorytoholdthebroker'sconfigurationanddata.Pathmustbewritable.

    Someofthesepropertiesmaybemandatoryincertainconfigurationsandthesystemmayaskyouforadditionalinput.

    UsingtheServer

    29

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

    --user:isamandatoryproperty!Pleaseprovidethedefaultusername:admin

    --password:ismandatorywiththisconfiguration:Pleaseprovidethedefaultpassword:

    --allow-anonymous|--require-login:isamandatoryproperty!Allowanonymousaccess?,validvaluesareY,N,True,Falsey

    Autotuningjournal...done!Yoursystemcanmake0.34writespermillisecond,yourjournal-buffer-timeoutwillbe2956000

    Youcannowstartthebrokerbyexecuting:

    "/user/server/bin/artemis"run

    Oryoucanrunthebrokerinthebackgroundusing:

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

    StartingandStoppingaBrokerInstance

    Assumingyoucreatedthebrokerinstanceunder/var/lib/mybrokerallyouneedtodostartrunningthebrokerinstanceisexecute:

    /var/lib/mybroker/bin/artemisrun

    Nowthatthebrokerisrunning,youcanoptionallyrunsomeoftheincludedexamplestoverifythethebrokerisrunningproperly.

    TostoptheApacheActiveMQArtemisinstanceyouwillusethesameartemisscript,butwiththestopargument.Example:

    /var/lib/mybroker/bin/artemisstop

    PleasenotethatApacheActiveMQArtemisrequiresaJava7orlaterruntimetorun.

    UsingtheServer

    30

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

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

    ServerJVMsettingsTherunscriptssetsomeJVMsettingsfortuningthegarbagecollectionpolicyandheapsize.WerecommendusingaparallelgarbagecollectionalgorithmtosmoothoutlatencyandminimiselargeGCpauses.

    BydefaultApacheActiveMQArtemisrunsinamaximumof1GiBofRAM.Toincreasethememorysettingschangethe-Xmsand-XmxmemorysettingsasyouwouldforanyJavaprogram.

    IfyouwishtoaddanymoreJVMargumentsortunetheexistingones,therunscriptsaretheplacetodoit.

    Pre-configuredOptionsThedistributioncontainsseveralstandardconfigurationsetsforrunning:

    Nonclusteredstand-alone.

    Clusteredstand-alone

    Replicatedstand-alone

    Shared-storestand-alone

    Youcanofcoursecreateyourownconfigurationandspecifyanyconfigurationwhenrunningtherunscript.

    LibraryPath

    UsingtheServer

    31

  • Ifyou'reusingtheAsynchronousIOJournalonLinux,youneedtospecifyjava.library.pathasapropertyonyourJavaoptions.Thisisdoneautomaticallyinthescripts.

    Ifyoudon'tspecifyjava.library.pathatyourJavaoptionsthentheJVMwillusetheenvironmentvariableLD_LIBRARY_PATH.

    YouwillneedtomakesurelibaioisinstalledonLinux.FormoreinformationrefertothelibaiochapteratRuntimeDependencies

    SystempropertiesApacheActiveMQArtemiscantakeasystempropertyonthecommandlineforconfiguringlogging.

    Formoreinformationonconfiguringlogging,pleaseseethesectiononLogging.

    ConfigurationfilesTheconfigurationfileusedtobootstraptheserver(e.g.bootstrap.xmlbydefault)referencesthespecificbrokerconfigurationfiles.

    broker.xml.ThisisthemainActiveMQconfigurationfile.Alltheparametersinthisfilearedescribedhere

    Itisalsopossibletousesystempropertysubstitutioninalltheconfigurationfiles.byreplacingavaluewiththenameofasystemproperty.Hereisanexampleofthiswithaconnectorconfiguration:

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

    Hereyoucanseewehavereplaced2valueswithsystempropertiesactivemq.remoting.netty.hostandactivemq.remoting.netty.port.Thesevalueswillbereplacedbythevaluefoundinthesystempropertyifthereisone,ifnottheydefaultbacktolocalhostor61616respectively.Itisalsopossibletonotsupplyadefault.i.e.${activemq.remoting.netty.host},howeverthesystempropertymustbesuppliedinthatcase.

    UsingtheServer

    32

  • BootstrapFileThestand-aloneserverisbasicallyasetofPOJOswhichareinstantiatedbyAirlinecommands.

    Thebootstrapfileisverysimple.Let'stakealookatanexample:

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

    Themainconfigurationfile.TheconfigurationfortheApacheActiveMQArtemiscoreserveriscontainedinbroker.xml.ThisiswhattheFileConfigurationbeanusestoconfigurethemessagingserver.

    TherearemanyattributeswhichyoucanconfigureApacheActiveMQArtemis.Inmostcasesthedefaultswilldofine,infacteveryattributecanbedefaultedwhichmeansafilewithasingleemptyconfigurationelementisavalidconfigurationfile.Thedifferentconfigurationwillbeexplainedthroughoutthemanualoryoucanrefertotheconfigurationreferencehere.

    WindowsServerOnwindowsyouwillhavetheoptiontorunActiveMQArtemisasaservice.Justusethefollowingcommandtoinstallit:

    UsingtheServer

    33

  • $./artemis-service.exeinstall

    Thecreateprocessshouldgiveyouahintoftheavailablecommandsavailablefortheartemis-service.exe

    UsingtheServer

    34

  • ApacheActiveMQArtemisAddressingandQueuesApacheActiveMQArtemishasauniqueaddressingmodelthatisbothpowerfulandflexibleandthatoffersgreatperformance.Theaddressingmodelcomprisesthreemainconcepts:addresses,queuesandroutingtypes.

    Anaddressrepresentsamessagingendpoint.Withintheconfiguration,atypicaladdressisgivenauniquename,0ormorequeues,andaroutingtype.

    Aqueueisassociatedwithanaddress.Therecanbemultiplequeuesperaddress.Onceanincomingmessageismatchedtoanaddress,themessagewillbesentontooneormoreofitsqueues,dependingontheroutingtypeconfigured.Queuescanbeconfiguredtobeautomaticallycreatedanddeleted.

    Aroutingtypedetermineshowmessagesaresenttothequeuesassociatedwithanaddress.AnApacheActiveMQArtemisaddresscanbeconfiguredwithtwodifferentroutingtypes.

    Table1.RoutingTypes

    Ifyouwantyourmessagesroutedto… Usethisroutingtype…

    Asinglequeuewithinthematchingaddress,inapoint-to-pointmanner. Anycast

    Everyqueuewithinthematchingaddress,inapublish-subscribemanner. Multicast

    Note:Itispossibletodefinemorethanoneroutingtypeperaddress,butthistypicallyresultsinananti-patternandisthereforenotrecommended.Ifanaddressdoesusebothroutingtypes,however,andtheclientdoesnotshowapreferenceforeitherone,thebrokertypicallydefaultstotheanycastroutingtype.TheoneexceptioniswhentheclientusestheMQTTprotocol.Inthatcase,thedefaultroutingtypeismulticast.|

    BasicAddressConfiguration

    AddressModel

    35

  • Thefollowingexamplesshowhowtoconfigurebasicpointtopointandpublishsubscribeaddresses.

    Point-to-PointMessaging

    Point-to-pointmessagingisacommonscenarioinwhichamessagesentbyaproducerhasonlyoneconsumer.AMQPandJMSmessageproducersandconsumerscanmakeuseofpoint-to-pointmessagingqueues,forexample.Defineananycastroutingtypeforanaddresssothatitsqueuesreceivemessagesinapoint-to-pointmanner.

    Whenamessageisreceivedonanaddressusinganycast,ApacheActiveMQArtemislocatesthequeueassociatedwiththeaddressandroutesthemessagetoit.Whenconsumersrequesttoconsumefromtheaddress,thebrokerlocatestherelevantqueueandassociatesthisqueuewiththeappropriateconsumers.Ifmultipleconsumersareconnectedtothesamequeue,messagesaredistributedamongsteachconsumerequally,providingtheconsumersareequallyabletohandlethem.

    Figure1.PointtoPointMessaging

    ConfiguringanAddresstoUsetheAnycastRoutingType

    Openthefile/etc/broker.xmlforediting.

    Addanaddressconfigurationelementanditsassociatedqueueiftheydonotexistalready.

    NoteFornormalPointtoPointsemantics,thequeuenameMUSTmatchtheaddressname.

    AddressModel

    36

  • ...

    Publish-SubscribeMessaging

    Inapublish-subscribescenario,messagesaresenttoeveryconsumersubscribedtoanaddress.JMStopicsandMQTTsubscriptionsaretwoexamplesofpublish-subscribemessaging.

    Toconfigureanaddresswithpublish-subscribesemantics,createanaddresswiththemulticastroutingtype.

    Figure2.Publish-Subscribe

    ConfiguringanAddresstoUsetheMulticastRoutingType

    Openthefile/etc/broker.xmlforediting.

    Addanaddressconfigurationelementwithmulticastroutingtype.

    AddressModel

    37

  • ...

    Whenclientsconnecttoanaddresswiththemulticastelement,asubscriptionqueuefortheclientwillbeautomaticallycreatedfortheclient.Itisalsopossibletopre-configuresubscriptionqueuesandconnecttothemdirectlyusingthequeue'sFullyQualifiedQueuenames.

    Optionallyaddoneormorequeueelementstotheaddressandwrapthemulticastelementaroundthem.Thisstepistypicallynotneededsincethebrokerwillautomaticallycreateaqueueforeachsubscriptionrequestedbyaclient.

    ...

    Figure3.Point-to-PointwithTwoQueues

    Point-to-PointAddressmultipleQueues

    Itisactuallypossibletodefinemorethanonequeueonanaddresswithananycastroutingtype.Whenmessagesarereceivedonsuchanaddress,theyarefirstlydistributedevenlyacrossallthedefinedqueues.UsingFullyQualifiedQueuenames,clientsareabletoselectthequeuethattheywouldliketosubscribeto.Shouldmorethanoneconsumerconnectdirecttoasinglequeue,ApacheActiveMQArtemiswilltakecareofdistributingmessagesbetweenthem,asintheexampleabove.

    AddressModel

    38

  • Figure3.Point-to-PointwithTwoQueues

    Note:ThisishowApacheActiveMQArtemishandlesloadbalancingofqueuesacrossmultiplenodesinacluster.ConfiguringaPoint-to-PointAddresswithtwoqueues,openthefile/etc/broker.xmlforediting.

    AddanaddressconfigurationwithAnycastroutingtypeelementanditsassociatedqueues.

    ...

    Point-to-PointandPublish-SubscribeAddresses

    Itispossibletodefineanaddresswithbothpoint-to-pointandpublish-subscribesemanticsenabled.Whilenottypicallyrecommend,thiscanbeusefulwhenyouwant,forexample,aJMSQueuesayordersandaJMSTopicnamedorders.Thedifferentroutingtypesmaketheaddressesappeartobedistinct.

    UsinganexampleofJMSClients,themessagessentbyaJMSqueueproducerwillberoutedusingtheanycastroutingtype.MessagessentbyaJMStopicproducerwillusethemulticastroutingtype.InadditionwhenaJMStopicconsumerattaches,itwillbe

    AddressModel

    39

  • attachedtoit’sownsubscriptionqueue.JMSqueueconsumerwillbeattachedtotheanycastqueue.

    Figure4.[Point-to-PointandPublish-Subscribe

    Note:Thebehaviorinthisscenarioisdependentontheprotocolbeingused.ForJMSthereisacleardistinctionbetweentopicandqueueproducersandconsumers,whichmakethelogicstraightforward.OtherprotocolslikeAMQPdonotmakethisdistinction.AmessagebeingsentviaAMQPwillberoutedbybothanycastandmulticastandconsumerswilldefaulttoanycast.Formoreinformation,pleasecheckthebehaviorofeachprotocolinthesectionsonprotocols.

    TheXMLsnippetbelowisanexampleofwhattheconfigurationforanaddressusingbothanycastandmulticastwouldlooklikein/etc/broker.xml.Notethatsubscriptionqueuesaretypicallycreatedondemand,sothereisnoneedtolistspecificqueueelementsinsidethemulticastroutingtype.

    ...

    Howtofiltermessages

    AddressModel

    40

  • ApacheActiveMQArtemissupportstheabilitytofiltermessagesusingApacheArtemisFilterExpressions.

    Filterscanbeappliedintwoplaces,onaqueueandonaconsumer.

    QueueFilter

    Whenafilterisappliedtoaqueue,messagesarefilterbeforetheysenttothequeue.Toaddaqueuefilterusethefilterelementwhenconfiguringaqueue.Openupthebroker.xmlandaddanaddresswithaqueue,usingthefilterelementtoconfigureafilteronthisqueue.

    Thefilterdefinedaboveensuresthatonlymessageswithanattribute"color='red'"issenttothisqueue.

    ConsumerFilters

    ConsumerfiltersareappliedaftermessageshavereachedaqueueandaredefinedusingtheappropriateclientAPIs.ThefollowJMSexampleshowshowtoconsumerfilterswork.

    1. Defineanaddresswithasinglequeue,withnofilterapplied.

    AddressModel

    41

  • ...//Sendsomemessagesfor(inti=0;i<3;i++){TextMessageredMessage=senderSession.createTextMessage("Red");redMessage.setStringProperty("color","red");producer.send(redMessage)

    TextMessagegreenMessage=senderSession.createTextMessage("Green");greenMessage.setStringProperty("color","green");producer.send(greenMessage)}

    Atthispointthequeuewouldhave6messages:red,green,red,green,red,green

    MessageConsumerredConsumer=redSession.createConsumer(queue,"color='red'");

    TheredConsumerhasafilterthatonlymatches"red"messages.TheredConsumerwillreceive3messages.

    red,red,red

    Theresultingqueuewouldnowbe

    green,green,green

    CreatingandDeletingAddressesandQueuesAutomaticallyYoucanconfigureApacheActiveMQArtemistoautomaticallycreateaddressesandqueues,andthendeletethemwhentheyarenolongerinuse.Thissavesyoufromhavingtopreconfigureeachaddressandqueuebeforeaclientcanconnecttoit.Automaticcreationanddeletionisconfiguredonaperaddressbasisandiscontrolledbyfollowing:

    AddressModel

    42

  • Parameter Description

    auto-create-addresses

    Whensettotrue,thebrokerwillcreatetheaddressrequestedbytheclientifitdoesnotexistalready.Thedefaultistrue.

    auto-delete-addresses

    Whensettotrue,thebrokerwillbedeleteanyauto-createdadddressonceallofit’squeueshavebeendeleted.Thedefaultistrue

    default-address-routing-type

    Theroutingtypetouseiftheclientdoesnotspecifyone.PossiblevaluesareMULTICASTandANYCAST.Seeearlierinthischapterformoreinformationaboutroutingtypes.ThedefaultvalueisMULTICAST.

    ConfiguringanAddresstobeAutomaticallyCreated

    Editthefile/etc/broker.xmlandaddtheauto-create-addresseselementtotheaddress-settingyouwantthebrokertoautomaticallycreate.

    (Optional)Addtheaddress-settingifitdoesnotexits.UsethematchparameterandtheTheApacheActiveMQArtemisWildcardSyntaxtomatchmorethanonespecificaddress.

    Setauto-create-addressestotrue

    (Optional)AssignMULTICASTorANYCASTasthedefaultroutingtypefortheaddress.

    Theexamplebelowconfiguresanaddress-settingtobeautomaticallycreatedbythebroker.ThedefaultroutingtypetobeusedifnotspecifiedbytheclientisMULTICAST.Notethatwildcardsyntaxisused.Anyaddressstartingwith/news/politics/willbeautomaticallycreatedbythebroker.

    ...trueMULTICAST...

    AddressModel

    43

  • ConfiguringanAddresstobeAutomaticallyDeleted

    Editthefile/etc/broker.xmlandaddtheauto-delete-addresseselementtotheaddress-settingyouwantthebrokertoautomaticallycreate.

    (Optional)Addtheaddress-settingifitdoesnotexits.UsethematchparameterandtheTheApacheActiveMQArtemisWildcardSyntaxtomatchmorethanonespecificaddress.

    Setauto-delete-addressestotrue

    Theexamplebelowconfiguresanaddress-settingtobeautomaticallydeletedbythebroker.Notethatwildcardsyntaxisused.Anyaddressrequestbytheclientthatstartswith/news/politics/isconfiguredtobeautomaticallydeletedbythebroker.

    ...trueMULTICAST...

    FullyQualifiedQueueNamesInternallythebrokermapsaclient’srequestforanaddresstospecificqueues.Thebrokerdecidesonbehalfoftheclientwhichqueuestosendmessagestoorfromwhichqueuetoreceivemessages.However,moreadvancedusecasesmightrequirethattheclientspecifyaqueuedirectly.Inthesesituationstheclientanduseafullyqualifiedqueuename,byspecifyingboththeaddressnameandthequeuename,separatedbya::.

    CurrentlyArtemissupportsfullyqualifiedqueuenamesonCore,AMQP,JMS,OpenWire,MQTTandStompprotocolsforreceivingmessagesonly.

    SpecifyingaFullyQualifiedQueueName

    AddressModel

    44

  • Inthisexample,theaddressfooisconfiguredwithtwoqueuesq1,q2asshownintheconfigurationbelow.

    ...

    Intheclientcode,useboththeaddressnameandthequeuenamewhenrequestingaconnectionfromthebroker.Remembertousetwocolons,::,toseparatethenames,asintheexampleJavacodebelow.

    StringFQQN="foo::q1";Queueq1session.createQueue(FQQN);MessageConsumerconsumer=session.createConsumer(q1);

    ConfiguringaPrefixtoConnecttoaSpecificRoutingTypeNormally,ifaApacheActiveMQArtemisreceivsamessagesenttoaparticularaddress,thathasbothanycastandmulticastroutingtypesenable,ApacheActiveMQArtemiswillrouteacopyofthemessagetooneoftheanycastqueuesandtoallofthemulticastqueues.

    However,clientscanspecifyaspecialprefixwhenconnectingtoanaddresstospecifywhethertoconnectusinganycastormulticast.TheprefixesarecustomvaluesthataredesignatedusingtheanycastPrefixandmulticastPrefixparameterswithintheURLofanacceptor.

    ConfiguringanAnycastPrefix

    AddressModel

    45

  • In/etc/broker.xml,addtheanycastPrefixtotheURLofthedesiredacceptor.Intheexamplebelow,theacceptorisconfiguredtouseanycast://fortheanycastPrefix.Clientcodecanspecifyanycast://foo/iftheclientneedstosendamessagetoonlyoneoftheanycastqueues.

    ...tcp://0.0.0.0:61616?protocols=AMQP;anycastPrefix=anycast://...

    ConfiguringaMulticastPrefix

    In/etc/broker.xml,addtheanycastPrefixtotheURLofthedesiredacceptor.Intheexamplebelow,theacceptorisconfiguredtousemulticast://forthemulticastPrefix.Clientcodecanspecifymulticast://foo/iftheclientneedsthemessagesenttoonlythemulticastqueuesoftheaddress.

    ...tcp://0.0.0.0:61616?protocols=AMQP;multicastPrefix=multicast://...

    AdvancedAddressConfiguration

    Pre-configuringsubscriptionqueuesemantics

    Inmostcasesit’snotnecessarytopre-createsubscriptionqueues.Therelevantprotocolmanagerstakecareofcreatingsubscriptionqueueswhenclientsrequesttosubscribetoanaddress.Thetypeofsubscriptionqueuecreated,dependsonwhatpropertiesthe

    AddressModel

    46

  • clientrequest.E.g.durable,non-shared,sharedetc...Protocolmanagersusesspecialqueuenamestoidentifywhichqueuesbelowtowhichconsumersandusersneednotworryaboutthedetails.

    However,therearescenarioswhereausermaywanttousebrokersideconfigurationtopre-configureasubscription.AndlaterconnecttothatqueuedirectlyusingaFullyQualifiedQueuename..Theexamplesbelowshowhowtousebrokersideconfigurationtopre-configureaqueuewithpublishsubscribebehaviorforshared,non-shared,durableandnon-durablesubscriptionbehavior.

    Configuringashareddurablesubscriptionqueuewithupto10concurrentconsumers

    Thedefaultbehaviorforqueuesistonotlimitthenumberconnectedqueueconsumers.Themax-consumersparameterofthequeueelementcanbeusedtolimitthenumberofconnectedconsumersallowedatanyonetime.

    Openthefile/etc/broker.xmlforediting.

    ...true

    Configuringanon-shareddurablesubscription

    Thebrokercanbeconfiguredtopreventmorethanoneconsumerfromconnectingtoaqueueatanyonetime.Thesubscriptionstoqueuesconfiguredthiswayaretherefore"non-shared".Todothissimplysetthemax-consumersparameterto"1"

    AddressModel

    47

  • ...true

    Pre-configuringaqueueasanon-durablesubscriptionqueue

    Non-durablesubscriptionsareagainusuallymanagedbytherelevantprotocolmanager,bycreatinganddeletingtemporaryqueues.

    Ifauserrequirestopre-createaqueuethatbehaveslikeanon-durablesubscriptionqueuethepurge-on-no-consumersflagcanbeenabledonthequeue.Whenpurge-on-no-consumersissettotrue.Thequeuewillnotstartreceivingmessagesuntilaconsumerisattached.Whenthelastconsumerisdetachedfromthequeue.Thequeueispurged(it'smessagesareremoved)andwillnotreceiveanymoremessagesuntilanewconsumerisattached.

    Openthefile/etc/broker.xmlforediting.

    ...

    AdditionalInformation:ProtocolManagers,Address

    AddressModel

    48

  • AprotocolmanagermapsprotocolspecificconceptsdowntotheApacheActiveMQArtemiscoremodelofaddresses,queuesandroutingtypes.Forexample,whenaclientsendsaMQTTsubscriptionpacketwiththeaddresses

    /house/room1/lights/house/room2/lights

    TheMQTTprotocolmanagerunderstandsthatthetwoaddressesrequiremulticastsemantics.Theprotocolmanagerwillthereforefirstlooktoensurethatmulticastisenabledforbothaddresses.Ifnot,itwillattempttodynamicallycreatethem.Ifsuccessful,theprotocolmanagerwillthencreatespecialsubscriptionqueueswithspecialnames,foreachsubscriptionrequestedbytheclient.

    Thespecialnameallowstheprotocolmanagertoquicklyidentifytherequiredclientsubscriptionqueuesshouldtheclientdisconnectandreconnectatalaterdate.Ifthesubscriptionistemporarytheprotocolmanagerwilldeletethequeueoncetheclientdisconnects.

    Whenaclientrequeststosubscribetoapointtopointaddress.Theprotocolmanagerwilllookupthequeueassociatedwiththepointtopointaddress.Thisqueueshouldhavethesamenameastheaddresss.

    Note:Ifthequeueisautocreated,itwillbeautodeletedoncetherearenoconsumersandnomessagesinit.FormoreinformationonautocreateseethenextsectionConfiguringAddressesandQueuesviaAddressSettings

    ConfiguringAddressesandQueuesviaAddressSettingsTherearesomeattributesthataredefinedagainstanaddresswildcardratherthanaspecificaddress/queue.Hereanexampleofanaddress-settingentrythatwouldbefoundinthebroker.xmlfile.

    AddressModel

    49

  • DLA35000ExpiryQueuetrue100000200000truePAGE-1NOTIFY5

    Theideawithaddresssettings,isyoucanprovideablockofsettingswhichwillbeappliedagainstanyaddressesthatmatchthestringinthematchattribute.Intheaboveexamplethesettingswouldonlybeappliedtotheaddress"order.foo"addressbutyoucanalsousewildcardstoapplysettings.See:Thechapteronthewildcardsyntax.

    Forexample,ifyouusedthematchstringjms.queue.#thesettingswouldbeappliedtoalladdresseswhichstartwithjms.queue.whichwouldbeallJMSqueues.

    Themeaningofthespecificsettingsareexplainedfullythroughouttheusermanual,howeverhereisabriefdescriptionwithalinktotheappropriatechapterifavailable.

    max-delivery-attemptsdefineshowmanytimeacancelledmessagecanberedeliveredbeforesendingtothedead-letter-address.Afullexplanationcanbefoundhere.

    redelivery-delaydefineshowlongtowaitbeforeattemptingredeliveryofacancelledmessage.seehere.

    expiry-addressdefineswheretosendamessagethathasexpired.seehere.

    expiry-delaydefinestheexpirationtimethatwillbeusedformessageswhichareusingthedefaultexpirationtime(i.e.0).Forexample,ifexpiry-delayissetto"10"andamessagewhichisusingthedefaultexpirationtime(i.e.0)arrivesthenitsexpirationtimeof"0"willbechangedto"10."However,ifamessagewhichisusinganexpirationtimeof"20"arrivesthenitsexpirationtimewillremainunchanged.Settingexpiry-delayto"-1"willdisablethisfeature.Thedefaultis"-1".

    last-value-queuedefineswhetheraqueueonlyuseslastvaluesornot.seehere.

    AddressModel

    50

  • max-size-bytesandpage-size-bytesareusedtosetpagingonanaddress.Thisisexplainedhere.

    redistribution-delaydefineshowlongtowaitwhenthelastconsumerisclosedonaqueuebeforeredistributinganymessages.seehere.

    send-to-dla-on-no-route.Ifamessageissenttoanaddress,buttheserverdoesnotrouteittoanyqueues,forexample,theremightbenoqueuesboundtothataddress,ornoneofthequeueshavefiltersthatmatch,thennormallythatmessagewouldbediscarded.Howeverifthisparameterissettotrueforthataddress,ifthemessageisnotroutedtoanyqueuesitwillinsteadbesenttothedeadletteraddress(DLA)forthataddress,ifitexists.

    address-full-policy.Thisattributecanhaveoneofthefollowingvalues:PAGE,DROP,FAILorBLOCKanddetermineswhathappenswhenanaddresswheremax-size-bytesisspecifiedbecomesfull.ThedefaultvalueisPAGE.IfthevalueisPAGEthenfurthermessageswillbepagedtodisk.IfthevalueisDROPthenfurthermessageswillbesilentlydropped.IfthevalueisFAILthenfurthermessageswillbedroppedandanexceptionwillbethrownontheclient-side.IfthevalueisBLOCKthenclientmessageproducerswillblockwhentheytryandsendfurthermessages.SeethefollowingchaptersformoreinfoFlowControl,Paging.

    slow-consumer-threshold.Theminimumrateofmessageconsumptionallowedbeforeaconsumerisconsidered"slow."Measuredinmessages-per-second.Defaultis-1(i.e.disabled);anyothervalidvaluemustbegreaterthan0.

    slow-consumer-policy.Whatshouldhappenwhenaslowconsumerisdetected.KILLwillkilltheconsumer'sconnection(whichwillobviouslyimpactanyotherclientthreadsusingthatsameconnection).NOTIFYwillsendaCONSUMER_SLOWmanagementnotificationwhichanapplicationcouldreceiveandtakeactionwith.Seeslowconsumersformoredetailsonthisnotification.

    slow-consumer-check-period.Howoftentocheckforslowconsumersonaparticularqueue.Measuredinseconds.Defaultis5.Seeslowconsumersformoreinformationaboutslowconsumerdetection.

    auto-create-jms-queues.WhetherornotthebrokershouldautomaticallycreateaJMSqueuewhenaJMSmessageissenttoaqueuewhosenamefitstheaddressmatch(remember,aJMSqueueisjustacorequeuewhichhasthesameaddressandqueue

    AddressModel

    51

  • name)oraJMSconsumertriestoconnecttoaqueuewhosenamefitstheaddressmatch.Queueswhichareauto-createdaredurable,non-temporary,andnon-transient.Defaultistrue.ThisisDEPRECATED.Seeauto-create-queues.

    auto-delete-jms-queues.Whetherornotthebrokershouldautomaticallydeleteauto-createdJMSqueueswhentheyhaveboth0consumersand0messages.Defaultistrue.ThisisDEPRECATED.Seeauto-delete-queues.

    auto-create-jms-topics.WhetherornotthebrokershouldautomaticallycreateaJMStopicwhenaJMSmessageissenttoatopicwhosenamefitstheaddressmatch(remember,aJMStopicisjustacoreaddresswhichhasoneormorecorequeuesmappedtoit)oraJMSconsumertriestosubscribetoatopicwhosenamefitstheaddressmatch.Defaultistrue.ThisisDEPRECATED.Seeauto-create-addresses.

    auto-delete-jms-topics.Whetherornotthebrokershouldautomaticallydeleteauto-createdJMStopicsoncethelastsubscriptiononthetopichasbeenclosed.Defaultistrue.ThisisDEPRECATED.Seeauto-delete-addresses.

    auto-create-queues.Whetherornotthebrokershouldautomaticallycreateaqueuewhenamessageissentoraconsumertriestoconnecttoaqueuewhosenamefitstheaddressmatch.Queueswhichareauto-createdaredurable,non-temporary,andnon-transient.Defaultistrue.

    auto-delete-queues.Whetherornotthebrokershouldautomaticallydeleteauto-createdqueueswhentheyhaveboth0consumersand0messages.Defaultistrue.

    config-delete-queues.Howthebrokershouldhandlequeuesdeletedonconfigreload,bydeletepolicy:OFForFORCE.Seeconfig-reloadformoredetails.DefaultisOFF.

    auto-create-addresses.Whetherornotthebrokershouldautomaticallycreateanaddresswhenamessageissenttooraconsumertriestoconsumefromaqueuewhichismappedtoanaddresswhosenamefitstheaddressmatch.Defaultistrue.

    auto-delete-addresses.Whetherornotthebrokershouldautomaticallydeleteauto-createdaddressesoncetheaddressnolongerhasanyqueues.Defaultistrue.

    config-delete-addresses.Howthebrokershouldhandleaddressesdeletedonconfigreload,bydeletepolicy:OFForFORCE.Seeconfig-reloadformoredetails.DefaultisOFF.

    AddressModel

    52

  • UsingJMSAlthoughApacheActiveMQArtemisprovidesaJMSagnosticmessagingAPI,manyuserswillbemorecomfortableusingJMS.

    JMSisaverypopularAPIstandardformessaging,andmostmessagingsystemsprovideaJMSAPI.IfyouarecompletelynewtoJMSwesuggestyoufollowtheOracleJMStutorial-afullJMStutorialisoutofscopeforthisguide.

    ApacheActiveMQArtemisalsoshipswithawiderangeofexamples,manyofwhichdemonstrateJMSAPIusage.AgoodplacetostartwouldbetoplayaroundwiththesimpleJMSQueueandTopicexample,butwealsoprovideexamplesformanyotherpartsoftheJMSAPI.AfulldescriptionoftheexamplesisavailableinExamples.

    Inthissectionwe'llgothroughthemainstepsinconfiguringtheserverforJMSandcreatingasimpleJMSprogram.We'llalsoshowhowtoconfigureanduseJNDI,andalsohowtouseJMSwithApacheActiveMQArtemiswithoutusinganyJNDI.

    AsimpleorderingsystemForthischapterwe'regoingtouseaverysimpleorderingsystemasourexample.Itisasomewhatcontrivedexamplebecauseofitsextremesimplicity,butitservestodemonstratetheverybasicsofsettingupandusingJMS.

    WewillhaveasingleJMSQueuecalledOrderQueue,andwewillhaveasingleMessageProducersendinganordermessagetothequeueandasingleMessageConsumerconsumingtheordermessagefromthequeue.

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

    JNDIConfiguration

    UsingJMS

    53

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

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

    Note

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

    ConnectionFactoryJNDIAJMSconnectionfactoryisusedbytheclienttomakeconnectionstotheserver.Itknowsthelocationoftheserveritisconnectingto,aswellasmanyotherconfigurationparameters.

    Here'sasimpleexampleoftheJNDIcontextenvironmentforaclientlookingupaconnectionfactorytoaccessanembeddedinstanceofApacheActiveMQArtemis:

    java.naming.factory.initial=org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactoryconnectionFactory.invmConnectionFactory=vm://0

    InthisinstancewehavecreatedaconnectionfactorythatisboundtoinvmConnectionFactory,anyentrywithprefixconnectionFactory.willcreateaconnectionfactory.

    IncertainsituationstherecouldbemultipleserverinstancesrunningwithinaparticularJVM.InthatsituationeachserverwouldtypicallyhaveanInVMacceptorwithauniqueserver-ID.AclientusingJMSandJNDIcanaccountforthisbyspecifyingaconnctionfactoryforeachserver,likeso:

    UsingJMS

    54

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

    HereisalistofallthesupportedURLschemes:

    vm

    tcp

    udp

    jgroups

    Mostclientswon'tbeconnectingtoanembeddedbroker.Clientswillmostcommonlyconnectacrossanetworkaremotebroker.Here'sasimpleexampleofaclientconfiguringaconnectionfactorytoconnecttoaremotebrokerrunningonmyhost:5445:

    java.naming.factory.initial=org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactoryconnectionFactory.ConnectionFactory=tcp://myhost:5445

    IntheexampleabovetheclientisusingthetcpschemefortheproviderURL.Aclientmayalsospecifymultiplecomma-delimitedhost:portcombinationsintheURL(e.g.(tcp://remote-host1:5445,remote-host2:5445)).Whetherthereisoneormanyhost:portcombinationsintheURLtheyaretreatedastheinitialconnector(s)fortheunderlyingconnection.

    Theudpschemeisalsosupportedwhichshoulduseahost:portcombinationthatmatchesthegroup-addressandgroup-portfromthecorrespondingbroadcast-groupconfiguredontheActiveMQArtemisserver(s).

    EachschemehasaspecificsetofpropertieswhichcanbesetusingthetraditionalURLquerystringformat(e.g.scheme://host:port?key1=value1&key2=value2)tocustomizetheunderlyingtransportmechanism.Forexample,ifaclientwantedtoconnecttoaremoteserverusingTCPandSSLitwouldcreateaconnectionfactorylikeso,tcp://remote-host:5445?ssl-enabled=true.

    AllthepropertiesavailableforthetcpschemearedescribedinthedocumentationregardingtheNettytransport.

    UsingJMS

    55

  • Noteifyouareusingthetcpschemeandmultipleaddressesthenaquerycanbeappliedtoalltheurl'sorjusttoanindividualconnector,sowhereyouhave

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

    clientID=1234

    thenthehttpEnabledpropertyisonlysetontheindividualconnectorswhereastheclientIdissetontheactualconnectionfactory.AnyconnectorspecificpropertiessetonthewholeURIwillbeappliedtoalltheconnectors.

    Theudpschemesupports4properties:

    localAddress-Ifyouarerunningwithmultiplenetworkinterfacesonthesamemachine,youmaywanttospecifythatthediscoverygrouplistensonlyonlyaspecificinterface.Todothisyoucanspecifytheinterfaceaddresswiththisparameter.

    localPort-Ifyouwanttospecifyalocalporttowhichthedatagramsocketisboundyoucanspecifyithere.Normallyyouwouldjustusethedefaultvalueof-1whichsignifiesthatananonymousportshouldbeused.ThisparameterisalwaysspecifiedinconjunctionwithlocalAddress.

    refreshTimeout-Thisistheperiodthediscoverygroupwaitsafterreceivingthelastbroadcastfromaparticularserverbeforeremovingthatserversconnectorpairentryfromitslist.Youwouldnormallysetthistoavaluesignificantlyhigherthanthebroadcast-periodonthebroadcastgroupotherwiseserversmightintermittentlydisappearfromthelisteventhoughtheyarestillbroadcastingduetoslightdifferencesintiming.Thisparameterisoptional,thedefaultvalueis10000milliseconds(10seconds).

    discoveryInitialWaitTimeout-Iftheconnectionfactoryisusedimmediatelyaftercreationthenitmaynothavehadenoughtimetoreceivedbroadcastsfromallthenodesinthecluster.Onfirstusage,theconnectionfactorywillmakesureitwaitsthislongsincecreationbeforecreatingthefirstconnection.Thedefaultvalueforthisparameteris10000milliseconds.

    Lastly,thejgroupsschemeissupportedwhichprovidesanalternativetotheudpschemeforserverdiscovery.TheURLpatterniseitherjgroups://channelName?file=jgroups-xml-conf-filenamewherejgroups-xml-conf-filenamereferstoanXMLfileontheclasspaththatcontainstheJGroupsconfigurationoritcanbejgroups://channelName?properties=some-jgroups-properties.InbothinstancethechannelNameisthenamegiventothejgroupschannelcreated.

    UsingJMS

    56

  • TherefreshTimeoutanddiscoveryInitialWaitTimeoutpropertiesaresupportedjustlikewithudp.

    Thedefaulttypeforthedefaultconnectionfactoryisoftypejavax.jms.ConnectionFactory.Thiscanbechangedbysettingthetypelikeso

    java.naming.factory.initial=org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactoryjava.naming.provider.url=tcp://localhost:5445?type=CF

    Inthisexampleitisstillsettothedefault,belowshowsalistoftypesthatcanbeset.

    ConfigurationforConnectionFactoryTypes

    type interface

    CF(default) javax.jms.ConnectionFactory

    XA_CF javax.jms.XAConnectionFactory

    QUEUE_CF javax.jms.QueueConnectionFactory

    QUEUE_XA_CF javax.jms.XAQueueConnectionFactory

    TOPIC_CF javax.jms.TopicConnectionFactory

    TOPIC_XA_CF javax.jms.XATopicConnectionFactory

    DestinationJNDI

    JMSdestinationsarealsotypicallylookedupviaJNDI.Aswithconnectionfactories,destinationscanbeconfiguredusingspecialpropertiesintheJNDIcontextenvironment.Thepropertynameshouldfollowthepattern:queue.ortopic..ThepropertyvalueshouldbethenameofthequeuehostedbytheApacheActiveMQArtemisserver.Forexample,iftheserverhadaJMSqueueconfiguredlikeso:

    Andiftheclientwantedtobindthisqueueto"queues/OrderQueue"thentheJNDIpropertieswouldbeconfiguredlikeso:

    UsingJMS

    57

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

    Itisalsopossibletolook-upJMSdestinationswhichhaven'tbeenconfiguredexplicitlyintheJNDIcontextenvironment.ThisispossibleusingdynamicQueues/ordynamicTopics/inthelook-upstring.Forexample,iftheclientwantedtolook-uptheaforementioned"OrderQueue"itcoulddososimplybyusingthestring"dynamicQueues/OrderQueue".Note,thetextthatfollowsdynamicQueues/ordynamicTopics/mustcorrespondexactlytothenameofthedestinationontheserver.

    Thecode

    Here'sthecodefortheexample:

    Firstwe'llcreateaJNDIinitialcontextfromwhichtolookupourJMSobjects.Iftheabovepropertiesaresetinjndi.propertiesanditisontheclasspaththenanynew,emptyInitialContextwillbeinitializedusingthoseproperties:

    UsingJMS

    58

  • InitialContextic=newInitialContext();

    //Nowwe'lllookuptheconnectionfactoryfromwhichwecancreate//connectionstomyhost:5445:

    ConnectionFactorycf=(ConnectionFactory)ic.lookup("ConnectionFactory");

    //AndlookuptheQueue:

    QueueorderQueue=(Queue)ic.lookup("queues/OrderQueue");

    //NextwecreateaJMSconnectionusingtheconnectionfactory:

    Connectionconnection=cf.createConnection();

    //AndwecreateanontransactedJMSSession,withAUTO\_ACKNOWLEDGE//acknowledgemode:

    Sessionsession=connection.createSession(false,Session.AUTO_ACKNOWLEDGE);

    //WecreateaMessageProducerthatwillsendorderstothequeue:

    MessageProducerproducer=session.createProducer(orderQueue);

    //AndwecreateaMessageConsumerwhichwillconsumeordersfromthe//queue:

    MessageConsumerconsumer=session.createConsumer(orderQueue);

    //Wemakesurewestarttheconnection,ordeliverywon'toccuronit:

    connection.start();

    //WecreateasimpleTextMessageandsendit:

    TextMessagemessage=session.createTextMessage("Thisisanorder");producer.send(message);

    //Andweconsumethemessage:

    TextMessagereceivedMessage=(TextMessage)consumer.receive();System.out.println("Gotorder:"+receivedMessage.getText());

    Itisassimpleasthat.ForawiderangeofworkingJMSexamplespleaseseetheexamplesdirectoryinthedistribution.

    UsingJMS

    59

  • Warning

    PleasenotethatJMSconnections,sessions,producersandconsumersaredesignedtobere-used.

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

    DirectlyinstantiatingJMSResourceswithoutusingJNDI

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

    WithApacheActiveMQArtemisyoucandoexactlythat.ApacheActiveMQArtemissupportsthedirectinstantiationofJMSQueue,TopicandConnectionFactoryinstances,soyoudon'thavetouseJNDIatall.

    Forafullworkingexampleofdirectinstantiationpleaselookatthe"InstantiateJMSObjectsDirectly"exampleundertheJMSsectionoftheexamples.SeetheExamplessectionformoreinfo.

    Here'soursimpleexample,rewrittentonotuseJNDIatall:

    WecreatetheJMSConnectionFactoryobjectviatheActiveMQJMSClientUtilityclass,noteweneedtoprovideconnectionparametersandspecifywhichtransportweareusing,formoreinformationonconnectorspleaseseeConfiguringtheTransport.

    UsingJMS

    60

  • TransportConfigurationtransportConfiguration=newTransportConfiguration(NettyConnectorFactory.class.getName());

    ConnectionFactorycf=ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF,transportConfiguration);

    //WealsocreatetheJMSQueueobjectviatheActiveMQJMSClientUtility//class:

    QueueorderQueue=ActiveMQJMSClient.createQueue("OrderQueue");

    //NextwecreateaJMSconnectionusingtheconnectionfactory:

    Connectionconnection=cf.createConnection();

    //AndwecreateanontransactedJMSSession,withAUTO\_ACKNOWLEDGE//acknowledgemode:

    Sessionsession=connection.createSession(false,Session.AUTO_ACKNOWLEDGE);

    //WecreateaMessageProducerthatwillsendorderstothequeue:

    MessageProducerproducer=session.createProducer(orderQueue);

    //AndwecreateaMessageConsumerwhichwillconsumeordersfromthe//queue:

    MessageConsumerconsumer=session.createConsumer(orderQueue);

    //Wemakesurewestarttheconnection,ordeliverywon'toccuronit:

    connection.start();

    //WecreateasimpleTextMessageandsendit:

    TextMessagemessage=session.createTextMessage("Thisisanorder");producer.send(message);

    //Andweconsumethemessage:

    TextMessagereceivedMessage=(TextMessage)consumer.receive();System.out.println("Gotorder:"+receivedMessage.getText());

    SettingTheClientID

    ThisrepresentstheclientidforaJMSclientandisneededforcreatingdurablesubscriptions.ItispossibletoconfigurethisontheconnectionfactoryandcanbesetviatheclientIdelement.Anyconnectioncreatedbythisconnectionfactorywillhavethis

    UsingJMS

    61

  • setasitsclientid.

    SettingTheBatchSizeforDUPS_OK

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

    SettingTheTransactionBatchSize

    Whenreceivingmessagesinatransactionitispossibletoconfiguretheconsumertosendacknowledgementsinbatchesratherthanindividuallysavingvaluablebandwidth.ThiscanbeconfiguredontheconnectionfactoryviathetransactionBatchSizeelementandissetinbytes.Thedefaultis1024*1024.

    SettingTheDestinationCache

    ManyframeworkssuchasSpringresolvethedestinationbynameoneveryoperation,thiscancauseaperformanceissueandextracallstothebroker,inascenariowheredestinations(addresses)arepermanentbrokerside,suchastheyaremanagedbyaplatformoroperationsteam.usingdestinationCacheelement,youcantoggleonthedestinationcachetoimprovetheperformanceandreducethecallstothebroker.Thisshouldnotbeusedifdestinations(addresses)arenotpermanentbrokerside,asindynamiccreation/deletion.

    UsingJMS

    62

  • UsingCoreApacheActiveMQArtemiscoreisacompletelyJMS-agnosticmessagingsystemwithitsownAPI.WecallthisthecoreAPI.

    Ifyoudon'twanttouseJMSorotherprotocolsyoucanusethecoreAPIdirectly.ThecoreAPIprovidesallthefunctionalityofJMSbutwithoutmuchofthecomplexity.ItalsoprovidesfeaturesthatarenotavailableusingJMS.

    CoreMessagingConceptsSomeofthecoremessagingconceptsaresimilartoJMSconcepts,butcoremessagingconceptsdifferinsomeways.IngeneralthecoremessagingAPIissimplerthantheJMSAPI,sinceweremovedistinctionsbetweenqueues,topicsandsubscriptions.We'lldiscusseachofthemajorcoremessagingconceptsinturn,buttoseetheAPIindetail,pleaseconsulttheJavadoc.

    Message

    Amessageistheunitofdatawhichissentbetweenclientsandservers.

    Amessagehasabodywhichisabuffercontainingconvenientmethodsforreadingandwritingdataintoit.

    Amessagehasasetofpropertieswhicharekey-valuepairs.Eachpropertykeyisastringandpropertyvaluescanbeoftypeinteger,long,short,byte,byte[],String,double,floatorboolean.

    Amessagehasanaddressitisbeingsentto.Whenthemessagearrivesontheserveritisroutedtoanyqueuesthatareboundtotheaddress-ifthequeuesareboundwithanyfilter,themessagewillonlyberoutedtothatqueueifthefiltermatches.Anaddressmayhavemanyqueuesboundtoitorevennone.Theremayalsobeentitiesotherthanqueues,likedivertsboundtoaddresses.

    Messagescanbeeitherdurableornondurable.Durablemessagesinadurablequeuewillsurviveaservercrashorrestart.Nondurablemessageswillneversurviveaservercrashorrestart.

    UsingCore

    63

  • Messagescanbespecifiedwithapriorityvaluebetween0and9.0representsthelowestpriorityand9representsthehighest.ApacheActiveMQArtemiswillattempttodeliverhigherprioritymessagesbeforelowerpriorityones.

    Messagescanbespecifiedwithanoptionalexpirytime.ApacheActiveMQArtemiswillnotdelivermessagesafteritsexpirytimehasbeenexceeded.

    Messagesalsohaveanoptionaltimestampwhichrepresentsthetimethemessagewassent.

    ApacheActiveMQArtemisalsosupportsthesending/consumingofverylargemessagesmuchlargerthancanfitinavailableRAMatanyonetime.

    Address

    Aservermaintainsamappingbetweenanaddressandasetofqueues.Zeroormorequeuescanbeboundtoasingleaddress.Eachqueuecanbeboundwithanoptionalmessagefilter.Whenamessageisrouted,itisroutedtothesetofqueuesboundtothemessage'saddress.Ifanyofthequeuesareboundwithafilterexpression,thenthemessagewillonlyberoutedtothesubsetofboundqueueswhichmatchthatfilterexpression.

    Otherentities,suchasdivertscanalsobeboundtoanaddressandmessageswillalsoberoutedthere.

    Note

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

    Forexample,aJMStopicwouldbeimplementedbyasingleaddresstowhichmanyqueuesarebound.Eachqueuerepresentsasubscriptionofthetopic.AJMSQueuewouldbeimplementedasasingleaddresstowhichonequeueisbound-thatqueuerepresentstheJMSqueue.

    Queue

    Queuescanbedurable,meaningthemessagestheycontainsurviveaservercrashorrestart,aslongasthemessagesinthemaredurable.Nondurablequeuesdonotsurviveaserverrestartorcrashevenifthemessagestheycontainaredurable.

    UsingCore

    64

  • Queuescanalsobetemporary,meaningtheyareautomaticallydeletedwhentheclientconnectionisclosed,iftheyarenotexplicitlydeletedbeforethat.

    Queuescanbeboundwithanoptionalfilterexpression.Ifafilterexpressionissuppliedthentheserverwillonlyroutemessagesthatmatchthatfilterexpressiontoanyqueuesboundtotheaddress.

    Manyqueuescanbeboundtoasingleaddress.Aparticularqueueisonlyboundtoamaximumofoneaddress.

    ServerLocator

    ClientsuseServerLocatorinstancestocreateClientSessionFactoryinstances.ServerLocatorinstancesareusedtolocateserversandcreateconnectionstothem.

    InJMStermsthinkofaServerLocatorinthesamewayyouwouldaJMSConnectionFactory.

    ServerLocatorinstancesarecreatedusingtheActiveMQClientfactoryclass.

    ClientSessionFactory

    ClientsuseClientSessionFactoryinstancestocreateClientSessioninstances.ClientSessionFactoryinstancesarebasicallytheconnectiontoaserver

    InJMStermsthinkofthemasJMSConnections.

    ClientSessionFactoryinstancesarecreatedusingtheServerLocatorclass.

    ClientSession

    AclientusesaClientSessionforconsumingandproducingmessagesandforgroupingthemintransactions.ClientSessioninstancescansupportbothtransactionalandnontransactionalsemanticsandalsoprovideanXAResourceinterfacesomessagingoperationscanbeperformedaspartofaJTAtransaction.

    ClientSessioninstancesgroupClientConsumersandClientProducers.

    ClientSessioninstancescanberegisteredwithanoptionalSendAcknowledgementHandler.Thisallowsyourclientcodetobenotifiedasynchronouslywhensentmessageshavesuccessfullyreachedtheserver.ThisuniqueApacheActiveMQArtemisfeature,allowsyoutohavefullguaranteesthatsentmessageshavereachedtheserverwithouthaving

    UsingCore

    65

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

  • toblockoneachmessagesentuntilaresponseisreceived.Blockingoneachmessagessentiscostlysinceitrequiresanetworkroundtripforeachmessagesent.BynotblockingandreceivingsendacknowledgementsasynchronouslyyoucancreatetrueendtoendasynchronoussystemswhichisnotpossibleusingthestandardJMSAPI.FormoreinformationonthisadvancedfeaturepleaseseethesectionGuaranteesofsendsandcommits.

    ClientConsumer

    ClientsuseClientConsumerinstancestoconsumemessagesfromaqueue.CoreMessagingsupportsbothsynchronousandasynchronousmessageconsumptionsemantics.ClientConsumerinstancescanbeconfiguredwithanoptionalfilterexpressionandwillonlyconsumemessageswhichmatchthatexpression.

    ClientProducer

    ClientscreateClientProducerinstancesonClientSessioninstancessotheycansendmessages.ClientProducerinstancescanspecifyanaddresstowhichallsentmessagesarerouted,ortheycanhavenospecifiedaddress,andtheaddressisspecifiedatsendtimeforthemessage.

    Warning

    PleasenotethatClientSession,ClientProducerandClientConsumerinstancesaredesignedtobere-used.

    It'sananti-patterntocreatenewClientSession,ClientProducerandClientConsumerinstancesforeachmessageyouproduceorconsume.Ifyoudothis,yourapplicationwillperformverypoorly.ThisisdiscussedfurtherinthesectiononperformancetuningPerformanceTuning.

    AsimpleexampleofusingCoreHere'saverysimpleprogramusingthecoremessagingAPItosendandreceiveamessage.Logicallyit'scomprisedoftwosections:firstlysettinguptheproducertowriteamessagetoanaddresss,andsecondly,creatingaqueuefortheconsumer,creatingtheconsumerandstartingit.

    UsingCore

    66

  • ServerLocatorlocator=ActiveMQClient.createServerLocatorWithoutHA(newTransportConfiguration(InVMConnectorFactory.class.getName()));

    //Inthissimpleexample,wejustuseonesessionforbothproducingandreceiving

    ClientSessionFactoryfactory=locator.createClientSessionFactory();ClientSessionsession=factory.createSession();

    //Aproducerisassociatedwithanaddress...

    ClientProducerproducer=session.createProducer("example");ClientMessagemessage=session.createMessage(true);message.getBodyBuffer().writeString("Hello");

    //Weneedaqueueattachedtotheaddress...

    session.createQueue("example","example",true);

    //Andaconsumerattachedtothequeue...

    ClientConsumerconsumer=session.createConsumer("example");

    //Oncewehaveaqueue,wecansendthemessage...

    producer.send(message);

    //Weneedtostartthesessionbeforewecan-receive-messages...

    session.start();ClientMessagemsgReceived=consumer.receive();

    System.out.println("message="+msgReceived.getBodyBuffer().readString());

    session.close();

    UsingCore

    67

  • UsingAMQPApacheActiveMQArtemisisalsoapureAMQP1.0broker,withahighperformantandfeaturecompleteprotocolmanagerforAMQP.

    YoucanuseanyAMQP1.0compatibleclients.

    Ashortlistincludes:

    qpidclientsattheqpidproject.NETClientsJavascriptNodeJSJavaScriptRHEA

    ...andmanyothers.

    MessageConversionsThebrokerwillnotperformanymessageconversiontoanyotherprotocolswhensendingAMQPandreceivingAMQP.

    HoweverifyouintendyourmessagetobereceivedonaAMQPJMSClient,youmustfollowtheJMSMappingconvention:

    JMSMappingConventions

    IfyousendabodytypethatisnotrecognizedbythisspecificationtheconversionbetweenAMQPandanyotherprotocolwillmakeitaBinaryMessage.

    So,makesureyoufollowtheseconventionsifyouintendtocrossprotocolsorlanguages.Especiallyonthemessagebody.

    Acompatibilitysetting,allowsaligningthenamingconventionofAMQPqueues(JMSDurableandSharedSubscriptions)withCORE.Forbackwardscompatibilityreasons,youneedtoexplicitlyenablethisviabrokerconfiguration:

    amqp-use-core-subscription-namingtrue-usequeuenamingconventionthatisalignedwithCORE.false(DEFAULT)-useoldernamingconvention.

    UsingAMQP

    68

    http://qpid.apache.org/download.htmlhttps://blogs.apache.org/activemq/entry/using-net-libraries-with-activemqhttps://github.com/noodlefrenzy/node-amqp10https://github.com/grs/rheahttps://www.oasis-open.org/committees/download.php/53086/amqp-bindmap-jms-v1.0-wd05.pdf

  • ExampleWehaveafewexamplesaspartoftheArtemisdistribution:

    .NET:

    ./examples/protocols/amqp/dotnetProtonCPP

    ./examples/protocols/amqp/proton-cppRuby

    ./examples/protocols/amqp/proton-rubyJava(UsingtheqpidJMSClient)

    ./examples/protocols/amqp/queue

    UsingAMQP

    69

  • MappingJMSConceptstotheCoreAPIThischapterdescribeshowJMSdestinationsaremappedtoApacheActiveMQArtemisaddresses.

    ApacheActiveMQArtemiscoreisJMS-agnostic.ItdoesnothaveanyconceptofaJMStopic.AJMStopicisimplementedincoreasanaddresswithname=(thetopicname)andwithaMULTICASTroutingtypewithzeroormorequeuesboundtoit.Eachqueueboundtothataddressrepresentsatopicsubscription.

    Likewise,aJMSqueueisimplementedasanaddresswithname=(theJMSqueuename)withanANYCASTroutingtypeassocatiedwithit.

    Note.ThatwhilstitispossibletoconfigureaJMStopicandqueuewiththesamename,itisnotarecommendedconfigurationforusewithcrossprotocol.

    MappingJMSConceptstotheCoreAPI

    70

  • TheClientClasspathApacheActiveMQArtemisrequiresseveraljarsontheClientClasspathdependingonwhethertheclientusesApacheActiveMQArtemisCoreAPI,JMS,andJNDI.

    Warning

    AllthejarsmentionedherecanbefoundinthelibdirectoryoftheApacheActiveMQArtemisdistribution.Besureyouonlyusethejarsfromthecorrectversionoftherelease,youmustnotmixandmatchversionsofjarsfromdifferentApacheActiveMQArtemisversions.Mixingandmatchingdifferentjarversionsmaycausesubtleerrorsandfailurestooccur.

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

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

    Note

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

    TheClientClasspath

    71

  • ExamplesTheApacheActiveMQArtemisdistributioncomeswithover90runout-of-the-boxexamplesdemonstratingmanyofthefeatures.

    Theexamplesareavailableinboththebinaryandsourcedistributionundertheexamplesdirectory.Examplesaresplitbythefollowingsourcetree:

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

    protocols-Protocolspecificexamplesopenwiremqttstompamqp

    AsetofJavaEEexamplesarealsoprovidedwhichneedWildFlyinstalledtobeabletorun.

    RunningtheExamplesTorunanyexample,simplycdintotheappropriateexampledirectoryandtypemvnverifyormvninstall(Fordetailspleasereadthereadme.htmlineachexampledirectory).

    Youcanusetheprofile-Pexamplestorunmultipleexamplesunderanyexampletree.

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

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

    #runninganexamplewithoutrunningtheservermvnverify-PnoServer

    Examples

    72

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

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

    SeveralexamplesuseUDPclusteringwhichmaynotworkinyourenvironmentbydefault.Onlinuxthecommandwouldbe:

    routeadd-net224.0.0.0netmask240.0.0.0devlo

    Thiscommandshouldberunasroot.Thiswillredirectanytrafficdirectedto224.0.0.0totheloopbackinterface.OnMacOSX,thecommandisslightlydifferent:

    sudorouteadd224.0.0.0127.0.0.1-netmask240.0.0.0

    AlltheexamplesusetheMavenplugin,whichcanbeusefulforrunningyourtestserversaswell.

    Thisisthecommonoutputwhenrunninganexample.OnthiscasetakenfromtheQueueexample:

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

    Examples

    73

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

    Examples

    74

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

    Youcannowstartthebrokerbyexecuting:

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

    Oryoucanrunthebrokerinthebackgroundusing:

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

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