public class RabbitUtil { @Autowired private ConnectionFactory connectionFactory; @Autowired private RabbitTemplate rabbitTemplate; private static RabbitUtil rabbitUtil; @PostConstruct private void init() { rabbitUtil = this; rabbitUtil.rabbitTemplate = this.rabbitTemplate; rabbitUtil.connectionFactory = this.connectionFactory; } public static RabbitTemplate getRabbitTemplate() { return rabbitUtil.rabbitTemplate; } public static ConnectionFactory getConnectionFactory() { return rabbitUtil.connectionFactory; } /** * 發送RMQ消息 * * @param message * @throws AmqpException */ public void convertAndSend(String message) throws AmqpException { convertAndSend(null, null, message, false); } /** * 發送RMQ消息 * * @param routingKey * @param message * @throws AmqpException */ public void convertAndSend(String routingKey, String message) throws AmqpException { convertAndSend(null, routingKey, message, false); } /** * 發送RMQ消息 * * @param exchange * @param routingKey * @param message * @throws AmqpException */ public static void convertAndSend(String exchange, String routingKey, String message) throws AmqpException { convertAndSend(exchange, routingKey, message, false); } private static void convertAndSend(String exchange, String routingKey, Object message, boolean waitForAck) throws AmqpException { if (waitForAck) { } else { if (StringUtils.isNotEmpty(exchange) && StringUtils.isNotEmpty(routingKey)) { getRabbitTemplate().convertAndSend(exchange, routingKey, message); } else if (StringUtils.isNotEmpty(routingKey)) { getRabbitTemplate().convertAndSend(routingKey, message); } else { getRabbitTemplate().convertAndSend(message); } } } /** * 查詢隊列消息數量 * @param queue * @throws Exception */ public static long getMessageCount(String queue) throws Exception { Connection connection = null; Channel channel = null; try { ConnectionFactory connectionFactory = getConnectionFactory(); connection = connectionFactory.createConnection(); channel = connection.createChannel(false); return channel.messageCount(queue); } finally { if(channel != null){ channel.close(); } if(connection != null){ connection.close(); } } }