消息队列-RabbitMQ-简单模式(代码)-生产者

前提是已经有可用的rabbitmq服务端,如果还没有 参考安装 

消息队列-RabbitMQ-Centos8安装RabbitMQ_if_icanfly的博客-CSDN博客1.环境安装使用PackageCloud Yum Repository安装依次执行下面这两条命令curl -s https://packagecloud.io/install/repositories/rabbitmq/rabbitmq-server/script.rpm.sh | sudo bashcurl -s https://packagecloud.io/install/repositories/rabbitmq/erlang/script.rpm.sh | sudo bhttps://blog.csdn.net/if_icanfly/article/details/123252256?spm=1001.2014.3001.5502

如上官方图:简单模式只有一个生产者,一个队列,一个消费者 没有交换机 

1.maven普通项目整合MQ

 新建一个普通的maven项目.导入mq的依赖

pom.xml文件中添加以下依赖

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

以下是代码  

 public static void main(String[] args) throws IOException, TimeoutException {
        //1.创建连接工厂
        ConnectionFactory conn = new ConnectionFactory();
        //2.设置参数
        conn.setHost("127.0.0.1");
        conn.setPort(5672);
        // 使用默认的虚拟机
        conn.setVirtualHost("/");
        conn.setUsername("xiang");
        conn.setPassword("564409");
        //3.创建连接
        Connection connection = conn.newConnection();
        //4.创建channel
        Channel channel = connection.createChannel();
        //5.创建队列
        /**
         * 参数说明:
         * String queue 队列名称
         * boolean durable 是否持久化
         * boolean exclusive 是否独占(只能有一个消费者)
         * boolean autoDelete 是否自动删除
         * Map<String, Object> arguments 参数()
         */
        channel.queueDeclare("hello", true, false, false, null);
        //6.发送消息
        /**
         * 参数说明
         * String exchange, 交换机名称
         * String routingKey, 路由键
         * boolean mandatory,是否强制
         * boolean immediate,是否立即
         * BasicProperties props, 配置
         * byte[] body 消息体
         */
        // 由于简单模式不需要交换机 所以这里交换机名称不填 路由key要跟上面创建的队列匹配 
        channel.basicPublish("","hello",null,"ceshi".getBytes());

        // 7.关闭资源
        channel.close();
        connection.close();
    }

由于简单模式是不需要交换机的 所以以上的代码没有创建交换机  

发送消息的时候 routingKey必须与队列名称完全匹配 否则消息无法到达队列 

2.spring整合MQ

创建一个maven项目,导入以下spring与spring整合mq的依赖以及测试依赖

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.1.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.1.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.amqp</groupId>
            <artifactId>spring-rabbit</artifactId>
            <version>2.3.10</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.1</version>
            <scope>test</scope>
        </dependency>

resource目录下新建一个配置文件spring-rabbitmq.xml 与mq.properties内容添加如下

 mq.properties(换成你自己的地址 密码 账号)

mq.host=127.0.0.1
mq.username=xiang
mq.password=564409
mq.port=5672
mq.vhost=/

spring-rabbitmq.xml 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:rabbit="http://www.springframework.org/schema/rabbit"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/rabbit
       http://www.springframework.org/schema/rabbit/spring-rabbit.xsd">
    <!--加载配置文件-->
    <context:property-placeholder location="classpath:rabbitmq.properties"/>

    <!-- 定义rabbitmq connectionFactory -->
    <rabbit:connection-factory id="connectionFactory" host="${mq.host}"
                               port="${mq.port}"
                               username="${mq.username}"
                               password="${mq.password}"
                               virtual-host="${mq.vhost}"/>
    <!--定义管理交换机、队列-->
    <rabbit:admin connection-factory="connectionFactory"/>

    <!--定义持久化队列,不存在则自动创建;不绑定到交换机则绑定到默认交换机
    默认交换机类型为direct,名字为:"",路由键为队列的名称
    -->
    <!--
        id:bean的名称
        name:queue的名称
        auto-declare:自动创建
        auto-delete:自动删除。 最后一个消费者和该队列断开连接后,自动删除队列
        durable:是否持久化
    -->

    <rabbit:queue id="spring_queue" name="spring_queue"  durable="true"  auto-declare="true"/>



    <!--定义rabbitTemplate对象操作可以在代码中方便发送消息-->
    <rabbit:template id="rabbitTemplate" connection-factory="connectionFactory"/>
</beans>

上面的配置也只配置了连接工厂  连接 以及队列 还有生成的rabbitTemplate 并没有配置交换机

测试代码:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationcontext.xml")
public class daxiang {

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Test
    public void test(){
        // 这里的第一个参数 routingKey 与配置文件中配置的队列名称完全匹配
        rabbitTemplate.convertAndSend("spring_queue","测试简单模式");
    }
}

结果:

 控制台可以看到,新建了名字叫做spring_queue的队列 且里面有一条未消费的消息

 3.springboot整合MQ

新建一个springboot的项目

3.1导入springboot整合rabbitmq的依赖 在pom文件中添加依赖

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

3.2在配置文件(application.properties)中添加链接工厂的参数

spring.rabbitmq.host=127.0.0.1
spring.rabbitmq.port=5672
spring.rabbitmq.username=xiang
spring.rabbitmq.password=564409
spring.rabbitmq.virtual-host=/

 3.3添加配置类 新建一个配置类RabbitMqConfig.java 在配置类中声明队列

import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMqConfig {


    /**
     * 由于这里演示的是简单工作模式 所以不需要交换机 直接创建队列即可
     * @return
     */

    @Bean
    public Queue orderQueue(){
        return QueueBuilder.durable("order").build();
    }

}

测试:在测试列类中进行测试

@SpringBootTest
class DemoApplicationTests {

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Test
    void contextLoads() {
        // 第一个参数是routingKey 需要与配置类中声明的队列名称完全匹配 后面为要发送的消息
        rabbitTemplate.convertAndSend("order","nihao ");
    }

}

结果: 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值