自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

聊聊Gateway集成Netty服務

開發(fā) 前端
Netty是一個異步的,事件驅動的網絡應用框架,用以快速開發(fā)高可靠、高性能的網絡應用程序。

一、Netty簡介

Netty是一個異步的,事件驅動的網絡應用框架,用以快速開發(fā)高可靠、高性能的網絡應用程序。

圖片

傳輸服務:提供網絡傳輸能力的管理;

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

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

二、Netty入門案例

1、服務端啟動

配置Netty服務器端程序,引導相關核心組件的加載;

public class NettyServer {

public static void main(String[] args) {

// EventLoop組,處理事件和IO
EventLoopGroup parentGroup = new NioEventLoopGroup();
EventLoopGroup childGroup = new NioEventLoopGroup();

try {

// 服務端啟動引導類
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(parentGroup, childGroup)
.channel(NioServerSocketChannel.class).childHandler(new ChannelInit());

// 異步IO的結果
ChannelFuture channelFuture = serverBootstrap.bind(8082).sync();
channelFuture.channel().closeFuture().sync();

} catch (Exception e){
e.printStackTrace();
} finally {
parentGroup.shutdownGracefully();
childGroup.shutdownGracefully();
}
}
}

2、通道初始化

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

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、自定義處理器

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

public class DefHandler extends SimpleChannelInboundHandler<HttpObject> {

@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject message) throws Exception {

if(message instanceof HttpRequest) {
// 請求解析
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()+"】");
}

// 響應構建
ByteBuf content = Unpooled.copiedBuffer("Netty服務", 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、測試請求

上面入門案例中,簡單的配置了一個Netty服務器端,啟動之后在瀏覽器中模擬訪問即可;

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

三、Gateway集成

1、依賴層級

項目中Gateway網關依賴的版本為2.2.5.RELEASE?,發(fā)現(xiàn)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)
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、基礎配置

在工程的配置文件中,簡單做一些基礎性的設置;

server:
port: 8081 # 端口號
netty: # Netty組件
connection-timeout: 3000 # 連接超時

2、屬性配置類

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

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

3、配置加載分析

圖片

  • 基于配置的屬性,定制化管理Netty服務的信息;
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服務工廠,基于上述入門案例,創(chuàng)建WebServer時,部分參數信息出自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項目中,Netty服務核心控制類,通過NettyReactiveWebServerFactory工廠類創(chuàng)建,對Netty生命周期的管理提供了一層包裝;

public class NettyWebServer implements WebServer {

private final HttpServer httpServer;
private final ReactorHttpHandlerAdapter handlerAdapter;

/**
* 啟動方法
*/
@Override
public void start() throws WebServerException {
if (this.disposableServer == null) {
this.disposableServer = startHttpServer();
// 控制臺日志
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();
}
// 對象銷毀
this.disposableServer = null;
}
}
}

2、管理類

Netty組件中抽象管理類,以安全的方式構建Http服務;

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

應用倉庫:
https://gitee.com/cicadasmile/butte-flyer-parent

責任編輯:武曉燕 來源: 知了一笑
相關推薦

2024-07-29 08:24:43

2024-11-22 00:09:15

2022-10-28 07:27:17

Netty異步Future

2022-03-04 08:10:35

NettyIO模型Reactor

2021-02-07 09:05:56

微服務結構云原生

2017-06-02 08:32:01

調度服務數據

2023-08-07 08:32:05

RocketMQ名字服務

2023-12-15 09:57:13

微服務鏈路服務

2024-06-13 08:24:43

SpringGateway線程池

2024-11-25 06:20:00

Netty封裝框架

2022-03-03 08:01:41

阻塞與非阻塞同步與異步Netty

2025-04-27 08:25:00

Netty零拷貝內存

2021-07-20 08:03:43

微服務應用程序

2024-11-04 08:00:00

Netty客戶端

2022-09-01 08:17:15

Gateway微服務網關

2023-01-29 09:06:24

微服務劃分關聯(lián)

2021-07-14 06:45:49

Windows.NetTopshelf

2022-05-09 08:34:01

FeignhttpJava

2018-05-09 08:18:26

微服務改造架構

2022-04-11 08:17:07

JVMJava進程
點贊
收藏

51CTO技術棧公眾號