springboot消息之@RabbitListener和@EnableRabbit


接上一節。

使用上述兩個注解可以實現監聽消息隊列。

1、我們在主配置類中加上@EnableRabbit開啟基於注解的RabbitMq

2、我們建立一個BookService.java並為相關方法加上@RabbitListener注解,啟動服務器:

package com.gong.springbootrabbitmq.service;

import com.gong.springbootrabbitmq.bean.Book;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

@Service
public class BookService {

    @RabbitListener(queues = "gong.news")
    public void recieve(Book book){
        System.out.println("收到消息:"+book);
    }

}

服務器啟動時我們就收到了消息,因為上一節我們往gong.news隊列中添加了一條消息。

我們如果繼續添加一條消息:也收到了

3、第二種收消息的模式

    @RabbitListener(queues = "gong")
    public void recieve2(Message message){
        System.out.println(message.getBody());
        System.out.println(message.getMessageProperties());
    }

啟動服務器:

[B@3c45f2e3
MessageProperties [headers={__TypeId__=com.gong.springbootrabbitmq.bean.Book}, contentType=application/json, contentEncoding=UTF-8, contentLength=0, receivedDeliveryMode=PERSISTENT, priority=0, redelivered=false, receivedExchange=exchange.fanout, receivedRoutingKey=, deliveryTag=1, consumerTag=amq.ctag-Y2Y5J6jRFYdOOzkrxz9VLA, consumerQueue=gong]

 


免責聲明!

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



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