25.02.2015 Views

Introducing Spring Framework

Introducing Spring Framework

Introducing Spring Framework

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 16 ■ Messaging with Your <strong>Spring</strong> Application<br />

Listing 16-4 shows the consumer that will be listening from the docs-txt queue. Next, the WebDocumentsConsumer<br />

class is shown in Listing 16-5.<br />

Listing 16-5. WebDocumentsConsumer.java<br />

package com.apress.isf.spring.amqp;<br />

import org.slf4j.Logger;<br />

import org.slf4j.LoggerFactory;<br />

import org.springframework.stereotype.Component;<br />

import com.apress.isf.java.model.Document;<br />

@Component("webConsumer")<br />

public class WebDocumentsConsumer implements RabbitMQConsumer{<br />

private static final Logger log = LoggerFactory.getLogger(WebDocumentsConsumer.class);<br />

}<br />

public void process(Document document) {<br />

log.debug("Web Document received: " + document);<br />

}<br />

Listing 16-5 shows the consumer that will be listening from the docs-web queue. As you can see, in every<br />

consumer you only log the document received. Of course, here you can add more processing; perhaps you need to<br />

send an e-mail to your subscribers or maybe you want to create a statistic of how many messages you received from<br />

each type. For now just the log will do.<br />

Also, if you look very carefully, every consumer is different from the one you did in Chapter 11. First, you used a<br />

Message object, then you needed to convert the body of the message from an array of bytes to String, and then you<br />

needed to convert it into an object using the Utils class, remember?<br />

Using a XML Marshaller for Message Conversion<br />

So how is RabbitMQ capable of understanding that you are sending a Document object and converting it into an array<br />

of bytes back and forth?<br />

The <strong>Spring</strong> <strong>Framework</strong> has some built-in utilities that help you to do this kind of conversion (from object<br />

to XML and vice versa) and you are going to use them. You will continue to use the XStream library<br />

(http://xstream.codehaus.org/) and now you will be using a <strong>Spring</strong> <strong>Framework</strong> Marshaller that will marshal the<br />

document into XML and un-marshal when you need to get it from String XML to object.<br />

Let’s take a look at the XML configurations, as shown in Listing 16-6. These configurations are the key to the solution.<br />

Listing 16-6. mydocuments-context.xml<br />

<br />

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!