文章目录
官网链接
https://www.rabbitmq.com/getstarted.html
1、 “Hello World!” 简单队列
生产者
package com.xyulu;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
public class Producer {
//定义队列
private final static String QUEUE_NAME = "hello";
public static void main(String[] args) throws Exception{
//创建连接工厂
ConnectionFactory factory = new ConnectionFactory();
//主机地址;默认为 localhost
factory.setHost("localhost");
factory.setUsername("guest");
factory.setPassword("guest");
//虚拟主机名称;默认为 /
factory.setVirtualHost("/");
factory.setPort(5672);
try (
//创建连接
Connection connection = factory.newConnection();
//创建信道
Channel channel = connection.createChannel()) {
/**
* 声明(创建)队列
* String queue - 队列名称
* boolean durable - 是否持久化
* boolean exclusive - 设置为排他队列后,该队列仅对首次连接可见,连接关闭后自动删除
* boolean autoDelete - 是否自动删除
* Map<String, Object> arguments - 队列其他属性
*/
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
String message = "Hello World!";
/**
* exchange – 交换机名称,如果没有指定则使用默认Default Exchage
* routingKey – 路由 key,简单模式可以传递队列名称
* props – 消息其它属性
* body – 消息内容
*/
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
System.out.println(" [x] Sent '" + message + "'");
}
}
}
消费者
package com.xyulu;
import com.rabbitmq.client.*;
public class Consumer {
private final static String QUEUE_NAME = "hello";
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
String message = new String(delivery.getBody(), "UTF-8");
System.out.println(" [x] Received '" + message + "'");
};
/**
* @param queue
* @param autoAck 自动回值 设置为true为表示消息接收到自动向mq回复接收到了,
* mq接收到回复会删除消息,设置为false则需要手动确认
* @param deliverCallback callback when a message is delivered
* @param shutdownSignalCallback callback when the channel/connection is shut down
*/
channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { });
}
}
2、Work queues 工作队列
轮询
生产者
package com.xyulu.word;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class Producer {
//定义队列
private final static String QUEUE_NAME = "hello";
public static void main(String[] args) throws Exception{
//创建连接工厂
ConnectionFactory factory = new ConnectionFactory();
//主机地址;默认为 localhost
factory.setHost("localhost");
try (
//创建连接
Connection connection = factory.newConnection();
//创建信道
Channel channel = connection.createChannel()) {
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
for (int i = 0; i < 20; i++){
String message = "Hello World!"+"====="+(i+1);
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
System.out.println(" [x] Sent '" + message + "'");
}
}
}
}
消费者1
package com.xyulu.work;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;
/**
* @Description TODO
* @Author luming
* @Date 2020/12/30
* @Version 1.0
*/
public class Consumer {
private final static String QUEUE_NAME = "hello";
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
//模拟消费耗时
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
String message = new String(delivery.getBody(), "UTF-8");
System.out.println(" [x] Received '" + message + "'");
/**
* 手动确认
* multiple 是否确认多条
*/
channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
};
channel.basicConsume(QUEUE_NAME, false, deliverCallback, consumerTag -> { });
}
}
消费者2
同消费者1
公平
修改消费者代码
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
后加入如下代码
int prefetchCount = 1;
//限制消费者每次只能接收一条消息,处理完才能再次接收
channel.basicQos(prefetchCount);
3、发布订阅队列
生产者发给交换机,由交换机发给绑定的队列
生产者
package com.xyulu.exchange;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
/**
* @Description TODO
* @Author luming
* @Date 2020/12/30
* @Version 1.0
*/
public class Send {
//定义队列
private final static String EXCHANGE_NAME = "exchange_fanout";
public static void main(String[] args) throws Exception{
//创建连接工厂
ConnectionFactory factory = new ConnectionFactory();
//主机地址;默认为 localhost
factory.setHost("localhost");
factory.setUsername("guest");
factory.setPassword("guest");
//虚拟主机名称;默认为 /
factory.setVirtualHost("/");
factory.setPort(5672);
try (
//创建连接
Connection connection = factory.newConnection();
//创建信道
Channel channel = connection.createChannel()) {
//绑定交换机
channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
String message = "Hello World!";
/**
* exchange – 交换机名称,如果没有指定则使用默认Default Exchage
* routingKey – 路由 key,简单模式可以传递队列名称
* props – 消息其它属性
* body – 消息内容
*/
channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes("UTF-8"));
System.out.println(" [x] Sent '" + message + "'");
}
}
}
消费者
package com.xyulu.exchange;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;
/**
* @Description TODO
* @Author luming
* @Date 2020/12/30
* @Version 1.0
*/
public class Recv1 {
private final static String EXCHANGE_NAME = "exchange_fanout";
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
//绑定交换机
channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
//获取队列(排他队列)
String queueName = channel.queueDeclare().getQueue();
//绑定队列和交换机机
channel.queueBind(queueName, EXCHANGE_NAME, "");
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
String message = new String(delivery.getBody(), "UTF-8");
System.out.println(" [x] Received '" + message + "'");
};
/**
* @param queue
* @param autoAck 自动回值
* @param deliverCallback callback when a message is delivered
* @param shutdownSignalCallback callback when the channel/connection is shut down
*/
channel.basicConsume(queueName, true, deliverCallback, consumerTag -> { });
}
}
4、路由队列
交换机使用路由 key 绑定队列
生产者
package com.xyulu.routing;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
/**
* @Description TODO
* @Author luming
* @Date 2020/12/30
* @Version 1.0
*/
public class Send {
//定义队列
private final static String EXCHANGE_NAME = "Routing";
public static void main(String[] args) throws Exception{
//创建连接工厂
ConnectionFactory factory = new ConnectionFactory();
//主机地址;默认为 localhost
factory.setHost("localhost");
factory.setUsername("guest");
factory.setPassword("guest");
//虚拟主机名称;默认为 /
factory.setVirtualHost("/");
factory.setPort(5672);
try (
//创建连接
Connection connection = factory.newConnection();
//创建信道
Channel channel = connection.createChannel()) {
//绑定交换机
channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
String infoMessage = "this is infoMessage";
String waringMessage = "this is waringMessage";
String errorMessage = "this is errorMessage";
String infoRoutingKey = "info";
String waringRoutingKey = "waring";
String errorRoutingKey = "error";
channel.basicPublish(EXCHANGE_NAME, infoRoutingKey, null, infoMessage.getBytes("UTF-8"));
channel.basicPublish(EXCHANGE_NAME, waringRoutingKey, null, waringMessage.getBytes("UTF-8"));
channel.basicPublish(EXCHANGE_NAME, errorRoutingKey, null, errorMessage.getBytes("UTF-8"));
System.out.println(" [x] Sent '" + infoMessage + "'");
System.out.println(" [x] Sent '" + waringMessage + "'");
System.out.println(" [x] Sent '" + errorMessage + "'");
}
}
}
消费者
package com.xyulu.routing;
import com.rabbitmq.client.*;
/**
* @Description TODO
* @Author luming
* @Date 2020/12/30
* @Version 1.0
*/
public class InfoRecv {
private final static String EXCHANGE_NAME = "Routing";
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
//绑定交换机
channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
//获取队列(排他队列)
String queueName = channel.queueDeclare().getQueue();
//绑定队列和交换机机
String infoRoutingKey = "info";
channel.queueBind(queueName, EXCHANGE_NAME, infoRoutingKey);
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
String message = new String(delivery.getBody(), "UTF-8");
System.out.println(" [x] Received '" + message + "'");
};
/**
* @param queue
* @param autoAck 自动回值
* @param deliverCallback callback when a message is delivered
* @param shutdownSignalCallback callback when the channel/connection is shut down
*/
channel.basicConsume(queueName, true, deliverCallback, consumerTag -> { });
}
}
5、主题队列 (使用最多)
使用通配符
*(star) can substitute for exactly one word.
#(hash) can substitute for zero or more words.
生产者
package com.xyulu.topic;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
/**
* @Description TODO
* @Author luming
* @Date 2020/12/30
* @Version 1.0
*/
public class Send {
//定义队列
private final static String EXCHANGE_NAME = "exchange_topic";
public static void main(String[] args) throws Exception{
//创建连接工厂
ConnectionFactory factory = new ConnectionFactory();
//主机地址;默认为 localhost
factory.setHost("localhost");
factory.setUsername("guest");
factory.setPassword("guest");
//虚拟主机名称;默认为 /
factory.setVirtualHost("/");
factory.setPort(5672);
try (
//创建连接
Connection connection = factory.newConnection();
//创建信道
Channel channel = connection.createChannel()) {
//绑定交换机
channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC);
String infoMessage = "this is infoMessage";
String waringMessage = "this is waringMessage";
String errorMessage = "this is errorMessage";
String infoRoutingKey = "info.message.orange";
String waringRoutingKey = "warning.rabbit.lazy";
String errorRoutingKey = "error.rabbit.message";
channel.basicPublish(EXCHANGE_NAME, infoRoutingKey, null, infoMessage.getBytes("UTF-8"));
channel.basicPublish(EXCHANGE_NAME, waringRoutingKey, null, waringMessage.getBytes("UTF-8"));
channel.basicPublish(EXCHANGE_NAME, errorRoutingKey, null, errorMessage.getBytes("UTF-8"));
System.out.println(" [x] Sent '" + infoMessage + "'");
System.out.println(" [x] Sent '" + waringMessage + "'");
System.out.println(" [x] Sent '" + errorMessage + "'");
}
}
}
消费者
package com.xyulu.topic;
import com.rabbitmq.client.*;
/**
* @Description TODO
* @Author luming
* @Date 2020/12/30
* @Version 1.0
*/
public class Recv {
private final static String EXCHANGE_NAME = "exchange_topic";
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
//绑定交换机
channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC);
//获取队列(排他队列)
String queueName = channel.queueDeclare().getQueue();
//绑定队列和交换机机
String RoutingKey = "#.message.#";
channel.queueBind(queueName, EXCHANGE_NAME, RoutingKey);
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
String message = new String(delivery.getBody(), "UTF-8");
System.out.println(" [x] Received '" + message + "'");
};
/**
* @param queue
* @param autoAck 自动回值
* @param deliverCallback callback when a message is delivered
* @param shutdownSignalCallback callback when the channel/connection is shut down
*/
channel.basicConsume(queueName, true, deliverCallback, consumerTag -> { });
}
}