openresty使用lua库文件

上一篇文章中 我们对 openresty 有了一个初步的认识,我们用到了自定义的 lua 模块。实际上 openresty 提供了很丰富的lua模块。让我们在实现某些场景的时候更加方便。可以在 openresty 安装目录下的 lualib 目录下看到很多已经存在的 lua文件如下:

[root@zk03 openresty]# cd lualib
[root@zk03 lualib]# ll
总用量 128
-rwxr-xr-x. 1 root root 126744 1月  29 04:50 cjson.so
drwxr-xr-x. 3 root root    174 1月  29 04:50 ngx
drwxr-xr-x. 2 root root     23 1月  29 04:50 rds
drwxr-xr-x. 2 root root     23 1月  29 04:50 redis
drwxr-xr-x. 8 root root   4096 1月  29 04:50 resty
[root@zk03 lualib]# cd ngx
[root@zk03 ngx]# ll
总用量 48
-rw-r--r--. 1 root root 5596 1月  29 04:50 balancer.lua
-rw-r--r--. 1 root root 1718 1月  29 04:50 base64.lua
-rw-r--r--. 1 root root 3070 1月  29 04:50 errlog.lua
-rw-r--r--. 1 root root 3728 1月  29 04:50 ocsp.lua
-rw-r--r--. 1 root root 1444 1月  29 04:50 process.lua
-rw-r--r--. 1 root root 7048 1月  29 04:50 re.lua
-rw-r--r--. 1 root root  365 1月  29 04:50 resp.lua
-rw-r--r--. 1 root root 3574 1月  29 04:50 semaphore.lua
drwxr-xr-x. 2 root root   25 1月  29 04:50 ssl
-rw-r--r--. 1 root root 7158 1月  29 04:50 ssl.lua

比如 resty目录下的 redis.lua 和 mysql.lua 可以操作redis 和mysql 数据库。
我们这里演示通过redis.lua 操作redis
修改配置文件(本文配置文件上一篇文章基础上进行修改 ,有疑问请参考上一篇文章)
编写lua脚本时一定要注意很容易出错。

[root@zk03 openresty]# vi demo/conf/nginx.conf
worker_processes 1;
error_log logs/error.log;
events {
   worker_connections 1024;
}
http {
  lua_package_path '$prefix/lualib/?.lua;;';
  lua_package_cpath '$prefix/lualib/?.so;;';
  server {
    listen 8888;
    location /demo {
      default_type text/html;
      content_by_lua_block {
        local redisModule=require "resty.redis";
        local redis=redisModule:new();
        redis:set_timeout("1000");
        ngx.say("=====begin connect redis server");
        local ok,err=redis:connect("127.0.0.1",6379);
        if not ok then
           ngx.say("===== connect redis failed");
            return;
        end
        ngx.say("begin set key value");
        ok,err=redis:set("hello","zhang");
        if not ok then
            ngx.say("set key value fail");
            return;
        end 
        ngx.say(" set key value success ");
         redis:close();
      }
    }
  }

访问 http://zk03:8888/demo 可以看到 输出结果如下:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/zhangxm_qz/article/details/87931078