美文网首页
Spring Boot学习笔记四--自定义@Async策略

Spring Boot学习笔记四--自定义@Async策略

作者: 哪吒小子 | 来源:发表于2019-04-07 23:29 被阅读0次

    本文的代码地址:GitHub Async Demo

    自定义一个 @Async 异步的策略

    1.ExecutorConfig

    @Configuration
    @EnableAsync
    public class ExecutorConfig {
        private static final Logger logger = LoggerFactory.getLogger(ExecutorConfig.class);
    
        private int corePoolSize = 10;
        private int maxPoolSize = 10;  //线程池的大小
        private int queueCapacity =20;//排队队列长度
    
        @Bean
        public AsyncTaskExecutor taskExecutor() {
            ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
            executor.setCorePoolSize(corePoolSize);
            executor.setMaxPoolSize(maxPoolSize);
            executor.setQueueCapacity(queueCapacity);
            executor.setThreadNamePrefix("Anno-Executor");
            executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
            executor.initialize();
            logger.info("taskExecutor initialize");
            return executor;
        }
    }
    

    2.UserService

    @Service
    public class UserService {
    
        @Async
        public void sayHello(int number) throws InterruptedException{
            Thread.sleep(2000L);
            System.out.println(">>>>"+number+">>>>");
        }
    }
    

    3.AsyncApplicationTests

    @RunWith(SpringRunner.class)
    @SpringBootTest
    @EnableAsync
    public class AsyncApplicationTests {
    
        @Autowired
        private UserService userService;
        @Test
        public void testAsync() throws InterruptedException{
            for (int i = 0; i < 20; i++) {
                userService.sayHello(i);
                Thread.sleep(1500);
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:Spring Boot学习笔记四--自定义@Async策略

          本文链接:https://www.haomeiwen.com/subject/eoxyvqtx.html