本文參考至官網:https://www.rabbitmq.com/getstarted.html
生產者:
import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; public class Send { private final static String QUEUE_NAM = "Hello"; public static void main(String[] args) { //創建連接工廠 ConnectionFactory factory = new ConnectionFactory(); //設置主機名(IP地址) 這裏沒有這是端口號,是因爲默認採用的默認端口號5672 factory.setHost("localhost"); try { //創建連接 Connection connection = factory.newConnection(); //創建信道 Channel channel = connection.createChannel(); //聲明隊列 channel.queueDeclare(QUEUE_NAM, false, false, false, null); String message = "Hello World"; //發佈消息 channel.basicPublish("", QUEUE_NAM, null, message.getBytes()); System.out.println("[x] Sent '" + message + "'" ); } catch (Exception e) { e.printStackTrace(); } } }
消費者:
import com.rabbitmq.client.*; import java.io.IOException; public class Receive { private final static String QUEUE_NAME = "Hello"; public static void main(String[] args) { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("127.0.0.1"); try { Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); // 創建默認消費者 Consumer consumer = new DefaultConsumer(channel) { public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { // 將獲取的消息打印至控制檯 System.out.println(new String(body)); } }; //監聽消息 channel.basicConsume(QUEUE_NAME, consumer); System.out.println("[*] Waiting for messages, To exit press Ctrl + c"); } catch (Exception e) { e.printStackTrace(); } } }
先執行生產者, 在界面看一看到新建的隊列 "Hello" 其中已經又一條消息準備好了!
執行消費者,可以看到隊列 "Hello" 中的消息已被消費!
消費者控制檯輸出:
Hello World 程序Over!!!