一、使用 CompletableFuture 实现异步任务
CompletableFuture 是 Java 8 新增的一个异步编程工具,它可以方便地实现异步任务。使用 CompletableFuture 需要满足以下条件:
1.异步任务的返回值类型必须是 CompletableFuture 类型。
2.在异步任务中使用 CompletableFuture.supplyAsync() 或 CompletableFuture.runAsync() 方法来创建异步任务。
3.在主线程中使用 CompletableFuture.get() 方法获取异步任务的返回结果。
我们创建一个服务类,里面包含了异步方法和普通同步方法。
import org.springframework.stereotype.Service;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
/**
* @author qinxun
* @date 2023-06-07
* @Descripion: 异步服务类
*/
@Service
public class AsyncService {
/**
* 普通同步任务操作1
*/
public String task1() throws InterruptedException {
TimeUnit.SECONDS.sleep(3);
return "任务执行完成1";
}
/**
* 普通同步任务操作2
*/
public String task2() throws InterruptedException {
TimeUnit.SECONDS.sleep(2);
return "任务执行完成2";
}
/**
* 普通同步任务操作3
*/
public String task3() throws InterruptedException {
TimeUnit.SECONDS.sleep(3);
return "任务执行完成3";
}
/**
* 异步操作1
*/
public CompletableFuture<String> asyncTask1() {
return CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return "异步任务执行完成1";
});
}
/**
* 异步操作2
*/
public CompletableFuture<String> asyncTask2() {
return CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return "异步任务执行完成2";
});
}
/**
* 异步操作3
*/
public CompletableFuture<String> asyncTask3() {
return CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return "异步任务执行完成3";
});
}
}
我们使用SpringBoot自带的测试类进行测试
import cn.hutool.core.date.StopWatch;
import com.example.quartzdemo.service.AsyncService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
/**
* @author qinxun
* @date 2023-06-07
* @Descripion: 异步处理测试
*/
@SpringBootTest
public class AsyncTest {
@Autowired
private AsyncService asyncService;
@Test
void test1() throws InterruptedException {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
// 异步操作
/* CompletableFuture<String> completableFuture1 = asyncService.asyncTask1();
CompletableFuture<String> completableFuture2 = asyncService.asyncTask2();
CompletableFuture<String> completableFuture3 = asyncService.asyncTask3();
System.out.println(completableFuture1.get());
System.out.println(completableFuture2.get());
System.out.println(completableFuture3.get());*/
// 同步操作
System.out.println(asyncService.task1());
System.out.println(asyncService.task2());
System.out.println(asyncService.task3());
stopWatch.stop();
System.out.println("耗时:" + stopWatch.getTotalTimeMillis());
}
}
我们先执行同步操作 发现普通同步方法是按顺序一个个操作的,各个方法不会同时处理。
任务执行完成1
任务执行完成2
任务执行完成3
耗时:8008
下面我们把这些操作换成异步的方法测试。
import cn.hutool.core.date.StopWatch;
import com.example.quartzdemo.service.AsyncService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
/**
* @author qinxun
* @date 2023-06-07
* @Descripion: 异步处理测试
*/
@SpringBootTest
public class AsyncTest {
@Autowired
private AsyncService asyncService;
@Test
void test1() throws InterruptedException, ExecutionException {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
// 异步操作
CompletableFuture<String> completableFuture1 = asyncService.asyncTask1();
CompletableFuture<String> completableFuture2 = asyncService.asyncTask2();
CompletableFuture<String> completableFuture3 = asyncService.asyncTask3();
System.out.println(completableFuture1.get());
System.out.println(completableFuture2.get());
System.out.println(completableFuture3.get());
// 同步操作
/*System.out.println(asyncService.task1());
System.out.println(asyncService.task2());
System.out.println(asyncService.task3());*/
stopWatch.stop();
System.out.println("耗时:" + stopWatch.getTotalTimeMillis());
}
}
程序执行结果:
异步任务执行完成1
异步任务执行完成2
异步任务执行完成3
耗时:3008
发现几个方法是异步同时进行的,没有先后的顺序,这样大大提高了程序执行效率。
二、基于注解 @Async实现异步任务
@Async 注解是 Spring 提供的一种轻量级异步方法实现方式,它可以标记在方法上,用来告诉 Spring 这个方法是一个异步方法,Spring 会将这个方法的执行放在异步线程中进行。使用 @Async 注解需要满足以下条件:
1.需要在 Spring Boot 主类上添加 @EnableAsync 注解启用异步功能。
2.需要在异步方法上添加 @Async 注解。
注意点:
1.注解@Async的方法不是public方法。
2.注解@Async的返回值只能为void或Future。
3.注解@Async方法使用static修饰也会失效。
4.spring无法扫描到异步类,没加注解@Async或@EnableAsync注解。
5.调用方与被调用方不能在同一个类。
6.类中需要使用@Autowired或@Resource等注解自动注入,不能自己手动new对象。
7.在Async方法上标注@Transactional是没用的.但在Async方法调用的方法上标注@Transcational有效。
首先我们在主启动类上加上@EnableAsync注解启用异步功能。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
@SpringBootApplication
// 主类上加上这个注解,开启异步功能
@EnableAsync
public class QuartzDemoApplication {
public static void main(String[] args) {
SpringApplication.run(QuartzDemoApplication.class, args);
}
}
接下来我们创建一个异步服务类,我们先不使用@Async注解来进行测试。
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
/**
* @author qinxun
* @date 2023-06-07
* @Descripion: 异步服务类
*/
@Service
public class AsyncService {
/**
* 同步任务操作1
*/
public String task1() throws InterruptedException {
TimeUnit.SECONDS.sleep(3);
return "任务执行完成1";
}
/**
* 同步任务操作2
*/
public String task2() throws InterruptedException {
TimeUnit.SECONDS.sleep(2);
return "任务执行完成2";
}
/**
* 同步任务操作3
*/
public String task3() throws InterruptedException {
TimeUnit.SECONDS.sleep(3);
return "任务执行完成3";
}
/**
* 异步操作1
*/
//@Async
public void asyncTask1() {
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("异步任务执行完成1");
}
/**
* 异步操作2
*/
public void asyncTask2() {
System.out.println("异步任务执行完成2");
this.asyncTask1();
}
}
我们继续使用SpringBoot自带的测试类进行测试
import cn.hutool.core.date.StopWatch;
import com.example.quartzdemo.service.AsyncService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
/**
* @author qinxun
* @date 2023-06-07
* @Descripion: 异步处理测试
*/
@SpringBootTest
public class AsyncTest {
@Autowired
private AsyncService asyncService;
@Test
void test1() {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
// 异步操作
asyncService.asyncTask2();
stopWatch.stop();
System.out.println("耗时:" + stopWatch.getTotalTimeMillis());
}
}
查询执行的结果:
异步任务执行完成2
异步任务执行完成1
耗时:5012
发现没有加上异步的注解,程序还是按顺序执行的,接下来我们在方法asyncTask2、asyncTask3上加@Async注解。
import cn.hutool.extra.spring.SpringUtil;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
/**
* @author qinxun
* @date 2023-06-07
* @Descripion: 异步服务类
*/
@Service
public class AsyncService {
/**
* 同步任务操作1
*/
public String task1() throws InterruptedException {
TimeUnit.SECONDS.sleep(3);
return "任务执行完成1";
}
/**
* 同步任务操作2
*/
public String task2() throws InterruptedException {
TimeUnit.SECONDS.sleep(2);
return "任务执行完成2";
}
/**
* 同步任务操作3
*/
public String task3() throws InterruptedException {
TimeUnit.SECONDS.sleep(3);
return "任务执行完成3";
}
/**
* 异步操作1
*/
public void asyncTask1() {
System.out.println("before-test");
AsyncService asyncService = SpringUtil.getBean(AsyncService.class);
asyncService.asyncTask2();
asyncService.asyncTask3();
System.out.println("end-test");
}
/**
* 异步操作2
*/
@Async
public void asyncTask2() {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("异步任务执行完成2");
}
/**
* 异步操作3
*/
@Async
public void asyncTask3() {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("异步任务执行完成3");
}
}
我们再创建一个服务类调用异步方法
import cn.hutool.core.date.StopWatch;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
/**
* @author qinxun
* @date 2023-06-08
* @Descripion: 调用方服务类
*/
@Service
public class TestService {
@Autowired
private AsyncService asyncService;
@Async
public void test() {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
// 调用异步方法
asyncService.asyncTask2();
asyncService.asyncTask3();
stopWatch.stop();
System.out.println("耗时:" + stopWatch.getTotalTimeMillis());
}
}
创建一个controller进行测试
import com.example.quartzdemo.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author qinxun
* @date 2023-06-07
* @Descripion:
*/
@RestController
public class AsyncController {
@Autowired
private TestService testService;
/**
* 测试异步
*/
@RequestMapping("/async")
public String testAsync() {
testService.test();
return "处理结束";
}
}
执行程序返回:
耗时:0
异步任务执行完成2
异步任务执行完成3
三、使用 TaskExecutor 实现异步任务
TaskExecutor 是 Spring 提供的一个接口,它定义了一个方法 execute(),用来执行异步任务。使用 TaskExecutor 需要满足以下条件:
- 需要在 Spring 配置文件中配置一个 TaskExecutor 实例;
- 在异步方法中调用 TaskExecutor 实例的 execute() 方法来执行异步任务。
创建一个异步配置类
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
/**
* @author qinxun
* @date 2023-06-07
* @Descripion: 异步处理配置类
*/
@Configuration
public class AsyncConfig implements AsyncConfigurer {
@Bean(name = "asyncExecutor")
public TaskExecutor asyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(100);
executor.setThreadNamePrefix("async-");
executor.initialize();
return executor;
}
@Override
public Executor getAsyncExecutor() {
return asyncExecutor();
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new SimpleAsyncUncaughtExceptionHandler();
}
}
相应的在异步服务类中使用这个自定义的异步配置
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
/**
* @author qinxun
* @date 2023-06-07
* @Descripion: 异步服务类
*/
@Service
public class AsyncService {
@Autowired
@Qualifier("asyncExecutor")
private TaskExecutor taskExecutor;
/**
* 同步任务操作1
*/
public String task1() throws InterruptedException {
TimeUnit.SECONDS.sleep(3);
return "任务执行完成1";
}
/**
* 同步任务操作2
*/
public String task2() throws InterruptedException {
TimeUnit.SECONDS.sleep(2);
return "任务执行完成2";
}
/**
* 同步任务操作3
*/
public String task3() throws InterruptedException {
TimeUnit.SECONDS.sleep(3);
return "任务执行完成3";
}
/**
* 异步操作1
*/
@Async
public void asyncTask1() {
taskExecutor.execute(() -> {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
System.out.println("异步任务执行完成1");
}
/**
* 异步操作2
*/
@Async
public void asyncTask2() throws InterruptedException {
taskExecutor.execute(() -> {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
System.out.println("异步任务执行完成2");
}
/**
* 异步操作3
*/
@Async
public void asyncTask3() throws InterruptedException {
taskExecutor.execute(() -> {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
System.out.println("异步任务执行完成3");
}
}
继续使用单元测试类进行测试
import cn.hutool.core.date.StopWatch;
import com.example.quartzdemo.service.AsyncService;
import com.example.quartzdemo.service.TestService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
/**
* @author qinxun
* @date 2023-06-07
* @Descripion: 异步处理测试
*/
@SpringBootTest
public class AsyncTest {
@Autowired
private TestService testService;
@Autowired
private AsyncService asyncService;
@Test
void test1() {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
// 异步操作
asyncService.asyncTask1();
asyncService.asyncTask2();
asyncService.asyncTask3();
stopWatch.stop();
System.out.println("耗时:" + stopWatch.getTotalTimeMillis());
}
}
耗时:4
异步任务执行完成2
异步任务执行完成3
异步任务执行完成1
从执行结果来看,我们实现了异步的处理。