我是靠谱客的博主 健壮饼干,这篇文章主要介绍netty在服务器端设置超时时间,现在分享给大家,希望可以做个参考。

设置很简单,直接官网上抄就行,然后把它放在第一位或者尽量靠前吧

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class MyChannelInitializer extends ChannelInitializer<Channel> { @Override public void initChannel(Channel channel) { channel.pipeline().addLast("idleStateHandler", new IdleStateHandler(60, 30, 0)); channel.pipeline().addLast("myHandler", new MyHandler()); } } // Handler should handle the IdleStateEvent triggered by IdleStateHandler. public class MyHandler extends ChannelDuplexHandler { @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent) { IdleStateEvent e = (IdleStateEvent) evt; if (e.state() == IdleState.READER_IDLE) { ctx.close(); } else if (e.state() == IdleState.WRITER_IDLE) { ctx.writeAndFlush(new PingMessage()); } } } } ServerBootstrap bootstrap = ...; ... bootstrap.childHandler(new MyChannelInitializer());

那么,我为什么还要写这篇博客呢?说多了都是泪,我花了近6小时的时间去验证这个请求超时设置是否成功。下面来听听我的翻车史。

我写这个服务器的是用来启动web项目的,类似tomcat的功能。源码可以在https://blog.csdn.net/fsgsggd/article/details/107817314 的项目地址上看到。

这是我的ChannelInitializer,超时时间处理,http请求信息的解码,自定义对http请求的处理。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.tczs.springmvc.netty; import io.netty.channel.ChannelHandler.Sharable; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpServerCodec; import io.netty.handler.timeout.IdleStateHandler; @Sharable public class SunChannelInitializer extends ChannelInitializer<SocketChannel>{ @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new IdleStateHandler(5,5, 0)); pipeline.addLast(new TimeOutHandler()); pipeline.addLast(new HttpServerCodec()); pipeline.addLast(new HttpObjectAggregator(512 * 1024)); pipeline.addLast(new HttpExecuteHandler()); } }

我打算postman来请求这个接口:

复制代码
1
2
3
4
5
6
7
8
@RequestMapping(url="/findByParam") public List<TestData.Person> findByParam(@Param("id")Integer id,@Param("name")String name,@Param("mobile")String mobile) throws UnknownHostException, IOException{ System.out.println("name-----"+name); Socket s = new Socket("news.baidu.com", 450); return testService.findByParam(id, name, mobile); }

可以看到这个接口肯定要花费很长时间,而且接口肯定报错了。那么为什么我上面设置的5秒超时时间不起作用呢?这就是我耗费6小时去验证的原因了。

首先,上面的设置是没有问题的。那么为什么没起作用,那就是我想的触发超时时间条件和它的触发超时时间条件是完全不在一个水平线上的。

我想的是从http连接开始到返回数据的这段时间,超过了设置的超时时间则触发。但它的不是。

看图:

它的读超时时间是连接开始到处理第一个入站handler的 channelRead0 方法,如果时间超过,则是读超时。

它的写超时时间是入站消息处理完的时间到写入第一个出站handler的 write 方法,如果时间超过,则是读超时。

想通了,再回首看这篇文章,写的是什么玩意啊,还要你说。

最后

以上就是健壮饼干最近收集整理的关于netty在服务器端设置超时时间的全部内容,更多相关netty在服务器端设置超时时间内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(69)

评论列表共有 0 条评论

立即
投稿
返回
顶部