Cosockets and Non-Blocking TCP
Use ngx.socket.tcp for async backend connections in content_by_lua.
What Are Cosockets?
OpenResty cosockets are non-blocking TCP/UDP sockets that integrate with Nginx's event loop. When waiting for data, they yield the coroutine, freeing the worker to handle other requests.
Creating a TCP Cosocket
Use ngx.socket.tcp() to create a cosocket. Connect, send, and receive all yield automatically when I/O would block.
-- content_by_lua_block
local sock = ngx.socket.tcp()
local ok, err = sock:connect("redis.local", 6379)
if not ok then
ngx.log(ngx.ERR, "Connect failed: ", err)
return ngx.exit(500)
endAll lessons in this course
- OpenResty Architecture
- Handling HTTP Requests in Lua
- Cosockets and Non-Blocking TCP
- Shared Memory Dictionaries