1、使用 Maven 创建 SpringBoot 项目,引入 Web 场景启动器。
2、编写异步服务类,注册到 IoC 容器:
// zze.springboot.task.service.AsyncService
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsyncService {
@Async // 标识方法将会异步执行
public void hello() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("hello");
}
}
3、使用注解开启异步任务支持:
// zze.springboot.task.TaskApplication
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
@EnableAsync // 开启异步任务支持
@SpringBootApplication
public class TaskApplication {
public static void main(String[] args) {
SpringApplication.run(TaskApplication.class, args);
}
}
4、编写控制器测试:
// zze.springboot.task.controller.AsyncController
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import zze.springboot.task.service.AsyncService;
@RestController
public class AsyncController {
@Autowired
private AsyncService asyncService;
@GetMapping("/hello")
public String testAsyncHello(){
asyncService.hello();
return "执行完毕";
/*
访问 localhost:8080/hello
a、立即返回了 “执行完毕”,并没有因为 asyncService.hello() 方法中的线程 sleep 等待 3 秒。
b、3 秒后控制台输出 hello
OK,异步任务执行成功
*/
}
}
评论区