①,pom依赖java
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.2.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
②,启用异步web
@EnableAsync//开启异步 @SpringBootApplication public class TaskApplication { public static void main(String[] args) { SpringApplication.run(TaskApplication.class, args); } }
import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; @Service public class AsyncService { /*@Async 注明这是个异步方法*/ @Async public void sync(){ try { //假设这里是耗时的业务操做 Thread.sleep(3000); System.out.println("睡够了"); } catch (InterruptedException e) { e.printStackTrace(); } } }
import com.ts.task.service.AsyncService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class AsyncController { @Autowired private AsyncService asyncService; @RequestMapping("/") public String index(){ asyncService.sync(); return "success"; } }
①,访问springboot应用,会快速在页面给出响应spring
②,3s后,控制台输出“睡够了”springboot