消息隊列RabbitMQ與Spring集成


1.RabbitMQ簡介

RabbitMQ是流行的開源消息隊列系統,用erlang語言開發。RabbitMQ是AMQP(高級消息隊列協議)的標准實現。 
官網:http://www.rabbitmq.com/

2.Spring集成RabbitMQ

2.1 maven配置

//pom.xml
<dependency>
      <groupId>com.rabbitmq</groupId>
      <artifactId>amqp-client</artifactId>
      <version>3.5.1</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.amqp</groupId>
        <artifactId>spring-rabbit</artifactId>
        <version>1.4.5.RELEASE</version>
    </dependency>

2.2 rabbmitmq配置文件

//rabbitmq-config.properties
mq.host=127.0.0.1
mq.username=test
mq.password=123456
mq.port=5672
mq.vhost=testmq

2.3 Spring配置

//application-mq.xml
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:rabbit="http://www.springframework.org/schema/rabbit" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
    http://www.springframework.org/schema/rabbit
    http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd" >

    <description>rabbitmq 連接服務配置</description>
    <!-- 連接配置 -->
    <rabbit:connection-factory id="connectionFactory" host="${mq.host}" username="${mq.username}" password="${mq.password}" port="${mq.port}"  virtual-host="${mq.vhost}"/>
    <rabbit:admin connection-factory="connectionFactory"/>

    <!-- spring template聲明-->
    <rabbit:template exchange="amqpExchange" id="amqpTemplate"  connection-factory="connectionFactory"  message-converter="jsonMessageConverter" />

    <!-- 消息對象json轉換類 -->
    <bean id="jsonMessageConverter" class="org.springframework.amqp.support.converter.Jackson2JsonMessageConverter" />  
</beans>

3. 在Spring中使用RabbitMQ

3.1 申明一個消息隊列Queue

//application-mq.xml
<rabbit:queue id="test_queue_key" name="test_queue_key" durable="true" auto-delete="false" exclusive="false" />

說明: 
durable:是否持久化
exclusive: 僅創建者可以使用的私有隊列,斷開后自動刪除
auto_delete: 當所有消費客戶端連接斷開后,是否自動刪除隊列

3.2 交換機定義

//application-mq.xml
<rabbit:direct-exchange name="test-mq-exchange" durable="true" auto-delete="false" id="test-mq-exchange">
    <rabbit:bindings>
        <rabbit:binding queue="test_queue_key" key="test_queue_key"/>
    </rabbit:bindings>
</rabbit:direct-exchange>

說明: 
rabbit:direct-exchange:定義exchange模式為direct,意思就是消息與一個特定的路由鍵完全匹配,才會轉發。 
rabbit:binding:設置消息queue匹配的key

3.3 發送消息Producer

//MQProducer.java
public interface MQProducer {
    /**
     * 發送消息到指定隊列
     * @param queueKey
     * @param object
     */
    public void sendDataToQueue(String queueKey, Object object);
}
@Service
public class MQProducerImpl implements MQProducer {
    @Autowired
    private AmqpTemplate amqpTemplate;

    private final static Logger LOGGER = Logger.getLogger(MQProducerImpl.class);
    /* (non-Javadoc)
     * @see com.stnts.tita.rm.api.mq.MQProducer#sendDataToQueue(java.lang.String, java.lang.Object)
     */
    @Override
    public void sendDataToQueue(String queueKey, Object object) {
        try {
            amqpTemplate.convertAndSend(queueKey, object);
        } catch (Exception e) {
            LOGGER.error(e);
        }

    }
}

說明: 
convertAndSend:將Java對象轉換為消息發送到匹配Key的交換機中Exchange,由於配置了JSON轉換,這里是將Java對象轉換成JSON字符串的形式。

原文:Convert a Java object to an Amqp Message and send it to a default exchange with a specific routing key.

3.4 異步接收消息Consumer

定義監聽器

//QueueListenter.java
@Component
public class QueueListenter implements MessageListener {

    @Override
    public void onMessage(Message msg) {
        try{
            System.out.print(msg.toString());
        }catch(Exception e){
            e.printStackTrace();
        }
    }

}

監聽配置

//application-mq.xml
<rabbit:listener-container connection-factory="connectionFactory" acknowledge="auto">
    <rabbit:listener queues="test_queue_key" ref="queueListenter"/>
</rabbit:listener-container>

說明: 
queues:監聽的隊列,多個的話用逗號(,)分隔 
ref:監聽器

3.5 JUnit測試

//TestQueue.java
@RunWith(value = SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
    "classpath:/ApplicationContext/ApplicationContext-mq.xml"})

public class TestQueue{
    @Autowired
    MQProducer mqProducer;

    final String queue_key = "test_queue_key";

    @Test
    public void send(){
        Map<String,Object> msg = new HashMap()<>;
        msg.put("data","hello,rabbmitmq!");
        mqProducer.sendDataToQueue(query_key,msg);
    }
}

運行測試程序,Run with JUnit,會發送一條消息到test_queue,監聽器監聽到消息后,打印出消息。

至此,已經完成了Spring和RabbmitMQ集成,配置,和使用。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM