rabbitmq生成消费+获取某一队列中消息数量
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.AMQP.Queue.DeclareOk;
import org.springframework.beans.factory.annotation.Value;
/**
* Producer
*/
public class ProducerAndCustomer {
// 1.创建连接连接到RabbitMQ
private ConnectionFactory factory = new ConnectionFactory();
@Value("${spring.rabbitmq.host}")
private String host;
@Value("${spring.rabbitmq.port}")
private Integer port;
@Value("${spring.rabbitmq.username}")
private String username;
@Value("${spring.rabbitmq.password}")
private String password;
{
// 2.设置地址、端口、账号、密码
factory.setHost(host);
factory.setPort(port);
factory.setUsername(username);
factory.setPassword(password);
}
/**
* 数据生产
* @param queueName 队列名称
* @param str 存入得数据
* @throws Exception
*/
public static void setMSG(String queueName,String str) throws Exception{
// 3.获取连接
Connection conn = factory.newConnection();
// 4.获取通道
Channel channel = conn.createChannel();
// 5.创建队列 1-队列名称 2-队列是否持久化 3-队列是否是独占 4-使用完之后是否删除此队列 5-其他属性
channel.queueDeclare(queueName, true, false, false, null);
// 6.发送消息
channel.basicPublish("", queueName, null, str.getBytes());
System.out.println(" [Producer] Sent '" + str + "'");
// 7.关闭资源
channel.close();
conn.close();
}
/**
* 数据消费
* @param queueName 队列名称
* @return
* @throws Exception
*/
public String getMSG(String queueName) throws Exception {
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(queueName,true, false, false, null);
// 同一时刻服务器只会发一条消息给消费者(能者多劳模式),空闲多的消费者,消费更多的消息
channel.basicQos(1);
QueueingConsumer consumer = new QueueingConsumer(channel);
/*
* 监听队列
* 参数1:队列名称
* 参数2:是否发送ack包,不发送ack消息会持续在服务端保存,直到收到ack。 可以通过channel.basicAck手动回复ack
* 参数3:消费者
*/
channel.basicConsume(queueName, false, consumer);
// 获取消息 一次只获取一个数据
// while (true) {
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
String message = new String(delivery.getBody());
System.out.println(" [消费者1] Received '" + message + "'");
// 手动返回ack包确认状态
channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
//channel.basicReject(); channel.basicNack(); //可以通过这两个函数拒绝消息,可以指定消息在服务器删除还是继续投递给其他消费者
// }
// 7.关闭资源
channel.close();
return message;
}
public int getRabbitMqSum()throws Exception{
// 创建链接
Connection connection = factory.newConnection();
// 创建信道
Channel channel = connection.createChannel();
// 创建一个type=direct 持久化的 非自动删除的交换器
channel.exchangeDeclare("EXCHANGE_NAME", "direct", true, false, null);
DeclareOk declareOk = channel.queueDeclarePassive("doctor");
// 获取队列中的消息个数
int sum = declareOk.getMessageCount();
return sum;
}
}
获取消息个数采用的这位大佬的博客:https://blog.youkuaiyun.com/m0_38012174/article/details/90899084