異步調用與同步調用
同步調用:一般來說,我們的程序基本上使用的都是同步調用,程序按定義的順序依次執行的過程,每一行代碼執行過程必須等待上一行代碼執行完畢後才執行。
異步調用:程序在執行時,無需等待執行的返回值可繼續執行後面的代碼。
顯而易見,同步有依賴相關性,而異步沒有,所以異步可併發執行,可提高執行效率,在相同的時間做更多的事情
Async異步調用
在SpringBoot中使用異步調用是很簡單的,只需要使用@Async註解即可實現方法的異步調用
1)主啓動類修改
@SpringBootApplication
@EnableAsync //開啓異步調用,啓用@Async註解
public class AsyncApplication {
public static void main(String[] args) {
SpringApplication.run(AsyncApplication.class, args);
}
}
2)@Async異步調用
@Service
public class UserService implements IUserService {
@Async //聲明異步調用
@Override
public void sendSms() {
System.out.println("********send sms************ 2");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("********send sms************ 3");
}
}
3)控制層測試
@RestController
public class IndexController {
@Autowired
private IUserService userService;
@GetMapping("/")
public void index(){
System.out.println("********************** 1");
userService.sendSms();
System.out.println("********************** 4");
}
}
4)測試結果:
不啓動異步:
********************** 1
********send sms************ 2
********send sms************ 3
********************** 4
啓動異步:
********************** 1
********************** 4
********send sms************ 2
********send sms************ 3
至此,SpringBoot實現Async異步調用完成