一、在spring boot中使用Async,来实现异步任务
在Spring Boot中,可以使用@Autowired注解将一个类的实例注入到另一个类中,并使用@Async注解来开启一个新的线程来运行该类的方法。下面是一个简单的示例:
1、添加Async的配置文件
在使用@Async注解之前,需要在Spring Boot的配置文件中开启异步支持:
spring:
task:
execution:
pool:
core-size: 10
max-size: 20
上面的配置会创建一个大小为10的线程池,最大线程数为20。这样,当我们调用doSomething方法时,它会在一个新的线程中执行。
在启动类中添加启用异步任务的注解
@EnableAsync
2、创建异步任务
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
@Component
public class MyService {
@Async
public void doSomething(String param) {
// 在新线程中执行的代码
System.out.println("Received parameter: " + param);
}
}
在上面的示例中,MyService类的doSomething()方法使用了@Async注解,表明该方法将在一个新的线程中执行。该方法接收一个字符串参数,并在新线程中输出该参数的值。
3、调用异步任务
现在,假设有另一个类需要传递参数给MyService类,并开启一个新的线程来执行doSomething()方法。可以在该类中使用@Autowired注解来注入MyService类的实例,并直接调用doSomething()方法,如下所示:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class AnotherClass {
@Autowired
private MyService myService;
public void runInNewThread(String param) {
new Thread(() -> {
myService.doSomething(param);
}).start();
}
}
在上面的示例中,AnotherClass类中的runInNewThread()方法接收一个字符串参数,并在新线程中调用MyService类的doSomething()方法,将该参数传递给它。要注意的是,AnotherClass类需要使用@Component注解标记为一个Spring组件,以便Spring容器可以扫描和管理它。
二、使用回调函数,处理异步任务的结果
使用异步编程有一个问题,就是异步操作完成后,如何处理它的结果呢?这时候可以使用回调函数来处理异步结果。
在Spring Boot中,可以使用CompletableFuture来处理异步结果。CompletableFuture是一个异步编程的工具类,可以让我们更方便地处理异步结果。
下面是一个使用CompletableFuture来处理异步结果的例子:
@Service
public class SomeService {
@Async
public CompletableFuture<Integer> longRunningMethod() {
// 耗时操作
int result = 100;
return CompletableFuture.completedFuture(result);
}
}
@Service
public class AnotherService {
@Autowired
private SomeService someService;
public void doSomething() {
CompletableFuture<Integer> future = someService.longRunningMethod();
future.thenAccept(result -> {
// 处理异步结果
System.out.println("异步结果:" + result);
});
}
}
上面的代码中,longRunningMethod方法返回一个CompletableFuture对象,表示异步结果。在doSomething方法中,我们调用longRunningMethod方法,并使用thenAccept方法注册一个回调函数,当异步结果完成后,回调函数会被执行。
回调函数的参数result表示异步结果,我们可以在回调函数中对结果进行处理,比如输出结果到控制台。