欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > IT业 > 初识队列MQ

初识队列MQ

2025/7/15 20:06:56 来源:https://blog.csdn.net/q12ERTYU/article/details/143505016  浏览:    关键词:初识队列MQ

 

MQ的基本概念

MQ(Message Queue)是一种技术服务,具有接收数据、存储数据、发送数据等功能。它是一个FIFO(先入先出)的队列,用于上下游传递消息,实现逻辑解耦和物理解耦。

为什么使用MQ:

MQ能帮助解决高并发流量削峰、异步处理、应用解耦等问题,提高系统性能和扩展性

RabbitMQ

RabbitMQ概述:RabbitMQ是一种分布式消息中间件,用于构建分布式系统的数据通信

RabbitMQ的工作原理:RabbitMQ通过交换机(Exchange)、队列(Queue)和绑定关系来实现消息的发送和接收。

 

Java客户端操作

常规操作:包括发送消息和接收消息。

• 交换机类型:RabbitMQ支持多种类型的交换机,包括广播交换(FanoutExchange)、定向交换机(Direct Exchange)和话题交换机(Topic Exchange)。•

声明队列和交换机:在Java客户端中,可以通过注解或API声明队列和交换机。

进阶操作

发送者的可靠性:包括发送者重连和发送者确认机制。

• MQ的可靠性:涉及数据持久化和Lazy Queue(惰性队列)。

• 接收者的可靠性:包括消费者确认机制、失败重试机制和业务幂等性。

• 延迟消息:通过死信交换机和延迟消息插件实现。

应用场景

 异步处理:将非核心业务流程以异步并行的方式执行,减少请求响应时间,提高系统吞吐量。

• 应用解耦:MQ作为中介,实现生产方和消费方的解耦。

• 流量削峰:在高并发场景下,通过MQ缓存消息,平滑处理流量高峰。

发送消息

import com.rabbitmq.client.Channel;

import com.rabbitmq.client.Connection;

import com.rabbitmq.client.ConnectionFactory;

 

public class SendMessage {

 

    private final static String QUEUE_NAME = "hello";

 

    public static void main(String[] argv) throws Exception {

        ConnectionFactory factory = new ConnectionFactory();

        factory.setHost("localhost"); // RabbitMQ服务地址

        try (Connection connection = factory.newConnection();

             Channel channel = connection.createChannel()) {

            channel.queueDeclare(QUEUE_NAME, false, false, false, null);

            String message = "Hello World!";

            channel.basicPublish("", QUEUE_NAME, null, message.getBytes());

            System.out.println(" [x] Sent '" + message + "'");

        }

    }

}

接受消息

import com.rabbitmq.client.*;

 

import java.io.IOException;

import java.nio.charset.StandardCharsets;

import java.util.concurrent.TimeoutException;

 

public class ReceiveMessage {

    private final static String QUEUE_NAME = "hello";

 

    public static void main(String[] argv) throws IOException, TimeoutException {

        ConnectionFactory factory = new ConnectionFactory();

        factory.setHost("localhost"); // RabbitMQ服务地址

        Connection connection = factory.newConnection();

        Channel channel = connection.createChannel();

 

        channel.queueDeclare(QUEUE_NAME, false, false, false, null);

        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

 

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {

            String message = new String(delivery.getBody(), StandardCharsets.UTF_8);

            System.out.println(" [x] Received '" + message + "'");

        };

        channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { });

    }

}

在Spring Boot中集成RabbitMQ的步骤和代码示例:

1.添加依赖在Spring Boot项目的`pom.xml`文件中添加`spring-boot-starter-amqp`依赖:<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-amqp</artifactId>

</dependency>

 

2.配置RabbitMQ在`application.properties`或`application.yml`文件中配置RabbitMQ的连接信息:

# RabbitMQ配置

spring.rabbitmq.host=localhost

spring.rabbitmq.port=5672

spring.rabbitmq.username=guest

spring.rabbitmq.password=guest

spring.rabbitmq.virtual-host=/

 

3.创建生产者使用`RabbitTemplate`类来发送消息:

import org.springframework.amqp.rabbit.core.RabbitTemplate;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;

 

@Component

public class Producer {

    @Autowired

    private RabbitTemplate rabbitTemplate;

 

    public void produce(String message) {

        System.out.println("Message: " + message);

        rabbitTemplate.convertAndSend("notice_queue", message);

    }

}

 

4.创建消费者使用`@RabbitListener`注解来创建消费者:消费者通过`@RabbitListener`注解创建侦听器端点,绑定`notice_queue`队列。import org.springframework.amqp.rabbit.annotation.RabbitHandler;

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

import org.springframework.stereotype.Component;

 

@Component

public class Consumer {

 

    @RabbitHandler

    @RabbitListener(queuesToDeclare = @Queue("notice_queue"))

    public void process(String message) {

        System.out.println("Received message: " + message);

    }

}

 

5.集成验证可以通过单元测试来验证消息的发送和接收:以上步骤和代码示例展示了如何在Spring Boot中集成RabbitMQ,实现消息的发送和接收。这些信息可以帮助您快速开始使用RabbitMQ在Spring Boot项目中进行消息队列的操作。

import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.test.context.SpringBootTest;

 

@SpringBootTest

public class RabbitMQTests {

    @Autowired

    Producer producer;

 

    @Test

    public void amqpTest() throws InterruptedException {

        // 生产者发送消息

        producer.produce("Hello RabbitMQ");

        // 让子弹飞一会儿

        Thread.sleep(1000);

    }

}

 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词