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]
扫描二维码关注公众号,回复: 9082546 查看本文章

猜你喜欢

转载自www.cnblogs.com/xiximayou/p/12294724.html