RabbitMQ入门案例生产者和消费者

Maven依赖

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

代码演示

消费者

package com.mq.rabbit.quickstart;

import com.rabbitmq.client.*;

/**
 * @Author 
 * @Date 2018/10/7 23:43
 * @Desc 消息的消费者
 */
public class Consumer {
    private final static String QUEUE_NAME = "hello";

    public static void main(String[] args)throws Exception {
        // 1、创建一个new ConnectionFactory
        //设置RabbitMQ所在主机ip或者主机名
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.200.130");
        //指定用户 密码
        factory.setUsername("rollen");
        factory.setPassword("root");
        //指定端口
        factory.setPort(AMQP.PROTOCOL.PORT);

        // 2、通过连接工厂创建连接
        Connection connection = factory.newConnection();
        // 3、创建一个channel
        Channel channel = connection.createChannel();
        //声明队列,主要为了防止消息接收者先运行此程序,队列还不存在时创建队列。
        channel.queueDeclare(QUEUE_NAME, true, false, false, null );
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
        // 创建消费者
        QueueingConsumer consumer = new QueueingConsumer(channel);
        // 设置channel
        channel.basicConsume(QUEUE_NAME, true, consumer);
        // 获取消息
        int count = 1;
        while (true){
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            String msg = new String(delivery.getBody());
            System.out.println("消息的消费者消费第【" + count + "】条消息: " + msg);
            count++;
        }

    }
}

生产者

package com.mq.rabbit.quickstart;

import com.rabbitmq.client.*;

/**
 * @Author 
 * @Date 2018/10/7 23:43
 * @Desc 消息的提供者
 */
public class Provider {
    private final static String QUEUE_NAME = "hello";

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

        // 创建一个new ConnectionFactory
        ConnectionFactory factory = new ConnectionFactory();
        //设置RabbitMQ所在主机ip或者主机名
        factory.setHost("192.168.200.130");
        //指定用户 密码
        factory.setUsername("rollen");
        factory.setPassword("root");
        //指定端口
        factory.setPort(AMQP.PROTOCOL.PORT);

        // 通过连接工厂创建连接
        Connection connection = factory.newConnection();
        // 创建一个channel
        Channel channel = connection.createChannel();
        // 声明一个队列:名称、持久性的(重启仍存在此队列)、非私有的、非自动删除的
        channel.queueDeclare(QUEUE_NAME, true, false, false, null);
        // 发送数据
        String msg = "Hello World";
        // 发送5条消息
        int count = 6;
        for (int i = 1; i < count; i++) {
            channel.basicPublish("", QUEUE_NAME, null, msg.getBytes());
            System.out.println("消息的生产者产生第【" + i + "】条消息: " + msg);
        }

        channel.close();
        connection.close();

    }
}

结果演示

消费者 

生产者

猜你喜欢

转载自blog.csdn.net/wildwolf_001/article/details/83215640