Openresty 與 Tengine

Openresty和Tengine基於 Nginx 的兩個衍生版本,某種意義上他們都和淘寶有關係,前者是前淘寶工程師agentzh主導開發的,後者是淘寶的一個開源項目;

Openresty的最大特點是引入了ngx_lua模塊,支持使用lua開發插件;

Tengine的特點是融入了因淘寶自身的一些業務帶來的新功能;

 

Tengine 簡介

tengine官方網站:http://tengine.taobao.org/index_cn.html

在 Nginx官方版本的基礎上增加的一些定製模塊如下:

1、支持動態加載模塊:通過加載so文件實現,不用再重新編譯整個項目了,配置如下:

dso {
     load ngx_http_lua_module.so;
     load ngx_http_memcached_module.so;
}

 

2、ngx_proc_daytime_module模塊,這個模塊允許開一個獨立的服務進程,該模塊本身並未實現具體的業務邏輯,而是構建了一個TCP Server框架,等待開發者來實現自己的業務;

 

3、ngx_http_concat_module模塊,用於合併多個文件的響應;

 

4、ngx_http_upstream_session_sticky_module模塊,該模塊是一個負載均衡模塊,通過cookie實現客戶端與後端服務器的會話保持, 在一定條件下可以保證同一個客戶端訪問的都是同一個後端服務器。

 

5、ngx_http_upstream_check_module模塊,用於檢查upstream上游服務器的健康狀況,如下是一個配置的例子:

複製代碼

upstream cluster1 {
        # simple round-robin
        server 192.168.0.1:80;
        server 192.168.0.2:80;

        check interval=3000 rise=2 fall=5 timeout=1000 type=http;
        check_http_send "HEAD / HTTP/1.0\r\n\r\n";
        check_http_expect_alive http_2xx http_3xx;
    }

複製代碼

 

6、trim filter模塊,用於刪除 html,內嵌 javascript 和 css 中的註釋以及重複的空白符,例如:

location / {
    trim on;
    trim_js on;
    trim_css on;
}

 

7、ngx_http_headers_module模塊,支持根據Content-Type來設置過期時間,例如:

expires_by_types       24h text/html;
    expires_by_types       modified +24h text/xml;
    expires_by_types       @15h30m text/xml;
    expires_by_types       0 text/xml;
    expires_by_types       -1 text/xml;
    expires_by_types       epoch text/xml;

 

8、ngx_http_limit_req_module模塊,限制訪問

9、擴展了ngx_http_log_module模塊,支持syslog和pipe;

 

 


 

 

Openresty 簡介

 

openresty官方網站:http://openresty.org/cn/index.html

agentzh自己對openresty的介紹:http://blog.zoomquiet.org/pyblosxom/oss/openresty-intro-2012-03-06-01-13.html

 

agentzh(章亦春)的openresty開源項目(基於nginx),通過各種插件、模塊,極大的擴展了nginx能幹的事情,而lua擴展更是可以用來定製非常複雜的業務邏輯。作者給nginx賦予的這些新的特性,使openresty在業務開發上變得更加簡單,對程序員更加友好,開發者可以在不需要對nginx源碼熟悉的情況下就直接使用一些高級特性,比如併發subrequest、dns異步解析、對第三方數據庫(如mysql、redis、memcached)等的訪問。

 

先簡單看一下openresty擴展的模塊:

 

 

  • LuaJIT                                       luaJIT解釋器

  • StandardLuaInterpreter               標準lua解釋器

  • LuaCjsonLibrary                          json庫

  • LuaNginxModule                       lua接口庫 (該模塊本身用C實現)

  • LuaRdsParserLibrary                   rds格式解析

  • LuaRedisParserLibrary                 redis響應解析庫

  • LuaRestyCoreLibrary                   LuaNginxModule模塊的lua實現

  • LuaRestyDNSLibrary                   dns解析庫

  • LuaRestyLockLibrary                

  • LuaRestyLrucacheLibrary             LRU cache庫

  • LuaRestyMemcachedLibrary     memcached訪問接口

  • LuaRestyMySQLLibrary                mysql訪問接口

  • LuaRestyRedisLibrary                  redis訪問接口

  • LuaRestyStringLibrary                 一些hash函數的接口

  • LuaRestyUploadLibrary              

  • LuaRestyUpstreamHealthcheckLibrary

  • LuaRestyWebSocketLibrary           ws協議解析庫

  • LuaUpstreamNginxModule             擴展了對upstream的支持    

 

 

瀏覽一下上述模塊,有幾個特點:

1、通過upstream機制已經可以支持對mysql、redis、postgreSQL、memcached 等數據庫的訪問(全都是異步無阻塞的);

2、跟lua擴展有關的模塊,提供給lua腳本調用的庫,api非常豐富,涉及各種的操作;

 


 

ngx_lua 模塊

 ngx_lua模塊的原理:

1、每個worker(工作進程)創建一個Lua VM,worker內所有協程共享VM;
2、將Nginx I/O原語封裝後注入 Lua VM,允許Lua代碼直接訪問;
3、每個外部請求都由一個Lua協程處理,協程之間數據隔離;
4、Lua代碼調用I/O操作等異步接口時,會掛起當前協程(並保護上下文數據),而不阻塞worker;
5、I/O等異步操作完成時還原相關協程上下文數據,並繼續運行;

 

ngx_lua 模塊提供的指令和API等:

指令名稱說明
lua_use_default_type是否使用default_type指令定義的Content-Type默認值
lua_code_cache*_by_lua_file文件是否cache
lua_regex_cache_max_entries
lua_regex_match_limit
lua_package_path用Lua寫的lua外部庫路徑(.lua文件)
lua_package_cpath用C寫的lua外部庫路徑(.so文件)
init_by_luamaster進程啓動時掛載的lua代碼
init_by_lua_file
init_worker_by_luaworker進程啓動時掛載的lua代碼,常用來執行一些定時器任務
init_worker_by_lua_file
set_by_lua設置變量
set_by_lua_file
content_by_luahandler模塊
content_by_lua_file
rewrite_by_lua
rewrite_by_lua_file
access_by_lua
access_by_lua_file
header_filter_by_luaheader filter模塊
header_filter_by_lua_file
body_filter_by_luabody filter模塊,ngx.arg[1]代表輸入的chunk,ngx.arg[2]代表當前chunk是否爲last
body_filter_by_lua_file
log_by_lua
log_by_lua_file
lua_need_request_body是否讀請求體,跟ngx.req.read_body()函數作用類似
lua_shared_dict創建全局共享的table(多個worker進程共享)
lua_socket_connect_timeoutTCP/unix 域socket對象connect方法的超時時間
lua_socket_send_timeoutTCP/unix 域socket對象send方法的超時時間
lua_socket_send_lowat設置cosocket send buffer的low water值
lua_socket_read_timeoutTCP/unix 域socket對象receive方法的超時時間
lua_socket_buffer_sizecosocket讀buffer大小
lua_socket_pool_sizecosocket連接池大小
lua_socket_keepalive_timeoutcosocket長連接超時時間
lua_socket_log_errors是否打開cosocket錯誤日誌
lua_ssl_ciphers
lua_ssl_crl
lua_ssl_protocols
lua_ssl_trusted_certificate
lua_ssl_verify_depth
lua_http10_buffering
rewrite_by_lua_no_postpone
lua_transform_underscores_in_response_headers
lua_check_client_abort是否監視client提前關閉請求的事件,如果打開監視,會調用ngx.on_abort()註冊的回調
lua_max_pending_timers
lua_max_running_timers

 

 

 

table說明
ngx.arg指令參數,如跟在content_by_lua_file後面的參數
ngx.var變量,ngx.var.VARIABLE引用某個變量
ngx.ctx請求的lua上下文
ngx.header響應頭,ngx.header.HEADER引用某個頭
ngx.status響應碼


API說明
ngx.log輸出到error.log
print等價於 ngx.log(ngx.NOTICE, ...)
ngx.send_headers發送響應頭
ngx.headers_sent響應頭是否已發送
ngx.resp.get_headers獲取響應頭
ngx.timer.at註冊定時器事件
ngx.is_subrequest當前請求是否是子請求
ngx.location.capture發佈一個子請求
ngx.location.capture_multi發佈多個子請求
ngx.exec
ngx.redirect
ngx.print輸出響應
ngx.say輸出響應,自動添加'\n'
ngx.flush刷新響應
ngx.exit結束請求
ngx.eof
ngx.sleep無阻塞的休眠(使用定時器實現)
ngx.get_phase
ngx.on_abort註冊client斷開請求時的回調函數
ndk.set_var.DIRECTIVE
ngx.req.start_time請求的開始時間
ngx.req.http_version請求的HTTP版本號
ngx.req.raw_header請求頭(包括請求行)
ngx.req.get_method請求方法
ngx.req.set_method請求方法重載
ngx.req.set_uri請求URL重寫
ngx.req.set_uri_args
ngx.req.get_uri_args獲取請求參數
ngx.req.get_post_args獲取請求表單
ngx.req.get_headers獲取請求頭
ngx.req.set_header
ngx.req.clear_header
ngx.req.read_body讀取請求體
ngx.req.discard_body扔掉請求體
ngx.req.get_body_data
ngx.req.get_body_file
ngx.req.set_body_data
ngx.req.set_body_file
ngx.req.init_body
ngx.req.append_body
ngx.req.finish_body
ngx.req.socket
ngx.escape_uri字符串的url編碼
ngx.unescape_uri字符串url解碼
ngx.encode_args將table編碼爲一個參數字符串
ngx.decode_args將參數字符串編碼爲一個table
ngx.encode_base64字符串的base64編碼
ngx.decode_base64字符串的base64解碼
ngx.crc32_short字符串的crs32_short哈希
ngx.crc32_long字符串的crs32_long哈希
ngx.hmac_sha1字符串的hmac_sha1哈希
ngx.md5返回16進制MD5
ngx.md5_bin返回2進制MD5
ngx.sha1_bin返回2進制sha1哈希值
ngx.quote_sql_strSQL語句轉義
ngx.today返回當前日期
ngx.time返回UNIX時間戳
ngx.now返回當前時間
ngx.update_time刷新時間後再返回
ngx.localtime
ngx.utctime
ngx.cookie_time返回的時間可用於cookie值
ngx.http_time返回的時間可用於HTTP頭
ngx.parse_http_time解析HTTP頭的時間
ngx.re.match
ngx.re.find
ngx.re.gmatch
ngx.re.sub
ngx.re.gsub
ngx.shared.DICT
ngx.shared.DICT.get
ngx.shared.DICT.get_stale
ngx.shared.DICT.set
ngx.shared.DICT.safe_set
ngx.shared.DICT.add
ngx.shared.DICT.safe_add
ngx.shared.DICT.replace
ngx.shared.DICT.delete
ngx.shared.DICT.incr
ngx.shared.DICT.flush_all
ngx.shared.DICT.flush_expired
ngx.shared.DICT.get_keys
ngx.socket.udp
udpsock:setpeername
udpsock:send
udpsock:receive
udpsock:close
udpsock:settimeout
ngx.socket.tcp
tcpsock:connect
tcpsock:sslhandshake
tcpsock:send
tcpsock:receive
tcpsock:receiveuntil
tcpsock:close
tcpsock:settimeout
tcpsock:setoption
tcpsock:setkeepalive
tcpsock:getreusedtimes
ngx.socket.connect
ngx.thread.spawn
ngx.thread.wait
ngx.thread.kill
coroutine.create
coroutine.resume
coroutine.yield
coroutine.wrap
coroutine.running
coroutine.status
ngx.config.debug編譯時是否有 --with-debug選項
ngx.config.prefix編譯時的 --prefix選項
ngx.config.nginx_version返回nginx版本號
ngx.config.nginx_configure返回編譯時 ./configure的命令行選項
ngx.config.ngx_lua_version返回ngx_lua模塊版本號
ngx.worker.exiting當前worker進程是否正在關閉(如reload、shutdown期間)
ngx.worker.pid返回當前worker進程的pid






常量說明
Core constantsngx.OK (0)
ngx.ERROR (-1)
ngx.AGAIN (-2)
ngx.DONE (-4)
ngx.DECLINED (-5)
ngx.nil
HTTP method constantsngx.HTTP_GET
ngx.HTTP_HEAD
ngx.HTTP_PUT
ngx.HTTP_POST
ngx.HTTP_DELETE
ngx.HTTP_OPTIONS  
ngx.HTTP_MKCOL    
ngx.HTTP_COPY      
ngx.HTTP_MOVE     
ngx.HTTP_PROPFIND 
ngx.HTTP_PROPPATCH 
ngx.HTTP_LOCK 
ngx.HTTP_UNLOCK    
ngx.HTTP_PATCH   
ngx.HTTP_TRACE  
HTTP status constantsngx.HTTP_OK (200)
ngx.HTTP_CREATED (201)
ngx.HTTP_SPECIAL_RESPONSE (300)
ngx.HTTP_MOVED_PERMANENTLY (301)
ngx.HTTP_MOVED_TEMPORARILY (302)
ngx.HTTP_SEE_OTHER (303)
ngx.HTTP_NOT_MODIFIED (304)
ngx.HTTP_BAD_REQUEST (400)
ngx.HTTP_UNAUTHORIZED (401)
ngx.HTTP_FORBIDDEN (403)
ngx.HTTP_NOT_FOUND (404)
ngx.HTTP_NOT_ALLOWED (405)
ngx.HTTP_GONE (410)
ngx.HTTP_INTERNAL_SERVER_ERROR (500)
ngx.HTTP_METHOD_NOT_IMPLEMENTED (501)
ngx.HTTP_SERVICE_UNAVAILABLE (503)
ngx.HTTP_GATEWAY_TIMEOUT (504) 
Nginx log level constantsngx.STDERR
ngx.EMERG
ngx.ALERT
ngx.CRIT
ngx.ERR
ngx.WARN
ngx.NOTICE
ngx.INFO
ngx.DEBUG

======專注高性能web服務器架構和開發=====


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章