1.连接redis集群需要用到llua-resty-redis-cluster模块
github地址:https://github.com/cuiweixie/lua-resty-redis-cluster
下载完成后,只需要用到包中2个文件rediscluster.lua和redis_slot.c
2.将lua-resty-redis-cluster/lib/redis_slot.c 拷贝到 openresty/lualib 目录下
将lua-resty-redis-cluster/lib/resty/rediscluster.lua 拷贝到 openresty/lualib/resty 目录下
3.cd 到 openresty/lualib目录下 执行下面命令进行编译
gcc redis_slot.c -fPIC -shared -o libredis_slot.so
问题:如果出现编译报错:failed to set…
找不到lua.h等文件
解决:应该是lua版本不对,自带的lua应该不好使
方式一:删除自带的lua,一般是/usr/lua和/usr/luac ,删除这两个文件
方式二:yum install lua-devel 下载一个依赖
方式三:自己重新再lua官网下载一个lua,重新安装一个lua(这个很好使)
4.在openresty的lualib目录下 创建文件lua2redis-cluster.lua文件并添加:
local config = {
name = "test",
serv_list = {
{ip="192.168.206.178", port = 7001},
{ip="192.168.206.178", port = 7002},
{ip="192.168.206.178", port = 7003},
{ip="192.168.206.178", port = 7004},
{ip="192.168.206.178", port = 7005},
{ip="192.168.206.178", port = 7006},
},
}
local redis_cluster = require "resty.rediscluster"
local red = redis_cluster:new(config)
for i = 1, 2 do
red:init_pipeline()
red:set("k1", "hello")
red:get("k1")
red:set("k2", "world")
red:get("k2")
local results = red:commit_pipeline()
local cjson = require "cjson"
ngx.say(cjson.encode(results))
end
red:close()
5.将上面的lua2redis-cluster.lua 文件路径添加到 nginx.conf
6.并重启nginx
nginx -s reload
7.测试:
在redis集群任一节点都可以 get k1的值 即说明lua连接redis集群成功