|
1 | 1 | 
|
2 | 2 | ### Lua require 相对路径
|
3 | 3 | + [Lua require 相对路径 博客园详解](http://www.cnblogs.com/smallboat/p/5552407.html)
|
4 |
| -+ 亲自试验总结 |
| 4 | ++ 相对路径总结 |
| 5 | + + **当前目录** :`/opt/openresty/nginx/conf/Lua` |
| 6 | + + 注意:如果在当前没有了,以下的代码运行是没有问题的 |
| 7 | + + 就是所有的lua脚本代码全部写在Lua文件夹下面去 |
| 8 | + + 拼接路径:`package.path = package.path ..';..\\?.lua';` |
| 9 | + + require 直接这样应用就是`Lua.functions` |
5 | 10 | + 目录结构
|
6 | 11 | ```
|
7 | 12 | root@tinywan:/opt/openresty/nginx/conf/Lua# pwd
|
|
54 | 59 | root@tinywan:/opt/openresty/nginx/conf/Lua# curl '127.0.0.1:80/api'
|
55 | 60 | Hello
|
56 | 61 | 102
|
57 |
| - ``` |
| 62 | + ``` |
| 63 | ++ 绝对路径总结 |
| 64 | + + 目录结果:`/opt/openresty/nginx/lua/resty` |
| 65 | + + 包路径:`package.path = package.path ..'/opt/openresty/nginx/lua/resty/?.lua;/opt/openresty/lualib/?.lua';` |
| 66 | + + 加载绝对路径的Redis的二次封装库,redis_iresty.lua文件: |
| 67 | + ``` |
| 68 | + package.path = package.path ..'/opt/openresty/nginx/lua/resty/?.lua;/opt/openresty/lualib/?.lua'; |
| 69 | + local redis_c = require "resty.redis" |
| 70 | + local ok, new_tab = pcall(require, "table.new") |
| 71 | + if not ok or type(new_tab) ~= "function" then |
| 72 | + new_tab = function (narr, nrec) return {} end |
| 73 | + end |
| 74 | + ``` |
| 75 | + + Redis的二次封装库的应用,test_redis2.lua文件: |
| 76 | + ``` |
| 77 | + package.path = '/opt/openresty/nginx/lua/?.lua;'; |
| 78 | + local redis = require("resty.redis_iresty") |
| 79 | + local red = redis:new() |
| 80 | + local ok, err = red:set("Redis1999", "Redis is an animal 1999") |
| 81 | + if not ok then |
| 82 | + ngx.say("failed to set dog: ", err) |
| 83 | + return |
| 84 | + end |
| 85 | + ``` |
| 86 | + + nginx.conf 配置文件(注意以下的目录路径和上面的不一样) |
| 87 | + ``` |
| 88 | + location /api { |
| 89 | + lua_code_cache off; |
| 90 | + content_by_lua_file /opt/openresty/nginx/lua/test_redis2.lua; |
| 91 | + } |
| 92 | + ``` |
| 93 | + + CURL 请求结果 |
| 94 | + ``` |
| 95 | + root@tinywan:/opt/openresty/nginx/conf/Lua# curl '127.0.0.1:80/api' |
| 96 | + Hello |
| 97 | + 102 |
| 98 | + ``` |
| 99 | + + Redis 数据库结果 |
| 100 | + ``` |
| 101 | + 127.0.0.1:6379> keys * |
| 102 | + 1) "dog" |
| 103 | + 2) "Redis2222222222" |
| 104 | + 3) "Redis1999" |
| 105 | + ``` |
| 106 | + |
0 commit comments