springboot 整合rabbitmq

首先导入坐标

使用 生产者:

package com.example.flyway;

import lombok.Data;
import org.junit.jupiter.api.Test;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.amqp.RabbitTemplateConfigurer;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class FlywayApplicationTests {

    @Test
    void contextLoads() {
    }

    @Autowired
    protected RabbitTemplate rabbitTemplate;

    @Test
    public void test()
    {
        rabbitTemplate.convertAndSend("hello" , "hello world");
    }
}

如果只有生产者去生产消息, 而没有消费者去消费消息, 那么rabbitmq不会创建队列。(重点) 因为没有消费者的队列时没有意义的。

当有消费者消费时, 队列才会被创建。

是基于消费者去创建交换机

package rabbitmq;

import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@RabbitListener(queuesToDeclare = @Queue("hello"))
public class Consumer {

    @RabbitHandler
    public void receivel(String message)
    {
        System.out.println("message = " + message);
    }
}

广播模式 消费者端:

    // 广播模式
    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue, //创建一个临时队列  @Queue(value = "xxx" ) 创建一个具名队列
                    exchange = @Exchange(value = "交换机名称" , type="交换机类型" ) // fanout  direct topic
            )
    })
    public void receive2(String message)
    {
        System.out.println("message" + message);
    }

动态路由  消费者端:

    
    // 动态路由
    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue, //创建一个临时队列  @Queue(value = "xxx" ) 创建一个具名队列
                    exchange = @Exchange(value = "topic" , type="topic" ), // fanout  direct topic
                    key = {"user.save" , "user.delete"}
            )
    })
    public void receive3(String message)
    {
        System.out.println("message" + message);
    }

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值