生产者:
package rabbitMq.direct;
import Utils.RabbitMqUtil;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
//生产者
public class TestRabbitMqP {
public static void main(String[] args) throws IOException, TimeoutException {
//传递的消息
String exchange="logs_direct";
//通过工具获取连接对象
Connection connection = RabbitMqUtil.getConnection();
//获取连接中通道
Channel channel = connection.createChannel();
/**
* 将通道声明指定交换机
* 参数:
* 1、交换机名称
* 2、交换机类型:direct 路由模式
*/
channel.exchangeDeclare(exchange,"direct");
//发送消息
String routingkey="info";
/**
* 消息发布
* 参数:
* 1、交换机名称
* 2、队列名称
* 3、传递消息的额外设置
* 4、消息内容
*/
channel.basicPublish(exchange,routingkey,null,("direct 路由模式,发送:"+routingkey).getBytes());
//关闭连接, 释放资源
RabbitMqUtil.closeConnectionAndChanel(channel,connection);
}
}
消费者1:
package rabbitMq.direct;
import Utils.RabbitMqUtil;
import com.rabbitmq.client.*;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
//消费者
public class TestRabbitMqC_1 {
public static void main(String[] args) throws IOException, TimeoutException {
//通过工具获取连接对象
Connection connection = RabbitMqUtil.getConnection();
//获取连接中通道
Channel channel = connection.createChannel();
/**
* 通道绑定交换机
* 参数:
* 1、交换机名称
* 2、交换机类型
*/
channel.exchangeDeclare("logs_direct","direct");
//临时队列
String queueName = channel.queueDeclare().getQueue();
//绑定交换机和队列
channel.queueBind(queueName,"logs_direct","info");
/**
* 消息订阅
* 参数:
* 1、需要消费的队列名称
* 2、是否开启消息自动队列
* 3、消费的回调接口
*/
channel.basicConsume(queueName,false,new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("==========================="+new String(body));
}
});
}
}
消费者2:
package rabbitMq.direct;
import Utils.RabbitMqUtil;
import com.rabbitmq.client.*;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
//消费者
public class TestRabbitMqC_2 {
public static void main(String[] args) throws IOException, TimeoutException {
//通过工具获取连接对象
Connection connection = RabbitMqUtil.getConnection();
//获取连接中通道
Channel channel = connection.createChannel();
/**
* 通道绑定交换机
* 参数:
* 1、交换机名称
* 2、交换机类型
*/
channel.exchangeDeclare("logs_direct","direct");
//临时队列
String queueName = channel.queueDeclare().getQueue();
//绑定交换机和队列
channel.queueBind(queueName,"logs_direct","info");
channel.queueBind(queueName,"logs_direct","error");
channel.queueBind(queueName,"logs_direct","waring");
/**
* 消息订阅
* 参数:
* 1、需要消费的队列名称
* 2、是否开启消息自动队列
* 3、消费的回调接口
*/
channel.basicConsume(queueName,false,new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("==========================="+new String(body));
}
});
}
}