下載解壓到lualib目錄以後,就算安裝完成了,下面來試用一下,更詳細的能夠到github上面看文檔css
conf/nginx.confhtml
worker_processes 1; error_log logs/error.log notice; events { worker_connections 1024; } http { lua_package_path "/Users/john/opensource/openresty-web-dev/demo9/lua/?.lua;/Users/john/opensource/openresty-web-dev/demo9/lualib/?.lua;/usr/local/openresty/lualib/?.lua"; server { listen 80; server_name localhost; lua_code_cache off; location / { root lua; # 這個很重要,否則模板文件會找不到 default_type "text/html; charset=utf-8"; content_by_lua_file lualib/lite/mvc.lua; } location ~ ^/js/|^/css/|\.html { root html; } } }
lua/index.lua前端
local template = require "resty.template" local _M = {} function _M.index() local model = {title = "hello template", content = "<h1>content</h1>"} -- 一、外部模板文件 -- template.render('tpl/index.html', model) -- 二、內嵌模板代碼 template.render([[ <html> <head> <meta charset="UTF-8"> <title>{{ title }}</title> </head> <body> {* content *} </body> </html> ]], model) end return _M
lua/tpl/index.htmljava
<html> <head> <meta charset="UTF-8"> <title>{{title}}</title> </head> <body> {* content *} </body> </html>
跟spring mvc 有點像,指定一個 view , model,而後就能夠渲染了,模板語法有不少種,{{ 變量 }} 會進行轉義,{ 不會轉義 },{% lua 代碼 %},跟jsp有點相似,可是很輕量,只有單個文件,更多用法能夠到github上面看。mysql
瀏覽器訪問 http://localhost/index ,輸出contentnginx
至此,服務端渲染就搞定了,已經能夠開發一些常見的web應用,使用openresty來作前端,而後經過http訪問後端的java,也能夠在前端,直接訪問mysql、redis,只不過mysql只能作一些簡單的非事務操做,由於lua-resty-mysql這個庫不支持事務,我在github上面問過春哥了,固然若是你直接調用存儲過程,把事務放在過程裏面控制的話也能夠,如今你能夠直接寫同步的代碼風格,就能得到高併發、低消耗,非堵塞等各類好處。git
咱們已經用openresty開發了pc版,還有微信版的web應用,已經運行幾個月了,很穩定,上手也簡單,開發的時候不用編譯,直接啓動一個nginx就搞定,部署的時候只須要10幾M的內存,還能夠用openresty作各類事情,高併發api、web防火牆,直接跑在nginx裏面,簡直爽歪歪,有機會跟你們分享。github
示例代碼 參見demo9部分web