我想发布到绑定到交换的多个队列(扇出在这里不起作用,因为我只想发布到选择性队列而不是所有队列)
代码如下:
public int pushDataOverRabbitMQ(String[] deviceIDs, String msg) throws IOException {
int retrunVal=0;
String EXCHANGE_NAME="DUSHTEST";
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(EXCHANGE_NAME, "direct",true);
for(int i=0;i<deviceIDs.length;i++){
try{
channel.queueDeclare(deviceIDs[i],true,false,false,null).getQueue();
channel.queueBind(deviceIDs[i], EXCHANGE_NAME, deviceIDs[i]);
//routing key and queue have the same value
channel.basicPublish(EXCHANGE_NAME, deviceIDs[i], new AMQP.BasicProperties.Builder()
.contentType("text/plain").deliveryMode(1)
.priority(1).userId("guest")
.build(),
msg.getBytes());
System.out.println(" [x] Sent '" + msg+ "'");
retrunVal= Constants.PUB_STATUS_SUCCESS;
}catch(Exception e){
e.printStackTrace();
retrunVal= Constants.PUB_STATUS_FAIL;
}
}
channel.close();
connection.close();
return retrunVal;
}
**deviceIDs**
包含两个字符串Dush-Micromax and MyDesktop
由于分数低,我无法上传图像,但在服务器端创建了三个队列。上面的代码将创建的队列绑定到交换器。
我之前创建了两个消费者,如下所示:
import java.io.IOException;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class RabbitSubscriptionModel {
/**
* @param args
*/
private final static String QUEUE_NAME = "MyDesktop";
// private final static String QUEUE_NAME = "Dush-Micromax";
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
final Channel channel = connection.createChannel();
try{
channel.queueDeclare(QUEUE_NAME, true, false, false, null);
}catch (Exception e) {
e.printStackTrace();
}
channel.basicConsume(QUEUE_NAME, false,"My-Consumer-Trial1", new GenericConsumer(channel));
// channel.basicConsume(QUEUE_NAME, false,"My-Consumer-Trial2", new GenericConsumer(channel));
}
}
我有两个消费者,即My-Consumer-Trial1 和 My-Consumer-Trial2
但是,我只在第一个消费者中接收数据,即:My-Consumer-Trial1。在仔细分析 rabbitMQ 管理控制台之后,似乎消费者没有发布到队列上,而第二次发布发生在一个新的队列上。所以我们总共有 三个队列,其中两个绑定到 EXCHANGE,一个在默认 EXCHANGE 下。