使用代码生成队列与交换机以及使用
使用代码生成队列与交换机以及使用
一、使用配置类
1.在配置类中使用两种方式创建队列,注意Queue的包
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.QueueBuilder;
@Bean
public Queue topicQueue1() {
return new Queue("topic1.queue");
}
@Bean
public Queue topicQueue2() {
return QueueBuilder.durable("topic2.queue").build();
}
2.在配置类中创建交换机
@Bean
public TopicExchange topicExchange() {
return ExchangeBuilder.topicExchange("topic.exchange").build();
}
3.在配置类中交换机与队列进行绑定,绑定多个路由键时,需要写多个方法,而不是在后面接with或在with里写多个参数。
@Bean
public Binding topicQueue1ToTopicExchange(Queue topicQueue1, TopicExchange topicExchange) {
return BindingBuilder.bind(topicQueue1).to(topicExchange).with("#.debu");
}
二、使用注解
在监听上添加注解内容,相比之前的@RabbitListener(queues = "simple.queue")来说,复杂很多
@RabbitListener(bindings = {
@QueueBinding(
value = @Queue(name = "topic1.queue"),
exchange = @Exchange(name = "topic.exchange", type = ExchangeTypes.TOPIC),
key = "#.debu"
)
})
public void getTopicMessage1(String msg) {
log.info("消费者1号 收到消息:{}", msg);
}
三、使用
消息生产者
@Autowired
private AmqpTemplate amqpTemplate;
//or
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
public void sendDirectMessage1() {
String directExchange = "direct.exchange";
amqpTemplate.convertAndSend(directExchange, "red", "颜色为red");
amqpTemplate.convertAndSend(directExchange, "blue", "颜色为blue");
amqpTemplate.convertAndSend(directExchange, "yellow", "颜色为yellow");
}

浙公网安备 33010602011771号