第一种通过bean创建
@Configuration
public class RabbitConfig {
//队列
@Bean
public Queue fanoutQueue(){
return new Queue("fanout.queue");
}
//交换机
@Bean
public FanoutExchange itcastFanout(){
return new FanoutExchange("itcast.fanout");
}
//绑定队列到交换机
@Bean
public Binding queueEcchange(Queue fanoutQueue,FanoutExchange fanoutExchange){
return BindingBuilder.bind(fanoutQueue).to(fanoutExchange);
}
}
除了new对象还可以用建造者模式
@Configuration
public class RabbitFanoutConfig {
@Bean
public Queue fanoutQueue(){
return QueueBuilder.durable("fanout.queue").build();
}
@Bean
public FanoutExchange itcastFanout(){
return ExchangeBuilder.fanoutExchange("itcast.fanout").build();
}
@Bean
public Binding fanoutQueueItcastFanout(Queue fanoutQueue,FanoutExchange itcastFanout){
return BindingBuilder.bind(fanoutQueue).to(itcastFanout);
}
}
第二种通过注解的方式创建
@Component
public class MessageListener
@RabbitListener(bindings = {
@QueueBinding(value = @Queue(name = "direct.queue",durable = "true"), //队列
exchange = @Exchange(name = "itcast.direct",type = ExchangeTypes.DIRECT), //交换机
key = {"blue"}) //路由key
})
public void handleDirectQueue(String message){
System.out.println("direct.queue:"+message);
}
}
最后还可以通过图形化页面创建队列和交换机。