對於RabbitMQ的監控,除了服務器基本信息(硬盤、CPU、內存、IO等)以及MQ的進程和端口,我們也可以通過請求url訪問管理API監控其集群和隊列的情況。在Java api 3.6.0以后,channel接口為我們提供了如下接口:
/** * Returns the number of messages in a queue ready to be delivered * to consumers. This method assumes the queue exists. If it doesn't, * an exception will be closed with an exception. * @param queue the name of the queue * @return the number of messages in ready state * @throws IOException Problem transmitting method. */ long messageCount(String queue) throws IOException; /** * Returns the number of consumers on a queue. * This method assumes the queue exists. If it doesn't, * an exception will be closed with an exception. * @param queue the name of the queue * @return the number of consumers * @throws IOException Problem transmitting method. */ long consumerCount(String queue) throws IOException;
messageCount:查詢隊列未消費的消息數,可以監控消息堆積的情況。
consumerCount:隊列的消費者個數,可以對消費者進行監控
Java實例:
public class JavaAPIMonitor { private static String queue_name = "test_queue"; public static void main(String[] args) throws Exception { ConnectionFactory factory = new ConnectionFactory(); // amqp://userName:password@hostName:portNumber/virtualHost factory.setUri("amqp://test:test@10.1.199.169:5672/test"); Connection conn = factory.newConnection(); // System.out.println(conn.getChannelMax()); Channel channel = conn.createChannel(); // System.out.println(channel.getChannelNumber()); System.out.println(channel.messageCount(queue_name)); System.out.println(channel.consumerCount(queue_name)); channel.close(); conn.close(); } } 運行結果: 277782 3
除此之外,也可以通過連接的狀態變化,進行監控,如:連接被阻塞(內存,CPU等不足)
ConnectionFactory factory = new ConnectionFactory(); Connection connection = factory.newConnection(); connection.addBlockedListener(new BlockedListener() { public void handleUnblocked() throws IOException { // 連接取消阻塞 } public void handleBlocked(String reason) throws IOException { // 連接阻塞 } }); connection.addShutdownListener(new ShutdownListener() { public void shutdownCompleted(ShutdownSignalException cause) { //連接關閉 } });
先關監控參考文章:
1.RabbitMQ之管理與監控
2.REST API監控RabbitMQ
3.如何監控RabbitMQ
4.使用AMQP模擬檢測來確認RabbitMQ是否運行
5.監控隊列狀態