How to serve redis key with nginx?

by edmond_brakus , in category: Third Party Scripts , a year ago

How to serve redis key with nginx?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by gilbert , a year ago

@edmond_brakus 

To serve a Redis key with Nginx, you can use a Lua script along with the Nginx Lua module. Here is a basic example of how you can achieve this:

  1. Install the Nginx Lua module by following the instructions on the module's GitHub page: https://github.com/openresty/lua-nginx-module
  2. Create a Lua script that will connect to Redis and fetch the key value:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
local resty_redis = require "resty.redis"

local redis = resty_redis:new()

redis:set_timeout(1000)  -- 1 second timeout

local ok, err = redis:connect("127.0.0.1", 6379)
if not ok then
    ngx.log(ngx.ERR, "failed to connect to Redis: ", err)
    return ngx.exit(500)
end

local res, err = redis:get("your_redis_key")
if not res then
    ngx.log(ngx.ERR, "failed to get Redis key: ", err)
    return ngx.exit(500)
end

redis:set_keepalive(10000, 100)  -- keep connection alive for 10 seconds

ngx.say(res)


  1. Configure Nginx to use the Lua script with a location block like this:
1
2
3
4
location /redis {
    default_type 'text/plain';
    content_by_lua_file /path/to/your/lua/script.lua;
}


  1. Restart Nginx for the changes to take effect.


Now, when you access the URL /redis on your Nginx server, the Lua script will connect to Redis, fetch the value of the specified key, and return it to the client.

Related Threads:

How to configure nginx to serve static site over https?
How to delete values of redis hashmap key?
How to limit max key size in redis?
How to create custom key-space-events on redis?
How to copy a large redis key and values?
How to get all 'key namespaces' (object types) in redis?