OpenResty 初探

OpenResty 是一个基于Nginx 与Lua 的高性能Web 平台,其内部集成了大量精良的Lua 库、第三方模块以及大多数的依赖项。

安装

Centos 为例:

1
2
3
4
5
6
7
8
9
# add the yum repo:
wget https://openresty.org/package/centos/openresty.repo
sudo mv openresty.repo /etc/yum.repos.d/

# update the yum index:
sudo yum check-update

# install
sudo yum install openresty

运行 openresty -h 查看帮助信息

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
nginx version: openresty/1.17.8.2
Usage: nginx [-?hvVtTq] [-s signal] [-c filename] [-p prefix] [-g directives]

Options:
-?,-h : this help
-v : show version and exit
-V : show version and configure options then exit
-t : test configuration and exit
-T : test configuration, dump it and exit
-q : suppress non-error messages during configuration testing
-s signal : send signal to a master process: stop, quit, reopen, reload
-p prefix : set prefix path (default: /usr/local/openresty/nginx/)
-c filename : set configuration file (default: conf/nginx.conf)
-g directives : set global directives out of configuration file

可以看到nginx默认路径为:/usr/local/openresty/nginx/。如果时从nginx迁移到openresty,只需要将相关配置复制过来即可。

注意:openresty 内部 nginx 版本和 openresty 版本差不多。openresty/1.17.8.2对应nginx版本1.17。

使用 Redis 示例

nginx.conf http模块增加:

1
2
3
4
5
6
init_by_lua '
        json = require "cjson";
        redis = require "resty.redis"
    ';

include /usr/local/openresty/nginx/conf/conf.d/*.conf;

test.conf

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
server {
    listen       8080;
    server_name  localhost;

    #charset koi8-r;

    #access_log  logs/host.access.log  main;

    set $redis_host "127.0.0.1";
    set $redis_port "6379";
    set $redis_pass "123";

    location / {
        root   html;
        index  index.html index.htm;
    }

		location /lua {
	        default_type 'text/html';
	        content_by_lua 'ngx.say("hello world")';
	  }

    location = /kvs
    {
        content_by_lua '
           local red = redis:new()
           local ok, err = red:connect(ngx.var.redis_host, ngx.var.redis_port)
           if not ok then
                ngx.say("failed to connect: ", err)
                return
           end
           local ok, err = red:auth(ngx.var.redis_pass)
           if not ok then
                ngx.say("failed to auth: ", err)
                return
           end

           local keys, err = red:keys("*")
           ngx.header.content_type = "text/plain"
           local kvs = {}
           for i, key in ipairs(keys) do
             kvs[key] = red:get(key)
           end
           ngx.say(json.encode(kvs))
        ';
    }
}

解释:

  • 访问 /lua 即输出 hello world
  • 访问 /kvs 即列出redis db0 所有key:val

参考:

updatedupdated2020-08-062020-08-06
Load Comments?