Enterprise Messaging With    Spring JMS    Bruce Snyder, Senior Software Engineer, SpringSourceFriday, July 8, 2011
Agenda    • Very brief introduction to JMS    • Synchronous JMS With Spring    • Asynchronous JMS With Spring             ...
What is JMS?    • JMS is:           – An API for client-side communications with a JMS provider           – Included in Ja...
JMS is an Abstraction                            4Friday, July 8, 2011
JMS Message                       5Friday, July 8, 2011
Point-to-Point Messaging                               6Friday, July 8, 2011
Publish/Subscribe Messaging                                  7Friday, July 8, 2011
Typical JMS Use                       8Friday, July 8, 2011
Raw JMS                       9Friday, July 8, 2011
JMS With Spring                       10Friday, July 8, 2011
Managed vs. Non-Managed JMS    • Managed           –   JMS provider in a Java EE container           –   JMS resource pool...
JMS With Spring                       12Friday, July 8, 2011
Spring JMS                       • JMS Template                          – Send and receive messages                      ...
JmsTemplate                                                                       Synchronous    •    browse()           –...
The Spring JmsTemplate                                                                      Synchronous   <bean id="connec...
The Spring JmsTemplate                                                                           Synchronous         // Us...
The Spring JmsTemplate                                                                            Synchronous    • Using s...
The Spring JmsTemplate                                                                Synchronous    • Using execute() and...
The Spring JmsTemplate                                                                  Synchronous    • Using execute() w...
The Spring JmsTemplate                                                                              Synchronous    • Using...
The Spring JmsTemplate                                                                       Synchronous    • Resolving JM...
The Spring JmsTemplate                                                                         Synchronous    • MessageCon...
The Spring JmsTemplate                                                    Synchronous    • JmsException hierarchy         ...
The Spring JmsTemplate                                                             Synchronous    • Automatically particip...
The Spring JmsTemplate                                                                      Synchronous    • JmsTemplate d...
Spring JMS                       • JMS Template                         – Send and receive messages                       ...
Managed vs. Non-Managed JMS                                                          Asynchronous         • Non-Managed   ...
JMS Transaction Support                                                           Asynchronous         • Non-Managed XA Tr...
Spring Message-Driven POJOs                                                             Asynchronous         • DefaultMess...
DefaultMessageListenerContainer                                                             Asynchronous    • Highly confi...
SimpleMessageListenerContainer                                        Asynchronous    • No dynamic scaling of consumers   ...
Supported Types of Message Listeners                                                                Asynchronous    • java...
MessageListener                                                                       Asynchronous    • Standard JMS Messa...
DefaultMessageListenerContainer                                                                          Asynchronous    •...
DefaultMessageListenerContainer                                                                         Asynchronous    • ...
SessionAwareMessageListener                                                                            Asynchronous    • P...
DefaultMessageListenerContainer                                                                          Asynchronous    •...
MessageListenerAdapter                                                    Asynchronous    • Handles all message content ty...
MessageListenerAdapter                                                                        Asynchronous          <bean ...
MessageListenerAdapter                                                         Asynchronous    • Handles all raw JMS messa...
MessageListenerAdapter                                                                        Asynchronous          <bean ...
Local Transactions                                                                        Asynchronous          <bean id="...
Global Transactions                                                                                 Asynchronous          ...
Global Transactions                                                                                 Asynchronous         ....
Thank You!           Q&AFriday, July 8, 2011
Upcoming SlideShare
Loading in …5
×

Enterprise Messaging With Spring JMS

9,061 views

Published on

Published in: Technology
0 Comments
8 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
9,061
On SlideShare
0
From Embeds
0
Number of Embeds
4
Actions
Shares
0
Downloads
244
Comments
0
Likes
8
Embeds 0
No embeds

No notes for slide

Enterprise Messaging With Spring JMS

  1. 1. Enterprise Messaging With Spring JMS Bruce Snyder, Senior Software Engineer, SpringSourceFriday, July 8, 2011
  2. 2. Agenda • Very brief introduction to JMS • Synchronous JMS With Spring • Asynchronous JMS With Spring 2Friday, July 8, 2011
  3. 3. What is JMS? • JMS is: – An API for client-side communications with a JMS provider – Included in Java EE • Also stand alone • JMS is not: – A spec for a message broker implementation 3Friday, July 8, 2011
  4. 4. JMS is an Abstraction 4Friday, July 8, 2011
  5. 5. JMS Message 5Friday, July 8, 2011
  6. 6. Point-to-Point Messaging 6Friday, July 8, 2011
  7. 7. Publish/Subscribe Messaging 7Friday, July 8, 2011
  8. 8. Typical JMS Use 8Friday, July 8, 2011
  9. 9. Raw JMS 9Friday, July 8, 2011
  10. 10. JMS With Spring 10Friday, July 8, 2011
  11. 11. Managed vs. Non-Managed JMS • Managed – JMS provider in a Java EE container – JMS resource pooling – Transaction support – Support for EJBs • Non-Managed – Stand alone JMS provider – Manual setup of JMS resources – No guarantee of transactions • Spring supports both environments 11Friday, July 8, 2011
  12. 12. JMS With Spring 12Friday, July 8, 2011
  13. 13. Spring JMS • JMS Template – Send and receive messages synchronously • Message Listener Container – Receive messages asynchronously – Message-Driven POJOs (MDPs) 13Friday, July 8, 2011
  14. 14. JmsTemplate Synchronous • browse() – Browse messages in a queue • convertAndSend() – Send messages synchronously – Convert a Java object to a JMS message • send() – Send a message synchronously using a MessageCreator • receive() and receiveAndConvert() – Receive messages synchronously • execute() – Provides access to callbacks for more complex scenarios • receiveSelected() and receiveSelectedAndConvert() – Receive filtered messages synchronously 14Friday, July 8, 2011
  15. 15. The Spring JmsTemplate Synchronous <bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory" p:brokerURL="tcp://localhost:61616" /> <bean id="destination" class="org.apache.activemq.command.ActiveMQQueue"> <constructor-arg value="FOO.TEST" /> </bean> <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate" p:connectionFactory-ref="connectionFactory" p:defaultDestination-ref="destination" /> <bean id="messageProducer" class="org.bsnyder.spring.jms.producer.SimpleMessageProducer" p:jmsTemplate-ref="jmsTemplate" /> 15Friday, July 8, 2011
  16. 16. The Spring JmsTemplate Synchronous // Use the default destination jmsTemplate.convertAndSend("Hello World!"); // Use a different destination jmsTemplate.convertAndSend(“TEST.BAR”, “Hello World!”); // Use a different destination String textMessage1 = (String) jmsTemplate.receiveAndConvert(); // Use a different destination String textMessage2 = (String) jmsTemplate.receiveAndConvert(“TEST.BAR”); 16Friday, July 8, 2011
  17. 17. The Spring JmsTemplate Synchronous • Using send() with a MessageCreator // Use a MessageCreator callback jmsTemplate.send(destination, new MessageCreator() { public Message createMessage(Session session) throws JMSException { TextMessage message = session.createTextMessage("Hello World!"); message.setIntProperty("someBusinessId", 22); return message; } }); // Receive raw JMS message TextMessage message = jmsTemplate.receive(); 17Friday, July 8, 2011
  18. 18. The Spring JmsTemplate Synchronous • Using execute() and the SessionCallback // Use a SessionCallback jmsTemplate.execute(new SessionCallback() { public Object doInJms(Session session) throws JMSException { Queue queue = session.createQueue("MY.TEST.QUEUE"); MessageProducer producer = session.createProducer(queue); TextMessage message = session.createTextMessage("Hello World!"); producer.send(message); } }); 18Friday, July 8, 2011
  19. 19. The Spring JmsTemplate Synchronous • Using execute() with the ProducerCallback // Use a ProducerCallback jmsTemplate.execute(new ProducerCallback() { public Object doInJms(Session session, MessageProducer producer) throws JMSException { TextMessage message = session.createTextMessage("Hello World!"); producer.send(destination, message); } return null; } }); 19Friday, July 8, 2011
  20. 20. The Spring JmsTemplate Synchronous • Using JMS selector expression // Using a selector expression String selectorExpression = “Timestamp BETWEEN 1218048453251 AND 1218048484330”; jmsTemplate.receiveSelected(destination, selectorExpression); 20Friday, July 8, 2011
  21. 21. The Spring JmsTemplate Synchronous • Resolving JMS destinations – DynamicDestinationResolver (default) • Look up destinations via a simple text name • Just calls session.createQueue() and session.createTopic() – JndiDestinationResolver • Option to fall back to DynamicDestinationResolver – BeanFactoryDestinationResolver • Look up beans that are javax.jms.Destination objects 21Friday, July 8, 2011
  22. 22. The Spring JmsTemplate Synchronous • MessageConverter – SimpleMessageConverter • String <-> javax.jms.TextMessage • Map <-> javax.jms.MapMessage • Serializable object <-> javax.jms.ObjectMessage • byte[] <-> javax.jms.BytesMessage 22Friday, July 8, 2011
  23. 23. The Spring JmsTemplate Synchronous • JmsException hierarchy – Spring-specific unchecked exceptions – Corresponds to JMSException • Advantage – Automatic clean up of JMS resources 23Friday, July 8, 2011
  24. 24. The Spring JmsTemplate Synchronous • Automatically participates in transactions • Provides support for: – Java EE transactions – Spring local transactions (Spring JmsTransactionManager) – Spring global transactions (Spring JtaTransactionManager) • XA requires an XA capable ConnectionFactory • XA resource enlistment is provider specific 24Friday, July 8, 2011
  25. 25. The Spring JmsTemplate Synchronous • JmsTemplate does not provide resource pooling – Utilizes fresh connection/session for every invocation • JMS resource pooling is responsibility of JMS provider • Spring provides support – SingleConnectionFactory • Returns same connection for all calls to createConnection() • Ignores all calls to close() – CachingConnectionFactory • Extends SingleConnectionFactory to add Session caching and automatic Connection recovery 25Friday, July 8, 2011
  26. 26. Spring JMS • JMS Template – Send and receive messages synchronously • Message Listener Container – Receive messages asynchronously – Message-Driven POJOs (MDPs) 26Friday, July 8, 2011
  27. 27. Managed vs. Non-Managed JMS Asynchronous • Non-Managed – JMS MessageConsumer registers a MessageListener – Manual lifecycle management • Managed – EJB Message-Driven Beans 27Friday, July 8, 2011
  28. 28. JMS Transaction Support Asynchronous • Non-Managed XA Transactions – A JMS MessageConsumer can use various acknowledge modes • AUTO_ACKNOWLEDGE • CLIENT_ACKNOWLEDGE • DUPS_OK_ACKNOWLEDGE • local JMS transaction – Standard JMS does not support asynchronous message consumption as part of a XA transaction • Managed XA Transactions – Officially supported only by EJBs 28Friday, July 8, 2011
  29. 29. Spring Message-Driven POJOs Asynchronous • DefaultMessageListenerContainer – Most commonly used container – Allows for dynamic scaling of queue consumers – Participates in external transactions • SimpleMessageListenerContainer – Very basic – Static configuration – No external transaction support 29Friday, July 8, 2011
  30. 30. DefaultMessageListenerContainer Asynchronous • Highly configurable – Dynamic scale up/down of consumers • Threads managed by the container – Customizable via the Spring TaskExecutor • Resource caching – Connection, Session, MessageConsumer – Default is to cache nothing so as work in Java EE environments – See the setCacheLevel() method for more info • Works in managed and non-managed environments • Supports XA message consumption 30Friday, July 8, 2011
  31. 31. SimpleMessageListenerContainer Asynchronous • No dynamic scaling of consumers • No support for XA transactions 31Friday, July 8, 2011
  32. 32. Supported Types of Message Listeners Asynchronous • javax.jms.MessageListener interface – Standard Java EE interface – Threading is up to you • SessionAwareMessageListener interface – Spring-specific interface – Provides access to the Session object • Very useful for request-response messaging • MessageListenerAdapter interface – Spring-specific interface – Allows for type-specific message handling – No JMS dependencies whatsoever 32Friday, July 8, 2011
  33. 33. MessageListener Asynchronous • Standard JMS MessageListener • Uses an onMessage() method public class MyMessageListener implements MessageListener { private static Logger LOG = Logger.getLogger(MyMessageListener.class); public void onMessage(Message message) throws JMSException { try { LOG.info("Consumed message: “ + message); // Do some processing here } catch (JMSException e) { LOG.error(e.getMessage(), e); } } 33Friday, July 8, 2011
  34. 34. DefaultMessageListenerContainer Asynchronous • XML configuration <bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory" p:brokerURL="tcp://localhost:61616" /> <bean id="messageListener" class="org.bsnyder.spring.jms.listener.SimpleMessageListener" /> <jms:listener-container concurrency="5-10"> <jms:listener destination="FOO.TEST" ref="messageListener"/> </jms:listener-container> 34Friday, July 8, 2011
  35. 35. DefaultMessageListenerContainer Asynchronous • Use more than one listener <bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory" p:brokerURL="tcp://localhost:61616" /> <bean id="widgetListener" class="org.bsnyder.spring.jms.listener.WidgetMessageListener" /> <bean id="gadgetListener" class="org.bsnyder.spring.jms.listener.GadgetMessageListener" /> <jms:listener-container concurrency="5-10"> <jms:listener destination="PRODUCTS.WIDGETS" ref="widgetListener"/> <jms:listener destination="PRODUCTS.GADGETS" ref="gadgetListener"/> </jms:listener-container> 35Friday, July 8, 2011
  36. 36. SessionAwareMessageListener Asynchronous • Provides access to the session • Uses an onMessage() method public class MySessionAwareMessageListener implements SessionAwareMessageListener { private static Logger LOG = Logger.getLogger(MySessionAwareMessageListener.class); public void onMessage(Message message, Session session) throws JMSException { try { LOG.info("Consumed message: “ + ((TextMessage)message).getText()); // Send a reply message TextMessage newMessage = session.createTextMessage(“This is a test”); MessageProducer producer = session.createProducer(message.getJMSReplyTo()); LOG.info("Sending reply message "); producer.send(newMessage); } catch (JMSException e) { LOG.error(e.getMessage(), e); } } } 36Friday, July 8, 2011
  37. 37. DefaultMessageListenerContainer Asynchronous • XML configuration <bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory" p:brokerURL="tcp://localhost:61616" /> <bean id="messageListener" class="org.bsnyder.spring.jms.listener.MySessionAwareMessageListener" /> <jms:listener-container concurrency="5-10"> <jms:listener destination="FOO.TEST" ref="messageListener"/> </jms:listener-container> 37Friday, July 8, 2011
  38. 38. MessageListenerAdapter Asynchronous • Handles all message content types • No reply message is sent (void return) public interface MessageDelegate { void processMessage(String text); void processMessage(Map map); void processMessage(byte[] bytes); void processMessage(Serializable obj); } 38Friday, July 8, 2011
  39. 39. MessageListenerAdapter Asynchronous <bean id="messageDelegate" class="org.springframework.jms.listener.adapter.MessageListenerAdapter" p:defaultListenerMethod="processMessage"> <constructor-arg> <bean class="org.bsnyder.spring.jms.adapter.MessageDelegateImpl" /> </constructor-arg> <property name="messageConverter"> <null/> </property> </bean> <jms:listener-container concurrency="5-10"> <jms:listener destination="FOO.TEST" ref="messageDelegate" /> </jms:listener-container> 39Friday, July 8, 2011
  40. 40. MessageListenerAdapter Asynchronous • Handles all raw JMS message types • No reply message is sent (void return) public interface MessageDelegate { void processMessage(TextMessage message); void processMessage(MapMessage message); void processMessage(BytesMessage message); void processMessage(ObjectMessage message); } 40Friday, July 8, 2011
  41. 41. MessageListenerAdapter Asynchronous <bean id="messageDelegate2" class="org.springframework.jms.listener.adapter.MessageListenerAdapter" p:defaultListenerMethod="processMessage"> <constructor-arg> <bean class="org.bsnyder.spring.jms.adapter.MessageDelegate2Impl" /> </constructor-arg> <property name="messageConverter"> <null/> </property> </bean> <jms:listener-container concurrency="5-10"> <jms:listener destination="FOO.TEST2" ref="messageDelegate2" /> </jms:listener-container> 41Friday, July 8, 2011
  42. 42. Local Transactions Asynchronous <bean id="messageDelegate" class="org.springframework.jms.listener.adapter.MessageListenerAdapter" p:defaultListenerMethod="processMessage"> <constructor-arg> <bean class="org.bsnyder.spring.jms.adapter.MessageDelegateImpl" /> </constructor-arg> <property name="messageConverter"> <null/> </property> </bean> <jms:listener-container concurrency="5-10" acknowledge=”transacted”> <jms:listener destination="FOO.TEST" ref="messageDelegate" /> </jms:listener-container> 42Friday, July 8, 2011
  43. 43. Global Transactions Asynchronous <bean id="activemqXaConnectionFactory" class="org.apache.activemq.ActiveMQXAConnectionFactory" p:brokerURL="tcp://localhost:61616" /> <bean id="atomikosConnectionFactory" class="com.atomikos.jms.AtomikosConnectionFactoryBean" init-method="init" destroy-method="close"> <property name="uniqueResourceName" value="simpleTransaction"/> <property name="xaConnectionFactory" ref="activemqXaConnectionFactory"/> </bean> <bean id="atomikosTransactionManager" class="com.atomikos.icatch.jta.J2eeTransactionManager" /> <bean id="atomikosUserTransaction" class="com.atomikos.icatch.jta.J2eeUserTransaction" /> <bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager" p:transactionManager-ref="atomikosTransactionManager" p:userTransaction-ref="atomikosUserTransaction"> </bean> ... 43Friday, July 8, 2011
  44. 44. Global Transactions Asynchronous ... <bean id="messageDelegate" class="org.springframework.jms.listener.adapter.MessageListenerAdapter" p:defaultListenerMethod="processMessage"> <constructor-arg> <bean class="org.bsnyder.spring.jms.adapter.MessageDelegateImpl" /> </constructor-arg> <property name="messageConverter"> <null/> </property> </bean> <jms:listener-container concurrency="5-10" connection-factory="atomikosConnectionFactory" transaction-manager="transactionManager" acknowledge="transacted"> <jms:listener destination="FOO.TEST" ref="messageDelegate" /> </jms:listener-container> 44Friday, July 8, 2011
  45. 45. Thank You! Q&AFriday, July 8, 2011

×