在Spring Boot中实现Endpoints的异步处理,可以使用@Async
注解和CompletableFuture
pom.xml
文件中添加以下依赖: <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
@EnableAsync
注解,以启用异步支持:import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
@SpringBootApplication
@EnableAsync
public class AsyncDemoApplication {
public static void main(String[] args) {
SpringApplication.run(AsyncDemoApplication.class, args);
}
}
@Async
注解标记你想要异步执行的方法。例如,创建一个名为MyAsyncService
的类:import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.util.concurrent.CompletableFuture;
@Service
public class MyAsyncService {
@Async
public CompletableFuture<String> asyncMethod() {
// 模拟长时间运行的任务
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return CompletableFuture.completedFuture("异步任务完成");
}
}
MyController
的类:import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;
import java.util.concurrent.CompletableFuture;
@RestController
public class MyController {
@Autowired
private MyAsyncService myAsyncService;
@GetMapping("/async")
public DeferredResult<String> asyncEndpoint() {
DeferredResult<String> deferredResult = new DeferredResult<>();
CompletableFuture<String> future = myAsyncService.asyncMethod();
future.whenComplete((result, throwable) -> {
if (throwable != null) {
deferredResult.setErrorResult(throwable);
} else {
deferredResult.setResult(result);
}
});
return deferredResult;
}
}
现在,当你访问/async
端点时,将会异步地执行MyAsyncService
中的asyncMethod()
方法。这意味着主线程不会被阻塞,而是继续处理其他请求。当异步任务完成时,结果将通过DeferredResult
对象返回给客户端。