springboot异步调用怎么实现
在Spring Boot中,可以使用@Async
注解来实现异步调用。
首先,在启动类中添加@EnableAsync
注解来启用异步调用功能。
@SpringBootApplication
@EnableAsync
public class YourApplication {
public static void main(String[] args) {
SpringApplication.run(YourApplication.class, args);
}
}
在需要进行异步调用的方法上添加@Async
注解。
@Service
public class YourService {
@Async
public void asyncMethod() {
// 异步执行的任务
}
}
调用异步方法。
@RestController
public class YourController {
@Autowired
private YourService yourService;
@GetMapping("/async")
public String async() {
yourService.asyncMethod();
return "Async method invoked.";
}
}
在上述代码中,YourService
类中的asyncMethod()
方法被标记为异步方法,当调用该方法时,Spring Boot会自动将该方法放入线程池中异步执行,不会阻塞当前线程。
需要注意的是,异步方法的返回值为void
,如果需要获取异步方法的执行结果,可以使用CompletableFuture
或者ListenableFuture
等方式来处理。
阅读剩余
THE END