美文网首页
openresty+lua+nginx实现详情页数据分发

openresty+lua+nginx实现详情页数据分发

作者: 隔壁小新 | 来源:发表于2019-04-29 15:47 被阅读0次

    1.下载openresty:

    登录 http://openresty.org/cn/ 中文网站
    安装openresty需要一下这些第三方插件
    yum install readline-devel pcre-devel perl openssl-devel gcc
    下载安装包

    图片.png

    2.下载并且安装lua

    登录官方网站:http://www.lua.org/download.html

    图片.png
    安装lua
    在 make linux test后在执行一句
    make install
    这样安装完毕
    在安装默认路径/usr/local/openresty/nginx/sbin/下通过 ./nginx启动
    这样openresty安装完成了

    3.配置第三方插件使nginx分发请求

    在github上搜索lua-resty-http项目在openrestry/lualib/resty下引用当前两个文件http.lua,和http_header.lua


    图片.png

    4.直接贴代码实现功能

    (```)
    server {
    listen 80;
    server_name localhost;

        #charset koi8-r;
    
        #access_log  logs/host.access.log  main;
    
        location / {
            #root   html;
            default_type text/html;
                content_by_lua_file  /local/test.lua;
            #index  index.html index.htm;
        }
    

    () 在local/下创建test.lua文件 ()
    local uri_args=ngx.req.get_uri_args()
    local productId = uri_args["productId"]
    local host = {"192.168.1.122:8080/user/test", "192.168.1.122:8080/user/test1"}
    local hash = ngx.crc32_long(productId)
    ngx.say(hash)
    hash = (hash % 2) + 1
    ngx.say(hash)
    backend = "http://"..host[hash]
    ngx.say(backend)
    local requestBody =backend.."?productId="..productId
    ngx.say(requestBody)
    local http = require("resty.http")
    local httpc = http.new()
    local resp, err = httpc:request_uri(backend ,{
    method = "GET"
    })
    if not resp then
    ngx.say("request error :", err)
    return
    end
    ngx.status = resp.status
    ngx.say(resp.status)
    ngx.say(resp.body)
    (```)
    代码分析
    1.获取请求信息
    2.对商品ip取模
    3.通过http模块调用取模后的地址进行分发

    相关文章

      网友评论

          本文标题:openresty+lua+nginx实现详情页数据分发

          本文链接:https://www.haomeiwen.com/subject/uziynqtx.html