1. 程式人生 > >SpringBoot 非同步任務

SpringBoot 非同步任務

SpringBoot 非同步任務

介紹
在Java應用中,絕大多數情況下都是通過同步的方式來實現互動處理的;但是在
處理與第三方系統互動的時候,容易造成響應遲緩的情況,之前大部分都是使用
多執行緒來完成此類任務,其實,在Spring 3.x之後,就已經內建了@Async來完
美解決這個問題。

兩個註解:
@EnableAysnc、 @Aysnc

1.主啟動類

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;

@EnableAsync  //開啟非同步註解功能
@SpringBootApplication
public class Springboot04TaskApplication {

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

2.控制器

import com.atguigu.task.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class AsyncController {

    @Autowired
    AsyncService asyncService;

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

3.服務類

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AsyncService {

    //告訴Spring這是一個非同步方法
    @Async
    public void hello(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("處理資料中...");
    }
}