Nginx + Lua + Redis

本文介绍了在不支持lua-resty-redis集群模式的情况下,通过Nginx、Lua和Redis2-nginx-module结合一致性hash实现分布式缓存的方法。详细讲述了从openresty的安装、lua脚本的编写到redis集群和非集群模式的试验过程,最终成功实现了数据在不同redis节点的分布。下一步将探讨如何在lua中支持redis集群。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
                
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值