SpringBoot整合RabbitMQ快速入门

本文介绍了RabbitMQ的基本概念、使用原因及它在分布式系统中的重要性。详细讲解了如何在SpringBoot项目中整合RabbitMQ,包括创建Maven工程、添加依赖、配置启动类和消费者。并提供了消费者端的简单模式运行结果。
摘要由CSDN通过智能技术生成

概述

1.概述
MQ全称为Message Queue,消息队列是应用程序和应用程序之间的通信方法。

2.为什么使用呢?
在项目中,可将一些无需即时返回且耗时的操作提取出来,进行异步处理,而这种异步处理的方式大大的节省 了服务器的请求响应时间,从而提高了系统的吞吐量

3.RabbitMQ是由erlang语言开发,基于AMQP(Advanced Message Queue 高级消息队列协议)协议实现的消息队 列,它是一种应用程序之间的通信方法,消息队列在分布式系统开发中应用非常广泛。

**RabbitMQ官方地址:http://www.rabbitmq.com/
**

4.RabbitMQ提供了6种模式
简单模式,work模式,Publish/Subscribe发布与订阅模式,Routing路由模式,Topics 主题模式,RPC远程调用模式

加油
5.创建Maven项目。

6.导入相关依赖。

 <dependencies>
        <dependency>
            <groupId>com.rabbitmq</groupId>
            <artifactId>amqp-client</artifactId>
            <version>5.6.0</version>
        </dependency>
    </dependencies>

7.项目结构
在这里插入图片描述
8.消费者,简单模式

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;


/**
 * 简单模式
 */
public class Producer {

    static final String QUEUE_NAME = "simple_queue";

    public static void main(String[] args) throws Exception {
        //1. 创建连接工厂(设置RabbitMQ的连接参数);
        ConnectionFactory connectionFactory = new ConnectionFactory();
        //主机;默认localhost
        connectionFactory.setHost("localhost");
        //连接端口;默认5672
        connectionFactory.setPort(5672);
        //虚拟主机;默认/
        connectionFactory.setVirtualHost("/zyk");
        //用户名;默认guest
        connectionFactory.setUsername("guest");
        //密码;默认guest
        connectionFactory.setPassword("guest");

        //2. 创建连接;
        Connection connection = connectionFactory.newConnection();
        //3. 创建频道;
        Channel channel = connection.createChannel();
        //4. 声明队列;
        /**
         * 参数1:队列名称
         * 参数2:是否定义持久化队列(消息会持久化保存在服务器上)
         * 参数3:是否独占本连接
         * 参数4:是否在不使用的时候队列自动删除
         * 参数5:其它参数
         */
        channel.queueDeclare(QUEUE_NAME, true, false, false, null);
        //5. 发送消息;
        String message = "你好!RabbitMQ~~";

        /**
         * 参数1:交换机名称;如果没有则指定空字符串(表示使用默认的交换机)
         * 参数2:路由key,简单模式中可以使用队列名称
         * 参数3:消息其它属性
         * 参数4:消息内容
         */
        channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
        System.out.println("已发送消息:" + message);
        //6. 关闭资源
        channel.close();
        connection.close();
    }
}

运行结果:
在这里插入图片描述在这里插入图片描述
消费者,简单模式


```java
import com.rabbitmq.client.*;
import com.zyk.rabbitmq.util.ConnectionUtil;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 简单模式,消费者接收消息
 */
public class Consumer {

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

        Connection connection = ConnectionUtil.getConnection();

        //创建频道
        Channel channel = connection.createChannel();

        //声明队列
        /**
         * 参数1:队列名称
         * 参数2:是否定义持久化队列
         * 3:是否独占连接
         * 4.是否在不适使用的时候队列自动删除
         * 5.其他参数
         * */
        channel.queueDeclare(Producer.QUEUE_NAME, true, false, false, null);


        //创建消费者
        DefaultConsumer defaultConsumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                /**
                 * 路由key
                 * 交换机
                 * 消息ID
                 * 接收到的消息
                 */
                System.out.println("路由key:" + envelope.getRoutingKey());

                System.out.println("交换机:" + envelope.getExchange());

                System.out.println("消息Id:" + envelope.getDeliveryTag());

                System.out.println("接收到的消息" + new String(body, "utf-8"));
            }
        };

        //监听队列
        /**
         * 参数1:队列名
         * 2:是否自动确认
         * 3:消息消费者
         */
        channel.basicConsume(Producer.QUEUE_NAME,true,defaultConsumer);
    }
}

运行结果
在这里插入图片描述

SpringBoot整合RabbitMQ

1.创建Maven工程。

2.添加依赖。

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.5.RELEASE</version>
    </parent>

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

3.添加启动引导类

/**
 * 生产者
 */
@SpringBootApplication
public class ProducerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ProducerApplication.class, args);
    }
}
/**
 * 消费者
 */
@SpringBootApplication
public class ConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class, args);
    }
}

4.配置类,在消费者这边。

/**
 * 配置类
 */
@Configuration
public class RabbitMQConfig {

    //交换机名称
    public static final String ZYK_TOPIC_EXCHANGE="zyk_topic_exchange";

    //队列名称
    public static final String ZYK_QUEUE="zyk_queue";

    //声明交换机
    @Bean("zykTopicExchange")
    public Exchange zykTopicExchange(){
        return ExchangeBuilder.topicExchange(ZYK_TOPIC_EXCHANGE).durable(true).build();
    }

    //声明队列
    @Bean("zykQueue")
    public Queue zykQueue(){
        return QueueBuilder.durable(ZYK_QUEUE).build();
    }

    //将队列绑定到交换机
    @Bean
    public Binding zykQueueExchange(@Qualifier("zykQueue") Queue queue,
                                    @Qualifier("zykTopicExchange")Exchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with("item.#").noargs();
    }
}

application.yml文件 消费者跟生产者配置文件一样。复制就OK。

spring:
  rabbitmq:
    host: localhost
    port: 5672
    virtual-host: /自己创建的虚拟主机
    username: 自己创建的账号
    password: 自己的密码

5.消费者

/**
 * 消费者
 */
@Component
public class MyListener {

    /**
     * 接收队列消息
     * @param message 接收到的消息
     */
    @RabbitListener(queues = "zyk_queue")
    public void myListener1(String message){
        System.out.println("消费者接收到消息:"+message);
    }
}

6.编写测试类

@RunWith(SpringRunner.class)
@SpringBootTest
public class RabbitMQTest {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Test
    public void test1(){
        rabbitTemplate.convertAndSend(RabbitMQConfig.ZYK_TOPIC_EXCHANGE,
                "item.insert","新增,路由key为:item.insert");

        rabbitTemplate.convertAndSend(RabbitMQConfig.ZYK_TOPIC_EXCHANGE,
                "item.update","修改,路由key为:item.update");

        rabbitTemplate.convertAndSend(RabbitMQConfig.ZYK_TOPIC_EXCHANGE,
                "item.delete","删除,路由key为:item.delete");
    }
}

7.测试类运行,启动消费者的启动引导类,运行结果如下。

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值