摘要:的这几天看了看的请求处理流程,因为之前一直用的和,一开始对的处理流程有点懵逼,找不到入口,后来跟了代码,在网上找了点资料,发现的入口在的方法该方法的作用就是把接收到的或者最终需要返回的,包装转换为和。
spring-cloud-gateway 的ReactorHttpHandlerAdapter
这几天看了看spring-cloud-gateway的请求处理流程,因为之前一直用的springboot1.x和spring4,一开始对spring-cloud-gateway的处理流程有点懵逼,找不到入口,后来跟了代码,在网上找了点资料,发现spring-cloud-gateway的入口在ReactorHttpHandlerAdapter的apply方法
</>复制代码
public class ReactorHttpHandlerAdapter implements BiFunction> {
private static final Log logger = HttpLogging.forLogName(ReactorHttpHandlerAdapter.class);
private final HttpHandler httpHandler;
public ReactorHttpHandlerAdapter(HttpHandler httpHandler) {
Assert.notNull(httpHandler, "HttpHandler must not be null");
this.httpHandler = httpHandler;
}
@Override
public Mono apply(HttpServerRequest reactorRequest, HttpServerResponse reactorResponse) {
NettyDataBufferFactory bufferFactory = new NettyDataBufferFactory(reactorResponse.alloc());
try {
ReactorServerHttpRequest request = new ReactorServerHttpRequest(reactorRequest, bufferFactory);
ServerHttpResponse response = new ReactorServerHttpResponse(reactorResponse, bufferFactory);
if (request.getMethod() == HttpMethod.HEAD) {
response = new HttpHeadResponseDecorator(response);
}
return this.httpHandler.handle(request, response)
.doOnError(ex -> logger.trace(request.getLogPrefix() + "Failed to complete: " + ex.getMessage()))
.doOnSuccess(aVoid -> logger.trace(request.getLogPrefix() + "Handling completed"));
}
catch (URISyntaxException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to get request URI: " + ex.getMessage());
}
reactorResponse.status(HttpResponseStatus.BAD_REQUEST);
return Mono.empty();
}
}
}
该方法的作用就是把接收到的HttpServerRequest或者最终需要返回的HttpServerResponse,包装转换为ReactorServerHttpRequest和ReactorServerHttpResponse。
spring-webflux当然,这篇文章的主要内容不是谈论spring-cloud-gateway了,因为之前一直用的spring4,所以对spring5当中的反应式编程范式和webflux不太了解,所以先写个demo了解一下
第一步:引入相关pom,测试的相关pom根据自己的需要引入
</>复制代码
org.springframework.boot
spring-boot-starter-parent
2.1.4.RELEASE
org.springframework.boot
spring-boot-starter-webflux
org.springframework.boot
spring-boot-starter-test
test
io.projectreactor
reactor-test
test
第二步:创建一个HandlerFunction
</>复制代码
public class TestFunction implements HandlerFunction {
@Override
public Mono handle(ServerRequest serverRequest) {
return ServerResponse.ok().body(
Mono.just(parse(serverRequest, "args1") + parse(serverRequest, "args2"))
, Integer.class);
}
private int parse(final ServerRequest request, final String param) {
return Integer.parseInt(request.queryParam(param).orElse("0"));
}
}
第三步:注入一个RouterFunction
</>复制代码
@Configuration
public class TestRouteFunction {
@Bean
public RouterFunction routerFunction() {
return RouterFunctions.route(RequestPredicates.GET("/add"), new TestFunction());
}
}
第四步:在webflux中,也可以使用之前的java注解的编程方式,我们也创建一个controller
</>复制代码
@RestController
@RequestMapping("/api/test")
public class HelloController {
@RequestMapping("/hello")
public Mono hello() {
return Mono.just("hello world");
}
}
第五步:创建启动类
</>复制代码
@SpringBootApplication
public class Spring5DemoApplication {
public static void main(String[] args) {
SpringApplication.run(Spring5DemoApplication.class, args);
}
}
第六步:启动项目,访问如下两个接口都可以
</>复制代码
http://localhost:8080/api/test/hello
http://localhost:8080/add?args1=2&args2=3
和spring-boot结合
通过上面的例子,我们看到基本的两个类:HandlerFunction和RouterFunction,同时webflux有如下特性:
异步非阻塞
响应式(reactive)函数编程,纯lambda表达式
不仅仅是在Servlet容器中tomcat/jetty中运行,同时支持NIO的Netty和Undertow中,实际项目中,我们往往与spring-boot项目结合,我们跟进代码可以看看spring-boot是在什么时候创建的server
一、SpringApplication
</>复制代码
public ConfigurableApplicationContext run(String... args) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
Collection exceptionReporters = new ArrayList<>();
configureHeadlessProperty();
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting();
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(
args);
ConfigurableEnvironment environment = prepareEnvironment(listeners,
applicationArguments);
configureIgnoreBeanInfo(environment);
Banner printedBanner = printBanner(environment);
context = createApplicationContext();
exceptionReporters = getSpringFactoriesInstances(
SpringBootExceptionReporter.class,
new Class[] { ConfigurableApplicationContext.class }, context);
prepareContext(context, environment, listeners, applicationArguments,
printedBanner);
refreshContext(context);
afterRefresh(context, applicationArguments);
stopWatch.stop();
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass)
.logStarted(getApplicationLog(), stopWatch);
}
listeners.started(context);
callRunners(context, applicationArguments);
}
catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, listeners);
throw new IllegalStateException(ex);
}
try {
listeners.running(context);
}
catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, null);
throw new IllegalStateException(ex);
}
return context;
}
我们只分析入口,其它代码暂时不管,找到refreshContext(context);这一行进去
二、ReactiveWebServerApplicationContext的refresh()
</>复制代码
@Override
public final void refresh() throws BeansException, IllegalStateException {
try {
super.refresh();
}
catch (RuntimeException ex) {
stopAndReleaseReactiveWebServer();
throw ex;
}
}
三、ReactiveWebServerApplicationContext的onRefresh()
</>复制代码
@Override
protected void onRefresh() {
super.onRefresh();
try {
createWebServer();
}
catch (Throwable ex) {
throw new ApplicationContextException("Unable to start reactive web server",
ex);
}
}
四、看到这里我们就找到入口方法了:createWebServer(),跟进去,找到NettyReactiveWebServerFactory中创建webserver
</>复制代码
@Override
public WebServer getWebServer(HttpHandler httpHandler) {
HttpServer httpServer = createHttpServer();
ReactorHttpHandlerAdapter handlerAdapter = new ReactorHttpHandlerAdapter(
httpHandler);
return new NettyWebServer(httpServer, handlerAdapter, this.lifecycleTimeout);
}
看到ReactorHttpHandlerAdapter这个类想必特别亲切,在开篇说过是spring-cloud-gateway的入口,createHttpServer方法的细节暂时没有去学习了,后续有时间去深入了解下
结语spring5的相关新特性也是在学习中,这一篇文章算是和springboot结合的入门吧,后续有时间再深入学习
更多文章可以访问博客:
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/74417.html
摘要:响应式编程是基于异步和事件驱动的非阻塞程序,只是垂直通过在内启动少量线程扩展,而不是水平通过集群扩展。三特性常用的生产的特性如下响应式编程模型适用性内嵌容器组件还有对日志消息测试及扩展等支持。 摘要: 原创出处 https://www.bysocket.com 「公众号:泥瓦匠BYSocket 」欢迎关注和转载,保留摘要,谢谢! 02:WebFlux 快速入门实践 文章工程: JDK...
摘要:在配置下上面启动的配置数据库名为账号密码也为。突出点是,即非阻塞的。四对象修改包里面的城市实体对象类。修改城市对象,代码如下城市实体类城市编号省份编号城市名称描述注解标记对应库表的主键或者唯一标识符。 摘要: 原创出处 https://www.bysocket.com 「公众号:泥瓦匠BYSocket 」欢迎关注和转载,保留摘要,谢谢! 这是泥瓦匠的第104篇原创 文章工程: JDK...
摘要:上一章我们提到过与,对于具体的介绍没说到,这一章我在这里简单介绍一下,既然提到和,那肯定得提到什么是响应式编程,什么是。 showImg(https://segmentfault.com/img/remote/1460000018819338?w=1024&h=500); 上一章我们提到过Mono 与 Flux,对于具体的介绍没说到,这一章我在这里简单介绍一下,既然提到Mono和Flu...
摘要:数据和信息是不可分离的,数据是信息的表达,信息是数据的内涵。数据本身没有意义,数据只有对实体行为产生影响时才成为信息。主要目标是为开发提供天然的模板,并且能在里面准确的显示。目前是自然更加推荐。 这是泥瓦匠的第105篇原创 文章工程: JDK 1.8 Maven 3.5.2 Spring Boot 2.1.3.RELEASE 工程名:springboot-webflux-4-thym...
摘要:二结构这个工程会对城市进行管理实现操作。负责将持久层数据操作相关的封装组织,完成新增查询删除等操作。原因是,直接使用和是非阻塞写法,相当于回调方式。反应了是的好处集合了非阻塞异步。其实是的一个补充。可以发布类型的元素。 摘要: 原创出处 https://www.bysocket.com 「公众号:泥瓦匠BYSocket 」欢迎关注和转载,保留摘要,谢谢! 这是泥瓦匠的第102篇原创 0...
阅读 3697·2021-10-08 10:04
阅读 1014·2019-08-30 15:54
阅读 2298·2019-08-29 16:09
阅读 1449·2019-08-29 15:41
阅读 2383·2019-08-29 11:01
阅读 1831·2019-08-26 13:51
阅读 1152·2019-08-26 13:25
阅读 1949·2019-08-26 13:24