1. 目标
我的目标是:使用redis做分布式缓存;使用lua API来访问redis缓存;使用nginx向客户端提供服务。基于这个目标,自然想到openresty。
2. openresty
第一次接触,理解的不多。感觉就是:1. 把nginx和lua结合起来,使得nginx开发更加方便;2. 提供一些模块,例如memcached、redis、mysql,postgres等等;FIX ME!
3. 失败的尝试:lua-resty-redis + redis集群模式
3.1 lua-resty-redis
lua-resty-redis是openresty(1.9.15.1)的一个组件,简单来说,它提供一个lua语言版的redis API,使用socket(lua sock)和redis通信。使用比较直观:
<pre name="code" class="plain">--连接
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000) -- 1 sec
local ok, err = red:connect("127.0.0.1", 6379)
--set
local res, err = red:set(key, value)
--get
local res, err = red:get(key)
3.2 redis集群部署
在localhost上开启6个redis实例,它们的端口是:7000-7005;其中3个为master,另外3个为slave。
具体配置与部署,见前一篇博客:点击打开链接 第4节。
3.3 试验
3.3.1 安装openresty
# cd /tmp/
# wget https://openresty.org/download/openresty-1.9.15.1.tar.gz
# tar zxvf openresty-1.9.15.1.tar.gz
# cd openresty-1.9.15.1
# yum install pcre-devel.x86_64
# yum install openssl-devel.x86_64
# ./configure --prefix=/usr/local/openresty-1.9.15 --with-luajit
# gmake
# gmake install
3.3.2 创建一个工程(名为objstore)并实现hello world
3.3.2.1 创建目录
# mkdir /var/objstore
# mkdir /var/objstore/lua
# mkdir /var/objstore/lualib
3.3.2.2 lua脚本(hello world)
# vim /var/objstore/lua/hello.lua
ngx.say("hello world!");
3.3.2.3 工程的nginx配置
# vim /var/objstore/objstore.conf
server {
listen 8080;
server_name _;
location /lua {
default_type 'text/html';
lua_code_cache off;
content_by_lua_file /var/objstore/lua/hello.lua;
}
}
3.3.2.4 把工程加入nginx
http {
include mime.types;
default_type application/octet-stream;
+ lua_package_path "/var/objstore/lualib/?.lua;;";
+ lua_package_cpath "/var/objstore/lualib/?.so;;";
+ include /var/objstore/objstore.conf;
3.3.2.5 启动nginx并测试
<pre name="code" class="plain"># /usr/local/openresty-1.9.15/nginx/sbin/nginx
nginx: [alert] lua_code_cache is off; this will hurt performance in /var/objstore/objstore.conf:7
这个alert是因为objstore.conf中把lua_code_cache为off;若设置为off,nginx不缓存lua脚本,每次改变lua代码,不必relo