一、環境準備
請看上一篇文章,Ubuntu18.04安裝RabbitMQ完成RabbitMQ服務端搭建,並創建admin用戶。
gradle添加RabbitMQ客戶端依賴。
compile group: 'com.rabbitmq', name: 'amqp-client', version: '3.6.5'
二、生產者創建
用戶名和密碼都爲admin,隊列名字爲test
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
/**
* Created by wzj on 2018/6/10.
*/
public class Producer
{
public final static String QUEUE_NAME = "test";
public static void main(String[] args) throws IOException, TimeoutException
{
//創建連接工廠
ConnectionFactory factory = new ConnectionFactory();
//設置RabbitMQ相關信息
factory.setHost("192.168.3.45");
factory.setVirtualHost("/");
factory.setUsername("admin");
factory.setPassword("admin");
factory.setPort(5672);
//創建一個新的連接
Connection connection = factory.newConnection();
//創建一個通道
Channel channel = connection.createChannel();
// 聲明一個隊列
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
//發送消息到隊列中
String message = "Hello RabbitMQ";
channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
System.out.println("Producer Send +'" + message + "'");
//關閉通道和連接
channel.close();
connection.close();
}
}
三、消費者創建
import com.rabbitmq.client.*;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
/**
* Created by wzj on 2018/6/10.
*/
public class Customer
{
private final static String QUEUE_NAME = "test";
public static void main(String[] args) throws IOException, TimeoutException
{
// 創建連接工廠
ConnectionFactory factory = new ConnectionFactory();
//設置RabbitMQ地址
factory.setHost("192.168.3.45");
factory.setVirtualHost("/");
factory.setUsername("admin");
factory.setPassword("admin");
//創建一個新的連接
Connection connection = factory.newConnection();
//創建一個通道
Channel channel = connection.createChannel();
//聲明要關注的隊列
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
System.out.println("Customer Waiting Received messages");
// 告訴服務器我們需要那個頻道的消息,如果頻道中有消息,就會執行回調函數handleDelivery
Consumer consumer = new DefaultConsumer(channel)
{
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException
{
String message = new String(body, "UTF-8");
System.out.println("Customer Received '" + message + "'");
}
};
//自動回覆隊列應答 -- RabbitMQ中的消息確認機制
channel.basicConsume(QUEUE_NAME, true, consumer);
}
}
四、測試
1、啓動消費者程序,程序會阻塞,等待生成者發送消息。
2、啓動生產者程序,會發現消費者程序接收到了消息。
Customer Waiting Received messages
Customer Received 'Hello RabbitMQ'