一篇博客带你学会Rabbitmq(后端必知必会)

Rabbitmq

简单案例

目录结构

在这里插入图片描述

引入依赖:

<!--AMQP依赖,包含RabbitMQ-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

生产者

publisher配置中添加:

spring:
  rabbitmq:
    host: ip # 主机名
    port: 5672 # 端口
    virtual-host: / # 虚拟主机
    username: guest # 用户名
    password: guest # 密码

编写测试类:

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringAmqpTest {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Test
    public void testSimpleQueue() {
        // 队列名称
        String queueName = "simple.queue";
        // 消息
        String message = "hello mq!";
        // 发送消息
        rabbitTemplate.convertAndSend(queueName, message);
    }
}

mq管理页面中创建一下simple.queue的队列,然后执行代码。

在这里插入图片描述

在这里插入图片描述

可以看到成功发送消息到消息队列中。

消费者

consumer中同样yaml中配置mq(与生产者同)。

然后编写消费监听类:

@Component
public class SpringRabbitListener {

    @RabbitListener(queues = "simple.queue")
    public void listenSimpleQueueMessage(String msg) throws InterruptedException {
        System.out.println("spring 消费者接收到消息:" + msg);
    }
}

启动:

在这里插入图片描述

就可以消费mq中的消息了。

WorkQueue模型

当然,一个队列,可以由多个消费者去监听。

来实现一下.

生产者:

    @Test
    public void testWorkQueue() throws InterruptedException {
        // 队列名称
        String queueName = "simple.queue";
        // 消息
        String message = "hello, message-";
        for (int i = 0; i < 50; i++) {
            // 发送消息
            rabbitTemplate.convertAndSend(queueName, message + i);
            Thread.sleep(30); // 每次
        }
    }

消费者(这里我们弄两个):

@Component
public class SpringRabbitListener {

    @RabbitListener(queues = "simple.queue")
    public void listenSimpleQueueMessage1(String msg) throws InterruptedException {
        System.out.println("消费者1接收到消息:" + msg);
    }

    @RabbitListener(queues = "simple.queue")
    public void listenSimpleQueueMessage2(String msg) throws InterruptedException {
        System.out.println("消费者2接收到消息:" + msg);
    }
}

启动看一下结果:

先启动消费者,再发送大量消息:

在这里插入图片描述

这里是因为mq有预分配,一人一半,消费能力一样,所以看起来像是轮流一人执行了一次一样,其实不是,后面会说到。

先发送大量消息,再启动消费者:

在这里插入图片描述

这里是因为消费者1先启动了,2还没启动呢,就被1消费完了。

所以我们改造一下测试代码,让消费者消费能力不同,同时让消费者先都启动,然后再送大量消息:

    @RabbitListener(queues = "simple.queue")
    public void listenSimpleQueueMessage1(String msg) throws InterruptedException {
        System.out.println("消费者1接收到消息:" + msg);
        Thread.sleep(20);
    }

    @RabbitListener(queues = "simple.queue")
    public void listenSimpleQueueMessage2(String msg) throws InterruptedException {
        System.out.println("消费者2接收到消息:" + msg);
        Thread.sleep(200);
    }
消费者2接收到消息:hello, message-0
消费者1接收到消息:hello, message-1
消费者1接收到消息:hello, message-3
消费者1接收到消息:hello, message-5
消费者2接收到消息:hello, message-2
消费者1接收到消息:hello, message-7
消费者1接收到消息:hello, message-9
消费者1接收到消息:hello, message-11
消费者2接收到消息:hello, message-4
消费者1接收到消息:hello, message-13
消费者1接收到消息:hello, message-15
消费者1接收到消息:hello, message-17
消费者1接收到消息:hello, message-19
消费者2接收到消息:hello, message-6
消费者1接收到消息:hello, message-21
消费者1接收到消息:hello, message-23
消费者1接收到消息:hello, message-25
消费者2接收到消息:hello, message-8
消费者1接收到消息:hello, message-27
消费者1接收到消息:hello, message-29
消费者1接收到消息:hello, message-31
消费者2接收到消息:hello, message-10
消费者1接收到消息:hello, message-33
消费者1接收到消息:hello, message-35
消费者1接收到消息:hello, message-37
消费者2接收到消息:hello, message-12
消费者1接收到消息:hello, message-39
消费者1接收到消息:hello, message-41
消费者1接收到消息:hello, message-43
消费者2接收到消息:hello, message-14
消费者1接收到消息:hello, message-45
消费者1接收到消息:hello, message-47
消费者1接收到消息:hello, message-49
消费者2接收到消息:hello, message-16
消费者2接收到消息:hello, message-18
消费者2接收到消息:hello, message-20
消费者2接收到消息:hello, message-22
消费者2接收到消息:hello, message-24
消费者2接收到消息:hello, message-26
消费者2接收到消息:hello, message-28
消费者2接收到消息:hello, message-30
消费者2接收到消息:hello, message-32
消费者2接收到消息:hello, message-34
消费者2接收到消息:hello, message-36
消费者2接收到消息:hello, message-38
消费者2接收到消息:hello, message-40
消费者2接收到消息:hello, message-42
消费者2接收到消息:hello, message-44
消费者2接收到消息:hello, message-46
消费者2接收到消息:hello, message-48

可以看到,其实rabbitmq默认有预分配(预取,每个消费者和队列中有一个通道,存放预取的消息),平均分消息,然后各自独立消费,所以消费者2要比消费者1消费完25条(50/2)消息时间长。

显然是不合理的,我们可以改造一下:

控制预取消息个数

配置中prefetch设置为1,每次消费完消息才取下一个。(能力越大,责任越大,消费快的,消费越多)

spring:
  rabbitmq:
    host: ip # 主机名
    port: 5672 # 端口
    virtual-host: / # 虚拟主机
    username: guest # 用户名
    password: guest # 密码
    listener:
      simple:
        prefetch: 1

重新试一下。

消费者2接收到消息:hello, message-0
消费者1接收到消息:hello, message-1
消费者1接收到消息:hello, message-2
消费者1接收到消息:hello, message-3
消费者1接收到消息:hello, message-4
消费者2接收到消息:hello, message-5
消费者1接收到消息:hello, message-6
消费者1接收到消息:hello, message-7
消费者1接收到消息:hello, message-8
消费者1接收到消息:hello, message-9
消费者2接收到消息:hello, message-10
消费者1接收到消息:hello, message-11
消费者1接收到消息:hello, message-12
消费者1接收到消息:hello, message-13
消费者1接收到消息:hello, message-14
消费者2接收到消息:hello, message-15
消费者1接收到消息:hello, message-16
消费者1接收到消息:hello, message-17
消费者1接收到消息:hello, message-18
消费者2接收到消息:hello, message-19
消费者1接收到消息:hello, message-20
消费者1接收到消息:hello, message-21
消费者1接收到消息:hello, message-22
消费者1接收到消息:hello, message-23
消费者2接收到消息:hello, message-24
消费者1接收到消息:hello, message-25
消费者1接收到消息:hello, message-26
消费者1接收到消息:hello, message-27
消费者1接收到消息:hello, message-28
消费者2接收到消息:hello, message-29
消费者1接收到消息:hello, message-30
消费者1接收到消息:hello, message-31
消费者1接收到消息:hello, message-32
消费者1接收到消息:hello, message-33
消费者2接收到消息:hello, message-34
消费者1接收到消息:hello, message-35
消费者1接收到消息:hello, message-36
消费者1接收到消息:hello, message-37
消费者1接收到消息:hello, message-38
消费者2接收到消息:hello, message-39
消费者1接收到消息:hello, message-40
消费者1接收到消息:hello, message-41
消费者1接收到消息:hello, message-42
消费者1接收到消息:hello, message-43
消费者2接收到消息:hello, message-44
消费者1接收到消息:hello, message-45
消费者1接收到消息:hello, message-46
消费者1接收到消息:hello, message-47
消费者1接收到消息:hello, message-48
消费者2接收到消息:hello, message-49

这样,消费能力大的(消费者1),消费的越多。

发布订阅

在这里插入图片描述

在这里插入图片描述

Fanout 交换机

Fanout 交换机会将收到的消息路由到每一个跟其绑定的queue上。

我们做一个交换机,两个队列,两个消费者分别连接两个队列。

定义交换机,队列,交换机与队列之间的连接:

/**
 * fanout交换机配置
 */
@Configuration
public class FanoutConfig {

    /**
     * 声明交换机,设置名称
     * @return
     */
    @Bean
    public FanoutExchange fanoutExchange() {
        return new FanoutExchange("lpy.fanout");
    }

    /**
     * 队列1
     * @return
     */
    @Bean
    public Queue fanoutQueue1() {
        return new Queue("fanout.queue1");
    }

    /**
     * 绑定交换机和队列1
     */
    @Bean
    public Binding bindingQueue1(Queue fanoutQueue1, FanoutExchange fanoutExchange) {

        return BindingBuilder.bind(fanoutQueue1).to(fanoutExchange);
    }


    /**
     * 队列1
     * @return
     */
    @Bean
    public Queue fanoutQueue2() {
        return new Queue("fanout.queue2");
    }

    /**
     * 绑定交换机和队列2
     */
    @Bean
    public Binding bindingQueue2(Queue fanoutQueue2, FanoutExchange fanoutExchange) {

        return BindingBuilder.bind(fanoutQueue2).to(fanoutExchange);
    }

}

定义监听接口:

    @RabbitListener(queues = "fanout.queue1")
    public void listenFanoutQueue1(String msg) {
        System.out.println("消费者1接收到Fanout消息:" + msg);
    }

    @RabbitListener(queues = "fanout.queue2")
    public void listenFanoutQueue2(String msg) {
        System.out.println("消费者2接收到Fanout消息:" + msg);
    }

发送消息:

    @Test
    public void testFanoutExchange() {
        // 队列名称
        String exchangeName = "lpy.fanout";
        // 消息
        String message = "hello fanout!";
        rabbitTemplate.convertAndSend(exchangeName, "", message);
    }

启动,运行:

在这里插入图片描述

可以看到,我们发的一个消息,被两个消费者消费了,说明实现成功,交换机把消息路由到了每个队列。

Direct 交换机

不同的消息路由到不同的队列,根据key路由建。

在这里插入图片描述

下面来实现一下,基于注解来声明队列和交换机,这样比较方便,直接定义再接口上。

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "direct.queue1"),
            exchange = @Exchange(name = "lpy.direct", type = ExchangeTypes.DIRECT),
            key = {"red", "blue"}
    ))
    public void listenDirectQueue1(String msg){
        System.out.println("消费者1接收到direct.queue1的消息:" + msg);
    }


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "direct.queue2"),
            exchange = @Exchange(name = "lpy.direct", type = ExchangeTypes.DIRECT),
            key = {"red", "yellow"}
    ))
    public void listenDirectQueue2(String msg){
        System.out.println("消费者2接收到direct.queue2的消息:" + msg);
    }

启动测试:

  1. key 为 red
 @Test
    public void testSendDirectExchange() {
        // 交换机名称
        String exchangeName = "lpy.direct";
        // 消息
        String message = "hello direct red";
        // 发送消息
        rabbitTemplate.convertAndSend(exchangeName, "red", message);

        // 消息
        String message2 = "hello direct blue";
        // 发送消息
        rabbitTemplate.convertAndSend(exchangeName, "blue", message2);

        // 消息
        String message3 = "hello direct yellow";
        // 发送消息
        rabbitTemplate.convertAndSend(exchangeName, "yellow", message3);
    }

在这里插入图片描述

可以看到,根据key来进行了路由。

Topic 交换机

Topic 交换机与Direct相似,只不过使用了key可以使用通配符。

RoutingKey一般由一个或多个单词组成,用“.”分割。

通配符规则

# 匹配一个或多个词

* 匹配一个词

例如:

举例:

a.#   可以匹配a.b.c、a.b等

a.*   只可以匹配a.b

现在来实验一下吧:

和Direct同样的写法,只是key改为通配符的:

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "topic.queue1"),
            exchange = @Exchange(name = "lpy.topic", type = ExchangeTypes.TOPIC),
            key = "a.*"
    ))
    public void listenTopicQueue1(String msg){
        System.out.println("消费者接收到topic.queue1的消息:" + msg);
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "topic.queue2"),
            exchange = @Exchange(name = "lpy.topic", type = ExchangeTypes.TOPIC),
            key = "a.#"
    ))
    public void listenTopicQueue2(String msg){
        System.out.println("消费者接收到topic.queue2的消息:" + msg);
    }

发送消息:

    @Test
    public void testSendTopicExchange() {
        // 交换机名称
        String exchangeName = "lpy.topic";
        // 消息
        String message = "hello topic a.b";
        // 发送消息
        rabbitTemplate.convertAndSend(exchangeName, "a.b", message);

        // 消息
        String message1 = "hello topic a.b.c";
        // 发送消息
        rabbitTemplate.convertAndSend(exchangeName, "a.b.c", message1);
    }

运行结果:

在这里插入图片描述

可以看到#确实可以匹配多个单词,而*只能匹配一个。

消息序列化

Spring默认会把你发送的消息通过JDK序列化为字节发送给MQ,接收消息的时候,再把字节反序列化为Java对象。

我们可以配置JSON方式来序列化,这样体积更小,可读性更高。

引入依赖:

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
</dependency>

添加配置类:

@Bean
public MessageConverter jsonMessageConverter(){
    return new Jackson2JsonMessageConverter();
}

接收和发送服务都需要添加。

发一个map消息:

    @Test
    public void testSendMap() throws InterruptedException {
        // 准备消息
        Map<String,Object> msg = new HashMap<>();
        msg.put("name", "小宇");
        msg.put("age", 18);
        // 发送消息
        rabbitTemplate.convertAndSend("simple.queue", msg);
    }
}

在这里插入图片描述

可以看到确实以json格式传输到mq了,非常不错。

  • 28
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Cosmoshhhyyy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值