cosocket简介
cosocket 是 OpenResty 世界中技术、实用价值最高部分。让我们可以用非常低廉的成本,优雅的姿势,比传统 socket 编程效率高好几倍的方式进行网络编程。无论资源占用、执行效率、并发能力都非常出色。
鲁迅有句名言“其实世界上本没有路,走的人多了便有了路”,其实对于 cosocket 的中文翻译貌似我也碰到了类似的问题。当我想给大家一个正面解释,爬过了官方 wiki 发现,原来作者本人(章亦春)也没有先给出 cosocket 定义。
看来只能通过一些侧面信息,从而让这条路逐渐的清晰起来。
cosocket = coroutine + socket
coroutine:协同程序(后面简称:协程) socket:网络套接字
OpenResty 中的 cosocket 不仅需要协程特性支撑,它还需 Nginx 非常最重要的“事件循环回调机制”,两部分结合在一起最终达到了 cosocket 效果,外加 Nginx 自身对各种资源的“小气”,LuaJIT 的执行效率,最终加分不少。在 Lua 世界中调用任何一个有关 cosocket 网络函数内部关键调用如图所示:
使用cosocket发起http请求
个github上有对cosocket的封装,lua-resty-http
在直接git clone到本地,在conf文件中添加lua_package_path
,提供了一些api,见https://github.com/pintsized/lua-resty-http
conf文件
worker_processes 2; #nginx worker 数量
error_log logs/error.log; #指定错误日志文件路径
events {
worker_connections 1024;
}
http {
lua_package_path "/home/zhangxiao/openresty-work/lua/?.lua;/home/zhangxiao/openresty-work/lua/lua-resty-http/lib/?.lua;;";
upstream md5_server{
server 127.0.0.1:81;
keepalive 20;
}
server {
listen 1024;
location /test {
content_by_lua_block {
ngx.req.read_body()
local args,err = ngx.req.get_uri_args()
local http=require "resty.http"
local httpc=http.new()
local res,err=httpc:request_uri(
"http://127.0.0.1:81/spe_md5",
{
method ="POST",
body=args.data,
}
)
if 200 ~= res.status then
ngx.exit(res.status)
end
if args.key == res.body then
ngx.say("valid request ")
else
ngx.say("invalid request")
end
}
}
location /spe_md5 {
proxy_pass http://md5_server;
#For HTTP, the proxy_http_version directive should be set to “1.1” and the “Connection”
#header field should be cleared.(from:http://nginx.org/en/docs/http/ngx_http_upstream_module.html#keepalive)
proxy_http_version 1.1;
proxy_set_header Connection "";
}
}# server port 1024
server {
listen 81;
location /spe_md5 {
content_by_lua_block {
ngx.req.read_body()
local data = ngx.req.get_body_data()
ngx.print(ngx.md5(data))
}
}
}
}
测试
curl -v -X GET 'localhost:1024/test?key=5d41402abc4b2a76b9719d911017c592&data=hello'
参考
openresty最佳实践