pulling table with redis on lua

715 Views Asked by At

I'm running LUA on Nginx. I decided to fetch some variables via Redis. I am using a table on lua. It is like this;

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

I'm printing on Nginx;

1.1.1.1
1.1.1.2

I want to keep the values here on Redis and not on Lua. My redis : http://prntscr.com/10sv3ln

My Lua command;

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

I'm printing on 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?

1

There are 1 best solutions below

1
On BEST ANSWER

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

Redis Hashes are maps between string fields and string values

You cannot store a Lua table as a hash value directly. 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.

You can use JSON for serialization:

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:

table
1.1.1.1
1.1.1.2