RabbitMQ Java客户端api简单运用
官网介绍:https://www.rabbitmq.com/getstarted.html
六种工作模式
- simple简单模式 :一个生产者对应一个消费者
- work工作模式 :一个生产者对应多个消费者
- publish订阅模式 :扇出 也称广播 生产者发送的消息所有消费者都要接收
- routing路由模式 :不同的消息被不同的队列消费 消息类型由key区别
- topic 主题模式 :不同的消息被不同的队列消费 消息类型由key和通配符区别
- RPC异步调用模式 :远程调用 客户端即是生产者也是消费者,向队列发送调用消息,同时监听响应队列。
下面对前五种常用模式做简单介绍及代码实现
准备工作
maven项目引入rabbitmq客户端依赖
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.9.0</version>
</dependency>
创建一个获取连接的工具类ConnectionUtil,方便后面使用
package com.populus.rabbitmq;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class ConnectionUtil {
private static ConnectionFactory FACTORY = new ConnectionFactory();
static {
FACTORY.setPort(5672);//RabbitMQ协议端口号
FACTORY.setHost("localhost");//RabbotMQ主机地址
FACTORY.setVirtualHost("javaVirtual");//虚拟机名称 随便起
FACTORY.setUsername("guest");//RabbotMQ连接用户名
FACTORY.setPassword("guest");//RabbotMQ连接密码
}
//提供获取连接的方法
public static Connection getConnection(){
try {
return FACTORY.newConnection();
} catch (IOException | TimeoutException e) {
e.printStackTrace();
}
return null;
}
}
1.simple简单模式
生产者,发送消息
消费者:接收消息,会一直等待消息到来。
生产者代码实现
package com.populus.rabbitmq;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class provide {
public static void main(String[] args) throws IOException, TimeoutException {
// 1.获取连接
Connection connection = ConnectionUtil.getConnection();
// 2.创建通道
Channel channel = connection.createChannel();
// 3.声明队列
channel.queueDeclare("queueName", false, false, false, null);
// 4.发布消息 (交换机名称,路由名称,消息属性,消息体)
channel.basicPublish("", "queueName", null, "这是一条消息".getBytes());
// 5.关闭通道
channel.close();
// 6.关闭连接
connection.close();
}
}
消费者代码实现
package com.populus.rabbitmq;
import com.rabbitmq.client.*;
import java.io.IOException;
public class Consumer {
public static void OneToOne() throws IOException {
// 1.获取连接
Connection connection = ConnectionUtil.getConnection();
// 2.获取通道
Channel channel = connection.createChannel();
// 3.声明队列 (队列名称,是否持久化队列,是否独占队列,用完是否自动删除队列,其他参数)
channel.queueDeclare("queueName", false, false, false, null);
// 4.获取队列消息 (队列名称,接收到消息后是否应答服务器,回调接口)
channel.basicConsume("queueName", true, new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) {
System.out.println("消费者" + new String(body));
}
});
}
运行结果
2.work工作模式
一个生产者对应多个消费者,资源竞争分为公平策略和非公平策略。公平策略是消费者们平分消息,非公平策略是多劳多得,消费快的可消费更多消息。默认是公平策略。
2.1 公平策略
生产者代码实现
package com.populus.rabbitmq;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class Provide {
public static void main(String[] args) throws IOException, TimeoutException {
// 1.获取连接
Connection connection = ConnectionUtil.getConnection();
// 2.创建通道
Channel channel = connection.createChannel();
// 3.声明队列 (队列名称,是否持久化队列,是否独占队列,用完是否自动删除队列,其他参数)
channel.queueDeclare("queueName", false, false, false, null);
// 4.发布消息(发送多条消息做测试)
for (int i = 1; i < 11; i++) {
channel.basicPublish("", "queueName", null, ("吃了第" + i + "个甜甜圈").getBytes());
}
channel.close();
connection.close();
}
}
消费者代码实现
package com.populus.rabbitmq;
import com.rabbitmq.client.*;
import java.io.IOException;
public class Consumer1 {
// 公平消费
public static void FairsStrategy() throws IOException {
// 1.获取连接
Connection connection = ConnectionUtil.getConnection();
// 2.创建通道
Channel channel = connection.createChannel();
// 3.声明队列 (队列名称,是否持久化队列,是否独占队列,用完是否自动删除队列,其他参数)
channel.queueDeclare("queueName", false, false, false, null);
// 4.获取队列消息 (队列名称,接收到消息后是否应答服务器,回调接口)
channel.basicConsume("queueName", true, 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));
}
});
}
}
复制一份到Consumer2类,此时一个生产者,两个消费者
运行结果
2.2 非公平策略
生产者代码同上
消费者1
package com.populus.rabbitmq;
import com.rabbitmq.client.*;
import java.io.IOException;
public class Consumer1 {
// 非公平消费
public static void UnFairsStrategy() throws IOException {
// 1.获取连接
Connection connection = ConnectionUtil.getConnection();
// 2.获取通道
final Channel channel = connection.createChannel();
// 3.声明队列 (队列名称,是否持久化队列,是否独占队列,用完是否自动删除队列,其他参数)
channel.queueDeclare("queueName", false, false, false, null);
// 4.一次消费一条消息
channel.basicQos(1);
// 5.获取队列消息 (队列名称,接收到消息后是否应答服务器,回调接口)
channel.basicConsume("queueName", false, 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(), true);
}
});
}
}
消费者2
package com.populus.rabbitmq;
import com.rabbitmq.client.*;
import java.io.IOException;
public class Consumer2 {
// 非公平消费
public static void UnFairsStrategy() throws IOException {
// 1.获取连接
Connection connection = ConnectionUtil.getConnection();
// 2.获取通道
final Channel channel = connection.createChannel();
// 3.声明队列 (队列名称,是否持久化队列,是否独占队列,用完是否自动删除队列,其他参数)
channel.queueDeclare("queueName", false, false, false, null);
// 4.一次消费一条消息
channel.basicQos(1);
// 5.获取队列消息 (队列名称,接收到消息后是否应答服务器,回调接口)
channel.basicConsume("queueName", false, new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
// 模拟消费消息慢
try {
Thread.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("消费者2" + new String(body));
// 6.手动确认消息
channel.basicAck(envelope.getDeliveryTag(), true);
}
});
}
}
运行结果
3.publish订阅模式
扇出 也称广播 生产者发送的消息所有消费者都要接收。每个消费者都有自己的队列,生产者发送消息到交换机,由交换机来把消息发送给队列,因此每个队列都要绑定交换机。
生产者代码
package com.populus.rabbitmq;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class Provide {
public static void main(String[] args) throws IOException, TimeoutException {
// 1.获取连接
Connection connection = ConnectionUtil.getConnection();
// 2.创建通道
Channel channel = connection.createChannel();
// 3.声明队列 (队列名称,是否持久化队列,是否独占队列,用完是否自动删除队列,其他参数)
channel.queueDeclare("queueName", false, false, false, null);
// 4.声明交换机 (交换机名称,交换机类型)
channel.exchangeDeclare("fanoutExchange","fanout");
// 5.发布消息 (交换机名称,路由名称,消息属性,消息体)
for (int i = 1; i < 11; i++) {
channel.basicPublish("fanoutExchange", "", null, ("吃了第" + i + "个甜甜圈").getBytes());
}
channel.close();
connection.close();
}
}
消费者代码
消费者1
package com.populus.rabbitmq;
import com.rabbitmq.client.*;
import java.io.IOException;
public class Consumer1 {
// 广播
public static void broadcast() throws IOException {
// 1.获取连接
Connection connection = ConnectionUtil.getConnection();
// 2.创建通道
Channel channel = connection.createChannel();
// 3.创建临时队列
String queue = channel.queueDeclare().getQueue();
// 4.声明交换机 (交换机名称,交换机类型)
channel.exchangeDeclare("fanoutExchange", "fanout");
// 3.临时队列与交换机绑定 (队列名称,交换机名称,routingKey)
channel.queueBind(queue, "fanoutExchange", "");
// 5.获取队列消息 (队列名称,接收到消息后是否应答服务器,回调接口)
channel.basicConsume(queue, true, 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));
}
});
}
}
复制一份到Consumer2类,此时一个生产者,两个消费者
运行结果
4.routing路由模式
不同的消息被不同的队列消费。队列与交换机的绑定不再是任意绑定,而是要指定一个RoutingKey
(路由key),生产者向交换机发送消息时,也必须指定消息的 RoutingKey。交换机根据RoutingKey判断,将消息发送给与RoutingKey完全一致的队列。
生产者代码
package com.populus.rabbitmq;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class Provide {
public static void main(String[] args) throws IOException, TimeoutException {
// 1.获取连接
Connection connection = ConnectionUtil.getConnection();
// 2.创建通道
Channel channel = connection.createChannel();
// 3.声明队列 (队列名称,是否持久化队列,是否独占队列,用完是否自动删除队列,其他参数)
channel.queueDeclare("queueName", false, false, false, null);
// 4.声明交换机 (交换机名称,交换机类型)
channel.exchangeDeclare("directExchange","direct");
// 5.声明 routing key
String appleKey = "apple";
String orangeKey = "orange";
// 6.发布消息 (交换机名称,路由名称,消息属性,消息体)
channel.basicPublish("directExchange", appleKey, null, ("吃到了苹果味甜甜圈").getBytes());
channel.basicPublish("directExchange", orangeKey, null, ("吃到了橘子味甜甜圈").getBytes());
channel.close();
connection.close();
}
}
消费者代码
消费者1
package com.populus.rabbitmq;
import com.rabbitmq.client.*;
import java.io.IOException;
public class Consumer1 {
// 路由 -直连
public static void Routing() throws IOException {
// 1.获取连接
Connection connection = ConnectionUtil.getConnection();
// 2.创建通道
Channel channel = connection.createChannel();
// 3.创建临时队列
String queue = channel.queueDeclare().getQueue();
// 4.声明交换机 (交换机名称,交换机类型)
channel.exchangeDeclare("directExchange", "direct");
// 5.临时队列与交换机绑定 (队列名称,交换机名称,routingKey)
channel.queueBind(queue, "directExchange", "apple");
// 6.获取队列消息 (队列名称,接收到消息后是否应答服务器,回调接口)
channel.basicConsume(queue, true, 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));
}
});
}
}
消费者2
package com.populus.rabbitmq;
import com.rabbitmq.client.*;
import java.io.IOException;
public class Consumer2 {
// 路由 -直连
public static void Routing() throws IOException {
// 1.获取连接
Connection connection = ConnectionUtil.getConnection();
// 2.创建通道
Channel channel = connection.createChannel();
// 3.创建临时队列
String queue = channel.queueDeclare().getQueue();
// 4.声明交换机 (交换机名称,交换机类型)
channel.exchangeDeclare("directExchange", "direct");
// 5.临时队列与交换机绑定 (队列名称,交换机名称,routingKey)
channel.queueBind(queue, "directExchange", "orange");
// 6.获取队列消息 (队列名称,接收到消息后是否应答服务器,回调接口)
channel.basicConsume(queue, true, 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));
}
});
}
}
运行结果
5.topic 主题模式
不同的消息被不同的队列消费 消息类型由key和通配符区别。Topic
类型与Direct
相比,都是可以根据RoutingKey把消息路由到不同的队列。只不过Topic
类型可以让队列在绑定Routingkey`的时候使用通配符。
* 匹配一个词 例:rabbit.a
# 匹配一个或多个词 例:rabbit.a或rabbit.a.b等
生产者代码
package com.populus.rabbitmq;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class Provide {
public static void main(String[] args) throws IOException, TimeoutException {
// 1.获取连接
Connection connection = ConnectionUtil.getConnection();
// 2.创建通道
Channel channel = connection.createChannel();
// 3.声明队列 (队列名称,是否持久化队列,是否独占队列,用完是否自动删除队列,其他参数)
channel.queueDeclare("queueName", false, false, false, null);
// 4.声明交换机 (交换机名称,交换机类型)
channel.exchangeDeclare("topicExchange","topic");
// 5.声明 routing key
String topicKey1 = "topic.aa";
String topicKey2 = "topic.aa.bb";
// 6.发布消息
channel.basicPublish("topicExchange",topicKey1,null,("匹配了"+topicKey1).getBytes());
channel.basicPublish("topicExchange",topicKey2,null,("匹配了"+topicKey2).getBytes());
channel.close();
connection.close();
}
}
消费者代码
消费者1
package com.populus.rabbitmq;
import com.rabbitmq.client.*;
import java.io.IOException;
public class Consumer1 {
// 路由 -通配符
public static void Topic() throws IOException {
// 1.获取连接
Connection connection = ConnectionUtil.getConnection();
// 2.创建通道
Channel channel = connection.createChannel();
// 3.创建临时队列
String queue = channel.queueDeclare().getQueue();
// 4.声明交换机 (交换机名称,交换机类型)
channel.exchangeDeclare("topicExchange","topic");
// 5.临时队列与交换机绑定 (队列名称,交换机名称,routingKey)
channel.queueBind(queue,"topicExchange","topic.*");
// 6.获取队列消息 (队列名称,接收到消息后是否应答服务器,回调接口)
channel.basicConsume(queue,true,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));
}
});
}
}
消费者2
package com.populus.rabbitmq;
import com.rabbitmq.client.*;
import java.io.IOException;
public class Consumer2 {
// 路由 -通配符
public static void Topic() throws IOException {
// 1.获取连接
Connection connection = ConnectionUtil.getConnection();
// 2.创建通道
Channel channel = connection.createChannel();
// 3.创建临时队列
String queue = channel.queueDeclare().getQueue();
// 4.声明交换机 (交换机名称,交换机类型)
channel.exchangeDeclare("topicExchange","topic");
// 5.临时队列与交换机绑定 (队列名称,交换机名称,routingKey)
channel.queueBind(queue,"topicExchange","topic.#");
// 6.获取队列消息 (队列名称,接收到消息后是否应答服务器,回调接口)
channel.basicConsume(queue,true,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));
}
});
}
}
运行结果
6.RPC异步调用模式
远程调用 客户端即是生产者也是消费者,向队列发送调用消息,同时监听响应队列。不常用,了解即可。