Springboot 创建异步程序

Springboot 异步执行程序

  • 使用注解@EnableAsync开启异步,会自动扫描
  • 定义@Component @Async作为组件被容器扫描

示例

入口

@SpringBootApplication
// 扫描所有需要的包,包含一些自用的工具类包所在的路径
@ComponentScan(basePackages = {"com.yxc.imail"})
// 开启异步调用方法
@EnableAsync
public class ImailApplication {
public static void main(String[] args) {
SpringApplication.run(ImailApplication.class, args);
}
}

组件类

@Component
public class AsyncTask {
// 判断任务执行完成,要使用Future
@Async
public Future<Boolean> do1() throws Exception {
long start = System.currentTimeMillis();
Thread.sleep(1000);
long end = System.currentTimeMillis();
System.out.println("Do1 Used: " + (end - start) + " ms");
return new AsyncResult<>(true);
}

@Async
public Future<Boolean> do2() throws Exception {
    long start = System.currentTimeMillis();
    Thread.sleep(700);
    long end = System.currentTimeMillis();
    System.out.println("Do2 Used: " + (end - start) + " ms");
    return new AsyncResult<>(true);
}

@Async
public Future<Boolean> do3() throws Exception {
    long start = System.currentTimeMillis();
    Thread.sleep(600);
    long end = System.currentTimeMillis();
    System.out.println("Do3 Used: " + (end - start) + " ms");
    return new AsyncResult<>(true);
}

}

Controller类

@RestController
public class TestController {
@Autowired
private AsyncTask asyncTask;
@GetMapping("/asynctest")
public String asynctest() throws Exception {
long start = System.currentTimeMillis();
Future<Boolean> a = asyncTask.do1();
Future<Boolean> b = asyncTask.do2();
Future<Boolean> c = asyncTask.do3();
while (!a.isDone() || !b.isDone() || !c.isDone()) {
if (a.isDone() && b.isDone() && c.isDone()) {
break;
}
}
long end = System.currentTimeMillis();
String result = "Task Used " + (end - start) + " ms Total";
System.out.println(result);
return result;
}
}

结果

Do3 Used: 601 ms
Do2 Used: 700 ms
Do1 Used: 1000 ms
Task Used 1029 ms Total

使用场景

  • 发送短信
  • 发送邮件
  • 消息推送

使用多线程,线程池,消息队列等都可以实现相同场景

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • mean to add the formatted="false" attribute?.[ 46% 47325/...
    ProZoom阅读 2,727评论 0 3
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,997评论 19 139
  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,452评论 0 10
  • 总觉无事, 感觉自己很慌乱。 早起吃饭, 喝水, 上课。 可是听不进去。
    樊小篱阅读 187评论 0 0
  • 慌忙。 比这次感觉更强烈的是两年前。 第一次认真的看待感情,并全身心的投入,但被冷落之后。那种被掏空,但又自尊心极...
    汝窑阅读 251评论 0 0