Keyval#

该模块允许使用来自“键值”对的变量值,这些值存储在共享内存或 Redis 存储中。

加载模块#

要使用该模块,必须在 main{} 的上下文中加载它:

load_module modules/ngx_http_keyval_module.so;

配置示例#

keyval_zone zone=one:32k;
keyval $arg_key $value zone=one;

server {
    listen 80;
    server_name localhost;

    location /get {
        return 200 "key '$arg_key' has value = '$value'\\n";
    }

    location /set {
        set $value $arg_value;
        return 200 "'$arg_key' key added with '$arg_value' value\\n";
    }
}

在共享内存区域 'one' 中添加和修改条目是通过将值分配给变量 $value 来完成的。键的值存储在变量 $arg_key 中。在此配置中,这是指令 set

set $value $arg_value;

演示#

让我们通过请求定义一些值:

$ curl "localhost/set/?key=one&value=TextForKeyOne"

  'one' key added with 'TextForKeyOne' value
$ curl "localhost/set/?key=two&value=TextForKeyTwo"

  'two' key added with 'TextForKeyTwo' value

让我们检查一下:

$ curl "localhost/get/?key=one"

  key 'one' has value = 'TextForKeyOne'
$ curl "localhost/get/?key=two"

  key 'two' has value = 'TextForKeyTwo'

使用 Redis#

让我们修改配置,以便在 Redis 存储中存储“键值”对:

keyval_zone_redis zone=oneredis;
keyval $arg_key $value zone=oneredis;

server {
    listen 80;
    server_name localhost;

    location /get {
        return 200 "key '$arg_key' has value = '$value'\\n";
    }

    location /set {
        set $value $arg_value;
        return 200 "'$arg_key' key added with '$arg_value' value\\n";
    }
}

让我们通过请求将一个“键值”对添加到 Redis 存储中:

$ curl "localhost/set/?key=one&value=TextForKeyOne"

  'one' key added with 'TextForKeyOne' value

同样的操作也可以通过 Redis 本身完成:

$ redis-cli

  127.0.0.1:6379> set oneredis:two 'text for key two'

  OK

  127.0.0.1:6379>

让我们检查一下:

$ redis-cli --scan

  "oneredis:one"
  "oneredis:two"
$ curl "localhost/get/?key=one"

  key 'one' has value = 'TextForKeyOne'
$ curl "localhost/get/?key=two"

  key 'two' has value = 'text for key two'

附加信息#

指令和源代码的完整描述可在以下网址找到: kjdev/nginx-keyval.