第一步導入依賴 :
<dependency> <groupId>com.rabbitmq</groupId> <artifactId>amqp-client</artifactId> <version>3.4.1</version>
</dependency>
第二步編寫一個連接類獲取MQ的連接:ConnectionUtil
package com.example.springboot_rabbitmq.util; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; public class ConnectionUtil { public static Connection getConnection() throws Exception { //定義連接工廠 ConnectionFactory factory = new ConnectionFactory(); //設置服務地址 factory.setHost("localhost"); //端口 factory.setPort(5672); //設置賬號信息,用戶名、密碼、vhost factory.setVirtualHost("/"); factory.setUsername("guest"); factory.setPassword("guest"); // 通過工程獲取連接 Connection connection = factory.newConnection(); if (connection.isOpen()){ System.out.println("連接成功"); }else{ System.out.println("連接失敗"); } return connection; } public static void main(String[] args) { //測試連接 try { System.out.println(ConnectionUtil.getConnection()); } catch (Exception e) { e.printStackTrace(); } } }
第三步:啟動本地服務端
測試連接:
連接成功沒毛病
下面使用瀏覽器訪問:http://localhost:15672
window下安裝RabbitMQ教程:https://www.cnblogs.com/nongzihong/p/11578255.html
第四步:生產者發送消息到隊列
package com.example.springboot_rabbitmq.simple; import com.example.springboot_rabbitmq.util.ConnectionUtil; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; public class Send { private final static String QUEUE_NAME = "q_test_01"; public static void main(String[] argv) throws Exception { // 獲取到連接以及mq通道 Connection connection = ConnectionUtil.getConnection(); // 從連接中創建通道 Channel channel = connection.createChannel(); // 聲明(創建)隊列 channel.queueDeclare(QUEUE_NAME, false, false, false, null); // 消息內容 String message = "Hello World!"; channel.basicPublish("", QUEUE_NAME, null, message.getBytes()); System.out.println(" [x] Sent '" + message + "'"); //關閉通道和連接 channel.close(); connection.close(); } }
管理工具中查看消息:
第五步:消費者從隊列中獲取消息
package com.example.springboot_rabbitmq.simple; import com.example.springboot_rabbitmq.util.ConnectionUtil; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.QueueingConsumer; public class Recv { private final static String QUEUE_NAME = "q_test_01"; public static void main(String[] argv) throws Exception { // 獲取到連接以及mq通道 Connection connection = ConnectionUtil.getConnection(); // 從連接中創建通道 Channel channel = connection.createChannel(); // 聲明隊列 channel.queueDeclare(QUEUE_NAME, false, false, false, null); // 定義隊列的消費者 QueueingConsumer consumer = new QueueingConsumer(channel); // 監聽隊列 channel.basicConsume(QUEUE_NAME, true, consumer); // 獲取消息 while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String message = new String(delivery.getBody()); System.out.println(" [x] Received '" + message + "'"); } } }
信息獲取成功