SpringBoot整合RabbitMQ能者多劳、手动ACK(开源版MQ、阿里云MQ)

一、开源版RabbitMQ

1.依赖:

<dependency>
    <groupId>com.rabbitmq</groupId>
    <artifactId>amqp-client</artifactId>
    <version>5.5.0</version> <!-- 支持开源所有版本 -->
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

2.yml配置:

spring:
 rabbitmq:
   host: 127.0.0.1
   port: 5672
   listener:
     simple:
       # 开启能者多劳模式
       prefetch: 1
       # 开启手动ACK
       acknowledge-mode: manual

3.消费者:监听名为:person_queue 的队列

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;


import java.io.IOException;

@Component
public class PersonQueueConsumer {

    @RabbitListener(queues = "person_queue")
    public void process(String msg, Channel channel, Message message) throws InterruptedException, IOException {
        // 从MQ获取消息
        channel.basicQos(1);

        // 执行业务
        System.out.println("person_queue 监听的数据为  : " + msg + "开始业务处理…………");
        Thread.sleep(3000);

        // 确认ACK
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}

 以上,便可实现能者多劳模式。

二、阿里云RabbitMQ

1.依赖:

<dependency>
    <groupId>com.alibaba.mq-amqp</groupId>
    <artifactId>mq-amqp-client</artifactId>
    <version>1.0.5</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

 

2.yml配置

spring:
  rabbitmq:
    host: xxxx
    port: xxxx
    username: xxxx
    password: xxxx
    virtual-host: xxxx

3.RabbitMQ配置类:


import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConfig {

    @Value("${spring.rabbitmq.host}")
    private String host;

    @Value("${spring.rabbitmq.port}")
    private int port;

    @Value("${spring.rabbitmq.username}")
    private String username;

    @Value("${spring.rabbitmq.password}")
    private String password;

    @Value("${spring.rabbitmq.virtual-host}")
    private String virtualHost;

    @Bean
    public ConnectionFactory connectionFactory() {
        // 初始化RabbitMQ连接配置connectionFactory。
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setHost(host);
        connectionFactory.setPort(port);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        // VirtualHost可以在RabbitMQ控制台手动创建,也可以在这里自动创建。
        connectionFactory.setVirtualHost(virtualHost);
        // 请务必开启Connection自动重连功能,保证服务端发布时客户端可自动重新连接上服务端。
        connectionFactory.getRabbitConnectionFactory().setAutomaticRecoveryEnabled(true);
		    // 缓存模式推荐设置为CONNECTION。
        connectionFactory.setCacheMode(CachingConnectionFactory.CacheMode.CONNECTION);
        // CONNECTION模式下,最大可缓存的connection数量。
        connectionFactory.setConnectionCacheSize(10);
        // CONNECTION模式下,最大可缓存的Channel数量。
        connectionFactory.setChannelCacheSize(64);
        
        return connectionFactory;
    }

    @Bean
    public SimpleRabbitListenerContainerFactory simpleRoutingConnectionFactory(ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        // 手动ACK
        factory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        return factory;
    }


    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        // RabbitMQ消息模板,该模板封装了多种常用的消息操作。
        return new RabbitTemplate(connectionFactory);
    }
}

 4.消费者:绑定配置类的:simpleRoutingConnectionFactory,监听名为:artificial_queue的队列

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;


/**
 * @author djh
 * @since 2023-08-08
 */
@Component
@Slf4j
public class Test {
    @RabbitListener(containerFactory = "simpleRoutingConnectionFactory", queues = "artificial_queue")
    public void receiveFromMyQueue(Message message, Channel channel) {
        try {
            channel.basicQos(1);
        } catch (IOException e) {
            log.error("ArtificialConsumer从mq获取消息失败:" + e);
        }

        // 获取消息
        byte[] body = message.getBody();
        String msg = new String(body, StandardCharsets.UTF_8);

        // 业务代码

        try {
            // 手动ACK
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            log.error("ArtificialConsumer提交消息失败:" + e);
        }
    }
}

 以上,便可实现能者多劳模式。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
SpringBoot整合RabbitMQ中进行手动签收的方法如下所示: 1. 首先,你可以创建一个消费者类,并在该类上添加`@RabbitListener`注解,指定监听的队列。例如,可以创建一个名为`FanoutReceiverB`的消费者类,使用`@RabbitListener(queues = "fanout.B")`指定监听队列为"fanout.B"。 2. 在消费者类中,可以使用`@RabbitHandler`注解标注一个处理消息的方法,该方法接受一个消息参数。例如,在`FanoutReceiverB`类中,可以定义一个名为`process`的方法,参数为`Map testMessage`,用来处理接收到的消息。 3. 在处理方法中,你可以根据业务逻辑进行相应的处理,并手动确认消息的签收。你可以使用`channel.basicAck`方法来手动确认消息的签收。例如,可以在`process`方法中调用`channel.basicAck`方法来手动确认消息的签收。 4. 最后,你需要在pom.xml文件中添加RabbitMQ的相关依赖。可以添加`spring-boot-starter-amqp`和`spring-boot-starter`依赖。例如,在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> ``` 通过以上步骤,你就可以在SpringBoot中实现手动签收RabbitMQ消息了。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [RabbitMQSpringBoot中实现手动签收重试三次进入死信队列](https://blog.csdn.net/shang_0122/article/details/120617954)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [Springboot 整合RabbitMq ,原来这么简单](https://blog.csdn.net/biglow/article/details/119633573)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值