SpringBoot 整合 RabbitMQ

一、生产者配置

所在项目为 Producer。

1. 添加maven依赖

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

2. 配置 application.yml

spring:
  rabbitmq:
    addresses: 121.43.153.00:5672
    username: guest
    password: guest
    virtual-host: /
    connection-timeout: 15000

    # 启用消息确认模式
    publisher-confirm-type: correlated
    # 设置return消息模式,注意要和 template.mandatory 一起去配合使用
    publisher-returns: true
    template:
      mandatory: true

3. 发送消息的示例代码:

package com.didiok.component;

import java.util.Map;
import java.util.UUID;

import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;


@Component
public class Sender {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 	这里就是确认消息的回调监听接口,用于确认消息是否被 broker 所收到
     */
    final RabbitTemplate.ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback(){

        /**
         * 确认消息后的处理
         * @param correlationData 作为消息的唯一标识
         * @param ack broker 返回的ack应答
         * @param cause 失败时,这里记录失败原因
         */
        @Override
        public void confirm(CorrelationData correlationData, boolean ack, String cause) {
            System.out.println("confirm执行,correlationDataId:"
                    + correlationData.getId()
                    + ",ack:"
                    + ack
                    + ", cause:"
                    + cause);
        }
    };

    /**
     * 对外发送消息的方法
     * @param message 消息的具体内容
     * @param properties 额外的附加属性
     */
    public void send(Object message, Map<String, Object> properties){

        MessageHeaders headers = new MessageHeaders(properties);
        Message msg = MessageBuilder.createMessage(message, headers);

        // 添加confirm机制的回调函数
        rabbitTemplate.setConfirmCallback(confirmCallback);

        MessagePostProcessor messagePostProcessor = new MessagePostProcessor() {
            @Override
            public org.springframework.amqp.core.Message postProcessMessage(org.springframework.amqp.core.Message message) throws AmqpException {
                System.out.println("postProcessMessage:"+message);
                return message;
            }
        };
        // 指定业务唯一的id
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString().trim());
        // 发消息
        rabbitTemplate.convertAndSend("exchange-test",
                "springboot.producer",
                msg,
                messagePostProcessor,
                correlationData);
    }
}

二、消费者

所在项目为 Consumer。

1. 添加依赖

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

2. 配置 application.yml

spring:
  rabbitmq:
    addresses: 121.43.153.00:5672
    username: guest
    password: guest
    virtual-host: /
    connection-timeout: 15000

    listener:
      simple:
        ## 	表示消费者消费成功消息以后需要手工的进行签收(ack),默认为auto
        acknowledge-mode: manual
        # 并发数
        concurrency: 5
        max-concurrency: 10
        # broker 在接受到消费者的ack之前允许推送给消费者的消息数量
        prefetch: 1

3. 接收消息并消费的示例代码:

package com.didiok.component;

import java.io.IOException;

import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import com.rabbitmq.client.Channel;


@Component
public class Receiver {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 组合使用监听
     * @RabbitListener @QueueBinding @Queue @Exchange
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "queue-test",
                    durable = "true"),
            exchange = @Exchange(
                    name = "exchange-test",
                    durable = "true",
                    type = "topic",
                    ignoreDeclarationExceptions = "true"),
            key = "springboot.*"))
    @RabbitHandler
    public void onMessage(Message message, Channel channel) throws IOException {

        //	1. 收到消息以后进行业务端消费处理
        System.out.println("收到消息:" + message.getPayload());

        //  2. 处理成功之后 获取deliveryTag 并进行手工的ACK操作, 因为我们配置文件里配置的是 手工签收 spring.rabbitmq.listener.simple.acknowledge-mode=manual
        Long deliveryTag = (Long) message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
        System.out.println(deliveryTag);
        channel.basicAck(deliveryTag, false);
    }
}

三、测试

在生产者端编写测试代码,也就是在 Producer 项目中编写测试代码。

package com.test;

import java.util.HashMap;
import java.util.Map;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.imooc.Application;
import com.imooc.component.Sender;


@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class MQTest {

    @Autowired
    private Sender sender;

    @Test
    public void sendMessage() throws InterruptedException {
        String message = "你好,我是消息,我要来了";
        Map<String, Object> properties = new HashMap<>();
        properties.put("attr", "附加属性");
        properties.put("attr2", "另一个附加属性");

        // 发送消息
        sender.send(message, properties);

        Thread.sleep(10000);
    }
}

运行之后,生产者端打印出的信息:

 消费者端打印的信息:

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring Boot框架可以很容易地与RabbitMQ进行集成。为了实现这个目标,你需要在项目的依赖项中添加两个关键的依赖项。首先,你需要添加spring-boot-starter-amqp依赖项,它提供了与RabbitMQ进行通信的必要类和方法。其次,你还需要添加spring-boot-starter-web依赖项,以便在项目中使用Web功能。 在你的项目中创建两个Spring Boot应用程序,一个是RabbitMQ的生产者,另一个是消费者。通过这两个应用程序,你可以实现消息的发送和接收。生产者应用程序负责将消息发送到RabbitMQ的消息队列,而消费者应用程序则负责从队列中接收并处理消息。这样,你就可以实现基于RabbitMQ的消息传递系统。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [SpringBoot整合RabbitMQ](https://blog.csdn.net/K_kzj_K/article/details/106642250)[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_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [Springboot 整合RabbitMq ,用心看完这一篇就够了](https://blog.csdn.net/qq_35387940/article/details/100514134)[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_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [undefined](undefined)[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_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值