简体   繁体   English

在 lua 上用 redis 拉表

[英]pulling table with redis on lua

I'm running LUA on Nginx.我在 Nginx 上运行 LUA。 I decided to fetch some variables via Redis.我决定通过 Redis 获取一些变量。 I am using a table on lua.我正在使用 lua 上的表。 It is like this;是这样的;

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

I'm printing on Nginx;我在 Nginx 上打印;

1.1.1.1
1.1.1.2

I want to keep the values here on Redis and not on Lua.我想将值保留在 Redis 上,而不是 Lua 上。 My redis: http://prntscr.com/10sv3ln我的 redis: http://prntscr.com/10sv3ln

My Lua command;我的 Lua 命令;

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

I'm printing on Nginx;我在 Nginx 上打印;

{"1.1.1.1","1.1.1.2",}

Its data does not come as a table and functions do not work.它的数据不是表格形式,功能也不起作用。 How can I call this data like local ip_blacklist?如何将这些数据称为本地 ip_blacklist?

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

Redis Hashes are maps between string fields and string values Redis 哈希是字符串字段和字符串值之间的映射

You cannot store a Lua table as a hash value directly.您不能将 Lua 表直接存储为 hash 值。 As I understand, you have stored a literal string {"1.1.1.1","1.1.1.2",} using RedisInsight, but it doesn't work that way.据我了解,您使用 RedisInsight 存储了一个文字字符串{"1.1.1.1","1.1.1.2",} ,但它不起作用。

You can use JSON for serialization:您可以使用 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
        }
    }
}

Output: Output:

table
1.1.1.1
1.1.1.2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM