SpringBoot异步回调
在Spring Boot中,可以使用@Async
注解来创建异步任务,并通过Future
接口来实现回调。以下是一个简单的例子:
- 首先,在Spring Boot的配置类中开启异步支持:
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
@Override
@Bean
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(10);
executor.setQueueCapacity(25);
executor.initialize();
return executor;
}
}
- 创建异步服务类:
@Service
public class AsyncService {
@Async
public Future<String> executeAsyncTask() {
// 模拟耗时操作
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return new AsyncResult<>("任务完成");
}
}
- 在你的控制器或者业务层中调用异步服务,并通过
Future
接口实现回调:
@RestController
public class MyController {
@Autowired
private AsyncService asyncService;
@GetMapping("/start-async-task")
public String startAsyncTask() throws ExecutionException, InterruptedException {
Future<String> future = asyncService.executeAsyncTask();
// 异步任务完成时,可以在这里处理结果
String result = future.get();
return "任务启动,结果:" + result;
}
}
在上述代码中,executeAsyncTask
方法被标记为@Async
,这意味着它会在另一个线程中执行。Future
接口用于获取异步执行的结果。当调用future.get()
时,调用线程会阻塞,直到异步任务完成。这种模式可以用于执行长时间运行的任务,并在任务完成时通过回调机制获取通知。
评论已关闭