首页 > 其他分享 >Springboot整合RabbitMQ基本使用

Springboot整合RabbitMQ基本使用

时间:2022-11-19 16:35:46浏览次数:50  
标签:Springboot 队列 RabbitMQ Bean springframework 整合 org import public

1、依赖

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

2、rabbitmq链接配置

spring:
  rabbitmq:
    host: 127.0.0.1
    port: 5672
    username: wq
    password: qifeng
    virtual-host: /
    #开启ack
    listener:
      direct:
        acknowledge-mode: manual
        prefetch: 1 # 限制一次拉取消息的数量
      simple:
        acknowledge-mode: manual #采取手动应答
        #concurrency: 1 # 指定最小的消费者数量
        #max-concurrency: 1 #指定最大的消费者数量
        retry:
          enabled: true # 是否支持重试

3、生产者

  • 声明交换机、队列、绑定关于
package com.wanqi.mq;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Description TODO
 * @Version 1.0.0
 * @Date 2022/11/19
 * @Author wandaren
 */
@Configuration
public class RabbitMQConfig {
    public static final String EXCHANGE_NAME = "boot_topic_exchange";
    public static final String QUEUE_NAME = "boot_queue";
    //交换机
    @Bean("bootExchange")
    public Exchange bootExchange(){
        return ExchangeBuilder.topicExchange(EXCHANGE_NAME).durable(true)
                .build();
    }
    //
    @Bean("bootQueue")
    public Queue bootQueue(){
        return QueueBuilder.durable(QUEUE_NAME).build();
    }
    //队列和交换机绑定关系
    /*
        知道哪个队列
        知道哪个交换机
        知道routing key
     */
    @Bean
    public Binding bindingQueueExchange(@Qualifier("bootQueue") Queue queue,
                                        @Qualifier("bootExchange") Exchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with("boot.#").noargs();
    }
}

  • 发送消息
package com.wanqi;

import com.wanqi.mq.RabbitMQConfig;
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;

@SpringBootTest
class SpringbootMqProducersApplicationTests {
	@Autowired
	private RabbitTemplate rabbitTemplate;

	@Test
	void contextLoads() {
		rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME, "boot.test", "boot mq hello~~~");
	}

}

4、消费者

package com.wanqi.listener;

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;

/**
 * @Description TODO
 * @Version 1.0.0
 * @Date 2022/11/19
 * @Author wandaren
 */
@Component
public class RabbitMQListener {

    @RabbitListener(queues = {"boot_queue"})
    public void listenerQueue(Object msg, Message message, Channel channel) {
        final long deliveryTag = message.getMessageProperties().getDeliveryTag();

        try {
            System.out.println(msg.toString());
            System.out.println(new String(message.getBody()));
//            int x = 3/0;
            channel.basicAck(deliveryTag, true);
        } catch (Exception e) {
            try {
                channel.basicNack(deliveryTag, true, true);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
}

5、死信队列

消息成为死信的三种情况
1、队列消息长度到达限制;
2、消费者拒接消费消息,并且不重回队列;
3、原队列存在消息过期设置,消息到达超时时间未被消费;

5.1、声明交换机、队列、绑定队列

  • topic模式
package com.wanqi.mq;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Description TODO
 * @Version 1.0.0
 * @Date 2022/11/19
 * @Author wandaren
 */
@Configuration
public class QDRabbitMQConfig {
    //交换机名称
    public static final String ITEM_EXCHANGE = "item_exchange";
    public static final String DEAD_EXCHANGE = "dead_exchange";
    //队列名称
    public static final String ITEM_QUEUE = "item_queue";
    public static final String DEAD_QUEUE = "dead_queue";

    //声明业务交换机
    @Bean("itemExchange")
    public Exchange itemExchange(){
        return ExchangeBuilder.topicExchange(ITEM_EXCHANGE).durable(true).build();
    }
    //声明死信交换机
    @Bean("deadExchange")
    public Exchange deadExchange(){
        return ExchangeBuilder.topicExchange(DEAD_EXCHANGE).durable(true).build();
    }

    /**
     * 声明普通队列,设置队列消息过期时间,队列长度,绑定的死信队列
     */
    @Bean("itemQueue")
    public Queue itemQueue(){
        return QueueBuilder
                .durable(ITEM_QUEUE)
                // 队列消息过期时间
                .ttl(10000)
                // 队列长度
                .maxLength(15)
                // 声明当前队列绑定的死信交换机
                .deadLetterExchange(DEAD_EXCHANGE)
                // 声明当前队列死信转发的路由key
                .deadLetterRoutingKey("infoDead.haha")
                .build();
    }
    /**
     * 死信队列,消费者需要监听的队列
     */
    @Bean("deadQueue")
    public Queue deadQueue(){
        return QueueBuilder
                .durable(DEAD_QUEUE)
                .build();
    }

    //绑定队列和交换机(业务)
    @Bean
    public Binding itemQueueExchange(@Qualifier("itemQueue") Queue queue,
                                     @Qualifier("itemExchange") Exchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with("infoRouting.#").noargs();
    }
    //绑定队列和交换机(死信)
    @Bean
    public Binding deadQueueExchange(@Qualifier("deadQueue") Queue queue,
                                     @Qualifier("deadExchange") Exchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with("infoDead.#").noargs();
    }

}

5.2、发送测试消息

package com.wanqi;

import com.wanqi.mq.RabbitMQConfig;
import com.wanqi.mq.RabbitMQConfig2;
import org.junit.jupiter.api.Test;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class SpringbootMqProducersApplicationTests {
	@Autowired
	private RabbitTemplate rabbitTemplate;
    
	// 原队列存在消息过期设置,消息到达超时时间未被消费;
	@Test
	void contextLoads3() {
		MessageProperties messageProperties = new MessageProperties();
		// 设置过期时间,单位:毫秒
		messageProperties.setExpiration("5000");
		byte[] msgBytes = "rabbitmq ttl message ...".getBytes();
		Message message = new Message(msgBytes, messageProperties);

		//发送消息
		rabbitTemplate.convertAndSend(QDRabbitMQConfig.ITEM_EXCHANGE,"infoRouting.hehe",message);
		System.out.println("发送消息成功");
	}
    // 模拟队列消息长度到达限制
	@Test
	void contextLoads4() {
		for (int i = 0; i < 20; i++) {
			rabbitTemplate.convertAndSend(QDRabbitMQConfig.ITEM_EXCHANGE,"infoRouting.hehe",i + "---message");

		}
	}
}

5.3、消费者

package com.wanqi.listener;

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;

/**
 * @Description TODO
 * @Version 1.0.0
 * @Date 2022/11/19
 * @Author wandaren
 */
@Component
public class RabbitMQListener {
    @RabbitListener(queues = {"dead_queue"})
    public void listenerQueue2(Object msg, Message message, Channel channel) {
        final long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            System.out.println(msg.toString());
            channel.basicAck(deliveryTag, true);
        } catch (Exception e) {
            try {
                channel.basicNack(deliveryTag, true, true);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
}

6、延迟队列(TTL + 死信队列)

6.1、声明交换机、队列、绑定队列

  • direct模式

package com.wanqi.mq;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Description TODO
 * @Version 1.0.0
 * @Date 2022/11/19
 * @Author wandaren
 */
@Configuration
public class TtlQueueConfig {
    //普通交换机名称
    public static final String X_CHANGE = "X_Exchange";
    //死信交换机名称
    public static final String Y_DEAD_CHANGE = "Y_Exchange";
    //普通队列
    public static final String QUEUE_A = "QA_QUEUE";
    public static final String QUEUE_B = "QB_QUEUE";
    //死信队列
    public static final String DEAD_QUEUE_D = "QD_QUEUE";

    //声明普通交换机
    @Bean("xExchange")
    public DirectExchange xExchange() {
        return ExchangeBuilder.directExchange(X_CHANGE).durable(true)
                .build();
    }

    //声明死信交换机
    @Bean("yExchange")
    public DirectExchange yExchange() {
        return ExchangeBuilder.directExchange(Y_DEAD_CHANGE).durable(true)
                .build();
    }

    /**
     * 声明队列,延迟10秒
     */

    @Bean("queueA")
    public Queue queueA() {

        return QueueBuilder.durable(QUEUE_A)
                .deadLetterExchange(Y_DEAD_CHANGE) //死信交换机
                .deadLetterRoutingKey("YD")  //死信RoutingKey
                .ttl(10000)  //消息过期时间
                .build();
    }

    /**
     * 声明队列,延迟40秒
     *
     * @return
     */
    @Bean("queueB")
    public Queue queueB() {
        return QueueBuilder.durable(QUEUE_B)
                .deadLetterExchange(Y_DEAD_CHANGE) //死信交换机
                .deadLetterRoutingKey("YD")  //死信RoutingKey
                .ttl(40000)  //消息过期时间
                .build();
    }


    /**
     * 死信队列,消费者需要监听的队列
     */
    @Bean("queueD")
    public Queue queueD() {
        return QueueBuilder.durable(DEAD_QUEUE_D).build();
    }


    //绑定  X_CHANGE绑定queueA
    @Bean
    public Binding queueABindingX(@Qualifier("queueA") Queue queueA, @Qualifier("xExchange") DirectExchange xExchange) {
        return BindingBuilder.bind(queueA).to(xExchange).with("XA");
    }

    //绑定  X_CHANGE绑定queueB
    @Bean
    public Binding queueBBindingX(@Qualifier("queueB") Queue queueB, @Qualifier("xExchange") DirectExchange xExchange) {
        return BindingBuilder.bind(queueB).to(xExchange).with("XB");
    }


    //绑定  Y_CHANGE绑定queueD
    @Bean
    public Binding queueDBindingY(@Qualifier("queueD") Queue queueD, @Qualifier("yExchange") DirectExchange yExchange) {
        return BindingBuilder.bind(queueD).to(yExchange).with("YD");
    }
}

6.2、发送消息

    @Test
    void contextLoads5() {
        String message = "延迟队列消息";
        rabbitTemplate.convertAndSend(TtlQueueConfig.X_CHANGE, "XA", "TTL=10s的队列:" + message);
        rabbitTemplate.convertAndSend(TtlQueueConfig.X_CHANGE, "XB", "TTL=40s的队列:" + message);
    }

6.3、消费

package com.wanqi.listener;

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;
import java.util.Date;

/**
 * @Description TODO
 * @Version 1.0.0
 * @Date 2022/11/19
 * @Author wandaren
 */
@Component
public class RabbitMQListener {
    @RabbitListener(queues = "QD_QUEUE")
    public void receiveMessage(Object msg,Message message, Channel channel){
        final long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            System.out.println(msg.toString());
            System.out.print("当前时间: " + new Date());
            System.out.println("  收到死信队列的消息:" + msg);
            channel.basicAck(deliveryTag, true);
        } catch (Exception e) {
            try {
                channel.basicNack(deliveryTag, true, true);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
}

标签:Springboot,队列,RabbitMQ,Bean,springframework,整合,org,import,public
From: https://www.cnblogs.com/wandaren/p/16906262.html

相关文章

  • 【Java】 Springboot+Vue 大文件断点续传
     同事在重构老系统的项目时用到了这种大文件上传 第一篇文章是简书的这个:https://www.jianshu.com/p/b59d7dee15a6 是夏大佬写的vue-uploader组件:https://www......
  • SpringBoot2.x 事务
    1.事务管理方式 事务管理对于企业应用来说是至关重要的,即使出现异常情况,它也可以保证数据的一致性。spring支持编程式事务管理和声明式事务管理两种方式。 编程......
  • springboot controller
    传值@RestControllerpublicclassHelloController{@GetMapping("/hello")publicStringhello(Stringnickname){return"我是帅哥"+nickname;}}http://l......
  • springboot热部署
    <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><optional>true</optional>......
  • RabbitMQ学习笔记(三)
    三利用RabbitMQ高级特性,完善项目的可靠性3.1如何保证消息的可靠性3.1.1发送方需要使用RabbitMQ发送端确认机制,确认消息成功发送到RabbitMQ并被处理需要使用RabbitM......
  • Springboot 配置 Security流程
    装入依赖引入spring-sercurity<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependen......
  • 十二天----->阿里云短信服务的整合:
    开通短信服务的整合一、新建短信微服务整合阿里云短信服务,注册时候发送手机验证码在service创建子模块service_msm创建包的结构,创建controller和service等结构......
  • SpringBoot整合JUnit
    这个不用自己整合,在创建好SpringBoot项目后在Test文件夹中就能找到,相关的依赖也导入进去了。这里只是进行一个详细的说明。  @SpringBootTest类型:测试类注解位置:测......
  • springboot+minio实现分片上传(超大文件快速上传)
    ​ 设计由来在实际的项目开发中常遇到超大附件上传的情况,有时候客户会上传GB大小的文件,如果按照普通的MultipartFile方式来接收上传的文件,那么无疑会把服务器给干崩......
  • SpringBoot提供的三种配置文件格式
    1、application.properties(传统格式/默认格式)e.g.server.port=80 2、application.yml(主流格式、推荐使用)e.g.server:  port:81 3、application.yamle.g.ser......