1. 程式人生 > 實用技巧 >RabbitMQ-快速入門

RabbitMQ-快速入門

一、生產者

public static void main(String[] args) throws IOException, TimeoutException {
//1.建立連線工廠
ConnectionFactory connectionFactory = new ConnectionFactory();
//2.設定引數
connectionFactory.setHost("127.0.0.1");//ip,預設localhost
connectionFactory.setPort(5672);//埠,預設5672
connectionFactory.setVirtualHost("/");//虛擬機器,預設/
connectionFactory.setUsername("guest");//使用者名稱,預設guest
connectionFactory.setPassword("guest");//密碼,預設guest
//3.建立連線
Connection connection = connectionFactory.newConnection();
//4.建立channel
Channel channel = connection.createChannel();
//5.建立佇列
/**
* 引數:1、佇列名稱
* 2、是否持久化
* 3、是否獨佔,只有一個消費者監聽佇列,當connection關閉時,是否刪除佇列
* 4、是否自動刪除,當沒有consumer時,自動刪除掉
* 5、相關引數,一般為null
*/
channel.queueDeclare("hello_world",true,false,false,null);
//6.傳送訊息
/**
* 引數: 1、交換機名稱
* 2、佇列名稱
* 3、配置資訊
* 4、傳送訊息資料
*/
String body="hello rabbitmq...";
channel.basicPublish("","hello_world",null,body.getBytes());
//7.釋放資源
channel.close();
connection.close();
}

二、消費者

public static void main(String[] args) throws IOException, TimeoutException {
//建立連線工廠
ConnectionFactory connectionFactory = new ConnectionFactory();
//設定引數
connectionFactory.setHost("127.0.0.1");//ip,預設localhost
connectionFactory.setPort(5672);//埠,預設5672
connectionFactory.setVirtualHost("/");//虛擬機器,預設/
connectionFactory.setUsername("guest");//使用者名稱,預設guest
connectionFactory.setPassword("guest");//密碼,預設guest
//建立連線
Connection connection = connectionFactory.newConnection();
//建立channel
Channel channel = connection.createChannel();
//接收訊息
Consumer consumer=new DefaultConsumer(channel){
/**
* 回撥方法,收到訊息自動執行
* @param consumerTag 標識
* @param envelope 獲取交換機,路由key等資訊
* @param properties 配置資訊
* @param body 獲取的訊息
* @throws IOException
*/
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("consumerTag:"+consumerTag);
System.out.println("envelope:"+envelope);
System.out.println("properties:"+properties);
System.out.println("body:"+new String(body));
}
};
/**
* 引數: 1、佇列名稱
* 2、是否自動確認
* 3、回撥物件
*/
channel.basicConsume("hello_world",true,consumer);
}

三、測試結果