网站首页> 文章专栏> RabbitMQ-声明队列和交换机
声明队列和交互机
在消费者中创建一个FanoutConfiguration
@Configuration public class FanoutConfiguration { @Bean public FanoutExchange fanoutExchange(){ // ExchangeBuilder.fanoutExchange("hmall.fanout2").build(); return new FanoutExchange("hmall.fanout2"); } @Bean public Queue fanoutQueue3(){ // QueueBuilder.durable("fanout.queue3").build(); return new Queue("fanout.queue3"); } @Bean public Binding fanoutBinding3(Queue fanoutQueue3,FanoutExchange fanoutExchange){ return BindingBuilder.bind(fanoutQueue3).to(fanoutExchange); } @Bean public Queue fanoutQueue4(){ // QueueBuilder.durable("fanout.queue3").build(); return new Queue("fanout.queue4"); } @Bean public Binding fanoutBinding4(){ return BindingBuilder.bind(fanoutQueue4()).to(fanoutExchange()); } }
2,创建一个Direct交换机
@Configuration
public class DirectConfiguration {
@Bean
public DirectExchange directExchange(){
// ExchangeBuilder.fanoutExchange("hmall.fanout2").build();
return new DirectExchange("hmall.direct2");
}
@Bean
public Queue directQueue3(){
// QueueBuilder.durable("fanout.queue3").build();
return new Queue("direct.queue3");
}
@Bean
public Binding directBinding3(Queue directQueue3,DirectExchange directExchange){
return BindingBuilder.bind(directQueue3).to(directExchange).with("red");
}
}
基于注解声明队列和交换机
1,在生产者中的监听器中创建
@Slf4j
@Component
public class SpringRabbitListener {
@RabbitListener(bindings = @QueueBinding(
value = @Queue(name = "dircet.queue3",durable = "true"),
exchange = @Exchange(name = "hamll.direct1",type = ExchangeTypes.DIRECT),
key = {"red","blue"}
))
public void listenDircetQueueMessage3(String msg){
System.out.println("china.# dircet.queue3:" + msg);
}
@RabbitListener(bindings = @QueueBinding(
value = @Queue(name = "dircet.queue4",durable = "true"),
exchange = @Exchange(name = "hamll.direct1",type = ExchangeTypes.DIRECT),
key = {"china.#","#.news"}
))
public void listenDircetQueueMessage4(String msg){
System.out.println("#.news 收到了 dircet.queue4:" + msg);
}
}
以上配置完成,请动手尝试一下!
2024-05-22 16:22:53 回复