SpringBoot与消息队列RabbitMQ详解与整合(二)

一、消息队列监听

实际开发中,需要监听场景

SpringBoot为了简化开发,引入了相关注解。

/**
 * RabbiitMQ自动配置:
 *      1、自动配置类:RabbitAutoConfiguration
 *      2、自动配置了连接工厂ConnectionFactory
 *      3、RabbitProperties 封装了 RabbitMQ的配置
 *      4、RabbitTemplate:给RabbitMQ发送和接收消息
 *      5、AmqpAdmin:RabbitMQ系统管理功能组件
 *              AmqpAdmin:创建和删除 Queue,Exchange,Binding
 *      6、@EnableRabbit + @RabbitListener(queues = {"atguigu.news"}):监听消息队列的内容
 *
 */

1、BookService

监听消息队列

@Service
public class BookService {
    /**
     * 只要这个消息队列中有Book数据进入,该方法就会被调用
     * @param book
     */
    @RabbitListener(queues = {"atguigu.news"})
    public void receive(Book book){
        System.out.println("收到消息 -- " + book);
    }

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

2、开启基于注解的RabbitMQ模式

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

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

3、

 

二、AmqpAdmin:RabbitMQ系统管理功能组件

1、AmqpAdmin:创建和删除 Queue,Exchange,Binding

 2、测试创建交换器

@SpringBootTest
class SpringbootAmqpApplicationTests {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private AmqpAdmin amqpAdmin;

    @Test
    public void createExchange(){
        Exchange exchange = new DirectExchange("amqpadmin.exchange");
        amqpAdmin.declareExchange(exchange);
        System.out.println("创建完成...");
    }

3、创建绑定规则

    @Test
    public void createExchange(){
        /*Exchange exchange = new DirectExchange("amqpadmin.exchange");
        amqpAdmin.declareExchange(exchange);
        System.out.println("创建完成...");*/
       /* amqpAdmin.declareQueue(new Queue("amqpadmin.queue", true));*/
        //创建绑定规则
        amqpAdmin.declareBinding(new Binding("amqpadmin.queue", Binding.DestinationType.QUEUE , "amqpadmin.exchange", "amqp.hei", null));
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值