1. 程式人生 > >【Springboot】之 非同步處理(@Async)

【Springboot】之 非同步處理(@Async)

前言

使用非同步是為了縮短等待時間。 即:主執行緒儘早處理完並返回資訊,能更快響應;而副執行緒執行其他操作用於完善。

一、配置類

作用:配置執行緒池,實現執行緒複用。

  1. 通過 @EnableAsync 開啟對非同步任務的支援
  2. 實際執行的 Bean 的方法中使用 @Async 註解來宣告這個是一個非同步任務
@Slf4j
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {

    @Override
    public Executor getAsyncExecutor()
{ ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(3); executor.setMaxPoolSize(10); executor.setQueueCapacity(100); executor.setThreadNamePrefix("AsyncThread-"); executor.initialize(); //如果不初始化,導致找到不到執行器 return
executor; } // 用於捕獲非同步異常 @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { //return new AsyncExceptionHandler(); return null; } }

二、實際呼叫方法

@Async 註解來宣告一個非同步任務

如下,當然去掉 implements UserService 也是可以的

@Slf4j
@Service
public class UserServiceImpl
implements UserService { @Async @Override public void executeUserInfo(Integer userId) { log.info("enter executeUserInfo userId : {}, threadId : {}", userId, Thread.currentThread().getId()); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } log.info("exit executeUserInfo userId : {}, threadId : {}", userId, Thread.currentThread().getId()); } }

三、測試執行

寫一個 controller

@Slf4j
@RestController
@RequestMapping("/async")
public class AsyncController {

    @GetMapping(value = "/test1")
    public String test1() {
        log.info("enter test1, threadId : {}", Thread.currentThread().getId());

        userService.executeUserInfo(1);
        userService.executeUserInfo(2);
        userService.executeUserInfo(3);

        log.info("exit test1, threadId : {}", Thread.currentThread().getId());

        return "123";
    }

}

那麼呼叫這個介面 /async/test1 時,日誌如下: 在這裡插入圖片描述