import com.rabbitmq.client.*;
import java.io.IOException;
/**
* 验证通过信道 Channel 的 basicPublish() 方法发送消息,且指定 mandatory 为 true。
* 如果将 mandatory 参数设为 true 时,交换器无法根据自身的类型和路由键找到一个符合条件的队列,
* 那么 RabbitMQ 会调用 Basic.Return 命令将消息返回给生产者。
* 如果将 mandatory 参数设为 false 时,交换器无法根据自身的类型和路由键找到一个符合条件的队列,
* 则消息直接被丢弃。
* @author Administrator
* @date 2022年2月17日13:59:29
*/
public class PushMessage2 {
private static final String EXCHANGE_NAME = "exchange_" +
PushMessage2.class.getSimpleName();
/**
* 发送消息
*/
private void sender() {
Connection connection = null;
try {
// 创建连接
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("127.0.0.1");
factory.setPort(5672);
connection = factory.newConnection();
// 创建通道
Channel channel = connection.createChannel();
channel.exchangeDeclare(EXCHANGE_NAME, "topic");
// 发送消息
System.out.println("[Send] Sending Message...");
boolean mandatory = true;
byte[] msg = "hello wrold".getBytes();
channel.basicPublish(EXCHANGE_NAME, "www.hxstrive.com",
mandatory, MessageProperties.PERSISTENT_TEXT_PLAIN, msg);
} catch(Exception e) {
e.printStackTrace();
} finally {
if ( connection != null ) {
try {
connection.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 消费消息
*/
private void consumer() {
try {
// 创建连接
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("127.0.0.1");
factory.setPort(5672);
Connection connection = factory.newConnection();
// 创建通道
Channel channel = connection.createChannel();
channel.exchangeDeclare(EXCHANGE_NAME, "topic");
// 绑定exchange与queue
String queueName = channel.queueDeclare().getQueue();
channel.queueBind(queueName, EXCHANGE_NAME, "*.hxstrive.com");
System.out.println("[Receive] Waiting Message...");
// 消费消息
channel.basicConsume(queueName, true, new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope,
AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("[Receive] Receive Message :: " + new String(body));
}
});
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
PushMessage2 demo = new PushMessage2();
demo.consumer();
demo.sender();
}
}