异步调用与同步调用
同步调用:一般来说,我们的程序基本上使用的都是同步调用,程序按定义的顺序依次执行的过程,每一行代码执行过程必须等待上一行代码执行完毕后才执行。
异步调用:程序在执行时,无需等待执行的返回值可继续执行后面的代码。
显而易见,同步有依赖相关性,而异步没有,所以异步可并发执行,可提高执行效率,在相同的时间做更多的事情
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异步调用完成