package com.shi.rout;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import org.junit.Test;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConsumerCancelledException;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.QueueingConsumer.Delivery;
import com.rabbitmq.client.ShutdownSignalException;
import com.shi.util.RabbitMqUtils;
public class RoutTest {
private final static String EXCHANGE_NAME = "exchange_direct";
private final static String KEY_1 ="a";
private final static String KEY_2 ="b";
private final static String KEY_3 ="a";
private final static String QUEUE_1 ="queue_direct_1";
private final static String QUEUE_2 ="queue_direct_2";
@Test
public void send() throws IOException, TimeoutException {
Connection connection = RabbitMqUtils.getConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(EXCHANGE_NAME, "direct");
String message = " 施爷 路由模式direct 向你发送了一条消息....";
channel.basicPublish(EXCHANGE_NAME, KEY_1, null, message.getBytes());
System.out.println(" [x] sent:"+message);
channel.close();
connection.close();
}
@Test
public void reic1() throws IOException, TimeoutException, ShutdownSignalException, ConsumerCancelledException, InterruptedException {
Connection connection = RabbitMqUtils.getConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_1, false, false, false, null);
channel.queueBind(QUEUE_1, EXCHANGE_NAME, KEY_2);
channel.basicQos(1);
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume(QUEUE_1, false,consumer);
while(true) {
Delivery delivery = consumer.nextDelivery();
String message = new String(delivery.getBody());
System.out.println( "[x] reiv1 :" + message);
channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
}
}
@Test
public void reic2() throws IOException, TimeoutException, ShutdownSignalException, ConsumerCancelledException, InterruptedException {
Connection connection = RabbitMqUtils.getConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_2, false, false, false, null);
channel.queueBind(QUEUE_2, EXCHANGE_NAME, KEY_3);
channel.basicQos(1);
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume(QUEUE_2, false,consumer);
while(true) {
Delivery delivery = consumer.nextDelivery();
String message = new String(delivery.getBody());
System.out.println( "[x] reiv2 :" + message);
channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
}
}
}