Spring的異步線程處理

Spring封裝了JDK的線程池和線程調用,並使用標籤就可以開啓多線程調用。

先進行一個Spring的線程池配置

@Configuration
@EnableAsync
public class ThreadPoolConfig implements AsyncConfigurer {
    @Bean
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(Runtime.getRuntime().availableProcessors());
        executor.setMaxPoolSize(Runtime.getRuntime().availableProcessors() * 5);
        executor.setQueueCapacity(Runtime.getRuntime().availableProcessors() * 2);
        executor.setThreadNamePrefix("this-executor-");
        executor.initialize();
        return executor;
    }

    @Bean
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new SimpleAsyncUncaughtExceptionHandler();
    }
}

再編寫一個Service的異步方法調用,這裏是帶返回值的,不帶返回值的方法比較簡單,這裏就不舉例了。

@Service
@Slf4j
public class ThreadTasks {
    /**
     * 如果異步方法有返回值,一定要使用Future包裝,否則無法返回
     * @return
     * @throws InterruptedException
     */
    @Async
    public Future<String> startTask() throws InterruptedException {
        Thread.sleep(3000);
        log.info("this is async task");
        return new AsyncResult<>("123456");
    }
}

最後寫一個Controller,對該異步方法進行調用

@RestController
public class AsyncTaskController {
    @Autowired
    private ThreadTasks tasks;

    @GetMapping("/users-anon/useTask")
    public String useSyncTask() throws InterruptedException, ExecutionException {
        Future<String> future = tasks.startTask();
        return future.get();
    }
}

最後運行下來,我們可以看到每次都是不同的線程執行

2020-09-21 16:33:53.027  INFO [user-center,3e635fca3d1259da,d30e8b6372922137,false] 1126 --- [this-executor-1] com.cloud.user.service.ThreadTasks       : this is async task
2020-09-21 16:35:27.664  INFO [user-center,9b68efbb2c848d7b,895ed921f6c8fe03,false] 1126 --- [this-executor-2] com.cloud.user.service.ThreadTasks       : this is async task

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章