322
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 1.28 1.29 1.30 1.31 1.32 1.33 1.34 1.35 1.36 1.37 Table of Contents Introduction Legal Notice Preface Project Info Versions Messaging Concepts Architecture Using the Server Upgrading Address Model Protocols and Interoperability AMQP MQTT STOMP OpenWire Core Mapping JMS Concepts to the Core API Using JMS The Client Classpath Examples Routing Messages With Wild Cards Wildcard Syntax Filter Expressions Persistence Configuring Transports Configuration Reload Detecting Dead Connections Detecting Slow Consumers Avoiding Network Isolation Detecting Broker Issues (Critical Analysis) Resource Manager Configuration Flow Control Guarantees of sends and commits Message Redelivery and Undelivered Messages Message Expiry Large Messages Paging 1

activemq.apache.org · 2019. 10. 8. · 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 1.28 1.29 1.30

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

  • 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

    1.28

    1.29

    1.30

    1.31

    1.32

    1.33

    1.34

    1.35

    1.36

    1.37

    TableofContentsIntroduction

    LegalNotice

    Preface

    ProjectInfo

    Versions

    MessagingConcepts

    Architecture

    UsingtheServer

    Upgrading

    AddressModel

    ProtocolsandInteroperability

    AMQP

    MQTT

    STOMP

    OpenWire

    Core

    MappingJMSConceptstotheCoreAPI

    UsingJMS

    TheClientClasspath

    Examples

    RoutingMessagesWithWildCards

    WildcardSyntax

    FilterExpressions

    Persistence

    ConfiguringTransports

    ConfigurationReload

    DetectingDeadConnections

    DetectingSlowConsumers

    AvoidingNetworkIsolation

    DetectingBrokerIssues(CriticalAnalysis)

    ResourceManagerConfiguration

    FlowControl

    Guaranteesofsendsandcommits

    MessageRedeliveryandUndeliveredMessages

    MessageExpiry

    LargeMessages

    Paging

    1

  • 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

    1.57.1

    1.57.2

    1.58

    1.59

    1.60

    1.61

    1.62

    1.63

    1.64

    1.65

    1.66

    1.67

    1.68

    1.69

    1.70

    1.71

    1.72

    1.73

    1.74

    1.75

    1.38ScheduledMessages

    Last-ValueQueues

    ExclusiveQueues

    MessageGrouping

    ConsumerPriority

    ExtraAcknowledgeModes

    Management

    ManagementConsole

    Metrics

    Security

    MaskingPasswords

    BrokerPlugins

    ResourceLimits

    TheJMSBridge

    ClientReconnectionandSessionReattachment

    DivertingandSplittingMessageFlows

    CoreBridges

    DuplicateMessageDetection

    Clusters

    Federation

    AddressFederation

    QueueFederation

    HighAvailabilityandFailover

    GracefulServerShutdown

    LibaioNativeLibraries

    Threadmanagement

    EmbeddedWebServer

    Logging

    RESTInterface

    EmbeddingtheBroker

    ApacheKaraf

    ApacheTomcat

    SpringIntegration

    CDIIntegration

    InterceptingOperations

    DataTools

    MavenPlugin

    UnitTesting

    TroubleshootingandPerformanceTuning

    ConfigurationReference

    2

  • ApacheActiveMQArtemisUserManualTheUsermanualisanindepthmanualonallaspectsofApacheActiveMQArtemis

    Introduction

    3

  • 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

    4

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

  • PrefaceWhatisApacheActiveMQArtemis?

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

    ApacheActiveMQArtemisisanexampleofMessageOrientedMiddleware(MoM).ForadescriptionofMoMsandothermessagingconceptspleaseseetheMessagingConcepts.

    WhyuseApacheActiveMQArtemis?Herearejustafewofthereasons:

    100%opensourcesoftware.ApacheActiveMQArtemisislicensedusingtheApacheSoftwareLicensev2.0tominimisebarrierstoadoption.

    ApacheActiveMQArtemisisdesignedwithusabilityinmind.

    WritteninJava.RunsonanyplatformwithaJava8+runtime,that'severythingfromWindowsdesktopstoIBMmainframes.

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

    Fullfeatureset.Allthefeaturesyou'dexpectinanyseriousmessagingsystem,andothersyouwon'tfindanywhereelse.

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

    Seamlesshighavailability.WeprovideaHAsolutionwithautomaticclientfailoversoyoucanguaranteezeromessagelossorduplicationineventofserverfailure.

    Hugelyflexibleclustering.Createclustersofserversthatknowhowtoloadbalancemessages.Linkgeographicallydistributedclustersoverunreliableconnectionstoformaglobalnetwork.Configureroutingofmessagesinahighlyflexibleway.

    Preface

    5

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

    SoftwareDownload

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

    ProjectInformation

    Ifyouhaveanyuserquestionspleaseuseouruserforum

    Ifyouhavedevelopmentrelatedquestions,pleaseuseourdeveloperforum

    PopinandchattousinourIRCchannel

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

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

    Andmanythankstoallourcontributors,botholdandnewwhohelpedcreateApacheActiveMQArtemis.

    ProjectInfo

    6

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

  • VersionsThischapterprovidesthefollowinginformationforeachrelease:

    Alinktothefullreleasenoteswhichincludesallissuesresolvedintherelease.Abrieflistof"highlights"whenapplicable.Ifnecessary,specificstepsrequiredwhenupgradingfromthepreviousversion.

    Note:Iftheupgradespansmultipleversionsthenthestepsfromeachversionneedtobefollowedinorder.Note:FollowthegeneralupgradeprocedureoutlinedintheUpgradingtheBrokerchapterinadditiontoanyversion-specificupgradeinstructionsoutlinedhere.

    2.9.0

    Fullreleasenotes.

    Thiswasalightrelease.Itincludedahandfulofbugfixes,afewimprovements,andonemajornewfeature.

    Highlights:

    Supportexportingmetrics.

    2.8.1Fullreleasenotes.

    Thiswasmainlyabug-fixreleasewithanotabledependencychangeimpactingversionupgrade.

    Upgradingfrom2.8.0

    DuetothedependencyupgrademadeonARTEMIS-2319thebrokerstartscriptsneedtobeadjustedafterupgrading.

    On*nix

    Locatethis ifstatementin bin/artemis:

    if[-z"$LOG_MANAGER"];then

    #thisistheonefoundwhentheserverwascreated

    LOG_MANAGER="$ARTEMIS_HOME/lib/jboss-logmanager-2.0.3.Final.jar"

    fi

    Thisneedstobereplacedwiththisblock:

    if[-z"$LOG_MANAGER"];then

    #thisistheonefoundwhentheserverwascreated

    LOG_MANAGER="$ARTEMIS_HOME/lib/jboss-logmanager-2.1.10.Final.jar"

    fi

    WILDFLY_COMMON=`ls$ARTEMIS_HOME/lib/wildfly-common*jar2>/dev/null`

    if[-z"$WILDFLY_COMMON"];then

    #thisistheonefoundwhentheserverwascreated

    WILDFLY_COMMON="$ARTEMIS_HOME/lib/wildfly-common-1.5.1.Final.jar"

    fi

    Noticethatthe jboss-logmanagerversionhaschangedandthereisalsoanew wildfly-commonlibrary.

    Versions

    7

    https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12345527https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12345432https://issues.apache.org/jira/browse/ARTEMIS-2319

  • Notmuchfurtherdownthereisthisline:

    -Xbootclasspath/a:"$LOG_MANAGER"\

    Thislineshouldbechangedtobe:

    -Xbootclasspath/a:"$LOG_MANAGER:$WILDFLY_COMMON"\

    OnWindows

    Locatethispartof JAVA_ARGSin etc/artemis.profile.cmd:

    -Xbootclasspath/a:%ARTEMIS_HOME%\lib\jboss-logmanager-2.1.10.Final.jar

    Thisneedstobereplacedwiththis:

    -Xbootclasspath/a:%ARTEMIS_HOME%\lib\jboss-logmanager-2.1.10.Final.jar;%ARTEMIS_HOME%\lib\wildfly-common-1.5.1.

    Final.jar}

    2.8.0

    Fullreleasenotes.

    Highlights:

    SupportActiveMQ5featureJMSXGroupFirstForConsumer.Clarifyhandshaketimeouterrorwithremoteaddress.SupportduplicatedetectionforAMQPmessagesthesameascore.

    2.7.0

    Fullreleasenotes.

    Highlights:

    Supportadvanceddestinationoptionslike consumersBeforeDispatchStartsand timeBeforeDispatchStartsfrom5.x.Addsupportfordelaysbeforedeletingaddressesandqueuesvia auto-delete-queues-delayand auto-delete-addresses-delayAddressSettings.SupportloggingHTTPaccess.AddaCLIcommandtopurgeaqueue.SupportuserandrolemanipulationforPropertiesLoginModuleviamanagementinterfaces.Dockerimages.Auditlogging.Implementingconsumerpriority.SupportFQQNforproducers.Trackroutedandunroutedmessagessenttoanaddress.SupportconnectionpoolinginLDAPLoginModule.Supportconfiguringadefaultconsumerwindowsizevia default-consumer-window-sizeAddressSetting.Supportmasking key-store-passwordand trust-store-passwordinmanagement.xml.Support JMSXGroupSeq-1toclose/resetmessagegroupsfrom5.x.AllowconfigurationofRMIregistryport.

    Versions

    8

    https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12345169https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12342977https://github.com/apache/activemq-artemis/tree/master/artemis-docker

  • Supportrouting-typeconfigurationoncorebridge.Moveartemis-nativeasitsownproject,asactivemq-artemis-native.Supportfederatedqueuesandaddresses.

    2.6.4

    Fullreleasenotes.

    Thiswasmainlyabug-fixreleasewithafewimprovementsacouplenotablenewfeatures:

    Highlights:

    Addedtheabilitytosetthetextmessagecontentonthe producerCLIcommand.Supportreloadloggingconfigurationatruntime.

    2.6.3

    Fullreleasenotes.

    Thiswasmainlyabug-fixreleasewithafewimprovementsbutnosubstantialnewfeatures.

    2.6.2Fullreleasenotes.

    Thiswasabug-fixreleasewithnosubstantialnewfeaturesorimprovements.

    2.6.1

    Fullreleasenotes.

    Thiswasabug-fixreleasewithnosubstantialnewfeaturesorimprovements.

    2.6.0Fullreleasenotes.

    Highlights:

    Supportregularexpressionsformatchingclientcertificates.Support SASL_EXTERNALforAMQPclients.Newexamplesshowingvirtualtopicmappingandexclusivequeuefeatures.

    2.5.0

    Fullreleasenotes.

    Highlights:

    Exclusiveconsumers.EquivalentActiveMQ5.xVirtualTopicnamingabilities.

    Versions

    9

    https://github.com/apache/activemq-artemis-nativehttps://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12344010https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12343472https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12343404https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12343356https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12342903https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12342127

  • SSLCertificaterevocationlist.Last-valuequeuesupportforOpenWire.Supportmaskedpasswordsinbootstrap.xmandlogin.configConfigurablebrokerpluginimplementationforloggingvariousbrokerevents(i.e. LoggingActiveMQServerPlugin).OptiontouseOpenSSLproviderforNettyviathe sslProviderURLparameter.Enablesplittingofbroker.xmlintomultiplefiles.Enhancedmessagecountandsizemetricsforqueues.

    Upgradingfrom2.4.0

    1. DuetochangesfromARTEMIS-1644any acceptorthatneedstobecompatiblewithHornetQand/orArtemis1.xclientsneedstohave anycastPrefix=jms.queue.;multicastPrefix=jms.topic.inthe acceptorurl.Thisprefixusedtobeconfiguredautomaticallybehindthesceneswhenthebrokerdetectedtheseoldtypesofclients,butthatbrokecertainuse-caseswithnopossiblework-around.SeeARTEMIS-1644formoredetails.

    2.4.0

    Fullreleasenotes.

    Highlights:

    JMXconfigurationviaXMLratherthanhavingtousesystempropertiesviacommandlineorstartscript.ConfigurationofmaxframepayloadlengthforSTOMPweb-socket.AbilitytoconfigureHAusingJDBCpersistence.Implementrole-basedaccesscontrolformanagementobjects.

    Upgradingfrom2.3.0

    1. Create /etc/management.xml.Attheveryleast,thefilemustcontainthis:

    ThisconfiguresrolebasedauthorisationforJMX.ReadmoreintheManagementdocumentation.2. Ifconfigured,removetheJolokiawarfilefromthe webelementin /etc/bootstrap.xml:

    ThisisnolongerrequiredastheJolokiaRESTinterfaceisnowintegratedintotheconsolewebapplication.

    Ifthefollowingisabsentandyoudesiretodeploythewebconsolethenadd:

    Note:theJolokiaRESTinterfaceURLwillnowbeat http://:/console/jolokia

    2.3.0Fullreleasenotes.

    Highlights:

    Webadminconsole!

    Versions

    10

    https://issues.apache.org/jira/browse/ARTEMIS-1644https://issues.apache.org/jira/browse/ARTEMIS-1644https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12341540https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12341247

  • CriticalAnalysisanddeadlockdetectiononbrokerSupportNettynativekqueueonMac.Last-valuequeueforAMQP

    Upgradingfrom2.2.0

    1. Ifyoudesiretodeploythewebconsolethenaddthefollowingtothe webelementin/etc/bootstrap.xml:

    2.2.0Fullreleasenotes.

    Highlights:

    ScheduledmessageswiththeSTOMPprotocol.SupportforJNDIReferenceFactoryandJNDIStorable.Abilitytodeletequeuesandaddresseswhenbroker.xmlchanges.ClientauthenticationviaKerberosTLSCipherSuites(RFC2712).

    2.1.0

    Fullreleasenotes.

    Highlights:

    Brokerpluginsupport.SupportNettynativeepollonLinux.Abilitytoconfigurearbitrarysecurityrolemappings.AMQPperformanceimprovements.

    2.0.0

    Fullreleasenotes.

    Highlights:

    Hugeupdateinvolvingasignificantrefactoringoftheaddressingmodelyieldingthefollowingbenefits:SimplerandmoreflexibleXMLconfiguration.Supportforadditionalmessaginguse-cases.EliminatesconfusingJMS-specificqueuenamingconventions(i.e."jms.queue."&"jms.topic."prefixes).

    PureencodingofmessagessoprotocolslikeAMQPdon'tneedtoconvertmessagesto"core"formatunlessabsolutelynecessary."MAPPED"journaltypeforincreasedperformanceincertainuse-cases.

    1.5.6

    Fullreleasenotes.

    Highlights:

    Versions

    11

    https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12340541https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12339963https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12338813https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12340547

  • Bugfixes.

    1.5.5

    Fullreleasenotes.

    Highlights:

    Bugfixes.

    1.5.4Fullreleasenotes.

    Highlights:

    SupportOracle12CforJDBCpersistence.Bugfixes.

    1.5.3Fullreleasenotes.

    Highlights:

    Support"bytenotation"(e.g."K","KB","Gb",etc.)inbrokerXMLconfiguration.CLIcommandtorecalculatedisksynctimes.Bugfixes.

    1.5.2

    Fullreleasenotes.

    Highlights:

    SupportforpagingusingJDBC.Bugfixes.

    1.5.1

    Fullreleasenotes.

    Highlights:

    SupportoutgoingconnectionsforAMQP.Bugfixes.

    1.5.0

    Fullreleasenotes.

    Highlights:

    Versions

    12

    https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12339947https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12339158https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12339575https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12338833https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12338661https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12338118

  • AMQPperformanceimprovements.JUnitruleimplementationsomessagingresourceslikebrokerscanbeeasilyconfiguredintests.BasicCDIintegration.Storeuser'spasswordinhashformbydefault.

    1.4.0

    Fullreleasenotes.

    Highlights:

    "Global"limitfordiskusage.DetectandreloadcertainXMLconfigurationchangesatruntime.MQTTinterceptors.Supportadding/deletingqueuesviaCLI.New"browse"securitypermissionforclientswhoonlywishtolookatmessages.OptiontopopulateJMSXUserID."Dualauthentication"supporttoauthenticateSSL-basedandnon-SSL-basedclientsdifferently.

    1.3.0Fullreleasenotes.

    Highlights:

    BettersupportofOpenWirefeatures(e.g.reconnect,producerflow-control,optimizedacknowledgements)SSLkeystorereloadatruntime.InitialsupportforJDBCpersistence.Supportscheduledmessagesonlast-valuequeue.

    1.2.0Fullreleasenotes.

    Highlights:

    ImprovementsaroundperformanceOSGisupport.Supportfunctionalityequivalenttoall5.xJAASloginmodulesincluding:

    PropertiesfileLDAPSSLcertificate"Guest"

    1.1.0

    Fullreleasenotes.

    Highlights:

    MQTTsupport.TheexamplesnowusetheCLIprogrammaticallytocreate,start,stop,etc.serversreflectingrealcasesusedinproduction.

    Versions

    13

    https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12336052https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12328978https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12333274https://issues.apache.org/jira/secure/ReleaseNote.jspa?version=12332642&projectId=12315920

  • CLIimprovements.Therearenewtoolstocompactthejournalandadditionalimprovementstotheuserexperience.Configurableresourcelimits.Abilitytodisableserver-sidemessageload-balancing.

    1.0.0

    Fullreleasenotes.

    Highlights:

    Firstreleaseofthedonatedcode-baseasActiveMQArtemis!LotsoffeaturesforparitywithActiveMQ5.xincluding:

    OpenWiresupportAMQP1.0supportURLbasedconnectionsAuto-createaddresses/queuesJolokiaintegration

    Versions

    14

    https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12315920&version=12328953http://mail-archives.apache.org/mod_mbox/activemq-dev/201407.mbox/%3cCAKF+bsovr7Hvn-rMYkb3pF6hoGjx7nuJWzT_Nh8MyC4usRBX9A@mail.gmail.com%3e

  • MessagingConceptsApacheActiveMQArtemisisanasynchronousmessagingsystem,anexampleofMessageOrientedMiddleware,we'lljustcallthemmessagingsystemsintheremainderofthisbook.

    We'llfirstpresentabriefoverviewofwhatkindofthingsmessagingsystemsdo,wherethey'reusefulandthekindofconceptsyou'llhearaboutinthemessagingworld.

    Ifyou'realreadyfamiliarwithwhatamessagingsystemisandwhatit'scapableof,thenyoucanskipthischapter.

    GeneralConceptsMessagingsystemsallowyoutolooselycoupleheterogeneoussystemstogether,whilsttypicallyprovidingreliability,transactionsandmanyotherfeatures.

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

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

    Messagingsystemsdecouplethesendersofmessagesfromtheconsumersofmessages.Thesendersandconsumersofmessagesarecompletelyindependentandknownothingofeachother.Thisallowsyoutocreateflexible,looselycoupledsystems.

    Often,largeenterprisesuseamessagingsystemtoimplementamessagebuswhichlooselycouplesheterogeneoussystemstogether.MessagebusesoftenformthecoreofanEnterpriseServiceBus.(ESB).Usingamessagebustode-coupledisparatesystemscanallowthesystemtogrowandadaptmoreeasily.Italsoallowsmoreflexibilitytoaddnewsystemsorretireoldonessincetheydon'thavebrittledependenciesoneachother.

    Messagingstyles

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

    Point-to-Point

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

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

    Aclassicexampleofpointtopointmessagingwouldbeanorderqueueinacompany'sbookorderingsystem.Eachorderisrepresentedasamessagewhichissenttotheorderqueue.Let'simaginetherearemanyfrontendorderingsystemswhichsend

    MessagingConcepts

    15

    https://en.wikipedia.org/wiki/Message-oriented_middlewarehttps://en.wikipedia.org/wiki/Remote_procedure_callhttps://en.wikipedia.org/wiki/Enterprise_service_bushttps://en.wikipedia.org/wiki/Message_queuehttps://en.wikipedia.org/wiki/Publish_subscribe

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

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

    Publish-Subscribe

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

    Therecanbemanysubscriptionsonatopic,asubscriptionisjustanotherwordforaconsumerofatopic.Eachsubscriptionreceivesacopyofeachmessagesenttothetopic.Thisdiffersfromthemessagequeuepatternwhereeachmessageisonlyconsumedbyasingleconsumer.

    Subscriptionscanoptionallybedurablewhichmeanstheyretainacopyofeachmessagesenttothetopicuntilthesubscriberconsumesthem-eveniftheservercrashesorisrestartedinbetween.Non-durablesubscriptionsonlylastamaximumofthelifetimeoftheconnectionthatcreatedthem.

    Anexampleofpublish-subscribemessagingwouldbeanewsfeed.Asnewsarticlesarecreatedbydifferenteditorsaroundtheworldtheyaresenttoanewsfeedtopic.Therearemanysubscribersaroundtheworldwhoareinterestedinreceivingnewsitems-eachonecreatesasubscriptionandthemessagingsystemensuresthatacopyofeachnewsmessageisdeliveredtoeachsubscription.

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

    Inothercasesyoumaynotcareaboutaonceandonlyoncedeliveryguaranteeandarehappytocopewithduplicatedeliveriesorlostmessages-anexampleofthismightbetransientstockpriceupdates-whicharequicklysupersededbythenextupdateonthesamestock.Themessagingsystemallowsyoutoconfigurewhichdeliveryguaranteesyourequire.

    Transactions

    Messagingsystemstypicallysupportthesendingandacknowledgementofmultiplemessagesinasinglelocaltransaction.ApacheActiveMQArtemisalsosupportsthesendingandacknowledgementofmessageaspartofalargeglobaltransaction-usingtheJavamappingofXA:JTA.

    Durability

    MessagingConcepts

    16

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

  • Messagesareeitherdurableornondurable.Durablemessageswillbepersistedinpermanentstorageandwillsurviveserverfailureorrestart.Nondurablemessageswillnotsurviveserverfailureorrestart.Examplesofdurablemessagesmightbeordersortrades,wheretheycannotbelost.Anexampleofanondurablemessagemightbeastockpriceupdatewhichistransitoryanddoesn'tneedtosurvivearestart.

    MessagingAPIsandprotocols

    Howdoclientapplicationsinteractwithmessagingsystemsinordertosendandconsumemessages?

    SeveralmessagingsystemsprovidetheirownproprietaryAPIswithwhichtheclientcommunicateswiththemessagingsystem.

    Therearealsosomestandardwaysofoperatingwithmessagingsystemsandsomeemergingstandardsinthisspace.

    Let'stakeabrieflookatthese:

    JavaMessageService(JMS)

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

    JMSisaverypopularAPIandisimplementedbymostmessagingsystems.JMSisonlyavailabletoclientsrunningJava.

    JMSdoesnotdefineastandardwireformat-itonlydefinesaprogrammaticAPIsoJMSclientsandserversfromdifferentvendorscannotdirectlyinteroperatesinceeachwillusethevendor'sowninternalwireprotocol.

    ApacheActiveMQArtemisprovidesafullycompliantJMS1.1andJMS2.0clientimplementation.

    SystemspecificAPIs

    ManysystemsprovidetheirownprogrammaticAPIforwhichtointeractwiththemessagingsystem.Theadvantageofthisitallowsthefullsetofsystemfunctionalitytobeexposedtotheclientapplication.API'slikeJMSarenotnormallyrichenoughtoexposealltheextrafeaturesthatmostmessagingsystemsprovide.

    ApacheActiveMQArtemisprovidesitsowncoreclientAPIforclientstouseiftheywishtohaveaccesstofunctionalityoverandabovethataccessibleviatheJMSAPI.

    PleaseseeCoreforusingtheCoreAPIwithApacheActiveMQArtemis.

    RESTfulAPI

    RESTapproachestomessagingareshowingalotinterestrecently.

    ItseemsplausiblethatAPIstandardsforcloudcomputingmayconvergeonaRESTstylesetofinterfacesandconsequentlyaRESTmessagingapproachisaverystrongcontenderforbecomingthede-factomethodformessaginginteroperability.

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

    TheadvantageofaRESTapproachwithHTTPisinitssimplicityandthefacttheinternetisalreadytunedtodealwithHTTPoptimally.

    PleaseseeRestInterfaceforusingApacheActiveMQArtemis'sRESTfulinterface.

    AMQP

    MessagingConcepts

    17

    https://en.wikipedia.org/wiki/Java_Message_Servicehttps://en.wikipedia.org/wiki/Representational_State_Transferhttps://en.wikipedia.org/wiki/AMQP

  • AMQPisaspecificationforinteroperablemessaging.Italsodefinesawireformat,soanyAMQPclientcanworkwithanymessagingsystemthatsupportsAMQP.AMQPclientsareavailableinmanydifferentprogramminglanguages.

    ApacheActiveMQArtemisimplementstheAMQP1.0specification.Anyclientthatsupportsthe1.0specificationwillbeabletointeractwithApacheActiveMQArtemis.

    PleaseseeAMQPforusingAMQPwithApacheActiveMQArtemis.

    MQTT

    MQTTisalightweightconnectivityprotocol.Itisdesignedtoruninenvironmentswheredeviceandnetworksareconstrained.OutoftheboxApacheActiveMQArtemissupportsversionMQTT3.1.1.AnyclientsupportingthisversionoftheprotocolwillworkagainstApacheActiveMQArtemis.

    PleaseseeMQTTforusingMQTTwithApacheActiveMQArtemis.

    STOMP

    Stompisaverysimpletextprotocolforinteroperatingwithmessagingsystems.Itdefinesawireformat,sotheoreticallyanyStompclientcanworkwithanymessagingsystemthatsupportsStomp.Stompclientsareavailableinmanydifferentprogramminglanguages.

    PleaseseeStompforusingSTOMPwithApacheActiveMQArtemis.

    OpenWire

    ActiveMQ5.xdefinesitsownwireprotocol:OpenWire.InordertosupportActiveMQ5.xclients,ApacheActiveMQArtemissupportsOpenWire.AnyActiveMQ5.12.xorhighercanbeusedwithApacheActiveMQArtemis.

    PleaseseeOpenWireforusingOpenWirewithApacheActiveMQArtemis.

    HighAvailability

    HighAvailability(HA)meansthatthesystemshouldremainoperationalafterfailureofoneormoreoftheservers.ThedegreeofsupportforHAvariesbetweenvariousmessagingsystems.

    ApacheActiveMQArtemisprovidesautomaticfailoverwhereyoursessionsareautomaticallyreconnectedtothebackupserveroneventofliveserverfailure.

    FormoreinformationonHA,pleaseseeHighAvailabilityandFailover.

    Clusters

    Manymessagingsystemsallowyoutocreategroupsofmessagingserverscalledclusters.Clustersallowtheloadofsendingandconsumingmessagestobespreadovermanyservers.Thisallowsyoursystemtoscalehorizontallybyaddingnewserverstothecluster.

    Degreesofsupportforclustersvariesbetweenmessagingsystems,withsomesystemshavingfairlybasicclusterswiththeclustermembersbeinghardlyawareofeachother.

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

    MessagingConcepts

    18

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

  • ApacheActiveMQArtemisalsohastheabilitytoautomaticallyredistributemessagesbetweennodesofaclustertopreventstarvationonanyparticularnode.

    Forfulldetailsonclustering,pleaseseeClusters.

    Bridgesandrouting

    Somemessagingsystemsallowisolatedclustersorsinglenodestobebridgedtogether,typicallyoverunreliableconnectionslikeawideareanetwork(WAN),ortheinternet.

    Abridgenormallyconsumesfromaqueueononeserverandforwardsmessagestoanotherqueueonadifferentserver.Bridgescopewithunreliableconnections,automaticallyreconnectingwhentheconnectionsbecomesavailableagain.

    ApacheActiveMQArtemisbridgescanbeconfiguredwithfilterexpressionstoonlyforwardcertainmessages,andtransformationcanalsobehookedin.

    ApacheActiveMQArtemisalsoallowsroutingbetweenqueuestobeconfiguredinserversideconfiguration.Thisallowscomplexroutingnetworkstobesetupforwardingorcopyingmessagesfromonedestinationtoanother,formingaglobalnetworkofinterconnectedbrokers.

    FormoreinformationpleaseseeCoreBridgesandDivertingandSplittingMessageFlows.

    MessagingConcepts

    19

  • CoreArchitectureApacheActiveMQArtemiscoreisdesignedsimplyassetofPlainOldJavaObjects(POJOs)-wehopeyoulikeitsclean-cutdesign.

    EachApacheActiveMQArtemisserverhasitsownultrahighperformancepersistentjournal,whichitusesformessageandotherpersistence.

    Usingahighperformancejournalallowsoutrageouspersistencemessageperformance,somethingnotachievablewhenusingarelationaldatabaseforpersistence(althoughJDBCisstillanoptionifnecessary).

    ApacheActiveMQArtemisclients,potentiallyondifferentphysicalmachines,interactwiththeApacheActiveMQArtemisbroker.ApacheActiveMQArtemiscurrentlyshipstwoAPIimplementationsformessagingattheclientside:

    1. CoreclientAPI.ThisisasimpleintuitiveJavaAPIthatisalignedwiththeArtemisinternalCore.Allowingmorecontrolofbrokerobjects(e.gdirectcreationofaddressesandqueues).TheCoreAPIalsooffersafullsetofmessagingfunctionalitywithoutsomeofthecomplexitiesofJMS.

    2. JMS2.0clientAPI.ThestandardJMSAPIisavailableattheclientside.

    ApacheActiveMQArtemisalsoprovidesdifferentprotocolimplementationsontheserversoyoucanuserespectiveclientsfortheseprotocols:

    AMQPOpenWireMQTTSTOMPHornetQ(forusewithHornetQclients).Core(ArtemisCOREprotocol)

    JMSsemanticsareimplementedbyaJMSfacadelayerontheclientside.

    TheApacheActiveMQArtemisbrokerdoesnotspeakJMSandinfactdoesnotknowanythingaboutJMS,itisaprotocolagnosticmessagingserverdesignedtobeusedwithmultipledifferentprotocols.

    WhenauserusestheJMSAPIontheclientside,allJMSinteractionsaretranslatedintooperationsontheApacheActiveMQArtemiscoreclientAPIbeforebeingtransferredoverthewireusingthecoreprotocol.

    ThebrokeralwaysjustdealswithcoreAPIinteractions.

    Aschematicillustratingthisrelationshipisshowninfigure3.1below:

    Architecture

    20

  • Figure3.1showstwouserapplicationsinteractingwithanApacheActiveMQArtemisserver.UserApplication1isusingtheJMSAPI,whileUserApplication2isusingthecoreclientAPIdirectly.

    YoucanseefromthediagramthattheJMSAPIisimplementedbyathinfacadelayerontheclientside.

    Stand-aloneBrokerThenormalstand-alonemessagingbrokerconfigurationcomprisesacoremessagingbrokerandanumberofprotocolmanagersthatprovidesupportforthevariousprotocolmentionedearlier.

    Thestand-alonebrokerconfigurationusesAirlineforbootstrappingtheBroker.

    Thestand-alonebrokerarchitectureisshowninfigure3.3below:

    Architecture

    21

    https://github.com/airlift/airline

  • FormoreinformationonserverconfigurationfilesseeServerConfiguration

    EmbeddedBroker

    ApacheActiveMQArtemiscoreisdesignedasasetofsimplePOJOssoifyouhaveanapplicationthatrequiresmessagingfunctionalityinternallybutyoudon'twanttoexposethatasanApacheActiveMQArtemisbrokeryoucandirectlyinstantiateandembedbrokersinyourownapplication.

    ReadmoreaboutembeddingApacheActiveMQArtemis.

    IntegratedwithaJavaEEapplicationserverApacheActiveMQArtemisprovidesitsownfullyfunctionalJavaConnectorArchitecture(JCA)adaptorwhichenablesittobeintegratedeasilyintoanyJavaEEcompliantapplicationserverorservletengine.

    JavaEEapplicationserversprovideMessageDrivenBeans(MDBs),whichareaspecialtypeofEnterpriseJavaBeans(EJBs)thatcanprocessmessagesfromsourcessuchasJMSsystemsormailsystems.

    ProbablythemostcommonuseofanMDBistoconsumemessagesfromaJMSmessagingsystem.

    AccordingtotheJavaEEspecification,aJavaEEapplicationserverusesaJCAadaptertointegratewithaJMSmessagingsystemsoitcanconsumemessagesforMDBs.

    However,theJCAadapterisnotonlyusedbytheJavaEEapplicationserverforconsumingmessagesviaMDBs,itisalsousedwhensendingmessagetotheJMSmessagingsysteme.g.frominsideanEJBorservlet.

    WhenintegratingwithaJMSmessagingsystemfrominsideaJavaEEapplicationserveritisalwaysrecommendedthatthisisdoneviaaJCAadaptor.Infact,communicatingwithaJMSmessagingsystemdirectly,withoutusingJCAwouldbeillegalaccordingtotheJavaEEspecification.

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

    Architecture

    22

  • Figure3.2belowshowsaJavaEEapplicationserverintegratingwithaApacheActiveMQArtemisserverviatheApacheActiveMQArtemisJCAadaptor.NotethatallcommunicationbetweenEJBsessionsorentitybeansandMessageDrivenbeansgothroughtheadaptorandnotdirectlytoApacheActiveMQArtemis.

    ThelargearrowwiththeprohibitedsignshowsanEJBsessionbeantalkingdirectlytotheApacheActiveMQArtemisserver.Thisisnotrecommendedasyou'llmostlikelyendupcreatinganewconnectionandsessioneverytimeyouwanttointeractfromtheEJB,whichisananti-pattern.

    Architecture

    23

  • UsingtheServerThischapterwillfamiliariseyouwithhowtousetheApacheActiveMQArtemisserver.

    We'llshowwhereitis,howtostartandstopit,andwe'lldescribethedirectorylayoutandwhatallthefilesareandwhattheydo.

    FortheremainderofthischapterwhenwetalkabouttheApacheActiveMQArtemisserverwemeantheApacheActiveMQArtemisstandaloneserver,initsdefaultconfigurationwithaJMSServiceenabled.

    ThisdocumentwillrefertothefullpathofthedirectorywheretheActiveMQdistributionhasbeenextractedtoas${ARTEMIS_HOME}directory.

    Installation

    Afterdownloadingthedistribution,thefollowinghighlightssomeimportantfoldersonthedistribution:

    |___bin

    |

    |___examples

    ||___common

    ||___features

    ||___perf

    ||___protocols

    |

    |___lib

    ||___client

    |

    |___schema

    |

    |___web

    |___api

    |___hacking-guide

    |___migration-guide

    |___user-manual

    bin-binariesandscriptsneededtorunActiveMQArtemis.

    examples-Allmannerofexamples.Pleaserefertotheexampleschapterfordetailsonhowtorunthem.

    lib-jarsandlibrariesneededtorunActiveMQArtemis

    schema-XMLSchemasusedtovalidateActiveMQArtemisconfigurationfiles

    web-Thefolderwherethewebcontextisloadedwhenthebrokerruns.

    api-Theapidocumentationisplacedunderthewebfolder.

    user-manual-Theusermanualisplacedunderthewebfolder.

    CreatingaBrokerInstance

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

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

    UsingtheServer

    24

  • cd/var/lib

    ${ARTEMIS_HOME}/bin/artemiscreatemybroker

    Abrokerinstancedirectorywillcontainthefollowingsubdirectories:

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

    Atthispointyoumaywanttoadjustthedefaultconfigurationlocatedinthe etcdirectory.

    Options

    Thereareseveraloptionsyoucanusewhencreatinganinstance.

    Forafulllistofupdatedpropertiesalwaysuse:

    $./artemishelpcreate

    NAME

    artemiscreate-createsanewbrokerinstance

    SYNOPSIS

    artemiscreate[--addresses][--aio][--allow-anonymous]

    [--autocreate][--blocking][--cluster-password]

    [--cluster-user][--clustered][--data]

    [--default-port][--disable-persistence]

    [--encoding][--etc][--failover-on-shutdown][--force]

    [--global-max-size][--home][--host]

    [--http-host][--http-port]

    [--java-options][--mapped][--max-hops]

    [--message-load-balancing][--name]

    [--nio][--no-amqp-acceptor][--no-autocreate][--no-autotune]

    [--no-fsync][--no-hornetq-acceptor][--no-mqtt-acceptor]

    [--no-stomp-acceptor][--no-web][--paging][--password]

    [--ping][--port-offset][--queues]

    [--replicated][--require-login][--role][--shared-store]

    [--silent][--slave][--ssl-key]

    [--ssl-key-password][--ssl-trust]

    [--ssl-trust-password][--use-client-auth]

    [--user][--verbose][--]

    OPTIONS

    --addresses

    Commaseparatedlistofaddresses

    --aio

    Setsthejournalasasyncio.

    --allow-anonymous

    Enablesanonymousconfigurationonsecurity,oppositeof

    --require-login(Default:input)

    --autocreate

    Autocreateaddresses.(default:true)

    --blocking

    Blockproducerswhenaddressbecomesfull,oppositeof--paging

    (Default:false)

    --cluster-password

    Theclusterpasswordtouseforclustering.(Default:input)

    UsingtheServer

    25

  • --cluster-user

    Theclusterusertouseforclustering.(Default:input)

    --clustered

    Enableclustering

    --data

    DirectorywhereActiveMQdataarestored.Pathscanbeabsoluteor

    relativetoartemis.instancedirectory('data'bydefault)

    --default-port

    Theportnumbertouseforthemain'artemis'acceptor(Default:

    61616)

    --disable-persistence

    Disablemessagepersistencetothejournal

    --encoding

    Theencodingthattextfilesshoulduse

    --etc

    DirectorywhereActiveMQconfigurationislocated.Pathscanbeabsoluteor

    relativetoartemis.instancedirectory('etc'bydefault)

    --failover-on-shutdown

    Validforsharedstore:willshutdowntriggerafailover?(Default:

    false)

    --force

    Overwriteconfigurationatdestinationdirectory

    --global-max-size

    Maximumamountofmemorywhichmessagedatamayconsume(Default:

    Undefined,halfofthesystem'smemory)

    --home

    DirectorywhereActiveMQArtemisisinstalled

    --host

    Thehostnameofthebroker(Default:0.0.0.0orinputifclustered)

    --http-host

    Thehostnametouseforembeddedwebserver(Default:localhost)

    --http-port

    Theportnumbertouseforembeddedwebserver(Default:8161)

    --java-options

    Extrajavaoptionstobepassedtotheprofile

    --mapped

    Setsthejournalasmapped.

    --max-hops

    Numberofhopsontheclusterconfiguration

    --message-load-balancing

    Loadbalancingpolicyoncluster.[ON_DEMAND(default)|STRICT|

    OFF]

    --name

    Thenameofthebroker(Default:sameashost)

    --nio

    Setsthejournalasnio.

    --no-amqp-acceptor

    DisabletheAMQPspecificacceptor.

    UsingtheServer

    26

  • --no-autocreate

    DisableAutocreateaddresses.

    --no-autotune

    Disableautotuningonthejournal.

    --no-fsync

    Disableusageoffdatasync(channel.force(false)fromjavanio)on

    thejournal

    --no-hornetq-acceptor

    DisabletheHornetQspecificacceptor.

    --no-mqtt-acceptor

    DisabletheMQTTspecificacceptor.

    --no-stomp-acceptor

    DisabletheSTOMPspecificacceptor.

    --no-web

    Removetheweb-serverdefinitionfrombootstrap.xml

    --paging

    Pagemessagestodiskwhenaddressbecomesfull,oppositeof

    --blocking(Default:true)

    --password

    Theuser'spassword(Default:input)

    --ping

    Acommaseparatedstringtobepassedontothebrokerconfigas

    network-check-list.Thebrokerwillshutdownwhenallthese

    addressesareunreachable.

    --port-offset

    Offsetstheportsofeveryacceptor

    --queues

    Commaseparatedlistofqueues.

    --replicated

    Enablebrokerreplication

    --require-login

    Thiswillconfiguresecuritytorequireuser/password,oppositeof

    --allow-anonymous

    --role

    Thenamefortherolecreated(Default:amq)

    --shared-store

    Enablebrokersharedstore

    --silent

    Itwilldisablealltheinputs,anditwouldmakeabestguessfor

    anyrequiredinput

    --slave

    Validforsharedstoreorreplication:thisisaslaveserver?

    --ssl-key

    Thekeystorepathforembeddedwebserver

    --ssl-key-password

    Thekeystorepassword

    --ssl-trust

    Thetruststorepathincaseofclientauthentication

    UsingtheServer

    27

  • --ssl-trust-password

    Thetruststorepassword

    --use-client-auth

    Iftheembeddedserverrequiresclientauthentication

    --user

    Theusername(Default:input)

    --verbose

    Addsmoreinformationontheexecution

    --

    Thisoptioncanbeusedtoseparatecommand-lineoptionsfromthe

    listofargument,(usefulwhenargumentsmightbemistakenfor

    command-lineoptions

    Theinstancedirectorytoholdthebroker'sconfigurationanddata.

    Pathmustbewritable.

    Someofthesepropertiesmaybemandatoryincertainconfigurationsandthesystemmayaskyouforadditionalinput.

    ./artemiscreate/usr/server

    CreatingActiveMQArtemisinstanceat:/user/server

    --user:isamandatoryproperty!

    Pleaseprovidethedefaultusername:

    admin

    --password:ismandatorywiththisconfiguration:

    Pleaseprovidethedefaultpassword:

    --allow-anonymous|--require-login:isamandatoryproperty!

    Allowanonymousaccess?,validvaluesareY,N,True,False

    y

    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.

    TostoptheApacheActiveMQArtemisinstanceyouwillusethesame artemisscript,butwiththe stopargument.Example:

    /var/lib/mybroker/bin/artemisstop

    UsingtheServer

    28

  • PleasenotethatApacheActiveMQArtemisrequiresaJava7orlaterruntimetorun.

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

    Environmentvariablesareusedtoprovideeaseofchangingports,hostsanddatadirectoriesusedandcanbefoundinetc/artemis.profileonlinuxand etc\artemis.profile.cmdonWindows.

    ServerJVMsettingsTherunscriptssetsomeJVMsettingsfortuningthegarbagecollectionpolicyandheapsize.WerecommendusingaparallelgarbagecollectionalgorithmtosmoothoutlatencyandminimiselargeGCpauses.

    BydefaultApacheActiveMQArtemisrunsinamaximumof1GiBofRAM.Toincreasethememorysettingschangethe -Xmsand -XmxmemorysettingsasyouwouldforanyJavaprogram.

    IfyouwishtoaddanymoreJVMargumentsortunetheexistingones,therunscriptsaretheplacetodoit.

    LibraryPathIfyou'reusingtheAsynchronousIOJournalonLinux,youneedtospecify java.library.pathasapropertyonyourJavaoptions.Thisisdoneautomaticallyinthescripts.

    Ifyoudon'tspecify java.library.pathatyourJavaoptionsthentheJVMwillusetheenvironmentvariable LD_LIBRARY_PATH.

    YouwillneedtomakesurelibaioisinstalledonLinux.Formoreinformationrefertothelibaiochapter.

    Systemproperties

    ApacheActiveMQArtemiscantakeasystempropertyonthecommandlineforconfiguringlogging.

    Formoreinformationonconfiguringlogging,pleaseseethesectiononLogging.

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

    broker.xml.ThisisthemainActiveMQconfigurationfile.Alltheparametersinthisfilearedescribedhere

    Itisalsopossibletousesystempropertysubstitutioninalltheconfigurationfiles.byreplacingavaluewiththenameofasystemproperty.Hereisanexampleofthiswithaconnectorconfiguration:

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

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

    Bootstrapconfigurationfile

    UsingtheServer

    29

  • Thestand-aloneserverisbasicallyasetofPOJOswhichareinstantiatedbyAirlinecommands.

    Thebootstrapfileisverysimple.Let'stakealookatanexample:

    server-Instantiatesacoreserverusingtheconfigurationfilefromthe configurationattribute.ThisisthemainbrokerPOJOnecessarytodoalltherealmessagingwork.

    jaas-security-Configuressecurityfortheserver.The domainattributereferstotherelevantloginmoduleentryinlogin.config.

    web-ConfiguresanembeddedJettyinstancetoservewebapplicationsliketheadminconsole.

    Brokerconfigurationfile

    TheconfigurationfortheApacheActiveMQArtemiscoreserveriscontainedin broker.xml.ThisiswhattheFileConfigurationbeanusestoconfigurethemessagingserver.

    TherearemanyattributeswhichyoucanconfigureApacheActiveMQArtemis.Inmostcasesthedefaultswilldofine,infacteveryattributecanbedefaultedwhichmeansafilewithasingleempty configurationelementisavalidconfigurationfile.Thedifferentconfigurationwillbeexplainedthroughoutthemanualoryoucanrefertotheconfigurationreferencehere.

    WindowsServer

    OnwindowsyouwillhavetheoptiontorunActiveMQArtemisasaservice.Justusethefollowingcommandtoinstallit:

    $./artemis-service.exeinstall

    Thecreateprocessshouldgiveyouahintoftheavailablecommandsavailablefortheartemis-service.exe

    AddingRuntimeDependencies

    Runtimedependencieslikediverts,transformers,brokerplugins,JDBCdrivers,passworddecoders,etc.mustbeaccessiblebythebrokeratruntime.Packagethedependencyinajar,andputitonthebroker'sclasspath.Thiscanbedonebyplacingthejarfileinthe libdirectoryofthebrokerdistributionitselforinthe libdirectoryofthebrokerinstance.Abrokerinstancedoesnothavea libdirectorybydefaultsoitmayneedtobecreated.Itshouldbeonthe"top"levelwiththe bin, data, log,etc.directories.

    UsingtheServer

    30

  • UpgradingtheBrokerApacheActiveMQ5.x(andpreviousversions)isrunnableoutoftheboxbyexecutingthecommand: ./bin/activemqrun.TheActiveMQArtemisbrokerfollowsadifferentparadigmwheretheprojectdistributionservesasthebroker"home"andoneormorebroker"instances"arecreatedwhichreferencethe"home"forresources(e.g.jarfiles)whichcanbesafelysharedbetweenbrokerinstances.Therefore,aninstanceofthebrokermustbecreatedbeforeitcanberun.Thismayseemslikeanoverheadatfirstglance,butitbecomesverypracticalwhenupdatingtoanewArtemisversionforexample.

    TocreateanArtemisbrokerinstancenavigateintotheArtemishomefolderandrun: ./bin/artemiscreate/path/to/myBrokerInstanceonthecommandline.

    Becauseofthisseparationit'sveryeasytoupgradeArtemisinmostcases.

    Note:

    It'srecommendedtochooseafolderdifferentthantheonwhereApacheArtemiswasdownloaded.ThisseparationallowsyourunmultiplebrokerinstanceswiththesameArtemis"home"forexample.ItalsosimplifiesupdatingtonewerversionsofArtemis.

    GeneralUpgradeProcedureUpgradingmayrequiresomespecificstepsnotedintheversions,butthegeneralprocessisasfollows:

    1. Navigatetothe etcfolderofthebrokerinstancethat'sbeingupgraded2. Open artemis.profile( artemis.profile.cmdonWindows).Itcontainsapropertywhichisrelevantfortheupgrade:

    ARTEMIS_HOME='/path/to/apache-artemis-version'

    IfyourunArtemisasaserviceonwindowsyouhavetodothefollowingadditionalsteps:

    1. Navigatetothe binfolderofthebrokerinstancethat'sbeingupgraded2. Open artemis-service.xml.Itcontainsapropertywhichisrelevantfortheupgrade:

    The ARTEMIS_HOMEpropertyisusedtolinktheinstancewiththehome.Inmostcasestheinstancecanbeupgradedtoanewerversionsimplybychangingthevalueofthispropertytothelocationofthenewbrokerhome.Pleaserefertotheaforementionedversionsdocumentforadditionalupgradesteps(ifrequired).

    Upgrading

    31

  • AddressingModelApacheActiveMQArtemishasauniqueaddressingmodelthatisbothpowerfulandflexibleandthatoffersgreatperformance.Theaddressingmodelcomprisesthreemainconcepts:addresses,queues,androutingtypes.

    Address

    Anaddressrepresentsamessagingendpoint.Withintheconfiguration,atypicaladdressisgivenauniquename,0ormorequeues,andaroutingtype.

    Queue

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

    RoutingTypes

    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.

    Foradditionaldetailsabouttheseconceptsrefertothecorechapter.

    BasicAddressConfiguration

    Thefollowingexamplesshowhowtoconfigurebasicpointtopointandpublishsubscribeaddresses.

    Point-to-PointMessaging

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

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

    AddressModel

    32

  • Figure1.PointtoPointMessaging

    UsingtheAnycastRoutingType

    Openthefile /etc/broker.xmlforediting.

    Addanaddressconfigurationelementanditsassociatedqueueiftheydonotexistalready.

    Note:FornormalPointtoPointsemantics,thequeuenameMUSTmatchtheaddressname.

    Publish-SubscribeMessaging

    Inapublish-subscribescenario,messagesaresenttoeveryconsumersubscribedtoanaddress.JMStopicsandMQTTsubscriptionsaretwoexamplesofpublish-subscribemessaging.

    Toconfigureanaddresswithpublish-subscribesemantics,createanaddresswiththemulticastroutingtype.

    Figure2.Publish-Subscribe

    UsingtheMulticastRoutingType

    AddressModel

    33

  • Openthefile /etc/broker.xmlforediting.

    Addanaddressconfigurationelementwithmulticastroutingtype.

    Whenclientsconnecttoanaddresswiththemulticastelement,asubscriptionqueuefortheclientwillbeautomaticallycreatedfortheclient.Itisalsopossibletopre-configuresubscriptionqueuesandconnecttothemdirectlyusingthequeue'sFullyQualifiedQueuenames.

    Optionallyaddoneormorequeueelementstotheaddressandwrapthemulticastelementaroundthem.Thisstepistypicallynotneededsincethebrokerwillautomaticallycreateaqueueforeachsubscriptionrequestedbyaclient.

    Figure3.Point-to-PointwithTwoQueues

    Point-to-PointAddressmultipleQueues

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

    Figure3.Point-to-PointwithTwoQueues

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

    AddanaddressconfigurationwithAnycastroutingtypeelementanditsassociatedqueues.

    AddressModel

    34

  • Point-to-PointandPublish-SubscribeAddresses

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

    UsinganexampleofJMSClients,themessagessentbyaJMSmessageproducerwillberoutedusingtheanycastroutingtype.MessagessentbyaJMStopicproducerwillusethemulticastroutingtype.InadditionwhenaJMStopicconsumerattaches,itwillbeattachedtoit’sownsubscriptionqueue.JMSqueueconsumerwillbeattachedtotheanycastqueue.

    Figure4.Point-to-PointandPublish-Subscribe

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

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

    Howtofiltermessages

    ApacheActiveMQArtemissupportstheabilitytofiltermessagesusingApacheArtemisFilterExpressions.

    Filterscanbeappliedintwoplaces,onaqueueandonaconsumer.

    QueueFilter

    AddressModel

    35

  • Whenafilterisappliedtoaqueue,messagesarefilteredbeforetheyaresenttothequeue.Toaddaqueuefilterusethefilterelementwhenconfiguringaqueue.Openup /etc/broker.xmlandaddanaddresswithaqueue,usingthefilterelementtoconfigureafilteronthisqueue.

    Thefilterdefinedaboveensuresthatonlymessageswithanattribute "color='red'"issenttothisqueue.

    ConsumerFilters

    ConsumerfiltersareappliedaftermessageshavereachedaqueueandaredefinedusingtheappropriateclientAPIs.ThefollowingJMSexampleshowshowconsumerfilterswork.

    1. Defineanaddresswithasinglequeue,withnofilterapplied.

    ...

    //Sendsomemessages

    for(inti=0;i<3;i++){

    TextMessageredMessage=senderSession.createTextMessage("Red");

    redMessage.setStringProperty("color","red");

    producer.send(redMessage)

    TextMessagegreenMessage=senderSession.createTextMessage("Green");

    greenMessage.setStringProperty("color","green");

    producer.send(greenMessage)

    }

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

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

    TheredConsumerhasafilterthatonlymatches"red"messages.TheredConsumerwillreceive3messages.

    red,red,red

    Theresultingqueuewouldnowbe

    green,green,green

    AutomaticAddress/QueueManagement

    AddressModel

    36

  • YoucanconfigureApacheActiveMQArtemistoautomaticallycreateaddressesandqueues,andthendeletethemwhentheyarenolongerinuse.Thissavesyoufromhavingtopreconfigureeachaddressandqueuebeforeaclientcanconnecttoit.Automaticcreationanddeletionisconfiguredonaperaddressbasisandiscontrolledbyfollowing:

    Parameter Description

    auto-create-addresses

    Whensettotrue,thebrokerwillcreatetheaddressrequestedbytheclientifitdoesnotexistalready.Thedefaultis true.

    auto-delete-addresses

    Whensettotrue,thebrokerwillbedeleteanyauto-createdadddressonceallofit’squeueshavebeendeleted.Thedefaultis true

    default-address-routing-type

    Theroutingtypetouseiftheclientdoesnotspecifyone.Possiblevaluesare MULTICASTandANYCAST.Seeearlierinthischapterformoreinformationaboutroutingtypes.ThedefaultvalueisMULTICAST.

    AutoAddressCreation

    Editthefile /etc/broker.xmlandaddthe auto-create-addresseselementtothe address-settingyouwantthebrokertoautomaticallycreate.

    (Optional)Addthe address-settingifitdoesnotexist.Usethematchparameterandthewildcardsyntaxtomatchmorethanonespecificaddress.

    Set auto-create-addressesto true

    (Optional)Assign MULTICASTor ANYCASTasthedefaultroutingtypefortheaddress.

    Theexamplebelowconfiguresan address-settingtobeautomaticallycreatedbythebroker.ThedefaultroutingtypetobeusedifnotspecifiedbytheclientisMULTICAST.Notethatwildcardsyntaxisused.Anyaddressstartingwith/news/politics/willbeautomaticallycreatedbythebroker.

    true

    MULTICAST

    AutoAddressDeletion

    Editthefile /etc/broker.xmlandaddthe auto-delete-addresseselementtothe address-settingyouwantthebrokertoautomaticallycreate.

    (Optional)Addthe address-settingifitdoesnotexist.Usethematchparameterandthewildcardsyntaxtomatchmorethanonespecificaddress.

    Set auto-delete-addressesto true

    Theexamplebelowconfiguresan address-settingtobeautomaticallydeletedbythebroker.Notethatwildcardsyntaxisused.Anyaddressrequestbytheclientthatstartswith /news/politics/isconfiguredtobeautomaticallydeletedbythebroker.

    true

    MULTICAST

    "FullyQualified"QueueNames

    AddressModel

    37

  • Internallythebrokermapsaclient’srequestforanaddresstospecificqueues.Thebrokerdecidesonbehalfoftheclientwhichqueuestosendmessagestoorfromwhichqueuetoreceivemessages.However,moreadvancedusecasesmightrequirethattheclientspecifyaqueuedirectly.Inthesesituationstheclientusesafullyqualifiedqueuename,byspecifyingboththeaddressnameandthequeuename,separatedbya::.

    CurrentlyArtemissupportsfullyqualifiedqueuenamesonCore,AMQP,JMS,OpenWire,MQTTandSTOMPprotocolsforreceivingmessagesonly.

    SpecifyingaFullyQualifiedQueueName

    Inthisexample,theaddressfooisconfiguredwithtwoqueuesq1,q2asshownintheconfigurationbelow.

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

    StringFQQN="foo::q1";

    Queueq1session.createQueue(FQQN);

    MessageConsumerconsumer=session.createConsumer(q1);

    UsingPrefixestoDetermineRoutingType

    Normally,ifthebrokerreceivesamessagesenttoaparticularaddress,thathasboth ANYCASTand MULTICASTroutingtypesenable,itwillrouteacopyofthemessagetooneofthe ANYCASTqueuesandtoallofthe MULTICASTqueues.

    However,clientscanspecifyaspecialprefixwhenconnectingtoanaddresstoindicatewhichkindofroutingtypetouse.TheprefixesarecustomvaluesthataredesignatedusingtheanycastPrefixandmulticastPrefixparameterswithintheURLofanacceptor.

    ConfiguringanAnycastPrefix

    In /etc/broker.xml,addthe anycastPrefixtotheURLofthedesiredacceptor.Intheexamplebelow,theacceptorisconfiguredtouse anycast://forthe anycastPrefix.Clientcodecanspecify anycast://foo/iftheclientneedstosendamessagetoonlyoneofthe ANYCASTqueues.

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

    ConfiguringaMulticastPrefix

    In /etc/broker.xml,addthe multicastPrefixtotheURLofthedesiredacceptor.Intheexamplebelow,theacceptorisconfiguredtouse multicast://forthe multicastPrefix.Clientcodecanspecify multicast://foo/iftheclientneedstosendamessagetoonlyoneofthe MULTICASTqueues.

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

    AddressModel

    38

  • AdvancedAddressConfiguration

    StaticSubscriptionQueues

    Inmostcasesit’snotnecessarytostaticallyconfiguresubscriptionqueues.Therelevantprotocolmanagerstakecareofdynamicallycreatingsubscriptionqueueswhenclientsrequesttosubscribetoanaddress.Thetypeofsubscriptionqueuecreateddependsonwhatpropertiestheclientrequest.Forexample,durable,non-shared,sharedetc.Protocolmanagersusespecialqueuenamingconventionstoidentifywhichqueuesbelongtowhichconsumersandusersneednotworryaboutthedetails.

    However,therearescenarioswhereausermaywanttousebrokersideconfigurationtostaticallyconfigureasubscriptionandlaterconnecttothatqueuedirectlyusingaFullyQualifiedQueuename.Theexamplesbelowshowhowtousebrokersideconfigurationtostaticallyconfigureaqueuewithpublishsubscribebehaviorforshared,non-shared,durableandnon-durablesubscriptionbehavior.

    Shared,DurableSubscriptionQueueusingmax-consumers

    Thedefaultbehaviorforqueuesistonotlimitthenumberconnectedqueueconsumers.Themax-consumersparameterofthequeueelementcanbeusedtolimitthenumberofconnectedconsumersallowedatanyonetime.

    Openthefile /etc/broker.xmlforediting.

    true

    Non-shared,DurableSubscriptionQueue

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

    true

    Non-durableSubscriptionQueue

    Non-durablesubscriptionsareagainusuallymanagedbytherelevantprotocolmanager,bycreatinganddeletingtemporaryqueues.

    Ifauserrequirestopre-createaqueuethatbehaveslikeanon-durablesubscriptionqueuethepurge-on-no-consumersflagcanbeenabledonthequeue.Whenpurge-on-no-consumersissettotrue.Thequeuewillnotstartreceivingmessagesuntilaconsumerisattached.Whenthelastconsumerisdetachedfromthequeue.Thequeueispurged(itsmessagesareremoved)and

    AddressModel

    39

  • willnotreceiveanymoremessagesuntilanewconsumerisattached.

    Openthefile /etc/broker.xmlforediting.

    ExclusiveConsumerQueue

    Ifauserrequirestostaticallyconfigureaqueuethatroutesexclusivelytooneactiveconsumertheexclusiveflagcanbeenabledonthequeue.

    Whenexclusiveissettotruethequeuewillroutemessagestotheasingleactiveconsumer.Whentheactiveconsumerthatisbeingroutedtoisdetachedfromthequeue,ifanotheractiveconsumerexist,onewillbechosenandroutingwillnowbeexclusivetoit.

    SeeExclusiveQueueforfurtherinformation.

    Openthefile /etc/broker.xmlforediting.

    ProtocolManagersA"protocolmanager"mapsprotocol-specificconceptsdowntothecoreaddressingmodel(usingaddresses,queuesandroutingtypes).Forexample,whenaclientsendsaMQTTsubscriptionpacketwiththeaddresses:

    /house/room1/lights

    /house/room2/lights

    TheMQTTprotocolmanagerunderstandsthatthetwoaddressesrequire MULTICASTsemantics.Theprotocolmanagerwillthereforefirstlooktoensurethat MULTICASTisenabledforbothaddresses.Ifnot,itwillattempttodynamicallycreatethem.Ifsuccessful,theprotocolmanagerwillthencreatespecialsubscriptionqueueswithspecialnames,foreachsubscriptionrequestedbytheclient.

    Thespecialnameallowstheprotocolmanagertoquicklyidentifytherequiredclientsubscriptionqueuesshouldtheclientdisconnectandreconnectatalaterdate.Ifthesubscriptionistemporarytheprotocolmanagerwilldeletethequeueoncetheclientdisconnects.

    Whenaclientrequeststosubscribetoapointtopointaddress.Theprotocolmanagerwilllookupthequeueassociatedwiththepointtopointaddress.Thisqueueshouldhavethesamenameastheaddresss.

    Note:Ifthequeueisautocreated,itwillbeautodeletedoncetherearenoconsumersandnomessagesinit.FormoreinformationonautocreateseethenextsectionConfiguringAddressesandQueuesviaAddressSettings

    AddressModel

    40

  • ConfiguringAddressesandQueuesviaAddressSettings

    Therearesomeattributesthataredefinedagainstanaddresswildcardratherthanaspecificaddress/queue.Hereanexampleofanaddress-settingentrythatwouldbefoundinthe broker.xmlfile.

    DLA

    ExpiryQueue

    123

    5000

    1.0

    10000

    3

    100000

    -1

    20000

    PAGE

    true

    true

    false

    0

    -1

    0

    true

    -1

    NOTIFY

    5

    true

    true

    true

    true

    true

    true

    false

    0

    0

    OFF

    true

    true

    0

    OFF

    200

    false

    -1

    Theideawithaddresssettings,isyoucanprovideablockofsettingswhichwillbeappliedagainstanyaddressesthatmatchthestringinthe matchattribute.Intheaboveexamplethesettingswouldonlybeappliedtotheaddress"order.foo"addressbutyoucanalsousewildcardstoapplysettings.

    Forexample,ifyouusedthe matchstring queue.#thesettingswouldbeappliedtoalladdresseswhichstartwith queue.

    Themeaningofthespecificsettingsareexplainedfullythroughouttheusermanual,howeverhereisabriefdescriptionwithalinktotheappropriatechapterifavailable.

    dead-letter-addressistheaddresstowhichmessagesaresentwhentheyexceed max-delivery-attempts.Ifnoaddressisdefinedherethensuchmessageswillsimplybediscarded.Readmoreaboutundeliveredmessages.

    AddressModel

    41

  • expiry-addressdefineswheretosendamessagethathasexpired.Ifnoaddressisdefinedherethensuchmessageswillsimplybediscarded.Readmoreaboutmessageexpiry.

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

    max-delivery-attemptsdefineshowmanytimeacancelledmessagecanberedeliveredbeforesendingtothe dead-letter-address.Readmoreaboutundeliveredmessages.

    redelivery-delaydefineshowlongtowaitbeforeattemptingredeliveryofacancelledmessage.Defaultis 0.Readmoreaboutundeliveredmessages.

    redelivery-delay-multiplierdefinesthenumberbywhichthe redelivery-delaywillbemultipliedoneachsubsequentredeliveryattempt.Defaultis 1.0.Readmoreaboutundeliveredmessages.

    max-size-bytes, page-size-bytes,& page-max-cache-sizeareusedtoconfigurepagingonanaddress.Thisisexplainedhere.

    max-size-bytes-reject-thresholdisusedwiththeaddressfull BLOCKpolicy,themaximumsize(inbytes)anaddresscanreachbeforemessagesstartgettingrejected.Worksincombinationwith max-size-bytesforAMQPclientsonly.Defaultis-1(i.e.nolimit).

    address-full-policy.Thisattributecanhaveoneofthefollowingvalues: PAGE, DROP, FAILor BLOCKanddetermineswhathappenswhenanaddresswhere max-size-bytesisspecifiedbecomesfull.Thedefaultvalueis PAGE.IfthevalueisPAGEthenfurthermessageswillbepagedtodisk.Ifthevalueis DROPthenfurthermessageswillbesilentlydropped.Ifthevalueis FAILthenfurthermessageswillbedroppedandanexceptionwillbethrownontheclient-side.Ifthevalueis BLOCKthenclientmessageproducerswillblockwhentheytryandsendfurthermessages.SeetheFlowControlandPagingchaptersformoreinfo.

    message-counter-history-day-limitisthenumberofdaystokeepmessagecounterhistoryforthisaddressassumingthatmessage-counter-enabledis true.Defaultis 0.

    last-value-queueisdeprecated.See default-last-value-queue.Itdefineswhetheraqueueonlyuseslastvaluesornot.Defaultis false.Readmoreaboutlastvaluequeues.

    default-last-value-queuedefineswhetheraqueueonlyuseslastvaluesornot.Defaultis false.Thisvaluecanbeoverriddenatthequeuelevelusingthe last-valueboolean.Readmoreaboutlastvaluequeues.

    default-exclusive-queuedefineswhetheraqueuewillserveonlyasingleconsumer.Defaultis false.Thisvaluecanbeoverriddenatthequeuelevelusingthe exclusiveboolean.Readmoreaboutexclusivequeues.

    default-consumers-before-dispatchdefinesthenumberofconsumersneededonaqueueboundtothematchingaddressbeforemessageswillbedispatchedtothoseconsumers.Defaultis 0.Thisvaluecanbeoverriddenatthequeuelevelusingtheconsumers-before-dispatchboolean.Thisbehaviorcanbetunedusing delay-before-dispatchonthequeueitselforbyusingthe default-delay-before-dispatchaddress-setting.

    default-delay-before-dispatchdefinesthenumberofmillisecondsthebrokerwillwaitfortheconfigurednumberofconsumerstoconnecttothematchingqueuebeforeitwillbegintodispatchmessages.Defaultis -1(waitforever).

    redistribution-delaydefineshowlongtowaitwhenthelastconsumerisclosedonaqueuebeforeredistributinganymessages.Readmoreaboutclusters.

    send-to-dla-on-no-route.Ifamessageissenttoanaddress,buttheserverdoesnotrouteittoanyqueues(e.g.theremightbenoqueuesboundtothataddress,ornoneofthequeueshavefiltersthatmatch)thennormallythatmessagewouldbediscarded.However,ifthisparameteris truethensuchamessagewillinsteadbesenttothe dead-letter-address(DLA)forthat

    AddressModel

    42

  • address,ifitexists.

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

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

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

    auto-create-jms-queuesisdeprecated.See auto-create-queues.WhetherornotthebrokershouldautomaticallycreateaJMSqueuewhenaJMSmessageissenttoaqueuewhosenamefitstheaddress match(remember,aJMSqueueisjustacorequeuewhichhasthesameaddressandqueuename)oraJMSconsumertriestoconnecttoaqueuewhosenamefitstheaddressmatch.Queueswhichareauto-createdaredurable,non-temporary,andnon-transient.Defaultis true.

    auto-delete-jms-queuesisdeprecated.See auto-delete-queues.Whetherornotthebrokershouldautomaticallydeleteauto-createdJMSqueueswhentheyhaveboth0consumersand0messages.Defaultis true.

    auto-create-jms-topicsisdeprecated.See auto-create-addresses.WhetherornotthebrokershouldautomaticallycreateaJMStopicwhenaJMSmessageissenttoatopicwhosenamefitstheaddress match(remember,aJMStopicisjustacoreaddresswhichhasoneormorecorequeuesmappedtoit)oraJMSconsumertriestosubscribetoatopicwhosenamefitstheaddress match.Defaultis true.

    auto-delete-jms-topicsisdeprecated.See auto-delete-addresses.Whetherornotthebrokershouldautomaticallydeleteauto-createdJMStopicsoncethelastsubscriptiononthetopichasbeenclosed.Defaultis true.

    auto-create-queues.Whetherornotthebrokershouldautomaticallycreateaqueuewhenamessageissentoraconsumertriestoconnecttoaqueuewhosenamefitstheaddress match.Queueswhichareauto-createdaredurable,non-temporary,andnon-transient.Defaultis true.

    auto-delete-queues.Whetherornotthebrokershouldautomaticallydeleteauto-createdqueueswhentheyhaveboth0consumersandthemessagecountislessthanorequalto auto-delete-queues-message-count.Defaultis true.

    auto-delete-created-queues.Whetherornotthebrokershouldautomaticallydeletecreatedqueueswhentheyhaveboth0consumersandthemessagecountislessthanorequalto auto-delete-queues-message-count.Defaultis false.

    auto-delete-queues-delay.Howlongtowait(inmilliseconds)beforedeletingauto-createdqueuesafterthequeuehas0consumersandthemessagecountislessthanorequalto auto-delete-queues-message-count.Defaultis 0(deleteimmediately).Thebroker's address-queue-scan-periodcontrolshowoften(inmilliseconds)queuesarescannedforpotentialdeletion.Use -1todisablescanning.Thedefaultscanvalueis 30000.

    auto-delete-queues-message-count.Themessagecountthatthequeuemustbelessthanorequaltobeforedeletingauto-createdqueues.Todisablemessagecountcheck -1canbeset.Defaultis 0(emptyqueue).

    Note:theaboveauto-deleteaddresssettingscanalsobeconfiguredindividuallyatthequeuelevelwhenaclientautocreatesthequeue.

    ForCoreAPIitisexposedincreateQueuemethods.

    ForCoreJMSyoucansetitusingthedestinationqueueattributes my.destination?auto-delete=true&auto-delete-delay=120000&auto-delete-message-count=-1

    config-delete-queues.Howthebrokershouldhandlequeuesdeletedonconfigreload,bydeletepolicy: OFFor FORCE.Defaultis OFF.Readmoreaboutconfigurationreload.

    AddressModel

    43

  • auto-create-addresses.Whetherornotthebrokershouldautomaticallycreateanaddresswhenamessageissenttooraconsumertriestoconsumefromaqueuewhichismappedtoanaddresswhosenamefitstheaddress match.Defaultis true.

    auto-delete-addresses.Whetherornotthebrokershouldautomaticallydeleteauto-createdaddressesoncetheaddressnolongerhasanyqueues.Defaultis true.

    auto-delete-addresses-delay.Howlongtowait(inmilliseconds)beforedeletingauto-createdaddressesaftertheynolongerhaveanyqueues.Defaultis 0(deleteimmediately).Thebroker's address-queue-scan-periodcontrolshowoften(inmilliseconds)addressesarescannedforpotentialdeletion.Use -1todisablescanning.Thedefaultscanvalueis 30000.

    config-delete-addresses.Howthebrokershouldhandleaddressesdeletedonconfigreload,bydeletepolicy: OFFor FORCE.Defaultis OFF.Readmoreaboutconfigurationreload.

    management-browse-page-sizeisthenumberofmessagesamanagementresourcecanbrowse.Thisisrelevantforthe"browse"managementmethodexposedonthequeuecontrol.Defaultis 200.

    default-purge-on-no-consumersdefinesaqueue'sdefault purge-on-no-consumerssettingifnoneisprovidedonthequeueitself.Defaultis false.Thisvaluecanbeoverriddenatthequeuelevelusingthe purge-on-no-consumersboolean.Readmoreaboutthisfunctionality.

    default-max-consumersdefinesaqueue'sdefault max-consumerssettingifnoneisprovidedonthequeueitself.Defaultis -1(i.e.nolimit).Thisvaluecanbeoverriddenatthequeuelevelusingthe max-consumersboolean.Readmoreaboutthisfunctionality.

    default-queue-routing-typedefinestherouting-typeforanauto-createdqueueifthebrokerisunabletodeterminetherouting-typebasedontheclientand/orprotocolsemantics.Defaultis MULTICAST.Readmoreaboutroutingtypes.

    default-address-routing-typedefinestherouting-typeforanauto-createdaddressifthebrokerisunabletodeterminetherouting-typebasedontheclientand/orprotocolsemantics.Defaultis MULTICAST.Readmoreaboutroutingtypes.

    default-consumer-window-sizedefinesthedefault consumerWindowSizevaluefora COREprotocolconsumer,ifnotdefinedthedefaultwillbesetto1MiB(1024*1024bytes).Theconsumerwillusethisvalueasthewindowsizeifthevalueisnotsetontheclient.Readmoreaboutflowcontrol.

    AddressModel

    44

  • ProtocolsandInteroperabilityApacheActiveMQArtemishasapowerful&flexiblecorewhichprovidesafoundationuponwhichotherprotocolscanbeimplemented.Eachprotocolimplementationtranslatestheideasofitsspecificprotocolontothiscore.

    Thebrokershipswithaclientimplementationwhichinteractsdirectlywiththiscore.Ituseswhat'scalledthe"core"API,anditcommunicatesoverthenetworkusingthe"core"protocol.

    SupportedProtocols&APIs

    Thebrokerhasapluggableprotocolarchitecture.Protocolpluginscomeintheformofprotocolmodules.Eachprotocolmoduleisincludedonthebroker'sclasspathandloadedbythebrokeratboottime.Thebrokershipswith5protocolmodulesoutofthebox.The5modulesoffersupportforthefollowingprotocols:

    AMQPOpenWireMQTTSTOMPHornetQ

    APIsandOtherInterfaces

    AlthoughJMSisastandardizedAPI,itdoesnotdefineanetworkprotocol.TheActiveMQArtemisJMS2.0clientisimplementedontopofthecoreprotocol.Wealsoprovideaclient-sideJNDIimplementation.

    ThebrokeralsoshipswithaRESTmessaginginterface(nottobeconfusedwiththeRESTmanagementAPIprovidedviaourintegrationwithJolokia).

    ConfiguringAcceptors

    Inordertomakeuseofaparticularprotocol,atransportmustbeconfiguredwiththedesiredprotocolenabled.Thereisawholesectiononconfiguringtransportsthatcanbefoundhere.

    ThedefaultconfigurationshippedwiththeActiveMQArtemisdistributioncomeswithanumberofacceptorsalreadydefined,oneforeachoftheaboveprotocolsplusagenericacceptorthatsupportsallprotocols.Toenableprotocolsonaparticularacceptorsimplyaddthe protocolsurlparametertotheacceptorurlwherethevalueisoneormoreprotocols(separatedbycommas).Ifthe protocolsparameterisomittedfromtheurlallprotocolsareenabled.

    ThefollowingexampleenablesonlyMQTTonport1883

    tcp://localhost:1883?protocols=MQTT

    ThefollowingexampleenablesMQTTandAMQPonport1883

    tcp://localhost:5672?protocols=MQTT,AMQP

    Thefollowingexampleenablesallprotocolson 61616:

    ProtocolsandInteroperability

    45

  • tcp://localhost:61616

    Herearethesupportedprotocolsandtheircorrespondingvalueusedinthe protocolsurlparameter.

    Protocol protocolsvalue

    Core(Artemis&HornetQnative) CORE

    OpenWire(5.xnative) OPENWIRE

    AMQP AMQP

    MQTT MQTT

    STOMP STOMP

    ProtocolsandInteroperability

    46

  • AMQPApacheActiveMQArtemissupportstheAMQP1.0specification.Bydefaultthereare acceptorelementsconfiguredtoacceptAMQPconnectionsonports 61616and 5672.

    SeethegeneralProtocolsandInteroperabilitychapterfordetailsonconfiguringan acceptorforAMQP.

    YoucanuseanyAMQP1.0compatibleclients.

    Ashortlistincludes:

    qpidclients.NETClientsJavascriptNodeJSJavaScriptRHEA...andmanyothers.

    ExamplesWehaveafewexamplesaspartoftheArtemisdistribution:

    .NET:./examples/protocols/amqp/dotnet

    ProtonCPP./examples/protocols/amqp/proton-cpp./examples/protocols/amqp/proton-clustered-cpp

    Ruby./examples/protocols/amqp/proton-ruby

    Java(UsingtheqpidJMSClient)./examples/protocols/amqp/queue

    Interceptors./examples/features/standard/interceptor-amqp./examples/features/standard/broker-plugin

    MessageConversions

    ThebrokerwillnotperformanymessageconversiontoanyotherprotocolswhensendingAMQPandreceivingAMQP.

    HoweverifyouintendyourmessagetobereceivedbyanAMQPJMSClient,youmustfollowtheJMSMappingConventions.IfyousendabodytypethatisnotrecognizedbythisspecificationtheconversionbetweenAMQPandanyotherprotocolwillmakeitaBinaryMessage.Makesureyoufollowtheseconventionsifyouintendtocrossprotocolsorlanguages.Especiallyonthemessagebody.

    AcompatibilitysettingallowsaligningthenamingconventionofAMQPqueues(JMSDurableandSharedSubscriptions)withCORE.Forbackwardscompatibilityreasons,youneedtoexplicitlyenablethisviabrokerconfiguration:

    amqp-use-core-subscription-naming

    true-usequeuenamingconventionthatisalignedwithCORE.false(default)-useoldernamingconvention.

    Interceptingandchangingmessages

    AMQP

    47

    https://www.oasis-open.org/committees/tc_home.php?wg_abbrev=amqphttps://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

  • Interceptingandchangingmessages

    Wedon'trecommendchangingmessagesattheserver'ssideforafewreasons:

    AMQPmessagesaremeanttobeimmutableThemessagewon'tbetheoriginalmessagetheusersentAMQPhasthepossibilityofsigningmessages.Thesignaturewouldbebroken.Forperformancereasons.Wetrynottore-encode(orevendecode)messages.

    IfregardlesstheserecommendationsyoustillneedandwanttointerceptandchangeAMQPmessages,lookattheaforementionedinterceptorexamples.

    AMQPandsecurity

    TheApacheActiveMQArtemisServeracceptsthePLAIN,ANONYMOUS,andGSSAPISASLmechanism.Theseareimplementedonthebroker'ssecurityinfrastructure.

    AMQPanddestinations

    IfanAMQPLinkisdynamicthenatemporaryqueuewillbecreatedandeithertheremotesourceorremotetargetaddresswillbesettothenameofthetemporaryqueue.IftheLinkisnotdynamicthenthetheaddressoftheremotetargetorsourcewillusedforthequeue.Ifthisdoesnotexistthenitwillbeauto-createdifthesettingsallow.

    AMQPandMulticastAddresses(Topics)

    AlthoughAMQPhasnonotionof"topics"itisstillpossibletotreatAMQPconsumersorreceiversassubscriptionsratherthanjustconsumersonaqueue.Bydefaultanyreceivinglinkthatattachestoanaddressthathasonly multicastenabledwillbetreatedasasubscriptionandacorrespondingsubscriptionqueuewillbecreated.IftheTerminusDurabilityiseitherUNSETTLED_STATEor CONFIGURATIONthenthequeuewillbemadedurable(similartoaJMSdurablesubscription)andgivenanamemadeupfromthecontaineridandthelinkname,somethinglike my-container-id:my-link-name.IftheTerminusDurabilityisconfiguredas NONEthenavolatile multicastqueuewillbecreated.

    AMQPandCoordinations-HandlingTransactions

    AnAMQPlinkstargetcanalsobeaCoordinator.ACoordinatorisusedtohandletransactions.Ifacoordinatorisusedthentheunderlyingserversessionwillbetransactedandwillbeeitherrolledbackorcommittedviathecoordinator.

    Note:

    AMQPallowstheuseofmultipletransactionspersession, amqp:multi-txns-per-ssn,howeverinthisversionofApacheActiveMQArtemiswillonlysupportsingletransactionspersession.

    AMQPschedulingmessagedelivery

    AnAMQPmessagecanprovideschedulinginformationthatcontrolsthetimeinthefuturewhenthemessagewillbedeliveredattheearliest.Thisinformationisprovidedbyaddingamessageannotationtothesentmessage.

    Therearetwodifferentmessageannotationsthatcanbeusedtoscheduleamessageforlaterdelivery:

    AMQP

    48

  • x-opt-delivery-timeThespecifiedvaluemustbeapositivelongcorrespondingtothetimethemessageshouldbemadeavailablefordelivery(inmilliseconds).

    x-opt-delivery-delayThespecifiedvaluemustbeapositivelongcorrespondingtotheamountofmillisecondsafterthebrokerreceivesthegivenmessagebeforeitshouldbemadeavailablefordelivery.

    Ifbothannotationsarepresentinthesamemessagethenthebrokerwillpreferthemorespecific x-opt-delivery-timevalue.

    ConfiguringAMQPIdleTimeoutItispossibletoconfiguretheAMQPServer'sIDLETimeoutbysettingthepropertyamqpIdleTimeoutinmillisecondsontheacceptor.

    ThiswillmaketheservertosendanAMQPframeopentotheclient,withyourconfiguredtimeout/2.

    So,ifyouconfiguredyourAMQPIdleTimeouttobe60000,theserverwilltelltheclienttosendframesevery30,000milliseconds.

    ....;amqpIdleTimeout=;.....

    DisablingKeepalivechecks

    ifyousetamqpIdleTimeout=0thatwilltellclientstonotsendingkeepalivepacketstowardstheserver.OnthiscaseyouwillrelyonTCPtodeterminewhenthesocketneedstobeclosed.

    ....;amqpIdleTimeout=0;.....

    ThiscontainsarealexampleforconfiguringamqpIdleTimeout:

    tcp://0.0.0.0:5672?amqpIdleTimeout=0;tcpSendBufferSize=1048576;tcpReceiveBufferSize=10485

    76;protocols=AMQP;useEpoll=true;amqpCredits=1000;amqpMinCredits=300;directDeliver=false;batchDelay=10

    AMQP

    49

  • MQTTMQTTisalightweight,clienttoserver,publish/subscribemessagingprotocol.MQTThasbeenspecificallydesignedtoreducetransportoverhead(andthusnetworktraffic)andcodefootprintonclientdevices.ForthisreasonMQTTisideallysuitedtoconstraineddevicessuchassensorsandactuatorsandisquicklybecomingthedefactostandardcommunicationprotocolforIoT.

    ApacheActiveMQArtemissupportsMQTTv3.1.1(andalsotheolderv3.1codemessageformat).BydefaultthereareacceptorelementsconfiguredtoacceptMQTTconnectionsonports 61616and 1883.

    SeethegeneralProtocolsandInteroperabilitychapterfordetailsonconfiguringan acceptorforMQTT.

    ThebestsourceofinformationontheMQTTprotocolisinthe3.1.1specification.

    RefertotheMQTTexamplesforalookatsomeofthisfunctionalityinaction.

    MQTTQualityofServiceMQTToffers3qualityofservicelevels.

    Eachmessage(ortopicsubscription)candefineaqualityofservicethatisassociatedwithit.Thequalityofserviceleveldefinedonatopicisthemaximumlevelaclientiswillingtoaccept.Thequalityofservicelevelonamessageisthedesiredqualityofservicelevelforthismessage.Thebrokerwillattempttodelivermessagestosubscribersatthehighestqualityofservicelevelbasedonwhatisdefinedonthemessageandtopicsubscription.

    Eachqualityofserviceleveloffersalevelofguaranteebywhichamessageissentorreceived:

    QoS0: ATMOSTONCE

    Guaranteesthataparticularmessageisonlyeverreceivedbythesubscriberamaximumofonetime.Thisdoesmeanthatthemessagemayneverarrive.Thesenderandthereceiverwillattempttodeliverthemessage,butifsomethingfailsandthemessagedoesnotreachitsdestination(sayduetoanetworkconnection)themessagemaybelost.ThisQoShastheleastnetworktrafficoverheadandtheleastburdenontheclientandthebrokerandisoftenusefulfortelemetrydatawhereitdoesn'tmatterifsomeofthedataislost.

    QoS1: ATLEASTONCE

    Guaranteesthatamessagewillreachitsintendedrecipientoneormoretimes.Thesenderwillcontinuetosendthemessageuntilitreceivesanacknowledgmentfromtherecipient,confirmingithasreceivedthemessage.TheresultofthisQoSisthattherecipientmayreceivethemessagemultipletimes,andalsoincreasesthenetworkoverheadthanQoS0,(duetoacks).Inadditionmoreburdenisplacedonthesenderasitneedstostorethemessageandretryshoulditfailtoreceiveanackinareasonabletime.

    QoS2: EXACTLYONCE

    ThemostcostlyoftheQoS(intermsofnetworktrafficandburdenonsenderandreceiver)thisQoSwillensurethatthemessageisreceivedbyarecipientexactlyonetime.Thisensuresthatthereceivernevergetsanyduplicatecopiesofthemessageandwilleventuallygetit,butattheextracostofnetworkoverheadandcomplexityrequiredonthesenderandreceiver.

    MQTTRetainMessages

    MQTT

    50

    https://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html

  • MQTThasaninterestingfeatureinwhichmessagescanbe"retained"foraparticularaddress.Thismeansthatoncearetainmessagehasbeensenttoanaddress,anynewsubscriberstothataddresswillreceivethelastsentretainmessagebeforeanyothersmessages,thishappenseveniftheretainedmessagewassentbeforeaclienthasconnectedorsubscribed.AnexampleofwherethisfeaturemightbeusefulisinenvironmentssuchasIoTwheredevicesneedtoquicklygetthecurrentstateofasystemwhentheyareonboardedintoasystem.

    WillMessages

    Awillmessagecanbesentwhenaclientinitiallyconnectstoabroker.Clientsareabletoseta"willmessage"aspartoftheconnectpacket.Iftheclientabnormallydisconnects,sayduetoadeviceornetworkfailurethebrokerwillproceedtopublishthewillmessagetothespecifiedaddress(asdefinedalsointheconnectpacket).Othersubscriberstothewilltopicwillreceivethewillmessageandcanreactaccordingly.ThisfeaturecanbeusefulinanIoTstylescenariotodetecterrorsacrossapotentiallylargescaledeploymentofdevices.

    DebugLogging

    Detailedprotocollogging(e.g.packetsin/out)canbeactivatedviathefollowingsteps:

    1. Open /etc/logging.properties

    2. Add org.apac