springboot消息之@RabbitListener&@EnableRabbit监听消息队列的内容

本文详细介绍如何在SpringBoot项目中整合RabbitMQ,包括创建服务类、添加监听方法及配置启动类,实现消息接收与处理。通过示例代码展示如何在BookService类中接收来自RabbitMQ的消息。

1-新建service包BookService类

package com.example.springbootamqp.service;

import com.example.springbootamqp.bean.Book;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

@Service
public class BookService {

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

2-启动类上添加注解@EnableRabbit

package com.example.springbootamqp;

import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@EnableRabbit //开启基于注解的RabbitMQ模式
@SpringBootApplication
public class SpringbootRabbitmqAmqpApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootRabbitmqAmqpApplication.class, args);
    }

}

3-运行主程序类

Book类添加toString()方法

发送消息时,监听到消息

4-BookService中添加监听方法

import org.springframework.amqp.core.Message;
    @RabbitListener(queues = "atguigu")
    public void receive02(Message message){
        System.out.println(message.getBody());    //打印消息体
        System.out.println(message.getMessageProperties());     //打印消息头
    }

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值