spring对 rabbitmq client 的封装

消费模式

  • Spring 的封装采用了 push 的方案 , 不同于 kafka 的pull 方案

线程模型

  • SimpleRabbitListenerContainerFactory

    • CachingConnectionFactory
    	CachingConnectionFactory factory = new CachingConnectionFactory(
                    getRabbitConnectionFactoryBean(properties).getObject());
    
            //心跳新城
            factory.setConnectionThreadFactory(new ThreadFactory() {
                public final AtomicInteger id = new AtomicInteger();
    
                @Override
                public Thread newThread(Runnable r) {
                    return new Thread(r, MessageFormat.format("amqp-heart-{0}", id.getAndIncrement()));
                }
            });
    
            //默认的线程池和下面的差不多,在com.rabbitmq.client.impl.ConsumerWorkService构造方法中,大小为处理器的两倍
            //如果采用DirectRabbitListenerContainerFactory需要重写,增加线程池的中的线程数量,具体看你的应用是计算密集还是io密集,
            // io越密集,线程数设置越大
            //java.util.concurrent.Executors.DefaultThreadFactory
            final ExecutorService executorService = Executors.newFixedThreadPool(5, new ThreadFactory() {
                public final AtomicInteger id = new AtomicInteger();
    
                @Override
                public Thread newThread(Runnable r) {
                    return new Thread(r, MessageFormat.format("amqp-client-{0}", id.getAndIncrement()));
                }
            });
    
            //客户端线程池
            factory.setExecutor(executorService);
    
    • SimpleRabbitListenerContainerFactory
    	@Bean
        public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(
                SimpleRabbitListenerContainerFactoryConfigurer configurer,
                ConnectionFactory connectionFactory) {
            SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
            configurer.configure(factory, connectionFactory);
            factory.setTaskExecutor(new SimpleAsyncTaskExecutor("customer-consumer-"));
            return factory;
        }
    

    spring对 rabbitmq client 的封装_第1张图片

    • factory.setExecutor(executorService); 设置客户端线程池
    • factory.setTaskExecutor(new SimpleAsyncTaskExecutor("customer-consumer-")); 设置容器消费线程
    • 消费流程
      • factory.setConnectionThreadFactory() 设置心跳线程
      • 客户端线程池用来处理事件. 详情参照 https://blog.csdn.net/u013256816/article/details/70214929 负责把消息投递到 queue 此queue为 BlockingQueueConsumer
      • 设置的setTaskExecutor 再去queue 中消费
  • DirectRabbitListenerContainerFactory

    • 此消费模式比较简单了.直接在RabbitMQ客户端线程上调用MessageListener。在这种情况下,taskExecutor用于监视使用者的任务,业务逻辑直接在client线程池中端执行.

你可能感兴趣的:(spring)