使用SpringAMQP实现工作消息队列功能

1、在工程中引入spring-amqp的依赖

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

2、消息发送

2.1 首先配置MQ地址,在发送消息模块中的application.yml中添加配置:

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

2.2 然后在发送消息模块中编写测试类SpringAmqpWorkTest,并利用RabbitTemplate实现消息发送:

package cn.itheima.mq.helloworld;

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

/**
 * 发送消息测试类
 *
 * @author ning
 * @since 2022/12/2 20:09
 */

@SpringBootTest
public class SpringAmqpWorkTest {

    //注入收发消息模板
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Test
    void testSimpleWorkQueue() {
        //消息
        String msg = "hello, spring amqp!-";
        //队列名称
        String queueName = "simple.queue";
        for (int i = 1; i <= 100; i++) {
            //发送消息,转成字节数组发送
            rabbitTemplate.convertAndSend(queueName,msg + i);
        }

        System.out.println("消息发送完毕");
    }
}

3、接受消息(消费方/监听器)

3.1 首先配置MQ地址,在接受消息模块中的application.yml中添加配置:

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

3.2 然后在接受消息模块的listener包中新建一个类SpringWorkRabbitListener,代码如下:

package cn.itheima.mq.listener;

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

/**
 * 接收消息
 * 测试:工作模型(一个队列,可以由多个消费者平均消费)
 * @author ning
 * @since 2022/12/2 20:31
 */

@Component
public class SpringWorkRabbitListener {

    //声明要监听的队列
    //可以监听多个队列
    //监听一个:queues = ""
    //监听多个:queues = {""}
    @RabbitListener(queues = "simple.queue")
    public void listenWorkQueue1(String msg) {
        System.out.println("消费者1接受到了消息" + msg);
    }

    //声明要监听的队列
    //可以监听多个队列
    //监听一个:queues = ""
    //监听多个:queues = {""}
    @RabbitListener(queues = "simple.queue")
    public void listenWorkQueue2(String msg) {
        System.out.println("消费者2接受到了消息" + msg);
    }
}

以上消费者都是平均分配,这样不能实现能者多劳(有的机器性能好,有的机器性能差),如果想实现效率上的提升,只要让性能好的机器多处理,差的机器少处理,只需在消费模块配置以下配置即可:

spring:
  rabbitmq:
    listener:
      simple:
        prefetch: 1 # 每次只能获取一条消息,处理完成才能获取下一个消息
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值