ActiveMQ消息队列从入门到实践(4)—使用Spring JMS收发消息

Java消息服务(Java Message Service ,JMS)是一个Java标准,定义了使用消息代理的通用API 。在JMS出现之前,每个消息代理都有私有的API,这就使得不同代理之间的消息代码很难通用。但是借助JMS,所有遵从规范的实现都使用通用的接口,这就类似于JDBC为数据库操作提供了通用的接口一样。

Spring通过基于模板的抽象为JMS功能提供了支持,这个模板也就是JmsTemplate。使用JmsTemplate ,能够非常容易地在消息生产方发送队列和主题消息,在消费消息的那一方,也能够非常容易地接收这些消息。

QueueTopic比较如下图所示:

ActiveMQ消息队列从入门到实践(4)—使用Spring JMS收发消息_第1张图片

 

使用maven管理依赖包,增加pom.xml文件如下:


	
		junit
		junit
		4.12
		test
	
	
		org.apache.activemq
		activemq-all
		5.11.0
	
	
		org.springframework
		spring-jms
		4.1.4.RELEASE
	
	  
        org.springframework  
        spring-test  
        4.1.4.RELEASE  
     

  

队列(Queue)消息的收发

点对点消息,如果没有消费者在监听队列,消息将保留在队列中,直至消息消费者连接到队列为止。这种消息传递模型是传统意义上的懒模型或轮询模型。在此模型中,消息不是自动推动给消息消费者的,而是要由消息消费者从队列中请求获得(拉模式)。

 

Spring配置文件内容如下:




	
	
		
	
	
	
	
		
		
			queue1
		
	
	
	
	
		
		
		
	
	
	
	
		
	

	
	
		
	

 

消息生产者使用Spring JMS消息,减少重复代码(接口类ProducerService代码省略)如下:

package com.yoodb.mq.queue;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;

public class ProducerServiceImpl implements ProducerService {

  private JmsTemplate jmsTemplate;
  
  /**
   * 向指定队列发送消息
   */
  public void sendMessage(Destination destination, final String msg) {
    System.out.println("向队列" + destination.toString() + "发送了消息___" + msg);
    jmsTemplate.send(destination, new MessageCreator() {
      public Message createMessage(Session session) throws JMSException {
        return session.createTextMessage(msg);
      }
    });
  }

/**
 * 向默认队列发送消息
 */
  public void sendMessage(final String msg) {
	String destination =  jmsTemplate.getDefaultDestination().toString();
    System.out.println("向队列" +destination+ "发送了消息___" + msg);
    jmsTemplate.send(new MessageCreator() {
      public Message createMessage(Session session) throws JMSException {
        return session.createTextMessage(msg);
      }
    });

  }

  public void setJmsTemplate(JmsTemplate jmsTemplate) {
    this.jmsTemplate = jmsTemplate;
  }

}

 

消息消费者代码如下:

package com.yoodb.mq.queue;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.TextMessage;

import org.springframework.jms.core.JmsTemplate;

public class ConsumerServiceImpl implements ConsumerService {

	private JmsTemplate jmsTemplate;

	/**
	 * 接受消息
	 */
	public void receive(Destination destination) {
		TextMessage tm = (TextMessage) jmsTemplate.receive(destination);
		try {
			System.out.println("从队列" + destination.toString() + "收到了消息:\t"
					+ tm.getText());
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}

	public void setJmsTemplate(JmsTemplate jmsTemplate) {
		this.jmsTemplate = jmsTemplate;
	}

}

 

队列消息监听,在接受消息的时候,可以不用消息消费者代码的方式,Spring JMS同样提供了消息监听的模式,对应的配置和代码内容。

Spring配置文件如下:



	
	
		queue2
	







	
	
	

 

监听类代码如下:

package com.yoodb.mq.queue;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

public class QueueMessageListener implements MessageListener {
        //当收到消息时,自动调用该方法。
	public void onMessage(Message message) {
		TextMessage tm = (TextMessage) message;
		try {
			System.out.println("ConsumerMessageListener收到了文本消息:\t"
					+ tm.getText());
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}

}

 

主题(Topic)消息收发

pub/sub消息传递模型基本上是一个推模型。在该模型中,消息会自动广播,消息消费者无须通过主动请求或轮询主题的方法来获得新的消息。在使用Spring JMS的时候,主题[订阅/发布](Topic)和队列消息模式的主要差异体现在JmsTemplate中"pubSubDomain"是否设置为True。如果为True,则是Topic;如果是false或者默认,则是Queue。


 

Spring配置文件内容如下:



    
    guo_topic
    




    
    
    
    




    








    
    
    

 

 

消息发布者代码如下:

package com.yoodb.mq.topic;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
public class TopicProvider {
    private JmsTemplate topicJmsTemplate;
    /**
     * 向指定的topic发布消息
     * 
     * @param topic
     * @param msg
     */
    public void publish(final Destination topic, final String msg) {
        topicJmsTemplate.send(topic, new MessageCreator() {
        public Message createMessage(Session session) throws JMSException {
            System.out.println("topic name 是" + topic.toString()
            + ",发布消息内容为:\t" + msg);
            return session.createTextMessage(msg);
        }
    });
    }
    public void setTopicJmsTemplate(JmsTemplate topicJmsTemplate) {
        this.topicJmsTemplate = topicJmsTemplate;
    }
}

 

消息订阅者(监听)代码如下:

package com.yoodb.mq.topic;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
/**
 *和队列监听的代码一样。
 */
public class TopicMessageListener implements MessageListener {
    public void onMessage(Message message) {
        TextMessage tm = (TextMessage) message;
        try {
            System.out.println("TopicMessageListener \t" + tm.getText());
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}

 

测试代码如下:

package com.yoodb.mq;
import javax.jms.Destination;
import com.yoodb.mq.queue.ConsumerService;
import com.yoodb.mq.queue.ProducerService;
import com.yoodb.mq.topic.TopicProvider;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
 * 测试Spring JMS
 * 
 * 1.测试生产者发送消息
 * 
 * 2. 测试消费者接受消息
 * 
 * 3. 测试消息监听
 * 
 * 4.测试主题监听
 *
 */
@RunWith(SpringJUnit4ClassRunner.class)
// ApplicationContext context = new
// ClassPathXmlApplicationContext("applicationContext.xml");
@ContextConfiguration("/applicationContext.xml")
public class SpringJmsTest {
    /**
     * 队列名queue1
     */
    @Autowired
    private Destination queueDestination;
    
    /**
     * 队列名queue2
     */
    @Autowired
    private Destination queueDestination2;
    
    /**
     * 主题 guo_topic
     */
    @Autowired
    @Qualifier("topicDestination")
    private Destination topic;
    
    /**
     * 主题消息发布者
     */
    @Autowired
    private TopicProvider topicProvider;
    
    /**
     * 队列消息生产者
     */
    @Autowired
    @Qualifier("producerService")
    private ProducerService producer;
    
    /**
     * 队列消息生产者
     */
    @Autowired
    @Qualifier("consumerService")
    private ConsumerService consumer;
    
    /**
     * 测试生产者向queue1发送消息
     */
    @Test
    public void testProduce() {
    String msg = "Hello world!";
        producer.sendMessage(msg);
    }
    
    /**
     * 测试消费者从queue1接受消息
     */
    @Test
    public void testConsume() {
        consumer.receive(queueDestination);
    }
    
    /**
     * 测试消息监听
     * 
     * 1.生产者向队列queue2发送消息
     * 
     * 2.ConsumerMessageListener监听队列,并消费消息
     */
    @Test
    public void testSend() {
        producer.sendMessage(queueDestination2, "Hello China!!!");
    }
    
    /**
     * 测试主题监听
     * 1.生产者向主题发布消息
     * 2.ConsumerMessageListener监听主题,并消费消息
     */
    @Test
    public void testTopic() throws Exception {
        topicProvider.publish(topic, "Hello T-To-Top-Topi-Topic!");
    }
}

 

测试结果如下:

topic name 是topic://guo_topic,发布消息内容为:Hello T-To-Top-Topi-Topic!
TopicMessageListener Hello T-To-Top-Topi-Topic!
向队列queue://queue2发送了消息___Hello China!!!
ConsumerMessageListener收到了文本消息:Hello China!!!
向队列queue://queue1发送了消息___Hello world!
从队列queue://queue1收到了消息:Hello world!

 

其他相关文章推荐:

ActiveMQ消息队列从入门到实践(4)—使用Spring JMS收发消息

ActiveMQ消息队列从入门到实践(3)—通过ActiveMQ收发消息

ActiveMQ消息队列从入门到实践(2)—Windows安装activemq服务

ActiveMQ消息队列从入门到实践(1)—JMS的概念和JMS消息模型

你可能感兴趣的:(ActiveMQ消息队列从入门到实践(4)—使用Spring JMS收发消息)