springboot rabbitmq 自定义连接工厂

springboot 使用 rabbitmq 

1:使用默认的连接工厂,只需要在配置文件中配置全局参数即可

如 yml 文件的配置

spring:
  profiles:
    active: dev
  ########################## rabbitMq 配置 ################
  rabbitmq: 
    host: 127.0.0.1
    post: 5672
    username: guest
    password: guest
      listener:
        simple:
          # 开启消费端手动确认
          acknowledge-mode: manual
          prefetch: 4
2:如果你的项目需要连接多个MQ,或者要自定义连接配置,不想用全局的配置,那么就需要自己去设置连接工厂了
@Configuration
public class RabbitMqConfig {

    @Bean("myConnectionFactory")
    public CachingConnectionFactory connectionFactory(){
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        return connectionFactory;
    }
    @Bean("customContainerFactory")
    public SimpleRabbitListenerContainerFactory containerFactory(SimpleRabbitListenerContainerFactoryConfigurer configurer,
                                                                 @Qualifier("myConnectionFactory") ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();

        factory.setConnectionFactory(connectionFactory);
        //初始化消费者数量
        factory.setConcurrentConsumers(4);
        //最大消费者数量
        factory.setMaxConcurrentConsumers(4);
        //手动确认消息
        factory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        // 单个消费者一次接收的消息数,默认250
        factory.setPrefetchCount(10);
        configurer.configure(factory,connectionFactory);
        return factory;
    }
}

使用的时候

@RabbitListener(queues = "#{queue.name}",containerFactory = "customContainerFactory")
public class MagicMsgListener {

 @RabbitHandler
    public void receiveMsg(String msg, Message message, Channel channel) {
    
    }
}

 

你可能感兴趣的:(java,学习,rabbitmq,java)