1、在消费者服务中,利用注解声明队列、交换机,并将两者绑定
在listener包下创建SpringDirectRabbitListener类
package cn.itheima.mq.listener;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
/**
* 接收消息
* @author ning
* @since 2022/12/2 20:31
*/
@Component
public class SpringDirectRabbitListener {
/**
* 声明要监听的队列
* bindings 要绑定队列
* value 创建一个队列,name 队列名
* exchange 创建一个交换机,name 交换机名,type 交换机类型
* key 交换机根据key值来判断把消息转发给哪个队列
*/
@RabbitListener(bindings = @QueueBinding(
value = @Queue(name = "direct.queue1"),
exchange = @Exchange(name = "exchange.direct",type = ExchangeTypes.DIRECT),
key = {"blue","red"}
))
public void listenDirectQueue1(String msg) {
System.out.println("消费者1接受到了消息" + msg);
}
/**
* 声明要监听的队列
* bindings 要绑定队列
* value 创建一个队列,name 队列名
* exchange 创建一个交换机,name 交换机名,type 交换机类型
* key 交换机根据key值来判断把消息转发给哪个队列
*/
@RabbitListener(bindings = @QueueBinding(
value = @Queue(name = "direct.queue2"),
exchange = @Exchange(name = "exchange.direct",type = ExchangeTypes.DIRECT),
key = {"yellow","red"}
))
public void listenDirectQueue2(String msg) {
System.out.println("消费者2接受到了消息" + msg);
}
}
2、在生产者服务中,编写测试方法,向exchange.fanout发送消息
package cn.itheima.mq.helloworld;
import org.junit.jupiter.api.Test;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
/**
* 发送消息测试类
*
* @author ning
* @since 2022/12/2 20:09
*/
@SpringBootTest
public class SpringAmqpDirectTest {
//注入收发消息模板
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
void testSimpleDirectQueue() {
//消息
String msg = "hello, spring amqp!";
//交换机名称
String exchangeName = "exchange.direct";
//发送消息,转成字节数组发送
//给交换机发送消息是三个参数
//参数分别是:交互机名称、RoutingKey、消息
//RoutingKey:交换机根据这个key值来判断消息转发给谁
rabbitTemplate.convertAndSend(exchangeName,"blue",msg);
System.out.println("消息发送完毕");
}
}