SmallChi / JT808Platform

简单的JT808车辆监控平台
MIT License
97 stars 82 forks source link

关于ChildHandler下创建NettyTcpServerHandler等handler的lifetime的问题 #2

Closed 491134648 closed 4 years ago

491134648 commented 4 years ago

有个地方不是很明白,netty的ChildHandler是否意味着一个新的连接上来创建一个handler,该连接直到断开前都是这个handler,还是每次send消息后一个新的handler,如果是前者的话,是不是意味着该NettyTcpServerHandler实例handler实例的相关的构造函数注入的参数伴随着channel连接到断开的整个周期,如果相关的NettyTcpServerHandler中包含有相关的数据库连接等对象时,是不是意味着1W个连接,创建1W个数据库连接实例,在连接断开前一直不会被释放呢呢?

bootstrap .Option(ChannelOption.SoBacklog, configuration.SoBacklog) .ChildOption(ChannelOption.Allocator, serverBufferAllocator) .ChildHandler(new ActionChannelInitializer<IChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; using (var scope = serviceProvider.CreateScope()) { channel.Pipeline.AddLast("jt808TcpBuffer", new DelimiterBasedFrameDecoder(int.MaxValue, Unpooled.CopiedBuffer(new byte[] { JT808.Protocol.JT808Package.BeginFlag }), Unpooled.CopiedBuffer(new byte[] { JT808.Protocol.JT808Package.EndFlag }))); channel.Pipeline.AddLast("jt808TcpDecode", scope.ServiceProvider.GetRequiredService<UnionTcpDecoder>()); channel.Pipeline.AddLast("jt808TcpEncode", scope.ServiceProvider.GetRequiredService<UnionTcpEncoder>()); channel.Pipeline.AddLast("systemIdleState", new IdleStateHandler( configuration.ReaderIdleTimeSeconds, configuration.WriterIdleTimeSeconds, configuration.AllIdleTimeSeconds)); channel.Pipeline.AddLast("jt808TcpConnection", scope.ServiceProvider.GetRequiredService<NettyTcpConnectionHandler>()); channel.Pipeline.AddLast("jt808TcpService", scope.ServiceProvider.GetRequiredService<NettyTcpServerHandler>()); } }));

SmallChi commented 4 years ago

是的,要是操作数据库应该使用创建局部作用域的方式,而不是采用全局的作用域。