异步任务-springboot

异步任务-springboot

  • 异步:异步与同步相对,当一个异步过程调用发出后,调用者在没有得到结果之前,就可以继续执行后续操作。也就是说无论异步方法执行代码需要多长时间,跟主线程没有任何影响,主线程可以继续向下执行。

实例:


在service中写一个hello方法,让它延迟三秒

@Service
public class AsyncService {
    public void hello(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("数据正在处理!");
    }
}

让Controller去调用这个业务

@RestController
public class AsyncController {
    @Autowired
    AsyncService asyncService;
    @GetMapping("/hello")
    public String hello(){
        asyncService.hello();
        return "ok";
    }
}

启动SpringBoot项目,我们会发现三秒后才会响应ok。


所以我们要用异步任务去解决这个问题,很简单就是加一个注解。

  1. 在hello方法上@Async注解
@Service
public class AsyncService {
	//异步任务
    @Async
    public void hello(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("数据正在处理!");
    }
}
  1. 在SpringBoot启动类上开启异步注解的功能
@SpringBootApplication
//开启了异步注解的功能
@EnableAsync
public class Sprintboot09TestApplication {

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

}

问题解决,服务端瞬间就会响应给前端数据!

posted on 2022-04-07 20:35  汪汪程序员  阅读(404)  评论(0编辑  收藏  举报

导航