[記錄點滴] OpenResty中Redis操作總結


[記錄點滴] OpenResty中Redis操作總結

0x00 摘要

本文總結了在OpenResty中的操作,與大家分享,涉及知識點為Openresty, Lua, Redis。

0x01 操作記錄

操作使用 db.redis.redis_iresty。

1.1 初始化 & 基礎函數

set $redis_host 127.0.0.1;  -- In nginx.conf

local config = {
            ip = ngx.var.redis_host,
            port = 5379,
            db_index = 0,
            password = "xxxxx" 
            }
return config

local REDIS = require "db.redis.redis_iresty"
local REDIS_INSTANCE = REDIS:new(config)

function is_empty(t)
    return not t or t == nil or t == null or t == ngx.null    
end

1.2 流水線操作

REDIS_INSTANCE:init_pipeline()  
-- 這里可以寫具體相關操作
local respTable, err = REDIS_INSTANCE:commit_pipeline()  
if _.isEmpty(respTable) then 
  respTable = {} --比如默認值 -- 如果什么都找不到,redis 就返回 {}
end  

1.3 list操作

-- 將一個或多個值插入到列表頭部
REDIS_INSTANCE:lpush(LIST, id)

1.4 set操作

-- 向集合添加一個或多個成員
if 1 == REDIS_INSTANCE:sadd(SET_id, user_id) then ...
  
-- 移除集合中一個或多個成員  
if 1 == REDIS_INSTANCE:srem(SET_id, user_id) then ...

1.5 Hash操作

-- 為哈希表 key 中的指定字段的整數值加上增量 increment,具體增減由最后一個參數正負值決定
REDIS_INSTANCE:hincrby(HASH, HASH_KEY, -1);

-- 獲取所有給定字段的值
local keys = {"ID", "name"}
local resp, err = REDIS_INSTANCE:hmget( HASH,  unpack(hash_keys))
if resp == nil then ...

-- 獲取在哈希表中指定 key 的所有字段和值
local resp, err = REDIS_INSTANCE:hgetall(hash_key) 
if is_empty(resp) then ...

-- 將哈希表 key 中的字段 field 的值設為 value 
REDIS_INSTANCE:hset(HASH, HASH_KEY, 5);

1.6 zset操作

-- 移除有序集合中的一個或多個成員
REDIS_INSTANCE:zrem(ZSET, id); 

-- 有序集合中對指定成員的分數加上增量 increment
REDIS_INSTANCE:zincrby(ZSET, 1, id)

-- 向有序集合添加一個或多個成員,或者更新已存在成員的分數
REDIS_INSTANCE:zadd(ZSET, tonumber(user_id), id); 

-- 返回有序集合中指定成員的索引
if null ~= REDIS_INSTANCE:zrank(ZSET, id) then ...

-- 獲取有序集合的成員數
total_items, err = REDIS_INSTANCE:zcard(ZSET) 

-- 返回有序集中指定區間內的成員,通過索引,分數從高到低
resp, err = REDIS_INSTANCE:zrevrange(ZSET, start, finish) 

-- 通過索引區間返回有序集合指定區間內的成員
resp, err = REDIS_INSTANCE:zrange(ZSET, start, finish) 

-- 返回有序集中指定分數區間內的成員,分數從高到低排序
resp, err = REDIS_INSTANCE:zrevrangebyscore(key, max, min, 'LIMIT', offset, count) 

-- 通過分數返回有序集合指定區間內的成員
resp, err = REDIS_INSTANCE:zrangebyscore(key, min, max, 'LIMIT', offset, count) 

1.7 String操作

-- 刪除
local resp, err = REDIS_INSTANCE:del(key)    

-- 獲取指定 key 的值
local resp, err = REDIS_INSTANCE:get(key) 

-- 獲取所有(一個或多個)給定 key 的值
local keys = {"ID", "name"}
resp, err = REDIS_INSTANCE:mget(unpack(keys))


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM