openresty使用lua-resty-http模块

2,211 阅读1分钟

1、 简介

 github访问地址

 在lua中操作http请求有两种方式

 第一种方式:使用通过ngx.location.capture 去方式实现

 第二种方式:lua-resty-http,是用于访问外部 Http 资源,外部 web 服务,RESTFul 等的轻量级 http 库。因为openresty默认没有引入lua-resty-http,所以需要自行下载。

2 下载安装

2.1 下载解压

下载地址

image.png

image.png

2.2 上传

将解压后的下面三个文件上传到openresty/lualib/resty目录下

image.png

image.png

3 http使用示例

3.1 修改nginx配置文件

在http下加一行配置

解析域名用的dns

resolver 8.8.8.8;

在server加一个location配置

location /http {
            default_type text/html;
             content_by_lua_file lua/lua-resty-http.lua;
        }

image.png

3.2 添加文件lua-resty-http.lua

image.png

内容如下:

local http = require("resty.http")  

local httpc = http.new()  
  
local resp, err = httpc:request_uri("http://www.sogou.com", {  
    method = "GET",  
    path = "/web?query=resty.http",  
    headers = {  
        ["User-Agent"] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36"  
    }  
})  
  
if not resp then  
    ngx.say("request error :", err)  
    return  
end  
  
 
ngx.status = resp.status  
  
  
for k, v in pairs(resp.headers) do  
    if k ~= "Transfer-Encoding" and k ~= "Connection" then  
        ngx.header[k] = v  
    end  
end  
  
ngx.say(resp.body)  
  
httpc:close()

3.3 重启后访问

image.png

4 lua-resty-http实现一致性hash负载均衡简要示例

现在有两个服务可以访问,分别为192.168.28.111,192.168.28.112

4.1 修改ngxin配置文件

  在server下加一个location

location /hashlb {
           default_type text/html;
            content_by_lua_file lua/lua-resty-http-hash-lb.lua;
       }

4.2 添加文件lua-resty-http-hash-lb.lua

内容

local http = require("resty.http")  
local httpc = http.new()  
-- 服务ip
local hosts = {"192.168.28.111","192.168.28.112"}
-- 获取请求参数id
local item_id= ngx.var.id
-- 获取id的hash值
local id_hash = ngx.crc32_long(item_id)-- 取余
local index = (id_hash % 2) +1
-- 发起请求,根据余数确定向哪个服务发起请求  
local resp, err = httpc:request_uri("http://"..hosts[index], {  
    method = "GET",  
    path = "/sogou?query=resty.http",  
    headers = {  
        ["User-Agent"] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36"  
    }  
})  
  
if not resp then  
    ngx.say("request error :", err)  
    return  
end  
  
 
ngx.say(resp.body)  
  
httpc:close()

4.3 重启后访问

  http://120.46.199.14:8888/hashlb?id=1

  http://120.46.199.14:8888/hashlb?id=2

  http://120.46.199.14:8888/hashlb?id=3

  分别看实际访问的哪个服务

查看日志文件

image.png