从代码中我们可以看到,需要在配置中设置对于SimpleMessageListenerContainer做一些个性化的配置,例如设置监听队列,消费的客户端数量,被拒绝后是否重回队列,消息确认模式等等,还可以对消息进行重新组装以及监听到消息之后的操作等等。
@Configuration
@ComponentScan("com.example.streamsample.*")
public class RabbitMQConfig {
@Bean
public ConnectionFactory connectionFactory(){
CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
connectionFactory.setAddresses("127.0.0.1:5672");
connectionFactory.setUsername("guest");
connectionFactory.setPassword("guest");
connectionFactory.setVirtualHost("/");
return connectionFactory;
}
@Bean
public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory){
RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
rabbitAdmin.setAutoStartup(true);
return rabbitAdmin;
}
@Bean
public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory){
return new RabbitTemplate(connectionFactory);
}
@Bean
public DirectExchange exchange001(){
return new DirectExchange("exchange001",true,false);
}
@Bean
public TopicExchange exchange002(){
return new TopicExchange("exchange002",true,false);
}
@Bean
public Queue queue001(){
return new Queue("queue001",true);
}
@Bean
public Queue queue002(){
return new Queue("queue002",true);
}
@Bean
public Binding binding001(){
return BindingBuilder.bind(queue001()).to(exchange001()).with("rabbitmq");
}
@Bean
public Binding binding002(){
return BindingBuilder.bind(queue002()).to(exchange002()).with("spring.*");
}
@Bean
public SimpleMessageListenerContainer messageListenerContainer(ConnectionFactory connectionFactory){
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
container.setQueues(queue001(),queue002());
container.setConcurrentConsumers(1);
container.setMaxConcurrentConsumers(5);
container.setDefaultRequeueRejected(false);
container.setAcknowledgeMode(AcknowledgeMode.AUTO);
container.setConsumerTagStrategy(new ConsumerTagStrategy() {
@Override
public String createConsumerTag(String queue) {
return queue+"_"+ UUID.randomUUID();
}
});
container.setMessageListener(new ChannelAwareMessageListener() {
@Override
public void onMessage(Message message, Channel channel) throws Exception {
String msg = new String(message.getBody());
System.out.println("-----消费者:"+msg);
}
});
return container;
}
}