openresty开发系列26--openresty中使用redis模块

在一些高并发的场景中,我们常常会用到缓存技术,现在我们常用的分布式缓存redis是最知名的,

操作redis,我们需要引入redis模块 require "resty.redis";

我们现在做个可以操作redis进行赋值,读值的案例

一)连接redis服务器

---定义 redis关闭连接的方法
local function close_redis(red)  
    if not red then  
        return  
    end  
    local ok, err = red:close()  
    if not ok then  
        ngx.say("close redis error : ", err)  
    end  
end

local redis = require "resty.redis"  --引入redis模块
local red = redis:new()  --创建一个对象,注意是用冒号调用的
--设置超时(毫秒)  
red:set_timeout(1000)
--建立连接  
local ip = "10.11.0.215"  
local port = 6379
local ok, err = red:connect(ip, port)
if not ok then  
    ngx.say("connect to redis error : ", err)  
    return close_redis(red)  
end  
--调用API设置key  
ok, err = red:set("msg", "hello world")  
if not ok then  
    ngx.say("set msg error : ", err)  
    return close_redis(red)  
end  
--调用API获取key值  
local resp, err = red:get("msg")  
if not resp then  
    ngx.say("get msg error : ", err)  
    return close_redis(red)  
end

ngx.say("msg : ", resp)
close_redis(red)

请求结果   msg : hello world

--------------------------------
注意:得到的数据为空处理 ,redis返回的空 为null,所以不能用nil判断,而要用ngx.null判断
if resp == ngx.null then  
    resp = ‘‘  --比如默认值  
end

--------------连接授权的redis-----------------
在redis.conf配置文件 配置认证密码
requirepass redis123

注意:windows 启动redis时,配置redis.windows.conf;并且不能直接 双击redis-server.exe,
如果双击启动,默认不会找此目录下的配置文件;需要指定配置文件
解决方案:
1)cmd窗口中 运行 redis-server.exe redis.windows.conf
2)新建一个bat批处理文件  文件内容 redis-server.exe redis.windows.conf

连接报错set msg error : NOAUTH Authentication required.因为认证出错
在red:connect成功后,调用red:auth认证密码

ok, err = red:auth("redis123")
if not ok then
    ngx.say("failed to auth: ", err)
    return close_redis(red)
end

二)redis连接池

redis的连接是tcp连接,建立TCP连接需要三次握手,而释放TCP连接需要四次握手,而这些往返时延仅需要一次,
以后应该复用TCP连接,此时就可以考虑使用连接池,即连接池可以复用连接。
我们需要把close_redis函数改造一下

local function close_redis(red)  
    if not red then  
        return  
    end  
    --释放连接(连接池实现)  
    local pool_max_idle_time = 10000 --毫秒  
    local pool_size = 100 --连接池大小  
    local ok, err = red:set_keepalive(pool_max_idle_time, pool_size)  
    if not ok then  
        ngx.say("set keepalive error : ", err)  
    end
end

即设置空闲连接超时时间防止连接一直占用不释放;设置连接池大小来复用连接。
注意:
1、连接池是每Worker进程的,而不是每Server的;
2、当连接超过最大连接池大小时,会按照LRU算法回收空闲连接为新连接使用;
3、连接池中的空闲连接出现异常时会自动被移除;
4、连接池是通过ip和port标识的,即相同的ip和port会使用同一个连接池(即使是不同类型的客户端);
5、连接池第一次set_keepalive时连接池大小就确定下了,不会再变更;

注意:我们如何知道,redis连接对象是从连接池中获取的,还是新创建的连接呢??

使用 red:get_reused_times --->得到此连接被使用的次数

如果当前连接不是从内建连接池中获取的,该方法总是返回 0 ,也就是说,该连接还没有被使用过。

如果连接来自连接池,那么返回值永远都是非零。所以这个方法可以用来确认当前连接是否来自池子。

连接优化

采用连接池,连接带认证的redis

---定义 redis关闭连接的方法
local function close_redis(red)  
    if not red then  
        return  
    end  
    --释放连接(连接池实现)  
    local pool_max_idle_time = 10000 --毫秒  
    local pool_size = 100 --连接池大小  
    local ok, err = red:set_keepalive(pool_max_idle_time, pool_size)  
    if not ok then  
        ngx.say("set keepalive error : ", err)  
    end  
end

local redis = require "resty.redis"  --引入redis模块
local red = redis:new()  --创建一个对象,注意是用冒号调用的
--设置超时(毫秒)  
red:set_timeout(1000)
--建立连接  
local ip = "10.11.0.215"  
local port = 6379
local ok, err = red:connect(ip, port)
if not ok then  
    ngx.say("connect to redis error : ", err)  
    return close_redis(red)  
end

local count, err = red:get_reused_times()
if 0 == count then ----新建连接,需要认证密码
    ok, err = red:auth("redis123")
    if not ok then
        ngx.say("failed to auth: ", err)
        return
    end
elseif err then  ----从连接池中获取连接,无需再次认证密码
    ngx.say("failed to get reused times: ", err)
    return
end

--调用API设置key  
ok, err = red:set("msg", "hello world333333333")  
if not ok then  
    ngx.say("set msg error : ", err)  
    return close_redis(red)  
end  
--调用API获取key值  
local resp, err = red:get("msg")  
if not resp then  
    ngx.say("get msg error : ", err)  
    return close_redis(red)  
end

ngx.say("msg : ", resp)
close_redis(red)

=======================================

注意:连接池使用过程中,业务代码有select方法,会导致数据错乱

ok, err = red:select(1)  --->选择db
if not ok then
    ngx.say("failed to select db: ", err)
    return
end

如:
A业务使用了db1,所以使用了 select(1);

B业务使用默认的db0,select(0)遗漏

但A,B业务共用了连接池,很有可能 B业务拿到的 A业务使用的连接,而此连接操作的数据库db1;
而B业务中代码没有指定select数据库,所以B业务操作数据到了db1中;导致数据错乱

原文地址:https://www.cnblogs.com/reblue520/p/11434278.html

时间: 2024-08-30 03:56:38

openresty开发系列26--openresty中使用redis模块的相关文章

openresty开发系列16--lua中的控制结构if-else/repeat/for/while

openresty开发系列16--lua中的控制结构if-else/repeat/for/while 一)条件 - 控制结构 if-else if-else 是我们熟知的一种控制结构.Lua 跟其他语言一样,提供了 if-else 的控制结构. 1)单个 if 分支 型 if 条件 then --body end 条件为真 ,执行if中的body ----------------------- x = 10 if x > 0 then print("分支一") end ----

pycharm中使用redis模块入门

数据缓存系统:1:mongodb:是直接持久化,直接存储于硬盘的缓存系统2:redis: 半持久化,存储于内存和硬盘3:memcache:数据只能存储在内存里的缓存系统 redis是一个key-value存储系统,支持的value类型:string,list,set,zset(有序集合),hash(哈希类型),这些数据类型都支持:push/pop,add/remove及取交集并集和差集.这些操作都是原子性的. pyhcarm中安装redis模块 这里我们以python3为例 在cmd里输入 pi

openresty开发系列24--openresty中lua的引入及使用

openresty 引入 lua 一)openresty中nginx引入lua方式 1)xxx_by_lua   --->字符串编写方式  2) xxx_by_lua_block ---->代码块方式  3) xxx_by_lua_file  ---->直接引用一个lua脚本文件 我们案例中使用内容处理阶段,用content_by_lua演示 -----------------编辑nginx.conf----------------------- 第一种:content_by_lua l

openresty开发系列25--openresty中使用json模块

web开发过程中,经常用的数据结构为json,openresty中封装了json模块,我们看如何使用 一)如何引入cjson模块,需要使用requirelocal json = require("cjson") json.encode 将表格数据编码为 JSON 字符串格式:jsonString = json.encode(表格对象)用法示例: table 包含哈希键值对 和 数组键值对 -------------------test.lua-------------- 1)table

openresty开发系列1--网关API架构及选型

微服务架构在项目中的应用越来越多,我们知道在微服务架构风格中,一个大应用被拆分成为了多个小的服务系统提供出来,这些小的系统他们可以自成体系,也就是说这些小系统可以拥有自己的数据库,框架甚至语言等,这些小系统通常以提供 Rest Api 风格的接口来被 H5, Android, IOS 以及第三方应用程序调用.但是在UI上进行展示的时候,我们通常需要在一个界面上展示很多数据,这些数据可能来自于不同的微服务中,举个例子.    在一个电商系统中,查看一个商品详情页,这个商品详情页包含商品的标题,价格

openresty开发系列20--lua的时间操作

在 Lua 中,函数 time.date 和 difftime 提供了所有的日期和时间功能.在 OpenResty 的世界里,不推荐使用这里的标准时间函数,因为这些函数通常会引发不止一个昂贵的系统调用,同时无法为 LuaJIT JIT 编译,对性能造成较大影响.推荐使用 ngx_lua 模块提供的带缓存的时间接口,如 ngx.today, ngx.time, ngx.utctime, ngx.localtime, ngx.now, ngx.http_time,以及 ngx.cookie_time

openresty开发系列21--lua的模块

从lua5.1开始,Lua 加入了标准的模块管理机制,Lua 的模块是由变量.函数等已知元素组成的 table, 因此创建一个模块很简单,就是创建一个 table,然后把需要导出的常量.函数放入其中,最后返回这个 table 就行. 一)模块定义 模块的文件名 和 模块定义引用名称要一致 -- 文件名为 model.lua-- 定义一个名为 model 的模块model = {} -- 定义一个常量model.constant = "这是一个常量" -- 定义一个函数function

openresty开发系列3--nginx的平滑升级

nginx服务器从低版本升级为高版本,如果强行停止服务,会影响正在运行的进程. 平滑升级不会停掉正在运行中的进程,这些进程会继续处理请求.但不会接受新请求,这些老的进程在处理完请求之后会停止.此平滑升级过程中,新开的进程会被处理. 一)平滑升级进入nginx可执行程序的目录     #  cd /usr/local/nginx/sbin/     # sbin/nginx -v       nginx version: nginx/1.13.0    #查看nginx版本 1)下载高版本ngin

openresty开发系列15--lua基础语法4表table和运算符

lua中的表table 一)table (表)Table 类型实现了一种抽象的"关联数组".即可用作数组,也可以用作map.lua中没有数组和map,都是用table这个类型 --数组java   int[] intArr = new int[]{1,2,3,4,5,6};intArr[0]intArr[1]--map----> key value HashMap mapmap.add(key,value) -- 初始化表mytable = {} -- 指定值mytable[1]