下载解压到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