赞
踩
并发量非常大,服务器处理不够及时导致消息堆积的问题是很常见的。上篇文章简单的描述演示了一种解决方案就是增加消费者,提高消息处理速度,使用的是AMQP提供的监听器工厂SimpleRabbitListenerContainerFactory,本篇文章演示另一种方式,在消费者中开启线程池加快消息处理速度。
Java.util提供的ThreadPoolExecutor有七个核心参数
特点:
只使用为一的工作线程来执行任务,保证所有任务按照指定顺序执行FIFO
特点:
特点:
可以执行延迟任务,支持定时以及周期性操作。
使用Spring提供的ThreadPoolTaskExecutor
- package cn.itcast.mq.thread;
-
-
- import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
- import org.springframework.amqp.rabbit.connection.ConnectionFactory;
- import org.springframework.boot.autoconfigure.amqp.SimpleRabbitListenerContainerFactoryConfigurer;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.scheduling.annotation.EnableAsync;
- import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
-
- import java.util.concurrent.*;
-
- @Configuration
- @EnableAsync
- public class ThreadPoolConfig {
-
-
- /*定义线程池,提供多个线程消费消息
- */
-
- @Bean("pooltoconsumer")
- public ThreadPoolTaskExecutor pooltoconsumer()
- {
- //
- ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
- threadPoolTaskExecutor.setCorePoolSize(8);
- threadPoolTaskExecutor.setMaxPoolSize(20);
- threadPoolTaskExecutor.setQueueCapacity(100);
- threadPoolTaskExecutor.setKeepAliveSeconds(3);
- threadPoolTaskExecutor.setThreadNamePrefix("开启多个线程消费消息----");
- threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
- threadPoolTaskExecutor.initialize();
- return threadPoolTaskExecutor;
- }
- }
-
- @Async("pooltoconsumer")
- @RabbitListener(bindings = @QueueBinding(value = @Queue(name="demo.queue2"),exchange = @Exchange(name = "direct",type = ExchangeTypes.DIRECT),key = {"川菜"}) )
- public void chuancai(String msg)
- {
- //拆分消息
- String[] split = msg.split(":");
- order order = new order(split[0], split[1]);
- System.out.println(order.toString());
- //保存MYSQL
- orderService.save(order);
-
- //测试是否多个消费者
- System.out.println("线程" + Thread.currentThread().getName() + " 执行异步任务" +"----"+"川菜"+"----"+split[1]);
-
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。