RabbitMQ系列—RabbitMQ 代码演示

以下代码演示了如何使用RabbitMQ的客户端开发包,进行消息生产和消费。RabbitMQ的客户端开发包可以在RabbitMQ官网进行下载(http://www.rabbitmq.com/java-client.html),也可以使用Mavean官方库进行导入:

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

一、演示前的准备工作

进行具体编码前需要做一些准备工作:

  1. 创建Exchanges;
  2. 创建Queues;
  3. 绑定Exchanges和Queues。
1.1、创建Exchanges

这里写图片描述

1.2、创建Queues

这里写图片描述

1.3、绑定Exchanges和Queues

这里写图片描述

二、具体示例

2.1、RabbitMQ消息生产者
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

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

/**
 * 这个测试类,用于模拟消息生成者,每100毫秒,向rabbit集群写入不同的消息
 */
public class RabbitProducerThread implements Runnable {
    /**
     * 日志
     */
    private static final Log LOGGER = LogFactory.getLog(RabbitProducerThread.class);

    public static void main(String[] args) throws Exception {
        new Thread(new RabbitProducerThread()).start();
    }

    public void run() {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.1.168");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("root");
        connectionFactory.setPassword("root");

        Connection conn = null;
        Channel producerChannel = null;
        try {
            conn = connectionFactory.newConnection();
            producerChannel = conn.createChannel();
        } catch (Exception e) {
            RabbitProducerThread.LOGGER.error(e.getMessage(), e);
            System.exit(-1);
        }

        // 然后每隔100毫秒,发送一条数据
        while (true) {
            // 消息的唯一编号
            String uuid = UUID.randomUUID().toString();
            String message = uuid + ";time=" + new Date().getTime();
            // 设置一些参数
            BasicProperties properties = new BasicProperties().builder().type("String").contentType("text")
                    .contentEncoding("UTF-8").messageId(uuid).build();
            try {
                // 第一个参数是exchange交换器的名字
                // 第二个参数是进行消息路由的关键key
                producerChannel.basicPublish("test_exchange", "test_routingKey", properties, message.getBytes());
                RabbitProducerThread.LOGGER.info("消息发送:" + message);
            } catch (IOException e) {
                RabbitProducerThread.LOGGER.error(e.getMessage(), e);
            }

            synchronized (this) {
                try {
                    this.wait(3000);
                } catch (InterruptedException e) {
                    RabbitProducerThread.LOGGER.error(e.getMessage(), e);
                }
            }
        }
    }
}

启动后的样子

这里写图片描述

这里写图片描述

2.2、RabbitMQ消息消费者
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;

/**
 * 这个测试类,用于模拟消息消费者
 */
public class RabbitConsumerThread implements Runnable {

    /**
     * 日志
     */
    private static final Log LOGGER = LogFactory.getLog(RabbitConsumerThread.class);

    public static void main(String[] args) throws Exception {
        new Thread(new RabbitConsumerThread()).start();
    }

    public void run() {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.1.168");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("root");
        connectionFactory.setPassword("root");

        Connection conn = null;
        Channel consumerChannel = null;
        try {
            conn = connectionFactory.newConnection();
            consumerChannel = conn.createChannel();
        } catch (Exception e) {
            RabbitConsumerThread.LOGGER.error(e.getMessage(), e);
            System.exit(-1);
        }

        // 开始监控消息,(ack是手动的)
        QueueingConsumer queueingConsumer = null;
        try {
            queueingConsumer = new QueueingConsumer(consumerChannel);
            // 设置消费者订阅的消息队列名:test_queues
            consumerChannel.basicConsume("test_queues", false, queueingConsumer);
        } catch (IOException e) {
            RabbitConsumerThread.LOGGER.error(e.getMessage(), e);
            System.exit(-1);
        }

        // 停顿200毫秒,才处理下一条,以便模拟事件处理对应的消耗事件
        while (true) {
            QueueingConsumer.Delivery delivery = null;
            try {
                delivery = queueingConsumer.nextDelivery();// 如果队列里没有消息,程序会阻塞在这里
            } catch (Exception e) {
                RabbitConsumerThread.LOGGER.error(e.getMessage(), e);
            }
            long deliverytag = delivery.getEnvelope().getDeliveryTag();
            byte[] messageBytes = delivery.getBody();
            BasicProperties properties = delivery.getProperties();
            String message = new String(messageBytes);
            RabbitConsumerThread.LOGGER.info("收到事件======message = " + message + " | properties =" + properties);

            // 这里停顿200毫秒,模拟业务时间
            synchronized (this) {
                try {
                    this.wait(200);
                } catch (InterruptedException e) {
                    RabbitConsumerThread.LOGGER.error(e.getMessage(), e);
                }
            }

            RabbitConsumerThread.LOGGER.info("事件message = " + message + "处理完成,发送ack。等待下一条消息");
            try {
                // 发送ack:消息处理成功的确认信号
                consumerChannel.basicAck(deliverytag, false);
            } catch (IOException e) {
                RabbitConsumerThread.LOGGER.error(e.getMessage(), e);
            }
        }
    }
}

启动后的样子

这里写图片描述

这里写图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值