最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Gateway集成Netty服務(wù)的配置加載詳解

 更新時(shí)間:2023年02月28日 15:47:09   作者:知了一笑  
這篇文章主要為大家介紹了Gateway集成Netty服務(wù)的配置加載詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

一、Netty簡介

Gateway和Netty都有盲區(qū)的感覺;

Netty是一個(gè)異步的,事件驅(qū)動(dòng)的網(wǎng)絡(luò)應(yīng)用框架,用以快速開發(fā)高可靠、高性能的網(wǎng)絡(luò)應(yīng)用程序。

傳輸服務(wù):提供網(wǎng)絡(luò)傳輸能力的管理;

協(xié)議支持:支持常見的數(shù)據(jù)傳輸協(xié)議;

核心模塊:包括可擴(kuò)展事件模型、通用的通信API、零拷貝字節(jié)緩沖;

二、Netty入門案例

1、服務(wù)端啟動(dòng)

配置Netty服務(wù)器端程序,引導(dǎo)相關(guān)核心組件的加載;

public class NettyServer {
    public static void main(String[] args) {
        // EventLoop組,處理事件和IO
        EventLoopGroup parentGroup = new NioEventLoopGroup();
        EventLoopGroup childGroup = new NioEventLoopGroup();
        try {
            // 服務(wù)端啟動(dòng)引導(dǎo)類
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(parentGroup, childGroup)
                    .channel(NioServerSocketChannel.class).childHandler(new ChannelInit());
            // 異步IO的結(jié)果
            ChannelFuture channelFuture = serverBootstrap.bind(8082).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            parentGroup.shutdownGracefully();
            childGroup.shutdownGracefully();
        }
    }
}

2、通道初始化

ChannelInitializer特殊的通道處理器,提供一種簡單的方法,對(duì)注冊(cè)到EventLoop的通道進(jìn)行初始化;比如此處設(shè)置的編碼解碼器,自定義處理器;

public class ChannelInit extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel socketChannel) {
        // 獲取管道
        ChannelPipeline pipeline = socketChannel.pipeline();
        // Http編碼、解碼器
        pipeline.addLast("DefHttpServerCodec",new HttpServerCodec());
        // 添加自定義的handler
        pipeline.addLast("DefHttpHandler", new DefHandler());
    }
}

3、自定義處理器

處理對(duì)服務(wù)器端發(fā)起的訪問,通常包括請(qǐng)求解析,具體的邏輯執(zhí)行,請(qǐng)求響應(yīng)等過程;

public class DefHandler extends SimpleChannelInboundHandler<HttpObject> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject message) throws Exception {
        if(message instanceof HttpRequest) {
            // 請(qǐng)求解析
            HttpRequest httpRequest = (HttpRequest) message;
            String uri = httpRequest.uri();
            String method = 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()+"】");
            }
            // 響應(yīng)構(gòu)建
            ByteBuf content = Unpooled.copiedBuffer("Netty服務(wù)", CharsetUtil.UTF_8);
            FullHttpResponse response = new DefaultFullHttpResponse
                                        (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、測(cè)試請(qǐng)求

上面入門案例中,簡單的配置了一個(gè)Netty服務(wù)器端,啟動(dòng)之后在瀏覽器中模擬訪問即可;

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

三、Gateway集成

1、依賴層級(jí)

項(xiàng)目中Gateway網(wǎng)關(guān)依賴的版本為2.2.5.RELEASE,發(fā)現(xiàn)Netty依賴的版本為4.1.45.Final,是當(dāng)下比較主流的版本;

<!-- 1、項(xiàng)目工程依賴 -->
<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、自動(dòng)化配置

在Gateway網(wǎng)關(guān)的自動(dòng)化配置配置類中,提供了Netty配置的管理;

@AutoConfigureBefore({ HttpHandlerAutoConfiguration.class,WebFluxAutoConfiguration.class })
@ConditionalOnClass(DispatcherHandler.class)
public class GatewayAutoConfiguration {
    @Configuration(proxyBeanMethods = false)
    @ConditionalOnClass(HttpClient.class)
    protected static class NettyConfiguration {
        @Bean
        @ConditionalOnProperty(name = "spring.cloud.gateway.httpserver.wiretap")
        public NettyWebServerFactoryCustomizer nettyServerWiretapCustomizer(
                Environment environment, ServerProperties serverProperties) {
            return new NettyWebServerFactoryCustomizer(environment, serverProperties) {
                @Override
                public void customize(NettyReactiveWebServerFactory factory) {
                    factory.addServerCustomizers(httpServer -> httpServer.wiretap(true));
                    super.customize(factory);
                }
            };
        }
    }
}

四、配置加載

1、基礎(chǔ)配置

在工程的配置文件中,簡單做一些基礎(chǔ)性的設(shè)置;

server:
  port: 8081                  # 端口號(hào)
  netty:                      # Netty組件
    connection-timeout: 3000  # 連接超時(shí)

2、屬性配置類

在ServerProperties類中,并沒有提供很多顯式的Netty配置參數(shù),更多信息需要參考工廠類;

@ConfigurationProperties(prefix = "server", ignoreUnknownFields = true)
public class ServerProperties {
    private Integer port;
    public static class Netty {
        private Duration connectionTimeout;
    }
}

3、配置加載分析

  • 基于配置的屬性,定制化管理Netty服務(wù)的信息;
public class NettyWebServerFactoryCustomizer
        implements WebServerFactoryCustomizer<NettyReactiveWebServerFactory>{
    private final Environment environment;
    private final ServerProperties serverProperties;
    @Override
    public void customize(NettyReactiveWebServerFactory factory) {
        PropertyMapper propertyMapper = PropertyMapper.get().alwaysApplyingWhenNonNull();
        ServerProperties.Netty nettyProperties = this.serverProperties.getNetty();
        propertyMapper.from(nettyProperties::getConnectionTimeout).whenNonNull()
                .to((connectionTimeout) -> customizeConnectionTimeout(factory, connectionTimeout));
    }
}
  • NettyReactiveWeb服務(wù)工廠,基于上述入門案例,創(chuàng)建WebServer時(shí),部分參數(shù)信息出自LoopResources接口;
public class NettyReactiveWebServerFactory extends AbstractReactiveWebServerFactory {
    private ReactorResourceFactory resourceFactory;
    @Override
    public WebServer getWebServer(HttpHandler httpHandler) {
        HttpServer httpServer = createHttpServer();
        ReactorHttpHandlerAdapter handlerAdapter = new ReactorHttpHandlerAdapter(httpHandler);
        NettyWebServer webServer = new NettyWebServer(httpServer, handlerAdapter, this.lifecycleTimeout);
        webServer.setRouteProviders(this.routeProviders);
        return webServer;
    }
    private HttpServer createHttpServer() {
		HttpServer server = HttpServer.create();
		if (this.resourceFactory != null) {
        	LoopResources resources = this.resourceFactory.getLoopResources();
        	server = server.tcpConfiguration(
        			(tcpServer) -> tcpServer.runOn(resources).addressSupplier(this::getListenAddress));
        }
        return applyCustomizers(server);
	}
}

五、周期管理方法

1、控制類

Gateway項(xiàng)目中,Netty服務(wù)核心控制類,通過NettyReactiveWebServerFactory工廠類創(chuàng)建,對(duì)Netty生命周期的管理提供了一層包裝;

public class NettyWebServer implements WebServer {
    private final HttpServer httpServer;
    private final ReactorHttpHandlerAdapter handlerAdapter;
    /**
     * 啟動(dòng)方法
     */
    @Override
    public void start() throws WebServerException {
        if (this.disposableServer == null) {
            this.disposableServer = startHttpServer();
            // 控制臺(tái)日志
            logger.info("Netty started on port(s): " + getPort());
            startDaemonAwaitThread(this.disposableServer);
        }
    }
    private DisposableServer startHttpServer() {
        HttpServer server = this.httpServer;
        if (this.routeProviders.isEmpty()) {
            server = server.handle(this.handlerAdapter);
        }
        return server.bindNow();
    }
    /**
     * 停止方法
     */
    @Override
    public void stop() throws WebServerException {
        if (this.disposableServer != null) {
            // 釋放資源
            if (this.lifecycleTimeout != null) {
                this.disposableServer.disposeNow(this.lifecycleTimeout);
            }
            else {
                this.disposableServer.disposeNow();
            }
            // 對(duì)象銷毀
            this.disposableServer = null;
        }
    }
}

2、管理類

Netty組件中抽象管理類,以安全的方式構(gòu)建Http服務(wù);

public abstract class HttpServer {
    public static HttpServer create() {
        return HttpServerBind.INSTANCE;
    }
    public final DisposableServer bindNow() {
        return bindNow(Duration.ofSeconds(45));
    }
    public final HttpServer handle(BiFunction<? super HttpServerRequest, ? super
            HttpServerResponse, ? extends Publisher<Void>> handler) {
        return new HttpServerHandle(this, handler);
    }
}

參考源碼

編程文檔:

https://gitee.com/cicadasmile/butte-java-note

應(yīng)用倉庫:

https://gitee.com/cicadasmile/butte-flyer-parent

以上就是Gateway集成Netty服務(wù)的配置加載詳解的詳細(xì)內(nèi)容,更多關(guān)于Gateway集成Netty服務(wù)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論

凤阳县| 定西市| 东平县| 江城| 沙洋县| 泰和县| 旺苍县| 英吉沙县| 翁牛特旗| 兴海县| 八宿县| 吴旗县| 天等县| 仙桃市| 敦化市| 吴旗县| 大同县| 东乡| 通州市| 二连浩特市| 独山县| 平和县| 拜城县| 湘西| 古蔺县| 黑山县| 翁源县| 巴彦淖尔市| 泰顺县| 翁源县| 龙门县| 县级市| 孝义市| 城步| 都兰县| 康马县| 乳源| 扶余县| 深州市| 苍南县| 岗巴县|