1. spring configuration file for message acquisition by listener
Different from manual mode
<!-- Scanning package --> <context:component-scan base-package="com.djc.jms" /> <!-- ActiveMQ Connection factory --> <amq:connectionFactory id="amqConnectionFactory" brokerURL="tcp://localhost:61616" userName="admin" password="admin" /> <!-- Spring Caching Connection factory --> <bean id="connectionFactory" class="org.springframework.jms.connection.CachingConnectionFactory"> <property name="targetConnectionFactory" ref="amqConnectionFactory"></property> <property name="sessionCacheSize" value="100" /> </bean> <!-- Spring JmsTemplate News producer start--> <jms:listener-container destination-type="queue" container-type="default" connection-factory="connectionFactory"> <jms:listener destination="queue_test" ref="queueListener"/> </jms:listener-container> <jms:listener-container destination-type="topic" container-type="default" connection-factory="connectionFactory"> <jms:listener destination="topic_test" ref="topicListener1"/> <jms:listener destination="topic_test" ref="topicListener2" /> </jms:listener-container>
2.queue pattern
A class is needed to implement the MessageListener interface, which is handed over to spring management using @Component
@Component public class QueueListener implements MessageListener { @Override public void onMessage(Message arg0) { try { TextMessage message = (TextMessage) arg0; System.out.println("spring Receive a message=="+message.getText()); } catch (JMSException e) { e.printStackTrace(); } } }
3.topic mode
In order to test the topic pattern conveniently, two kinds of patterns are written to imitate two consumers.
//First class @Component public class TopicListener1 implements MessageListener { @Override public void onMessage(Message arg0) { try { MapMessage message = (MapMessage) arg0; System.out.println("TopicListener1 Receive a message=="+message.getString("username")); } catch (JMSException e) { e.printStackTrace(); } } //Second categories @Component public class TopicListener2 implements MessageListener { @Override public void onMessage(Message arg0) { try { MapMessage message = (MapMessage) arg0; System.out.println("TopicListener2 Receive a message=="+message.getString("username")); } catch (JMSException e) { e.printStackTrace(); } } }
4. test
Write a test class to facilitate testing and load configuration files
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext-mq-consumer.xml") public class SpringActiveMQListener { @Test public void testRun(){ while(true); //Keep the method running } }
Finally, by starting to write messages to the middleware, the listener will listen automatically.