1. 程式人生 > >springboot中使用非同步任務

springboot中使用非同步任務

在springboot中使用簡單的非同步任務

同步情況

首先來看一下同步情況下的程式碼,在service中添加了一個執行緒等待方法

@Service
public class AsyncService {

    public void asyncHello(){
        try {
            Thread.sleep(3000);
        }catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("hello...");
    }
}

在controller中當收到“/”請求時,會執行service中的asyncHello()方法再返回success;

@RestController
public class AsyncController {

    @Autowired
    private AsyncService asyncService;


    @GetMapping("/")
    public String asyncHello(){
        asyncService.asyncHello();
        return "success";
    }
}

執行結果為 頁面載入3秒後

才顯示success,控制檯同時輸出“hello...”

非同步情況

在應用入口類上新增@EnableAsync註解開啟非同步

@EnableAsync
@SpringBootApplication
public class DemoApplication {

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

在service的方法上加上@Async註解

@Service
public class AsyncService {

    @Async
    public void asyncHello(){
        try {
            Thread.sleep(3000);
        }catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("hello...");
    }
}

經過以上修改後,執行結果變為立即返回success,在等待3秒後,控制檯列印“hello...”