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

本文的代码地址: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);
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。