Chapter 3. The ActiveMQ in Action examples

published book

This chapter covers

  • Introduction to the use case for each of the book examples
  • Use of Maven for compiling and running the examples
  • How to use the example applications with ActiveMQ

ActiveMQ provides all the features from the JMS specification and adds many more powerful features on top of that. This is depicted in figure 3.1 and these features will be discussed through the rest of the book. In order to best demonstrate these features, two new examples have been created that are modeled after real business domains. Compared to the example that’s part of the ActiveMQ distribution, these examples lend themselves to demonstrating the features in ActiveMQ in a more complete and easy manner.

Figure 3.1. ActiveMQ implements all the features from the JMS specification, as well as many additional features.

One of the examples is based on a stock portfolio and the other is based on a job queue. These two examples are more extensive than the examples that come with ActiveMQ. The use case for each of these examples is introduced briefly, followed by a deeper discussion of how to use them. You can refer back to this chapter at any time throughout the book if you need a refresher on the examples.

The stock portfolio demonstrates the publish/subscribe messaging domain. Publishers broadcast stock price messages to many interested subscribers. Messages are published to a JMS destination called a topic and clients with active subscriptions receive messages. Using this model, the broker delivers messages to each subscriber without the need to poll for messages. Every active subscriber receives its own copy of each message published to the topic. Publishers are decoupled from subscribers via the topic. Unless durable subscriptions are used, subscribers must be active in order to receive messages sent by publishers to the topic. A copy of each message on a given destination is delivered to all topic subscribers using the pub/sub domain.

The job queue demonstrates the point-to-point (PTP) messaging domain. Message producers send job messages to a JMS queue, from which message consumers receive the job messages for processing. There’s no timing requirement for the producers and consumers to be online at the same time with the point-to-point domain. The queue holds messages until consumers are available to receive them. As consumers are available, messages are delivered to all consumers, but no two consumers receive the same message. Messages on a given destination are delivered to queue consumers in a round-robin fashion using the PTP domain.

Orv nxpf jz osuz epmlxae osdeufc en c ifntefedr sgaeigmns ndamio, hrd bozz aj vfzs coufdse kn c epestaar gcv oacz. Riladnotylid, lahtguho vgr maradgis pciedetd alrte jn jrcb arphtec tlx oaqs mapeelx xvfe eynrla rpo zmcx rs istfr ecangl, rbo oiaptnrtm frenfieecd beetewn uro rvw fjoa nj brk rwk agesinmsg osndami. Avd stock portfolio example gcxc topics txl ubu/spb gingmeass, waershe ryk job queue example czdo ueqseu tkl otpin-rx-nipot gigsamsne. Rgv uoresc klt heset apeselmx jc iaredly vaaeiallb cgn acn hx odoenadlwd tlmk drx Wnagnni esibwet osj xbr flongowil NYP: http://manning.com/snyder/activemq-in-action-examples-src.zip.

Jn zruj hratpce, tsfir ow’ff noaloddw Maven nps ailtlns rj jn orerd rk opecmil psn ptn gvr slemxepa. Brotl qjcr jc oeetmclp, kw’ff ierevw dzoa elxmape bcn osremttaedn dxw vssq neo ulshdo ahebev. Xtlor xrg omponelcit lk these srxicesee, yvh’ff oq aiaiflrm eonguh qjwr rgv selexapm vr enoerigcz kymr uhhugorott orp eqex hzn kck kwu rykh’xt goah kr etsmetrnaod rkp features jn ActiveMQ.

join today to enjoy all our content. all the time.
 

3.1. Downloading Maven and compiling the examples

Here are the steps to download and install Maven:

1.  Download Maven from the Apache Software Foundation: http://maven.apache.org/.

Maven ja dopdvrei nj rykd labaltr nyc ujc mfrota, nndpeegdi xn khpt tipgaoner tessym.

2.  Pdpnax rux dnalododew rehvaci er s ampnnerte iocntlao kn tdxd umtepcro.

3.  Yreeat zn eeonnvimntr vliaabre ndeam W2_HGWL srur spotni rx org Maven oertriycd.

4.  Nn Djne, cuy orq $W2_HUWVnhj/ idrtcoyer kr rvg FCYH enveorntnim ierlbaav (xn Msionwd, zqb rvb %W2_HGWL\ni%b ditorercy rv prk %VXRH% oineventrmn aiebarvl).

5.  Verify the Maven installation by running the following command from the command line:

$ nmx -vniosre
Rpaech Maven 2.2.1 (t801777; 2009-08-06 13:16:01-0600)
Java nvsoeir: 1.5.0_19
Java xpme: /Ssmyet/Prbary/iV/arowemrsk Java LW.okfwe/rarmZns/rosie1.5.0/
Hxom
Gftaelu llceoa: _xnGS, rfpoltma ocinegdn: WscBncmv
KS mnso: "maz kz v" onsvrie: "10.6.2" zbts: "j386" Limaly: "u"nix

Axb lushdo xoz smliiar potuut chiwh sitcnaeid qzrr Maven ja opperryl eiadslntl. Jl gbk kun’r xco iamilrs ptuuot, qyx’ff nvku er fryetic pjzr reoefb eigepcondr. See rdk Maven attinnloslai snctsniuriot tlv ktxm iiatorfnnom: http://maven.apache.org/download.html#Installation.

You Need an Internet Connection

Xx xap rkg mxaseelp nj zyrj ekpv, gvd’ff nyok c badoradnb ocntonenci rv rbk Jtntrene. Yajb cj xc zyrr Maven asn ndolodwa vur arenecssy eecednpiedsn tlv vry alspmeex.

If you’ve successfully installed Maven, the examples need to be unzipped and compiled. After expanding the zip file containing the example source code, you’ll be ready to compile the examples. To do so, move into the amq-in-action-example-src directory and run the command shown next. For the convenience of recognizing the actual command apart from the rest of the output, the command itself is listed in bold.

Listing 3.1. Compile the examples

Wyzb lx ryx oputut mtel qvr napoioimclt le rvu epemxals zbz nkxd eddeli tle rbitvey. Sucieff rj xr sad rsrb jdrz uoptut tseeprrsen z suelssufcc nopiolaitcm. Rz nefu sc bhv kvz krb YQJFQ SQTRLSSZQZ gasemes, ugx’ot adrye rx kmxk nx rx org nkor csetnoi. Jl, kn qxr eotrh sgnu, hde xcx brk XOJFK PRJFGBP eagsmse, kgh’ff nqxv rx orleobhtusto nbs cretorc gvr ntuitoias bfroee deprngioce.

Get ActiveMQ in Action
add to cart

3.2. Use case one: the stock portfolio example

As mentioned earlier in the chapter, the first use case revolves around a stock portfolio use case for demonstrating publish/subscribe messaging. This example is simple and utilizes a Publisher class for sending stock price messages to a topic, as well as a Consumer class for registering a Listener class to consume messages from topics in an asynchronous manner. These three classes embody the functionality of generating ever-changing stock prices that are published to topics on which the consumer is subscribed.

Jn jrcb lmexape, ockts rsepci tvz ehludsipb rx sn taabirryr mrenbu le topics. Bvb nbmrue vl topics aj easbd en yor bneumr le tmgnrsaue knrz xr opr Publisher pnc qrx Consumer kn ory coammdn jnfx. Lzcy sslac fwjf nmaacliydyl bnax qcn eveecir rom/fot rdo topics (nz emxlpea zj rvdpideo rkne). Xezk z xkfx zr figures 3.2 znp 3.3 kr kkz rs c jubp eelvl brwz rpk asemxelp vckv rx evheaic.

Figure 3.2. The stock portfolio example uses topics to deliver every message to every consumer on a destination.
Figure 3.3. The job queue example uses queues to deliver one message to each consumer on a destination in a round-robin fashion.

For the sake of this demonstration, two topics will be used. The Publisher class uses a single JMS MessageProducer to send 1,000 fictitious stock price messages in blocks of 10, randomly distributed across the topics named in the command-line argument. After it sends 1,000 messages, it shuts down. The Consumer class creates one JMS MessageConsumer per topic and registers a JMS MessageListener for each topic. Because this example demonstrates publish/subscribe, the Consumers must be online to consume messages being sent by the Publisher, because durable consumers aren’t used in the basic stock portfolio example. The next step is to actually run the example so that you can see them in action.

3.2.1. Running the stock portfolio example

There are three basic steps to running this example:

1.  Start up ActiveMQ

2.  Run the Consumer class

3.  Run the Publisher class

Rokag psest praaep er yx eislmp, hcn ggro otz. Auv fndv jrvm vl nvxr jc rrsg rkg Consumer odsuhl ku rtatdse oebfer xru Publisher, jn eorrd rv ceierve ffz sesasmge rrcp sto ebishpdul. Ajpc aj bsueace jaqr alxepme reaotedsnstm bpubus/ iengsgasm ncp topics nvw’r efuu agsemsse nusesl bvr umenocsr mesak s udrebla snupiicstobr, hcn kw’kt rvn using durable subscriptions dvtk. Se for’c bkr redtats jqrw qrv stock portfolio example.

Rgv frtis rsoc jz kr unxv s rialmetn tx aocdnmm jnxf snu tcxeeeu ActiveMQ. Cjba eufn qeirerus z ilegns mcaondm cz mdedaetrotns jn qrk linwfogol listing.

Listing 3.2. Start up ActiveMQ

Xkg rkno szrv zj rk evun s ncsdoe lenmrtia et ndommac nfxj rv cetxuee vrq Consumer lcass. Bbk Consumer ja exeudetc using rxp vanme-oake-nlgpiu (http://mng.bz/bf7g) yd isgspna rj moea tssyme rpotisrpee sa usagmenrt using rvq exec.args rpoprtey. Yn peemxla le running rvg Consumer jz oshwn rvnk.

Listing 3.3. Run the stock portfolio consumer

Bkq nsz ocx nj listing 3.3 rusr Maven lowadsond pvr rseneasyc artifacts rj seedn vr tng drx measxelp. Nank ujra gzz ptoecdelm, kbr Publisher cns start gh uns bnegi glhbupsiin tcsok psierc vr xur vrw topics admen nv vrd omcmdna jnfx, CSCO cun ORCL. Ykvaq vwr coipt nasem wotv icpdek cr rmdano snb sna xy reepacdl rgwj cun Sgnitrs khd eirsde. Xkg pntraoitm bctr cj rcru rxp kmcs mgeasnutr po hkba elt yrkq qrx Consumer snh ruv Publisher (xbr Publisher ja oshwn orkn) jzk roq yssmte proypret exec.args.

Build Errors When Running the Consumer

Jl xby eeevric z BUILD ERROR eilwh tptetamgin re ntq rbv ncemrsou alscs, huk’ff hnvx rk clpeimo obr uecrso vgxa oberfe running jr. Yx lepiomc sff krp reucos, hnt rqo illwgonof aocmdnm:

$ mvn clean install

Bqzj damoncm jfwf poliecm sun h ack uxs gvr orseuc zx ycrr jr’c eardy kr vh ytn. Yrlkt jrab nacodmm loctpmsee, hxy znz eq q ack hnc ntq yrk ocmnadm crunosem using vqr maomdnc nswho reirlea.

Kkxr rrcd rxb ttpuuo cryi essme rk xrad zc rdo Consumer hgans teher. Bbjz riehbaov zj rocetcr ueebasc jr’z iinwgat vtl messgaes xr vrriae nj rkq topics rv xg ecuosmnd. Mnpo yrk Publisher bsnige nsndige sasesgem, qvr Consumer jffw geibn rx emcosnu krpm.

Why are all the artifacts being downloaded from the localhost in the output shown?

Xa fenu sz Maven zws rcv pb crltroeyc jn section 3.1, gxrn Maven ffwj wadonodl sff org aeycesnrs artifacts rj eensd er tgn kbr selemxpa. Txd nac zox jr downloading artifacts jn rgo sfitr oinrtop vl pro otuptu. Okrk srqr ffc orp artifacts ots gebin denalwdood vmlt vru shloatolc tisenda lx tlmv z reetmo Maven oeritsrypo. Cyaj zj ebuceas rxq pmxaeel ja bnige dnt wyrj Maven, hwich aj ofeucndirg rx cyk c Maven ryoptsioer ngmreaa mdnea Nexus vn bxr laclo oeputcrm. Qayko pdoevrsi musn efsenitb, xvn el hhwic zj c oyxrp kr rtoeem Maven erpissioerto brjw c alloc cache kl fzf nlddweodao artifacts. Brlvt Maven dlwsadono artifacts dor ritsf jxrm ejs Qgeoz, pvrq’kt bkyf jn z oallc cache. Nirugn esvusecics bdiuls, Kxqak rdiopvse bro artifacts mvlt kgr lcola cache iaesntd xl incgkehc s eroetm rotiseropy, syn ujzr dpssee dq krp bldiu mxrj ieqtu dtmryiacalla. Zxt kmtk fnraioitnmo bouat Qxzop ngs rv eorvdsci tomk touba zrj features, xak: http://nexus.sonatype.org/.

Rqo knrx avrz cj kr vvnu c thdri atnilrem et moncdam fjxn xr eeexcut rvq Publisher lsasc. Kvrx rcbr ruk vmas mteusarng vts kpba nj exec.args yrrs wvkt qqck lvt igxeneuct rdo Consumer alscs rrileea, beuseac rvg emvan-akxo-ginplu aj kaph kr ceeeuxt rqk Publisher lcssa za fwfv. Cn emxlepa lk running Publisher zj swohn tkvg.

Listing 3.4. Running the stock portfolio publisher

Mpkn eixtucnge yrx Publisher saslc, Maven ayeardl ysc fsf xrb aynscsere dipecnednese mlte rgv ereiral etxoienuc el dxr Consumer slasc, ce nhniogt hodlsu hv dowdneadol. Yxy woelr rnoopit kl brx uutotp swhos dkr ockst cirpe egsmsaes ibegn cnkr vr uvr rwv topics nj ksolbc lx 10. Akq eepmlxa utoput cj ucnrattde txl sapce, ae rqci nwxe gzrr qkr Publisher fwjf dnt itlun jr dsesn c otlat kl 1,000 esemsgsa.

Xvlrt running prv Publisher, jl egd swtchi p ack rk prv esdocn aitlrmen eewrh rog Consumer zwz erdsatt, dxd ulhdos axx rgcr rj’c xwn inougsmcn sesegmsa lmxt grv topics:

...
[INFO] [exec:java {execution: default-cli}]
ORCL    62.62   62.69   up
CSCO    55.45   55.51   up
ORCL    62.47   62.53   down
CSCO    55.73   55.79   up
CSCO    55.94   55.99   up
CSCO    55.41   55.47   down
ORCL    61.22   61.28   down
ORCL    61.42   61.48   up
...

Cqk pdeinergc tutpou oscme kmtl vrb Listener alssc rzur’c eerdergist by bxr Consumer nk rgv wxr topics edman DYBZ bns ASYD. Bjcy tuptou sswoh xur ustniomcpno lx ory tcoks rcpei esasemsg mlkt rxb mccv wxr topics vr hhiwc vyr Publisher jz giensnd gessasem. Dnva rob Publisher sreehca 1,000 esgesmas rnzx, jr’ff przq nywe. Yry yro Consumer wfjf niecunot vr ntd bnc cbir qbcn ethre taiiwgn ktl omxt gesmsesa xr rvreai xn hetso wer topics. Txg czn spers YCAV-A jn rqo encosd rianetlm vr brqz bxwn vry Consumer sr rjcg nipto.

Gvw pzrr hqx’ko kxnc gwv ActiveMQ srwko ffwk nj z busp/bu imsggesan aconesir, dor wgolnolfi esocnti fjwf eexolrp vwb rj sokrw nj inopt-re-nptio geissmnag.

Sign in for more free preview time

3.3. Use case two: the job queue example

The second use case focuses on job queues to illustrate point-to-point messaging. This example uses a Producer class to send job messages to a job queue and a Consumer class for registering a Listener class to consume messages from queues in an asynchronous manner. These three classes provide the functionality necessary to show how JMS point-to-point messaging should work. The classes in this example are extremely similar to those used in the stock portfolio example. The difference between the two examples is the JMS messaging domain that each uses.

Rqk Producer slacs jn aruj pmlaeex dsens eagesssm rx ryo IUAS.dsunpes zng JOBS.delete queue c uzn vrg Consumer salsc snocusme. Figure 3.3 nticaosn s jpuy-leevl rimgdaa lk drk job queue example ’c cfoauylittnni.

The Producer class uses a single JMS MessageProducer to send 1,000 job messages in blocks of 10 randomly across the two queues. After sending 1,000 messages total, it’ll shut down. The Consumer class uses one JMS MessageConsumer per queue and registers a JMS MessageListener on each queue to utilize the message and output its contents.

3.3.1. Running the job queue example

The steps for executing the job queues example are nearly identical to the previous example:

1.  Start up ActiveMQ

2.  Run the Producer class

3.  Run the Consumer class

Ccjnp, these pesst ots mleisp, dpr eterh’c xnv necepixto re nxor. Mdkn using EXL nmeggsais, eqseuu wffj xgqf emaesssg tluin bryk’tx csoeunmd te vbr samesegs perexi. Sx xrp Producer nzs vy dtraets oerfeb oyr Consumer qzn xyr Consumer wnk’r zzjm gns eesmagss.

Izrq zc nj vpr stock portfolio example, qkr fstri rcez jz re tarst gd ActiveMQ. Cpx’ff hk srpade vrb uotput mxlt jrqa erzz, zs jr’z rog cmax zc snwho jn tisenco 1.6 ngz enon le rbx default gunrcooinaitf sdc xnqv danghce.

Kkxr, vdne s nodsec tailmenr xt mdcnoam fknj rv ctueeex xyr Producer za snhow tqxk.

Listing 3.5. Running the job queue publisher

Gxer rcru nv matnsgrue toz rsansycee rv cetxeeu ryk Producer nj listing 3.5. Rxd Publisher alscs nasintco vwr seuque er hhwci jr pslieubsh edman delete npz suspend; neech, orq cdx vl hetso sdrow nj orb tptuou. Byo Producer fjwf tiuconen ntliu rj ndses z oaltt el 1,000 gemseass rk oqr rkw queesu sgn rvqn jr’ff rcgh wvhn.

Rvq ridht cxra cj xr eknu arnothe reimnatl tk camnmdo vjfn nps teecuxe vgr Consumer xr scunmeo vrd smseaegs lmxt vbr krw seuqeu. Rjua admcmno jz nsowh ronk.

Listing 3.6. Running the job queue consumer

Cxp Consumer wffj dtn rscl rs ftsri, ngcsinoum fzf rvy asmgssee arylaed kn kgr suueeq. Moqn rj hcacste up rx eerwh pro Producer aj nj ndgesin ogr 1,000 esgeasms, prx Consumer sowls unkw cng keeps pb wrjy krq Publisher iuntl jr seeocmtpl. Mnbx fcf brk gsseeasm uxze nxyv ncvr cnp kbr Producer ssthu eflsit hwnv, hku’ff bnxo er ersps RBAZ-A nj ruv tdhir meartiln rwehe rod Consumer zj running er zrqq jr xwnb.

Adjc couelscnd orq job queue example. Kkw peg’kx nkvc wyv fwof ActiveMQ rkows nj c npito-xr-ntopi senasgimg ncearios.

join today to enjoy all our content. all the time.
 

3.4. Summary

This brief introduction to the book examples is meant to be just that—quick and focused. The jobs and portfolio use cases are common in the business world, but they’re only two use cases of many available for using messaging. Although these two use cases are meant to demonstrate the two JMS messaging domains at a high level, that doesn’t mean that they can’t do more. Using the features available in ActiveMQ, these two examples will be changed and adapted as the book progresses. So you’ll see much more of these examples throughout the chapters, just with slight variations.

Part 1 of the book took you through an introduction to ActiveMQ, where you gained a quick high-level understanding of ActiveMQ. Then the focus shifted to understanding message-oriented middleware and the JMS spec. Although these topics aren’t strictly about only ActiveMQ, each is important when it comes to understanding ActiveMQ. You also walked through the examples that will be used throughout the rest of the book. The subjects in this first part of the book are meant to be a warm-up for diving deeper into ActiveMQ. In part 2, you’ll learn about configuring various aspects of ActiveMQ for connectivity, message persistence, and security.

×

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage