rabbitmq有多種工作模式黔帕,這一節(jié)我們將闡述它的Work queues的用法。
1昆著、前提約束
- 已經(jīng)完成rabbitmq的第一個(gè)簡單的測(cè)試程序
http://www.reibang.com/p/77bfc4fe5a1a -
2尺棋、操作步驟
我們馬上要測(cè)試的rabbitmq的工作模式如下:
Work queues - 在src/main/java文件夾下創(chuàng)建包net.wanho.rabbitmq.workqueues
- 在net.wanho.rabbitmq.workqueues創(chuàng)建Worker.java
package net.wanho.rabbitmq.workqueues;
import com.rabbitmq.client.*;
import java.io.IOException;
public class Worker {
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("127.0.0.1");
factory.setPort(5672);
factory.setUsername("guest");
factory.setPassword("guest");
factory.setHost("localhost");
factory.setHost("localhost");
final Connection connection = factory.newConnection();
final Channel channel = connection.createChannel();
String queueName = "task_queue";
channel.queueDeclare(queueName, true, false, false, null);
DefaultConsumer consumer = new DefaultConsumer(channel) {
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
//交換機(jī)
String exchange = envelope.getExchange();
//路由key
String routingKey = envelope.getRoutingKey();
//消息id
long deliveryTag = envelope.getDeliveryTag();
//消息內(nèi)容
String msg = new String(body, "utf-8");
System.out.println("receive message:" + msg);
}
};
/*** 監(jiān)聽隊(duì)列String queue, boolean autoAck,Consumer callback *
* 參數(shù)明細(xì)
* 1、隊(duì)列名稱
* 2铆遭、是否自動(dòng)回復(fù),
* 設(shè)置為true為表示消息接收到自動(dòng)向mq回復(fù)接收到了沿猜,mq接收到回復(fù)會(huì)刪除消息枚荣,
* 設(shè)置為false則需要手動(dòng)回復(fù)
* 3、消費(fèi)消息的方法啼肩,消費(fèi)者接收到消息后調(diào)用此方法
* */
channel.basicConsume(queueName, true, consumer);
}
}
- 在net.wanho.rabbitmq.workqueues創(chuàng)建NewTask.java
package net.wanho.rabbitmq.workqueues;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;
public class NewTask {
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("127.0.0.1");
factory.setPort(5672);
factory.setUsername("guest");
factory.setPassword("guest");
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
String queueName = "task_queue";
channel.queueDeclare(queueName, true, false, false, null);
String message = "task";
channel.basicPublish("", queueName,
MessageProperties.PERSISTENT_TEXT_PLAIN,
message.getBytes("UTF-8"));
System.out.println("send" + message);
}
}
- 測(cè)試
先啟動(dòng)一個(gè)Worker橄妆,再啟動(dòng)一個(gè)Worker,再啟動(dòng)NewTask祈坠,始終只有一個(gè)Worker能收到消息害碾。
以上就是我們完成的rabbitmq的work queues模式的測(cè)試。這個(gè)模式其實(shí)與第一個(gè)demo是一致的赦拘。