ngx.socket.tcp 在被回收时会自动close吗?例如:local sock = ngx.socket.tcp()sock:connect(...)local bytes, err = sock:send(...)if not bytes then ngx.exit(500)endngx.exit(500)后sock会自动关闭吗?还是需要主动close?-- Azure.Wang
官网文档上是如此描述:“Socket objects that have not invoked this method (and associated connections) will be closed when the socket object is released by the Lua GC (Garbage Collector) or the current client HTTP request finishes processing.” 应该是在HTTP请求结束后释放,或者GC时候。如果你不是keepalive的话,就自己手动close把。手动释放是一种美德,明确的操作,而不是让系统自动回收。--blog: http://chenxiaoyu.org 2012/10/24 azure wang <azu...@gmail.com> ngx.socket.tcp 在被回收时会自动close吗?例如:local sock = ngx.socket.tcp()sock:connect(...)local bytes, err = sock:send(...)if not bytes then ngx.exit(500)endngx.exit(500)后sock会自动关闭吗?还是需要主动close?-- Azure.Wang
Hello! 2012/10/24 azure wang: > 还是加上手动close吧 呵呵。 > 在sock打开后 每个遇到错误的地方都主动close一下。 当 TCP/stream socket 对象出错时,socket 对象会自动关闭。所以不必在出错时再手动调用 close() 方法,因为那其实是空操作。 close 方法仅在之前的操作都成功的情况下调用才有意义。主动调用 close() 方法是推荐的做法,因为可以更早地释放相关的连接和内存资源,否则会推迟到 socket 对象被 Lua GC 的时候(而这个时间点一般是不能精确预期的)。 另外,建议尽量使用 set_keepalive() 调用替代 close() 调用;因为前者可以启用 TCP 连接池特性,可以节约 TCP 的连接建立和关闭所需的那么多次握手开销。 Best regards, -agentzh