文章出處
文章列表
這一章主要介紹怎么使用模板,進行后端渲染,主要用到了lua-resty-template這個庫,直接下載下來,放到lualib里面就行了,推薦第三方庫,已經框架都放到lualib目錄里面,lua目錄放項目源碼,比較好管理,可以知道那些是項目的,哪些是第三方庫,可復用的
下載解壓到lualib目錄之后,就算安裝完成了,下面來試用一下,更詳細的可以到github上面看文檔
conf/nginx.conf
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>"}
-- 1、外部模板文件
-- template.render('tpl/index.html', model)
-- 2、內嵌模板代碼
template.render([[
<html>
<head>
<meta charset="UTF-8">
<title>{{ title }}</title>
</head>
<body>
{* content *}
</body>
</html>
]], model)
end
return _M
lua/tpl/index.html
<html>
<head>
<meta charset="UTF-8">
<title>{{title}}</title>
</head>
<body>
{* content *}
</body>
</html>
跟spring mvc 有點像,指定一個 view , model,然后就可以渲染了,模板語法有很多種,{{ 變量 }} 會進行轉義,{* 不會轉義 *},{% lua 代碼 %},跟jsp有點類似,但是很輕量,只有單個文件,更多用法可以到github上面看。
瀏覽器訪問 http://localhost/index ,輸出content
至此,服務端渲染就搞定了,已經可以開發一些常見的web應用,使用openresty來做前端,然后通過http訪問后端的java,也可以在前端,直接訪問mysql、redis,只不過mysql只能做一些簡單的非事務操作,因為lua-resty-mysql這個庫不支持事務,我在github上面問過春哥了,當然如果你直接調用存儲過程,把事務放在過程里面控制的話也可以,現在你可以直接寫同步的代碼風格,就能獲得高并發、低消耗,非堵塞等各種好處。
我們已經用openresty開發了pc版,還有微信版的web應用,已經運行幾個月了,很穩定,上手也簡單,開發的時候不用編譯,直接啟動一個nginx就搞定,部署的時候只需要10幾M的內存,還可以用openresty做各種事情,高并發api、web防火墻,直接跑在nginx里面,簡直爽歪歪,有機會跟大家分享。
示例代碼 參見demo9部分
文章列表
全站熱搜