1、rabbitmq的啓動
1.1 前臺運行
rabbitmq-server
1.2 後臺運行
brew service start rabbitmq
2、在瀏覽器中輸入地址查看:
http://127.0.0.1:15672/
2.1
使用默認賬號登錄:guest/ guest
3、添加用戶
4、可以通過代碼自動創建隊列,請看下面裏例子
4.1、獲取MQ的連接
package com.example.rabbitmq.config;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
/**
* @author navy
* @version 1.0
* @date 2020-06-10 20:47
*/
public class ConnectionUtil {
public static Connection getConnection() throws Exception {
//定義連接工廠
ConnectionFactory factory = new ConnectionFactory();
//設置服務地址
factory.setHost("localhost");
//端口
factory.setPort(5672);
//設置賬號信息,用戶名、密碼、vhost
factory.setVirtualHost("testhost");
factory.setUsername("admin");
factory.setPassword("admin");
// 通過工程獲取連接
Connection connection = factory.newConnection();
return connection;
}
}
4.2、生產者發送消息到隊列
package com.example.rabbitmq.simple;
import com.example.rabbitmq.config.ConnectionUtil;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
/**
* @author navy
* @version 1.0
* @date 2020-06-10 20:53
*/
public class Send {
private final static String QUEUE_NAME = "q_test_02";
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! I am Navy";
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
System.out.println(" [x] Sent '" + message + "'");
//關閉通道和連接
channel.close();
connection.close();
}
}
4.3、管理工具中查看消息
4.4、 點擊上面的隊列名稱,查詢具體的隊列中的信息:
4.5、消費者從隊列中獲取消息
package com.example.rabbitmq.simple;
import com.example.rabbitmq.config.ConnectionUtil;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.QueueingConsumer;
/**
* @author navy
* @version 1.0
* @date 2020-06-10 21:15
*/
public class Recv {
private final static String QUEUE_NAME = "q_test_02";
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 + "'");
}
}
}
執行消費消息後,可以看到控制檯的數據爲0
這個是rabbitmq的一種簡單的消費模式.
瞭解更多相關MQ的知識,請掃碼關注下方公衆號: