Gateway集成Netty服务配置加载的方法是什么(gateway,netty,开发技术)

时间:2024-05-08 19:47:38 作者 : 石家庄SEO 分类 : 开发技术
  • TAG :

一、Netty简介

Gateway和Netty都有盲区的感觉;

Netty是一个异步的,事件驱动的网络应用框架,用以快速开发高可靠、高性能的网络应用程序。

Gateway集成Netty服务配置加载的方法是什么

传输服务:提供网络传输能力的管理;

协议支持:支持常见的数据传输协议;

核心模块:包括可扩展事件模型、通用的通信API、零拷贝字节缓冲;

二、Netty入门案例

1、服务端启动

配置Netty服务器端程序,引导相关核心组件的加载;

publicclassNettyServer{publicstaticvoidmain(String[]args){//EventLoop组,处理事件和IOEventLoopGroupparentGroup=newNioEventLoopGroup();EventLoopGroupchildGroup=newNioEventLoopGroup();try{//服务端启动引导类ServerBootstrapserverBootstrap=newServerBootstrap();serverBootstrap.group(parentGroup,childGroup).channel(NioServerSocketChannel.class).childHandler(newChannelInit());//异步IO的结果ChannelFuturechannelFuture=serverBootstrap.bind(8082).sync();channelFuture.channel().closeFuture().sync();}catch(Exceptione){e.printStackTrace();}finally{parentGroup.shutdownGracefully();childGroup.shutdownGracefully();}}}

2、通道初始化

ChannelInitializer特殊的通道处理器,提供一种简单的方法,对注册到EventLoop的通道进行初始化;比如此处设置的编码解码器,自定义处理器;

publicclassChannelInitextendsChannelInitializer<SocketChannel>{@OverrideprotectedvoidinitChannel(SocketChannelsocketChannel){//获取管道ChannelPipelinepipeline=socketChannel.pipeline();//Http编码、解码器pipeline.addLast("DefHttpServerCodec",newHttpServerCodec());//添加自定义的handlerpipeline.addLast("DefHttpHandler",newDefHandler());}}

3、自定义处理器

处理对服务器端发起的访问,通常包括请求解析,具体的逻辑执行,请求响应等过程;

publicclassDefHandlerextendsSimpleChannelInboundHandler<HttpObject>{@OverrideprotectedvoidchannelRead0(ChannelHandlerContextctx,HttpObjectmessage)throwsException{if(messageinstanceofHttpRequest){//请求解析HttpRequesthttpRequest=(HttpRequest)message;Stringuri=httpRequest.uri();Stringmethod=httpRequest.method().name();log.info("【HttpRequest-URI:"+uri+"】");log.info("【HttpRequest-method:"+method+"】");Iterator<Map.Entry<String,String>>iterator=httpRequest.headers().iteratorAsString();while(iterator.hasNext()){Map.Entry<String,String>entry=iterator.next();log.info("【Header-Key:"+entry.getKey()+";Header-Value:"+entry.getValue()+"】");}//响应构建ByteBufcontent=Unpooled.copiedBuffer("Netty服务",CharsetUtil.UTF_8);FullHttpResponseresponse=newDefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK,content);response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain;charset=utf-8");response.headers().set(HttpHeaderNames.CONTENT_LENGTH,content.readableBytes());ctx.writeAndFlush(response);}}}

4、测试请求

上面入门案例中,简单的配置了一个Netty服务器端,启动之后在浏览器中模拟访问即可;

http://127.0.0.1:8082/?id=1&name=Spring

三、Gateway集成

1、依赖层级

项目中Gateway网关依赖的版本为2.2.5.RELEASE,发现Netty依赖的版本为4.1.45.Final,是当下比较主流的版本;

<!--1、项目工程依赖--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway</artifactId><version>2.2.5.RELEASE</version></dependency><!--2、starter-gateway依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-webflux</artifactId><version>2.3.2.RELEASE</version></dependency><!--3、starter-webflux依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-reactor-netty</artifactId><version>2.3.2.RELEASE</version></dependency>

2、自动化配置

在Gateway网关的自动化配置配置类中,提供了Netty配置的管理;

@AutoConfigureBefore({HttpHandlerAutoConfiguration.class,WebFluxAutoConfiguration.class})@ConditionalOnClass(DispatcherHandler.class)publicclassGatewayAutoConfiguration{@Configuration(proxyBeanMethods=false)@ConditionalOnClass(HttpClient.class)protectedstaticclassNettyConfiguration{@Bean@ConditionalOnProperty(name="spring.cloud.gateway.httpserver.wiretap")publicNettyWebServerFactoryCustomizernettyServerWiretapCustomizer(Environmentenvironment,ServerPropertiesserverProperties){returnnewNettyWebServerFactoryCustomizer(environment,serverProperties){@Overridepublicvoidcustomize(NettyReactiveWebServerFactoryfactory){factory.addServerCustomizers(httpServer->httpServer.wiretap(true));super.customize(factory);}};}}}

四、配置加载

1、基础配置

在工程的配置文件中,简单做一些基础性的设置;

server:port:8081#端口号netty:#Netty组件connection-timeout:3000#连接超时

2、属性配置类

在ServerProperties类中,并没有提供很多显式的Netty配置参数,更多信息需要参考工厂类;

@ConfigurationProperties(prefix="server",ignoreUnknownFields=true)publicclassServerProperties{privateIntegerport;publicstaticclassNetty{privateDurationconnectionTimeout;}}

3、配置加载分析

Gateway集成Netty服务配置加载的方法是什么

  • 基于配置的属性,定制化管理Netty服务的信息;

publicclassNettyWebServerFactoryCustomizerimplementsWebServerFactoryCustomizer<NettyReactiveWebServerFactory>{privatefinalEnvironmentenvironment;privatefinalServerPropertiesserverProperties;@Overridepublicvoidcustomize(NettyReactiveWebServerFactoryfactory){PropertyMapperpropertyMapper=PropertyMapper.get().alwaysApplyingWhenNonNull();ServerProperties.NettynettyProperties=this.serverProperties.getNetty();propertyMapper.from(nettyProperties::getConnectionTimeout).whenNonNull().to((connectionTimeout)->customizeConnectionTimeout(factory,connectionTimeout));}}
  • NettyReactiveWeb服务工厂,基于上述入门案例,创建WebServer时,部分参数信息出自LoopResources接口;

publicclassNettyReactiveWebServerFactoryextendsAbstractReactiveWebServerFactory{privateReactorResourceFactoryresourceFactory;@OverridepublicWebServergetWebServer(HttpHandlerhttpHandler){HttpServerhttpServer=createHttpServer();ReactorHttpHandlerAdapterhandlerAdapter=newReactorHttpHandlerAdapter(httpHandler);NettyWebServerwebServer=newNettyWebServer(httpServer,handlerAdapter,this.lifecycleTimeout);webServer.setRouteProviders(this.routeProviders);returnwebServer;}privateHttpServercreateHttpServer(){ HttpServerserver=HttpServer.create(); if(this.resourceFactory!=null){ LoopResourcesresources=this.resourceFactory.getLoopResources(); server=server.tcpConfiguration( (tcpServer)->tcpServer.runOn(resources).addressSupplier(this::getListenAddress));}returnapplyCustomizers(server); }}

五、周期管理方法

1、控制类

Gateway集成Netty服务配置加载的方法是什么

Gateway项目中,Netty服务核心控制类,通过NettyReactiveWebServerFactory工厂类创建,对Netty生命周期的管理提供了一层包装;

publicclassNettyWebServerimplementsWebServer{privatefinalHttpServerhttpServer;privatefinalReactorHttpHandlerAdapterhandlerAdapter;/***启动方法*/@Overridepublicvoidstart()throwsWebServerException{if(this.disposableServer==null){this.disposableServer=startHttpServer();//控制台日志logger.info("Nettystartedonport(s):"+getPort());startDaemonAwaitThread(this.disposableServer);}}privateDisposableServerstartHttpServer(){HttpServerserver=this.httpServer;if(this.routeProviders.isEmpty()){server=server.handle(this.handlerAdapter);}returnserver.bindNow();}/***停止方法*/@Overridepublicvoidstop()throwsWebServerException{if(this.disposableServer!=null){//释放资源if(this.lifecycleTimeout!=null){this.disposableServer.disposeNow(this.lifecycleTimeout);}else{this.disposableServer.disposeNow();}//对象销毁this.disposableServer=null;}}}

2、管理类

Netty组件中抽象管理类,以安全的方式构建Http服务;

publicabstractclassHttpServer{publicstaticHttpServercreate(){returnHttpServerBind.INSTANCE;}publicfinalDisposableServerbindNow(){returnbindNow(Duration.ofSeconds(45));}publicfinalHttpServerhandle(BiFunction<?superHttpServerRequest,?superHttpServerResponse,?extendsPublisher<Void>>handler){returnnewHttpServerHandle(this,handler);}}
 </div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:Gateway集成Netty服务配置加载的方法是什么的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:JavaScript如何实现视差滚动效果下一篇:

3 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18