lua使用resty.http做nginx反向代理(https请求,docker容器化部署集群),一个域名多项目转发

下载使用

链接:https://pan.baidu.com/s/1uQ7yCzQsPWsF6xavFTpbZg

提取码:htay

--来自百度网盘超级会员V5的分享

bash 复制代码
在根目录下执行:
# 从 github 上下载文件
git clone https://github.com/ledgetech/lua-resty-http.git
# 将 lua-resty-http/lib/ 下的 resty 文件夹上传至服务器一下目录下(lua-5.4.2安装目录下)
/lua-5.4.2/
# 此模块主要用来发送 http 请求
# 也可选用 socket.http

ad_load.lua文件

bash 复制代码
ngx.header.content_type="application/json;charset=utf8"
local cjson = require("cjson")
local https = require 'resty.http'
local json = cjson:new()
--服务器一,域名拼接request_uri获得请求的路由和路由上的参数
-- local server_one_url = 'http://127.0.0.1:9059/index01';
-- local server_one_url = 'http://127.0.0.1:9059'..ngx.var.request_uri;
local server_one_url = ngx.var.url_ip..':'..ngx.var.url_port..ngx.var.request_uri;
local server_one_code = 'ONE_CODE';
-- ngx.say(server_one_url)
-- ngx.exit(ngx.OK)

--http get 请求方法
local function http_get(url)
    local http = https:new()
    local res, err = http:request_uri(url, {
        method = 'GET',
        headers = {
            ['Content-Type'] = 'application/json';
        }
    })
    if res.status == 200 then
        ngx.say(res.body)
    else
        -- ngx.say(res.status)
        ngx.say('服务器错误!')
    end
end

-- http post 请求方法
local function http_post(url, data)
    local http = https:new()
    local res, err = http:request_uri(url, {
        method = 'POST',
        body = data,
        headers = {
            ['Content-Type'] = 'application/json';
        }
    })
    if res.status == 200 then
        ngx.say(res.body)
    else
        ngx.say('服务器错误!')
    end
end

-- ngx.say(server_one_url)
-- ngx.say(ngx.var.request_method)
-- ngx.exit(ngx.OK)
if ngx.var.request_method == "GET" then
    --解析参数并做转发
    http_get(server_one_url)
elseif ngx.var.request_method == "POST" then
    --获取请求参数
    ngx.req.read_body()
    local data = ngx.req.get_body_data()
    --解析参数并做转发
    http_post(server_one_url, data)
end
bash 复制代码
    location / {
      if ($server_port = 9058 ) {
        # 定义使用内网ip,定义请求端口
        set $url_ip 'http://127.0.0.1';
        set $url_port '9059';
        content_by_lua_file /lua-5.4.2/ad_load.lua;
      }
    }
相关推荐
彭于晏689几秒前
Android广播
android·java·开发语言
弱冠少年26 分钟前
websockets库使用(基于Python)
开发语言·python·numpy
长天一色27 分钟前
C语言日志类库 zlog 使用指南(第五章 配置文件)
c语言·开发语言
一般清意味……38 分钟前
快速上手C语言【上】(非常详细!!!)
c语言·开发语言
卑微求AC39 分钟前
(C语言贪吃蛇)16.贪吃蛇食物位置随机(完结撒花)
linux·c语言·开发语言·嵌入式·c语言贪吃蛇
技术无疆1 小时前
【Python】Streamlit:为数据科学与机器学习打造的简易应用框架
开发语言·人工智能·python·深度学习·神经网络·机器学习·数据挖掘
金灰1 小时前
HTML5--裸体回顾
java·开发语言·前端·javascript·html·html5
爱上语文1 小时前
Java LeetCode每日一题
java·开发语言·leetcode
Манго нектар2 小时前
JavaScript for循环语句
开发语言·前端·javascript
程序猿小D2 小时前
第二百六十九节 JPA教程 - JPA查询OrderBy两个属性示例
java·开发语言·数据库·windows·jpa