Spring @Async 开启异步任务
程序员文章站
2022-04-15 12:40:45
...
在Java应用程序开发中,多数情况下都是通过同步的方式来实现交互处理的;但在于第三方系统对接交互是,容易造成响应迟缓,通常情况下,可以单独开启一个或多个线程来异步完成类任务,缩短了同步响应的时间。在spring 3之后,已内置了@Async,更方便的解决此问题。
异步调用,首先,同步就是整个处理过程顺序执行,当各个过程都执行完毕,并返回结果。 异步调用则是只是发送了调用的指令,调用者无需等待被调用的方法完全执行完毕;而是继续执行下面的流程。
通常情况下,Java程序开发中,在应对某些业务可以异步执行,不会影响到主业务流程时,都可以基于创建独立的线程去完成相应的异步调用逻辑,通过主线程和不同的线程之间的执行流程,从而在启动独立的线程之后,主线程继续执行而不会产生停滞等待的情况。
1、配置类
package com.async;
/**
* Created by Liuxd on 2018-09-11.
*/
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
@Configuration
@ComponentScan({"com.async"})
@EnableAsync//启用异步支持
public class SpringConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
//线程池
ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
pool.setCorePoolSize(5);
pool.setMaxPoolSize(200);
pool.setQueueCapacity(25);
pool.initialize();
return pool;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return null;
}
}
2、service业务处理类_开启异步支持
package com.async;
/**
* Created by Liuxd on 2018-09-11.
*/
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import java.util.concurrent.Future;
@Service
public class TaskService {
//声明异步
@Async
public void executeTask(Integer i) {
System.out.println("线程ID:" + Thread.currentThread().getId() + "执行异步任务:" + i);
}
//声明异步
@Async
public Future<String> executeTaskHasReturn(Integer i) {
System.out.println("线程ID:" + Thread.currentThread().getId() + "执行异步有返回的任务:" + i);
return new AsyncResult<>("success:"+i);
}
}
3、调用
package com.async;
/**
* Created by Liuxd on 2018-09-11.
*/
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import java.util.concurrent.Future;
public class TestAction {
public static void main(String[] args) {
System.out.println("主线程id:" + Thread.currentThread().getId() + "开始执行调用任务...");
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
TaskService taskService = context.getBean(TaskService.class);
for (int i = 0; i < 10; i++) {
taskService.executeTask(i);
Future<String> result = taskService.executeTaskHasReturn(i);
/*try {
System.out.println("异步程序执行结束,返回内容:" + result.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}*/
}
context.close();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("主线程id:" + Thread.currentThread().getId() + "程序结束!!");
}
}
上一篇: axios中get与post方式传参区别