RabbitMQ:Consumers的介绍和使用

1.声明

当前内容用于本人学习和复习中,主要包括RabbitMQ中的Consumer的介绍和使用

当前内容来源:RabbitMQ官方

2.官方的Consumers介绍

  1. Storing messages in queues is useless unless applications can consume them. In the AMQP 0-9-1 Model, there are two ways for applications to do this:

    1.1. Have messages delivered to them (“push API”)
    1.2. Fetch messages as needed (“pull API”)

消费者应该在程序中被消费,如果不能被消费那么消息也不用放入到队列中,在AMQP 0-9-1模型中,在程序中有两种方式去使用

1.1. 将消息推送给消费者
1.2. 消费者通过需要拉取消息

2.With the “push API”, applications have to indicate interest in consuming messages from a particular queue. When they do so, we say that they register a consumer or, simply put, subscribe to a queue. It is possible to have more than one consumer per queue or to register an exclusive consumer (excludes all other consumers from the queue while it is consuming).

3.Each consumer (subscription) has an identifier called a consumer tag. It can be used to unsubscribe from messages. Consumer tags are just strings.

关于这个推送模式,一般程序都是消费那些感兴趣的队列中的消息,同样的,我们通常都是说注册了一个消费者或者说是,订阅了一个队列。每个队列通常都不止一个消费者注册,或者注册一个唯一的消费者(就是只能有一个消费者的队列)

每个消费者(订阅)都会有意个唯一的标识在消费者的tag中。通常使用这个唯一标记去取消订阅消息。消费者标记通常只能是字符串

分析发现:消费者有两种模式获取消息:

  1. 推送方式(被动接收消息)
  2. 拉取方式(主动获取消息)

3.测试消费者消费消息的方式

关于推送方式,一般都是基于topic方式,就像前面的basicConsume方法一样,这个就是推送方式

这里主要测试拉取方式:这里的例子和东西使用前面的:Bindings的介绍和使用

注意这里需要向RabbitMqUtils中添加代码pull

// 拉取方式接收消息
	public GetResponse pull(final String queue, boolean durable, boolean autoAck) throws Exception {
		GetResponse response = null;
		try (Connection connection = factory.newConnection(); Channel channel = connection.createChannel();) {
			channel.queueDeclare(queue, durable, false, false, null);
			response = channel.basicGet(queue, autoAck);
		}
		return response;
	}

现在开始常见消费者,拉取消息

/**
 * @description 当前内容主要就是测试消费者拉取指定队列的消息
 * @author hy
 * @date 2020-05-14
 */
public class PullWayTest {
	public static void main(String[] args) throws Exception {
		RabbitMqUtils mqUtils = new RabbitMqUtils();
		GetResponse response = mqUtils.pull("New York city", true, true);
		if (response != null) {
			String string = new String(response.getBody(), "utf-8");
			int messageCount = response.getMessageCount();
			System.out.println("接收消息内容为==>" + string);
			System.out.println("消息总数==>" + messageCount);// 这里可以获取当前消息队列中剩余的消息数量一次只能拉取一条数据
		}
	}
}

然后开始使用ui界面开始发送消息(直接向China airport发送消息)
在这里插入图片描述
已经发送两条数据了

测试拉取(第一次)
在这里插入图片描述
测试拉取(第二次)
在这里插入图片描述
测试发现使用pull方式拉取指定队列的消息的时候,一次只能拉取一条数据

4.总结

1.Consumers就是消费者,主要就是消费当前的消息队列中的消息

2.消费消息有两种模式一种就是推送消费和拉取消费

以上纯属个人见解,如有问题请联系本人!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值