189 8069 5689

springboot的异步调用@Async注解

     异步调用,类似我们多年前的ajax调用,局部刷新,整体不变,当然,在java的后台的异步调用,类似于自己实现一个多线程的程序,任务开启一个线程后由它最去执行,我们其实是不能干预太多的。。

     在实际的开发中,如果某一个方法需要异步去执行,那么我们可以在它前面加上注解。@Async 

@SpringBootApplication
@EnableAsync
public class Application{

创新互联公司专注于射阳企业网站建设,响应式网站设计,商城开发。射阳网站建设公司,为射阳等地区提供建站服务。全流程按需规划网站,专业设计,全程项目跟踪,创新互联公司专业和态度为您提供的服务

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

}

@RequestMapping("")
public String doTask() throws InterruptedException{
long currentTimeMillis = System.currentTimeMillis();
this.task1();
this.task2();
this.task3();
long currentTimeMillis1 = System.currentTimeMillis();
return "task任务总耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms";
}

@Async  
public void task1() throws InterruptedException{  
    long currentTimeMillis = System.currentTimeMillis();  
    Thread.sleep(1000);  
    long currentTimeMillis1 = System.currentTimeMillis();  
    System.out.println("task1任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");  
}  

@Async  
public void task2() throws InterruptedException{  
    long currentTimeMillis = System.currentTimeMillis();  
    Thread.sleep(2000);  
    long currentTimeMillis1 = System.currentTimeMillis();  
    System.out.println("task2任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");  
}  

    比如需要调用一个发送短信的任务,实际短信是渠道方去发的,那么我们在把请求提交过去基本就结束了,这个时候就可以做一个异步的调用来实现。。

当前名称:springboot的异步调用@Async注解
当前链接:http://cdxtjz.cn/article/ghidep.html

其他资讯