消息模式实例

视频教程:https://ke.qq.com/course/304104

编写代码前,最好先添加好用户并设置virtual hosts

一、简单模式

1.导入jar包

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

2.创建连接

import com.idelan.rabbitmq.utils.ConnectionUtil;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection; public class Sender {
private final static String QUEUE = "testhello"; //队列名字 public static void main(String[] args) throws Exception{
//获取连接
Connection connection = ConnectionUtil.getConnection(); //创建通道
Channel channel = connection.createChannel(); //声明队列,如果队列存在则什么都不做,如果队列不存在才创建
//参数一: 队列的名字
//参数二: 是否持久化队列,我们的队列模式是在内存中的,如果rabbit重启会丢失,如果我们设置为true 则会保存到erlng自带的数据库中,重启会重新获取
//参数三: 是否排外,有两个作用,第一个当我们的链接关闭后是否会自动删除队列,作用二,是否私有当前队列,如果私有了,其他通道不可以访问当前队列,如果为true 一般适合一个队列消费者的时候
//参数四: 是否自动删除
//参数五 我们的一些其他的参数
channel.queueDeclare(QUEUE, false, false, false, null); //发送内容
channel.basicPublish("", QUEUE, null, "hello world".getBytes()); //关闭连接
channel.close();
connection.close();
}
}

3.消费者

import com.idelan.rabbitmq.utils.ConnectionUtil;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.QueueingConsumer; public class Receiver {
private final static String QUEUE = "testhello"; //队列名字 public static void main(String[] args) throws Exception{
Connection connection = ConnectionUtil.getConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE, false, false, false, null); QueueingConsumer consumer = new QueueingConsumer(channel);
//接收消息,参数二 是自动确认
channel.basicConsume(QUEUE, true, consumer); while (true) {
//获取消息 如果没有消息会等待,有的话就获取执行然后销毁,是一次性的
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
String message = new String(delivery.getBody());
System.out.println("message:"+message);
}
}
}

二、工作模式

1.生产者

import com.idelan.rabbitmq.utils.ConnectionUtil;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection; public class Sender {
private final static String QUEUE = "testwork"; //队列名字 public static void main(String[] args) throws Exception{
//获取连接
Connection connection = ConnectionUtil.getConnection(); //创建通道
Channel channel = connection.createChannel(); //声明队列,如果队列存在则什么都不做,如果队列不存在才创建
//参数一: 队列的名字
//参数二: 是否持久化队列,我们的队列模式是在内存中的,如果rabbit重启会丢失,如果我们设置为true 则会保存到erlng自带的数据库中,重启会重新获取
//参数三: 是否排外,有两个作用,第一个当我们的链接关闭后是否会自动删除队列,作用二,是否私有当前队列,如果私有了,其他通道不可以访问当前队列,如果为true 一般适合一个队列消费者的时候
//参数四: 是否自动删除
//参数五 我们的一些其他的参数
channel.queueDeclare(QUEUE, false, false, false, null); for (int i = 0; i < 20; i++){
//发送内容
channel.basicPublish("", QUEUE, null, ("hello world "+i).getBytes());
} //关闭连接
channel.close();
connection.close();
}
}

2.消费者1

import com.idelan.rabbitmq.utils.ConnectionUtil;
import com.rabbitmq.client.*; import java.io.IOException; public class Receiver1 {
private final static String QUEUE = "testwork"; //队列名字 public static void main(String[] args) throws Exception{
Connection connection = ConnectionUtil.getConnection();
final Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE, false, false, false, null); //告诉服务器,在我没有确认当前消息完成之前,不要给我发新消息
channel.basicQos(1); DefaultConsumer consumer = new DefaultConsumer(channel) { @Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
//当我们收到消息的时候调用
System.out.println("消费者1 收到的消息内容是:" + new String(body));
//确认 参数2,false为确认收到消息,true 为拒绝接收
channel.basicAck(envelope.getDeliveryTag(), false);
}
}; //注册消费者,参数2 收到确认,代表我们收到消息后需要手动告诉服务器,我们收到消息了
channel.basicConsume(QUEUE, false, consumer);
}
}

3.消费者2

import com.idelan.rabbitmq.utils.ConnectionUtil;
import com.rabbitmq.client.*; import java.io.IOException; public class Receiver2 {
private final static String QUEUE = "testwork"; //队列名字 public static void main(String[] args) throws Exception{
Connection connection = ConnectionUtil.getConnection();
final Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE, false, false, false, null); //告诉服务器,在我没有确认当前消息完成之前,不要给我发新消息
channel.basicQos(1);
DefaultConsumer consumer = new DefaultConsumer(channel) { @Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
//当我们收到消息的时候调用
System.out.println("消费者2 收到的消息内容是:" + new String(body));
//确认 参数2,false为确认收到消息,true 为拒绝接收
channel.basicAck(envelope.getDeliveryTag(), false);
}
}; //注册消费者,参数2 收到确认,代表我们收到消息后需要手动告诉服务器,我们收到消息了
channel.basicConsume(QUEUE, false, consumer);
}
}

三、发布订阅模式

1.生产者

import com.idelan.rabbitmq.utils.ConnectionUtil;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection; public class Sender {
private final static String EXCHANGE_NAME = "testexchange"; //定义交换机名字 public static void main(String[] args) throws Exception{ Connection connection = ConnectionUtil.getConnection();
Channel channel = connection.createChannel();
//声明交换机
channel.exchangeDeclare(EXCHANGE_NAME, "fanout");//定义一个交换机,类型是fanout //发布订阅模式,因为消息是先发布到交换机中,而交换机是没有保存功能的,所以如果没有消费者,消息则会丢失
channel.basicPublish(EXCHANGE_NAME, "", null, "发布订阅模式的消息".getBytes());
channel.close();
connection.close();
}
}

2.消费者1

import com.idelan.rabbitmq.utils.ConnectionUtil;
import com.rabbitmq.client.*; import java.io.IOException; public class Receiver1 {
private final static String EXCHANGE_NAME = "testexchange"; //定义交换机名字 public static void main(String[] args) throws Exception{
Connection connection = ConnectionUtil.getConnection();
final Channel channel = connection.createChannel();
channel.queueDeclare("testpubQueue1", false, false, false, null); //绑定队列到交换机
channel.queueBind("testpubQueue1", EXCHANGE_NAME, "");
channel.basicQos(1);
DefaultConsumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("消费者1:"+new String(body));
channel.basicAck(envelope.getDeliveryTag(),false);
}
};
channel.basicConsume("testpubQueue1", false, consumer);
}
}

3.消费者2

import com.idelan.rabbitmq.utils.ConnectionUtil;
import com.rabbitmq.client.*; import java.io.IOException; public class Receiver2 {
private final static String EXCHANGE_NAME = "testexchange"; //定义交换机名字 public static void main(String[] args) throws Exception{
Connection connection = ConnectionUtil.getConnection();
final Channel channel = connection.createChannel();
channel.queueDeclare("testpubQueue2", false, false, false, null); //绑定队列到交换机
channel.queueBind("testpubQueue2", EXCHANGE_NAME, "");
channel.basicQos(1);
DefaultConsumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("消费者2:"+new String(body));
channel.basicAck(envelope.getDeliveryTag(),false);
}
};
channel.basicConsume("testpubQueue2", false, consumer);
}
}

四、路由模式

1.生产者

import com.idelan.rabbitmq.utils.ConnectionUtil;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection; public class Sender {
private final static String EXCHANGE_NAME = "testexroute"; //定义交换机名字 public static void main(String[] args) throws Exception{ Connection connection = ConnectionUtil.getConnection();
Channel channel = connection.createChannel();
//声明交换机
channel.exchangeDeclare(EXCHANGE_NAME, "direct");//定义一个路由格式的交换机 //发布订阅模式,因为消息是先发布到交换机中,而交换机是没有保存功能的,所以如果没有消费者,消息则会丢失
// routingKey 为key1
channel.basicPublish(EXCHANGE_NAME, "key3", null, "路由模式的消息".getBytes());
channel.close();
connection.close();
}
}

2.消费者1

import com.idelan.rabbitmq.utils.ConnectionUtil;
import com.rabbitmq.client.*; import java.io.IOException; public class Receiver1 {
private final static String EXCHANGE_NAME = "testexroute"; //定义交换机名字 public static void main(String[] args) throws Exception{
Connection connection = ConnectionUtil.getConnection();
final Channel channel = connection.createChannel();
channel.queueDeclare("testRouteQueue1", false, false, false, null); //绑定队列到交换机
//参数3标记,绑定到交换机的时候会指定一个标记,只有和它一样的标记的消息才会被当前消费者接收到
channel.queueBind("testRouteQueue1", EXCHANGE_NAME, "key1");
//如果需要绑定多个标记 在执行一次即可
channel.queueBind("testRouteQueue1", EXCHANGE_NAME, "key3");
channel.basicQos(1);
DefaultConsumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("消费者1:"+new String(body));
channel.basicAck(envelope.getDeliveryTag(),false);
}
};
channel.basicConsume("testRouteQueue1", false, consumer);
}
}

3.消费者2

import com.idelan.rabbitmq.utils.ConnectionUtil;
import com.rabbitmq.client.*; import java.io.IOException; public class Receiver2 {
private final static String EXCHANGE_NAME = "testexroute"; //定义交换机名字 public static void main(String[] args) throws Exception{
Connection connection = ConnectionUtil.getConnection();
final Channel channel = connection.createChannel();
channel.queueDeclare("testRouteQueue2", false, false, false, null); //绑定队列到交换机
//参数3标记,绑定到交换机的时候会指定一个标记,只有和它一样的标记的消息才会被当前消费者接收到
channel.queueBind("testRouteQueue2", EXCHANGE_NAME, "key1");
//如果需要绑定多个标记 在执行一次即可
channel.queueBind("testRouteQueue2", EXCHANGE_NAME, "key2");
channel.basicQos(1);
DefaultConsumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("消费者2:"+new String(body));
channel.basicAck(envelope.getDeliveryTag(),false);
}
};
channel.basicConsume("testRouteQueue2", false, consumer);
}
}

五、主题模式

1.生产者

import com.idelan.rabbitmq.utils.ConnectionUtil;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection; public class Sender {
private final static String EXCHANGE_NAME = "testexchangetopic"; //定义交换机名字 public static void main(String[] args) throws Exception{ Connection connection = ConnectionUtil.getConnection();
Channel channel = connection.createChannel();
//声明交换机
channel.exchangeDeclare(EXCHANGE_NAME, "topic");//定义一个topic 格式的交换机 //发布订阅模式,因为消息是先发布到交换机中,而交换机是没有保存功能的,所以如果没有消费者,消息则会丢失
// routingKey 为key1
// * 只能匹配一个字符 # 可以匹配多个字符
channel.basicPublish(EXCHANGE_NAME, "abc.1.3", null, "topic模式的消息".getBytes());
channel.close();
connection.close();
}
}

2.消费者1

import com.idelan.rabbitmq.utils.ConnectionUtil;
import com.rabbitmq.client.*; import java.io.IOException; public class Receiver1 {
private final static String EXCHANGE_NAME = "testexchangetopic"; //定义交换机名字 public static void main(String[] args) throws Exception{
Connection connection = ConnectionUtil.getConnection();
final Channel channel = connection.createChannel();
channel.queueDeclare("testTopicQueue1", false, false, false, null); //绑定队列到交换机
//参数3标记,绑定到交换机的时候会指定一个标记,只有和它一样的标记的消息才会被当前消费者接收到
channel.queueBind("testTopicQueue1", EXCHANGE_NAME, "key.*");
//如果需要绑定多个标记 在执行一次即可
channel.queueBind("testTopicQueue1", EXCHANGE_NAME, "abc.#");
channel.basicQos(1);
DefaultConsumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("消费者1:"+new String(body));
channel.basicAck(envelope.getDeliveryTag(),false);
}
};
channel.basicConsume("testTopicQueue1", false, consumer);
}
}

3.消费者2

import com.idelan.rabbitmq.utils.ConnectionUtil;
import com.rabbitmq.client.*; import java.io.IOException; public class Receiver2 {
private final static String EXCHANGE_NAME = "testexchangetopic"; //定义交换机名字 public static void main(String[] args) throws Exception{
Connection connection = ConnectionUtil.getConnection();
final Channel channel = connection.createChannel();
channel.queueDeclare("testTopicQueue2", false, false, false, null); //绑定队列到交换机
//参数3标记,绑定到交换机的时候会指定一个标记,只有和它一样的标记的消息才会被当前消费者接收到
channel.queueBind("testTopicQueue2", EXCHANGE_NAME, "key.#");
//如果需要绑定多个标记 在执行一次即可
channel.queueBind("testTopicQueue2", EXCHANGE_NAME, "abc.*");
channel.basicQos(1);
DefaultConsumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("消费者2:"+new String(body));
channel.basicAck(envelope.getDeliveryTag(),false);
}
};
channel.basicConsume("testTopicQueue2", false, consumer);
}
}

RabbitMQ 消息模式的更多相关文章

  1. RabbitMQ消息队列(八)-通过Topic主题模式分发消息(.Net Core版)

    前两章我们讲了RabbitMQ的direct模式和fanout模式,本章介绍topic主题模式的应用.如果对direct模式下通过routingkey来匹配消息的模式已经有一定了解那fanout也很好 ...

  2. (九)RabbitMQ消息队列-通过Headers模式分发消息

    原文:(九)RabbitMQ消息队列-通过Headers模式分发消息 Headers类型的exchange使用的比较少,以至于官方文档貌似都没提到,它是忽略routingKey的一种路由方式.是使用H ...

  3. (八)RabbitMQ消息队列-通过Topic主题模式分发消息

    原文:(八)RabbitMQ消息队列-通过Topic主题模式分发消息 前两章我们讲了RabbitMQ的direct模式和fanout模式,本章介绍topic主题模式的应用.如果对direct模式下通过 ...

  4. (七)RabbitMQ消息队列-通过fanout模式将消息推送到多个Queue中

    原文:(七)RabbitMQ消息队列-通过fanout模式将消息推送到多个Queue中 前面第六章我们使用的是direct直连模式来进行消息投递和分发.本章将介绍如何使用fanout模式将消息推送到多 ...

  5. RabbitMQ之消息模式(下)

    目的: RabbitMQ之消息模式(上):https://www.cnblogs.com/huangting/p/11994539.html 消费端限流 消息的ACK与重回队列 TTL消息 死信队列 ...

  6. RabbitMQ之消息模式简单易懂,超详细分享~~~

    前言 上一篇对RabbitMQ的流程和相关的理论进行初步的概述,如果小伙伴之前对消息队列不是很了解,那么在看理论时会有些困惑,这里以消息模式为切入点,结合理论细节和代码实践的方式一起来学习. 正文 常 ...

  7. Rabbitmq -Publish_Subscribe模式- python编码实现

    what is Exchanges ?? Let's quickly go over what we covered in the previous tutorials: A producer is ...

  8. (转)RabbitMQ消息队列(九):Publisher的消息确认机制

    在前面的文章中提到了queue和consumer之间的消息确认机制:通过设置ack.那么Publisher能不到知道他post的Message有没有到达queue,甚至更近一步,是否被某个Consum ...

  9. (转)RabbitMQ消息队列(四):分发到多Consumer(Publish/Subscribe)

    上篇文章中,我们把每个Message都是deliver到某个Consumer.在这篇文章中,我们将会将同一个Message deliver到多个Consumer中.这个模式也被成为 "pub ...

随机推荐

  1. Apsara Clouder专项技能认证:实现调用API接口

    一.API 简介 1.API 的概念 API(Application Programming Interface应用程序编程接口)是一些预定义的函数,目的是提供应用程序与开发人员基于某软件或硬件得以访 ...

  2. java正则(贪婪、勉强)

    贪婪.勉强和侵占量词间的不同 在贪婪.勉强和侵占三个量词间有着细微的不同. 贪婪(*, ?, +):读入整个串,从后往前匹配 勉强(*?, ??, +?):从前往后匹配 侵占(*+, ?+, ++): ...

  3. Prefix and Suffix

    题目描述 Snuke is interested in strings that satisfy the following conditions: The length of the string ...

  4. [LC] 238. Product of Array Except Self

    Given an array nums of n integers where n > 1,  return an array output such that output[i] is equ ...

  5. P6跨级晋升P8再到P10,我的11年成长之路

    来自:语雀,作者:玉伯 链接:https://www.yuque.com/yubo/morning/grow-up-at-alibaba 注:这是在阿里内部前端大学的一个分享,整理了一份对外的版本,希 ...

  6. Linux中的一些点

    前言 本文记录一些日常使用linux的一些点. 系统负载评估 理解Linux系统负荷 查看 ps -ef [root@deployer ~]# ps -ef UID PID PPID C STIME ...

  7. codeforces #332 div 2 D. Spongebob and Squares

    http://codeforces.com/contest/599/problem/D 题意:给出总的方格数x,问有多少种不同尺寸的矩形满足题意,输出方案数和长宽(3,5和5,3算两种) 思路:比赛的 ...

  8. ConxtMenu高级用法

    ##背景我们经常在列表的页面中,点击列表中的行,一般进入详情页面,长按列表中一行,会弹出一个菜单,包含了对某一行的操作(编辑.删除等等),也知道通常的用法: 0x01. 在Activity中注册需要上 ...

  9. 在JavaScript里的“对象字面量”是什么意思?

    字面量表示如何表达这个值,一般除去表达式,给变量赋值时,等号右边都可以认为是字面量.字面量分为字符串字面量(string literal ).数组字面量(array literal)和对象字面量(ob ...

  10. 6. Go 语言中结构体的使用

    1. 结构体的定义格式 在go语言中结果的定义格式如下: 123 type structName struct { filedList} 列子如下: 1234 type Person struct { ...