SpringBoot教程 | SpringBoot实现异步操作
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.util.concurrent.Future;
@Service
public class AsyncService {
// 异步处理方法
@Async
public Future<String> asyncMethod() throws InterruptedException {
long start = System.currentTimeMillis();
Thread.sleep(1000); // 模拟耗时操作
long end = System.currentTimeMillis();
return new AsyncResult<>("异步操作执行时间:" + (end - start) + "ms");
}
}
// 在Controller中调用异步服务
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.Future;
@RestController
public class AsyncController {
@Autowired
private AsyncService asyncService;
@GetMapping("/async")
public String async() throws InterruptedException, ExecutionException {
Future<String> future = asyncService.asyncMethod();
return future.get(); // 获取异步操作的结果
}
}
在这个示例中,我们定义了一个异步服务AsyncService
,其中有一个asyncMethod
方法,使用@Async
注解标记,以便Spring Boot可以将其标识为异步方法。在AsyncController
中,我们通过自动装配的方式调用asyncMethod
,并通过Future
接口获取异步执行的结果。这个例子展示了如何在Spring Boot应用中实现简单的异步操作。
评论已关闭