您的位置:首页 > 数据库 > Redis

lua代码连接Centenos7的redis集群

2020-03-05 12:17 1236 查看
1、连接redis集群需要用到llua-resty-redis-cluster模块
2、下载lua-resty-redis-cluster模块
3、复制包中的 redis_slot.c 到openresty安装目录的lualib下,rediscluster.lua到lualib下的resty下(放的位置,代码中能require到就行)
4、编译.c文件成.so 文件
  • .c文件无法在nginx配置文件中引入,所以需要编译成.so文件
  • 语法
gcc SOURCE_FILES -fPIC -shared -o TARGET
  • 执行
[hadoop@slave1 lualib]$  gcc ./redis_slot.c -fPIC -shared -o ./libredis_slot.so

ps:不生成的话,运行后,会在nginx/logs/error.log中提示缺少libredis_slot.so

  • 执行编译时提示错误
[hadoop@slave1 lualib]$  gcc ./redis_slot.c -fPIC -shared -o ./libredis_slot.so./redis_slot.c:1:17: 错误:lua.h:没有那个文件或目录
./redis_slot.c:2:20: 错误:lualib.h:没有那个文件或目录
./redis_slot.c:3:21: 错误:lauxlib.h:没有那个文件或目录
  • 查看当前版本
    [hadoop@slave1 lualib]$ lua -v
    Lua 5.1.4 Copyright © 1994-2008 Lua.org, PUC-Rio

  • 怀疑lua版本问题,升级了下lua版本 升级操作

  • 再次编译

[hadoop@slave1 lualib]$  gcc ./redis_slot.c -fPIC -shared -o ./libredis_slot.so[hadoop@slave1 lualib]$ ls
cjson.so  librestysignal.so  ngx  rds  redis  rediscluster.lua  redis_slot.c  libredis_slot.so  resty  tablepool.lua

编译成功

5、编写Lua脚本代码
[hadoop@slave1 ~]$ vi /opt/apps/openresty/nginx/conf/Lua2RedisTest.lua

local config = {
name = "test",
serv_list = {
{ip="10.211.55.200", port = 7001},
{ip="10.211.55.200", port = 7002},
{ip="10.211.55.200", port = 7003},
{ip="10.211.55.200", port = 7004},
{ip="10.211.55.200", port = 7005},
{ip="10.211.55.200", port = 7006},
},
}
local redis_cluster = require "resty.rediscluster"
local red = redis_cluster:new(config)
for i = 1, 2 do
red:init_pipeline()
red:set("dog", "an animal")
red:get("dog")
red:set("dog", "hello")
red:get("dog")
local results = red:commit_pipeline()
local cjson = require "cjson"
ngx.say(cjson.encode(results))
end
red:close()
6、修改Nginx配置文件信息

listen默认是80 ,根据自己的端口分配情况分配,避免冲突。
content_by_lua_file ,地址指向编写的lua脚本的路径

[hadoop@slave1 ~]$ vi /opt/apps/openresty/nginx/conf/nginx.conf

7、测试
  • 执行
[hadoop@slave1 nginx]$ ./sbin/nginx -s reload
  • 浏览器查看,访问IP:8080,成功
  • 访问成功,日志是这样的

    ps:不好使的话记得看你的日志,查看Redis集群状态
  • 点赞
  • 收藏
  • 分享
  • 文章举报
世界这么大还遇见你 发布了20 篇原创文章 · 获赞 0 · 访问量 132 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: