Spring MVC:
@Service
public class TestService {
@Async
public void test(String header)
{
try {
Thread.sleep(600000);
System.out.println(header);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("test");
}
}
@RestController
public class TestController {
@Autowired
private TestService testService;
@GetMapping("/test")
public String test(){
String header = "";
// header = 从上下文里取出请求的header
testService.test(header);
return "ok";
}
}
@Async的代码里是一段比较耗时的操作,所以需要Controller立即响应并返回 ok 给前端,而不用等待 10 分钟再响应。
Web Flux:
@RestController
public class TestController {
@Autowired
private TestService testService;
@GetMapping("/test")
public Mono<String> async(){
return ReactiveRequestContextHolder.getRequest().flatMap(request -> {
// 这里如何编码呢
return Mono.just("ok");
});
}
}
问题请教:
- Spring MVC 的异步代码如何改写成 Web Flux,涉及 Controller 把上下文传递给 Service
- Web Flux 不使用 @Async 的情况下,如何做到立即响应,而不是等待 10 分钟之后再响应
