消息模式实例

视频教程: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. 引入插件的时候 提示particlesJS is not defined

    particlesJS is not defined   插件或者js文件在引入时需要注意引入顺序,每次都找很久的错误 一般引入min.js就可以,min.js意思就是压缩的js文件 引入时应该先加入 ...

  2. 项目引入nacos 日志不显示问题

    禁用nacos的日志即可解决 idea当中 添加vm options参数即可 -Dnacos.logging.default.config.enabled=false 打包后的启动命令  java - ...

  3. springboot学习笔记:12.解决springboot打成可执行jar在linux上启动慢的问题

    有时候,当你把你的springboot项目打成可执行的jar,放在linux上启动时,发现启动超级慢: 这往往是因为springboot内置tomcat启动时实例化SecureRandom对象随机数策 ...

  4. 洛谷-P3369-普通平衡树(Treap)

    题目传送门 标题说平衡树,那么应该AVL,红黑树都能过,但是这次做这题主要是学习Treap,所以花了几天搞出了这题.其他方法以后再说吧 Treap(带旋转) #include <bits/std ...

  5. python练习题——猜数字游戏

    增加了按照对半找数的方法来计算最短几次就可以猜到随机数,决定到游戏结束共猜数的次数: from random import * import numpy as np from numpy import ...

  6. Javascript面试题&知识点汇总

    问题&答案 什么时候 a ==1 && a== 2 && a==3 为 true? var a = { i: 1, toString: function () ...

  7. MAYA 卸载工具,完美彻底卸载清除干净maya各种残留注册表和文件

    是不是遇到MAYA/CAD/3DSMAX/INVENTOR安装失败?AUTODESK系列软件着实令人头疼,MAYA/CAD/3DSMAX/INVENTOR安装失败之后不能完全卸载!!!(比如maya, ...

  8. 吴裕雄--天生自然python学习笔记:Python3 XML 解析

    什么是 XML? XML 指可扩展标记语言(eXtensible Markup Language),标准通用标记语言的子集,是一种用于标记电子文件使其具有结构性的标记语言. XML 被设计用来传输和存 ...

  9. PHP生成word文档的三种实现方式

    PHP生成word原理 利用windows下面的 com组件 利用PHP将内容写入doc文件之中 具体实现: 利用windows下面的 com组件 原理:com作为PHP的一个扩展类,安装过offic ...

  10. idea 使用sonarlint报错解决方案

    在idea使用sonarlint可能出现以下报错: Plugin 'org.sonarlint.idea' failed to initialize and will be disabled. Ple ...