2014年3月1日 星期六

mac ngx_lua openresty 教學-1 install and hello world

自從開始用cocos2dx 寫lua腳本後,就一直很想把server端也改用lua
最近也買了一台mac,今天花了一晚搞定了這個想法
nginx+lua模組,我一開始是使用homebrew安裝nginx,
接著再裝openresty,各種痛...
所以我後來就把homebrew裝的nginx uninstall掉了。。。

原因是openresty包裡有自帶nginx了

所以我們只需要安裝openresty就可以了~:)
1. 下載http://openresty.org/download/ngx_openresty-1.4.2.7.tar.gz
2. 解開ngx_openresty-1.4.2.7.tar.gz
3. git clone https://github.com/chaoslawful/lua-nginx-module.git
4. cd lua-nginx-module
5. git checkout -b websocket origin/websocket
6. cd ../ngx_openresty-1.4.2.7/bundle
7. rm -Rf ngx_lua-0.8.9
8. ln -s ../../lua-nginx-module ngx_lua-0.8.9
9. cd ..
10. ./configure \
--with-cc-opt="-I/usr/local/include” \
--with-ld-opt="-L/usr/local/lib” \
--with-luajit --prefix=/usr/local 
11. make
12. make install
安装完成后
cd ../
git clone https://github.com/agentzh/lua-resty-websocket.git
拷贝websocket到lualib目录下
cp -r lua-resty-websocket/lib/resty/websocket /usr/local/lualib/resty/

安裝完之後,就要啟動nginx , 不過發現執行nginx 會找不到指令
因為我們安裝的是
openresty,所以要使用openresty才行
openresty -h , 相當於nginx的使用方法

html資料夾在 /usr/local/Cellar/openresty/1.4.2.9/nginx/html
conf檔在 /etc/openresty/nginx.conf

接下來我們要在nginx.conf裡加上一些lua的設定
在http{裡加入
lua_package_path "/usr/local/lualib/resty/websocket/?.lua;;";

在server{裡加入
lua_code_cache off;   <---這一句可以使修改lua檔案時 可以直接更新 , 在nginx重啟時會出現警告提示

把listen 80;修改成
listen 80 default so_keeplive=on;

接著新增以下
location /luatest {
default_type 'text/plain';
content_by_lua_file /usr/local/Cellar/openresty/1.4.2.9/nginx/html/luatest.lua;
}

最後再建立一支luatest.lua 放到上面指定的位置上
該lua程式碼簡單寫上 ngx.say("hello lua") 就行了

最後打開browser 連上 localhost/luatest 就可以看到結果了:)


沒有留言:

張貼留言