使用RabbitMQ,業務需求,想要知道隊列中還有多少待消費待數據。java
方式一:spring
@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; ConnectionFactory factory = new ConnectionFactory(); //設置ip,port,用戶名和祕密 factory.setHost(host); factory.setPort(port); factory.setUsername(username); factory.setPassword(password); //建立連接 Connection connection = factory.newConnection(); //建立信道 Channel channel = connection.createChannel(); //建立一個type=direct 持久化的 非自動刪除的交換器 channel.exchangeDeclare(EXCHANGE_NAME, "direct", true, false, null);
String []queues = queueNames.split(","); for(String queue : queues){ DeclareOk declareOk = channel.queueDeclarePassive(queue); //獲取隊列中的消息個數 int num = declareOk.getMessageCount(); }
方式二:json
spring配置文件:app
<!-- 鏈接配置 --> <rabbit:connection-factory id="rabbitConnectionFactory" host="#{app['mq.broker.host']}" port="#{app['mq.broker.port']}" username="#{app['mq.broker.username']}" password="#{app['mq.broker.password']}" virtual-host="/" publisher-confirms="true"/>
<!-- mq模板 --> <rabbit:template id="rabbitTemplate" connectionfactory="rabbitConnectionFactory" message-converter="jsonMessageConverter"/>
java代碼:spa
@Autowired private RabbitTemplate rabbitTemplate; ConnectionFactory connectionFactory = rabbitTemplate.getConnectionFactory(); // 建立鏈接 Connection connection = connectionFactory.createConnection(); // 建立通道 Channel channel = connection.createChannel(false); // 設置消息交換機 channel.exchangeDeclare("amp.topic", "direct", true, false, null); DeclareOk declareOk = channel.queueDeclarePassive(LETTER_CLASS_QUEUE); //獲取隊列中的消息個數 int queueCount = declareOk.getMessageCount(); result.put("queueCount", String.valueOf(queueCount)); // 關閉通道和鏈接 channel.close(); connection.close();