java-Spring MVC与反应流集成
作者:互联网
我在Spring MVC上构建了一个RESTful API应用程序.
最近,我在spring mvc和反应式流之间进行了一些集成(例如rxjava和project-reactor),并尝试使应用程序更具反应性.
我刚刚在下面建立了一些演示:
1.对于rxjava,我使用PublishSubject
private SerializedSubject<StreamResult, StreamResult> subject = PublishSubject.<StreamResult>create().toSerialized();
public ReactiveStreamController() {
this.subject.subscribe(streamResult -> {
String id = streamResult.getRequest().getParameter("id");
System.out.println("[" + Thread.currentThread().getName() + "] request received. id = " + id);
String random = StringUtils.isBlank(id) ? StringUtils.EMPTY : id;
ResponseVO vo = new ResponseVO(200, "success = " + random);
streamResult.getFuture().complete(vo);
}, Throwable::printStackTrace);
}
@ResponseBody
@RequestMapping(value = "/rxJava", method = RequestMethod.GET)
public CompletableFuture<ResponseVO> rxJavaController(HttpServletRequest httpServletRequest) {
StreamResult sr = new StreamResult();
sr.setRequest(httpServletRequest);
subject.onNext(sr);
return sr.getFuture();
}
2.用于项目反应堆
@ResponseBody
@RequestMapping(value = "/reactorCodeNew", method = RequestMethod.GET)
public CompletableFuture<ResponseVO> reactorCoreNewParadigm(HttpServletRequest servletRequest) {
Mono<ResponseVO> mono = Mono.just(servletRequest)
.subscribeOn(executorService)
.map(request -> {
String id = request.getParameter("id");
System.out.println("[" + Thread.currentThread().getName() + "] request received. id = " + id);
String random = StringUtils.isBlank(id) ? StringUtils.EMPTY : id;
ResponseVO vo = new ResponseVO(200, "success = " + random);
return vo;
})
.timeout(Duration.ofSeconds(2), Mono.just(new ResponseVO(500, "error")));
return mono.toCompletableFuture();
}
在运行两个演示时,我不太看到仅使用Java的CompletableFuture在控制器方法之间提供什么区别.
我所了解的反应式流以及我想要的是将servlet请求视为流,并使用诸如反压之类的功能来处理它.
我想知道:
1.是否有更好的方法使应用程序更具反应性?
2.将spring mvc与反应流集成在一起是否正确或兼容?如果是,我该如何执行背压功能?
我意识到也许我忘记声明为什么/如何在控制器中返回completablefuture了,实际上我注入了自定义的MethodReturnValueHandler来将CompletableFuture转换为DefferdResult.
public class CompletableFutureMethodReturnValueHandler extends DeferredResultMethodReturnValueHandler {
@Override
public boolean supportsReturnType(MethodParameter returnType) {
return CompletableFuture.class.isAssignableFrom(returnType.getParameterType());
}
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
CompletableFuture<?> completableFuture = (CompletableFuture<?>) returnValue;
super.handleReturnValue(CompletableDeferredResult.newInstance(completableFuture), returnType, mavContainer, webRequest);
}
}
解决方法:
Spring MVC基于Servlet API,并且大部分在内部进行阻塞,因此无法利用响应流行为.为Controller层编写适配器是不够的.
为此,Spring团队正在一项单独的计划中.关注SPR-14161和Spring博客(包括this和this)以了解有关反应式Spring的更多信息.
标签:project-reactor,rx-java,reactive-programming,java,spring-mvc 来源: https://codeday.me/bug/20191118/2029918.html