如何使用threadPoolExecutor进行异步弹簧

时间:2018-01-29 17:37:57

标签: spring multithreading spring-boot asynchronous

我要求在异步弹簧中为多个请求使用相同的线程。 这是我正在使用的代码:

这是Executor配置文件

 @Configuration
    @EnableAsync
    public class ExecutorConfig {

       @Bean(name = "threadPoolExecutor")
        public Executor getAsyncExecutor() {
            ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
            executor.setCorePoolSize(7);
            executor.setMaxPoolSize(42);
            executor.setQueueCapacity(11);
            executor.setThreadNamePrefix("threadPoolExecutor-");
            executor.initialize();
            return executor;
        }
    }

这是服务文件

public interface QueueService {
                public void createQueue();
                public void sendData();
        }

以下是服务实施

@Service
    public class QueueServiceImpl implements QueueService {

        @Override
        @Async("threadPoolExecutor")
        public void createQueue() {
            System.out.println(Thread.currentThread().getName());
        }

        @Override
        @Async("threadPoolExecutor")
        public void sendData() {
            // Need to use the same thread which created the queue
            // Thread.currentThread() should be same for both methods
            System.out.println(Thread.currentThread().getName());
        }
    }

这是控制器类

@RestController
    public class Controller {

         @Autowired
         QueueService queueService; 

         @RequestMapping(value="/create", method = RequestMethod.GET)
         public void createQueue()
         {
             queueService.createQueue();
         }

         @RequestMapping(value="/send", method = RequestMethod.GET)
         public void sendDataToQueue()
         {
             queueService.sendData();
         }
    }

这是Spring启动主应用程序

 @EnableAsync
    @SpringBootApplication
    public class Application {

        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    }

请让我知道如何在2个单独的请求中使用@Async来完成同一个线程完成的工作。

0 个答案:

没有答案