在 Spring Boot 中实现 RESTful 接口的快速响应,同时在后台继续处理耗时逻辑,可以使用异步处理技术。以下是一个详细的示例,展示如何使用 @Async 注解和 CompletableFuture 来实现这一需求。
- 使用 @Async 注解
步骤 1:启用异步支持
在你的主类或配置类中添加 @EnableAsync 注解:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
@SpringBootApplication
@EnableAsync
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
步骤 2:创建异步服务
创建一个服务类,并在需要异步执行的方法上添加 @Async 注解:
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class MyService {
@Async
public void processInBackground() {
// 处理耗时逻辑
try {
Thread.sleep(5000); // 模拟耗时操作
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("后台处理完成");
}
}
步骤 3:在控制器中调用异步服务
在你的控制器中调用异步服务,并立即返回响应:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class MyController {
@Autowired
private MyService myService;
@PostMapping("/process")
public String processRequest() {
myService.processInBackground();
return "处理已开始";
}
}