0

我在 Nginx 上运行 LUA。我决定通过 Redis 获取一些变量。我在lua上使用一张桌子。是这样的;

local ip_blacklist = {
"1.1.1.1",
"1.1.1.2",
}

我在 Nginx 上打印;

1.1.1.1
1.1.1.2

我想将这些值保留在 Redis 上而不是 Lua 上。我的redis:http://prntscr.com/10sv3ln

我的 Lua 命令;

local ip = red:hmget("iplist", "ip_blacklist")

我在 Nginx 上打印;

{"1.1.1.1","1.1.1.2",}

它的数据不是表格形式,功能也不起作用。如何将这些数据称为本地 ip_blacklist?

4

1 回答 1

0

https://redis.io/topics/data-types

Redis 哈希是字符串字段和字符串值之间的映射

您不能将 Lua 表直接存储为哈希值。据我了解,您已经{"1.1.1.1","1.1.1.2",}使用 RedisInsight 存储了一个文字字符串,但它不起作用。

您可以使用 JSON 进行序列化:

server {
    location / {
        content_by_lua_block {
            local redis = require('resty.redis')
            local json = require('cjson.safe')    
              
            local red = redis:new()
            red:connect('127.0.0.1', 6379)

            -- set a string with a JSON array as a hash value; you can use RedisInsight for this step
            red:hset('iplist', 'ip_blacklist', '["1.1.1.1", "1.1.1.2"]')
            
            -- read a hash value as a string (a serialized JSON array)
            local ip_blacklist_json = red:hget('iplist', 'ip_blacklist')
            -- decode the JSON array to a Lua table
            local ip_blacklist = json.decode(ip_blacklist_json)
            
            ngx.say(type(ip_blacklist))
            for _, ip in ipairs(ip_blacklist) do
                ngx.say(ip)
            end
        }
    }
}

输出:

table
1.1.1.1
1.1.1.2
于 2021-03-23T12:23:42.857 回答