首页 > 其他分享 >【网关开发】7.Openresty使用cosocket API 发送http与tcp网络请求

【网关开发】7.Openresty使用cosocket API 发送http与tcp网络请求

时间:2023-01-29 14:55:21浏览次数:58  
标签:status cosocket 网关 http err sock peer end local

目录

背景

为网关提供健康检查功能时需要对节点发送http或者tcp探活请求。Openresty 提供cosocket来处理非阻塞IO。

实现

跟工程结合在一起,这里简单拼接数据结构

local function __default_check_alive(status)
    return status >= 200 and status <= 299
end
local function debug_ctx()
    local ctx =  {
        peer = {ip = '10.218.22.239', port = '8090'},                                                 --目标机器
        ahc = {
            type = 'http',
            timeout = 3,
            check_http_send = "GET /ping HTTP/1.1\r\nHost: service_test.com\r\n\r\n",  -- 发送的数据内容
        },
        status_check = __default_check_alive
    }
    return ctx
end

发送http请求

local stream_sock = ngx.socket.tcp    -- 引入模块
local re_find = ngx.re.find

local function __check_http_peer(ahc, peer, status_check)
    local ok
    local req = ahc.check_http_send

    local sock, err = stream_sock()            -- 创建 TCP 的 cosocket 对象
    if not sock then
        ngx.log(ngx.ERR, "failed to create stream socket: " .. err)
        return false, err
    end

    sock:settimeout(ahc.timeout * 1000)      --设置超时时间

    ok, err = sock:connect(peer.ip, peer.port)  --建立连接
    if not ok then
        return false
    end

    local bytes, err = sock:send(req)    --发送数据
    if not bytes then
        return false
    end

    local status_line, err = sock:receive()  -- 接收数据
    if not status_line then
        if err == "timeout" then
            sock:close()  -- timeout errors do not close the socket.
        end
        return false
    end

    if status_check then
        local from, to, err = re_find(status_line,
                                      [[^HTTP/\d+\.\d+\s+(\d+)]],      --利用正则获取status code
                                      "joi", nil, 1)
        if err then
            ngx.log(ngx.ERR, "failed to parse status line: "..err)
        end

        if not from then
            sock:close()
            return false
        end

        local status = tonumber(status_line:sub(from, to))
        if not status_check(status) then
            -- ngx.log(ngx.ERR, status_line)
            sock:close()
            return false
        end
    end

    sock:close()
    return true
end

发送tcp请求


-- functional, check peer by tcp, returns bool indicate up or down
local function __check_tcp_peer(ahc, peer)
    local ok
    local sock, err = stream_sock()
    if not sock then
        ngx.log(ngx.ERR, "failed to create stream socket: " .. err)
        return false, err
    end

    sock:settimeout(ahc.timeout * 1000)

    ok, err = sock:connect(peer.ip, peer.port)
    if not ok then
        return false
    end
    sock:close()
    return true
end

遇到的问题

API disabled in the context of init_worker_by_lua*

这是因为我使用的地方是在init_worker_by_lua阶段,这阶段是不允许使用cosocket的,除了这些阶段还有
set_by_lua、log_by_lua、header_filter_by_lua、body_filter_by_lua、init_by_lua* 都是不允许使用的

-- 修改调用
ngx.timer.at(0, function (p, self)
        local ctx = down_peer_checker.debug_ctx()
        ngx.log(ngx.INFO,"down_peer_checker  check_peer "..tostring(down_peer_checker.check_peer(ctx)))
    end)

HTTP/1.1 400 Bad Request

主要是请求字符串格式问题、

GET /ping HTTP/1.1\r\n Host: service_test.com\r\n        错误
GET /ping HTTP/1.1\r\nHost: service_test.com\r\n\r\n   正确

总结与思考

cosocket知识与参考文章:https://zhuanlan.zhihu.com/p/507329735
存在部分封装,源码地址 https://github.com/zhaoshoucheng/openresty/blob/main/pkg/lua_script/upstream/down_peer_checker.lua

标签:status,cosocket,网关,http,err,sock,peer,end,local
From: https://www.cnblogs.com/zhaosc-haha/p/17069977.html

相关文章

  • httprunner框架
    '''一、httprunner命名规范类名以Test开头teststeps为测试步骤,每一个测试步骤叫做StepStep里的RunRequest,是待测的API名字;.py文件,必须以_test结尾二、httprunner......
  • HTTP提交方式-PATCH说明
    https://blog.csdn.net/weixin_36691991/article/details/108848835在使用postman请求接口得时候,使用get,post得时候我们是使用body下form-data来传输数据得,但是使用patch......
  • Servlet_urlpartten配置与HTTP_概述
    Servlet_urlpartten配置Servlet相关配置1.urlpartten:Servlet访问路径1.一个Servlet可以定义多个访问路径:@WebServlet({"/d4","/dd4","/ddd......
  • 中国联通家庭智能网关 EPON/4+1+WiFi(2.4G) 管理员登录
     光猫型号硬件版本软件版本天邑TEWA-800EV3.0Tianyi_V3.1.3一、打开中国联通智能网关登录界面GoogleChrome打开http://192.168.1.1/二、获取sessionKey......
  • fastapi socketio http cros solved
    D:\code_gitee\fastapi-socketio-example-main\fastapi-socketio-example-main\app.pyimportosimportpathlibimportsecretsimporttimefromtypingimportOption......
  • 【网关开发】6.lua绑定委托(delegate)实现多播调用
    目录背景实现原理实现细节应用测试思考与总结背景在程序开发过程中有时会遇到事件流的问题,某一个结果会触发A、B、C等一系列动作。需要将各种事件注册给委托类(Delegate)。......
  • HttpServletResponse下载文件
    下载文件获取下载文件路径下载的文件名设置浏览器能够支持下载获取下载文件的输入流创建缓冲区获取OutputStream对象将FileOutputStream流写入到buff......
  • https是否有优势
    刚才看了下https与http的区别,说前者通过加密来增加数据传输的安全性。如果传输的数据已经被第三方获取了,就像装钱的保险箱已经被带到第三者家里,这时任何加密手段的意义都被......
  • burpsuite抓https包的必要准备
    https的原理首先了解什么是https: HTTPS全称为HypertextTransferProtocolSecure,相当于是http协议的安全版本,跟http相比增加了加密这一环节 百度百科 https的具体......
  • upload-labs pass3,phpstudy中修改httpd.conf后无法解析.php3后缀。phpstudy中64与32系
    问题解决参考自:https://www.likecs.com/show-965809.html 注意:VC运行库(V14-x64)版本必须与Apache、PHP版本相同;VC就是MicrosoftVisualC++,可以通过控制面板查看否则......