Nginx的配置与开发学习(六)

版权声明:转载记得宣传奥~。~ https://blog.csdn.net/c_ym_ww/article/details/88179325

Nginx与Lua开发

  • Lua:是一个简洁,轻量,可扩展的脚本语言
  • 安装lua解释器:yum install lua

Lua的基础语法

  1. 服务器内:print(“hello world”);
  2. lua脚本
  3. 变量
  • a=[[alo123"]]
  • a=‘alo\n123"’
  • a=’\97lo\10\04923"’
  • 布尔类型只有nil和false,数字0,空字符串(’ \0’)都是true
  • lua中的变量如果没有特殊说明,全是全局变量
  1. while循环语句 和 for循环语句

    sum=0
    num=1
    while num<=100 do
      sum=sum+num
      num=num+1
    end
    print("sum=",sum)
    lua没有++或是+=这样的操作
    
    for循环
    sum=0
    for i=1 100 do
      sum=sum+i
    end
    
  2. if-else判断语句

    if age==40 and sex=="male" then
        print("大于40男人")
    elseif age>40 and sex~="female" then
        print("大于60非女人")
    else
        local age=io.read()
        print("Your age is"..age)   #字符串的拼接操作符
    end
    

Nginx+Lua优势

  • 充分的结合Nginx的并发处理epoll优势和Lua的轻量实现简单的功能和高并发场景

准备环境

参考网页

灰度发布

  • 按照一定的关系区别,分部分的代码进行上线,使代码的发布能平滑过渡上线。
    1. 用户的信息cookie等信息区别
    2. 根据用户的ip地址

dep.conf 配置

server {
    listen       80;
    server_name  localhost;

    #charset koi8-r;
    access_log  /var/log/nginx/log/host.access.log  main;
    
    location /hello {
        default_type 'text/plain';
        content_by_lua 'ngx.say("hello, lua")';
    }
 
    location /myip {
        default_type 'text/plain';
        content_by_lua '
            clientIP = ngx.req.get_headers()["x_forwarded_for"]
            ngx.say("IP:",clientIP)
            ';
    }

    location / {
        default_type "text/html"; 
        content_by_lua_file /opt/app/lua/dep.lua;
        #add_after_body "$http_x_forwarded_for";
    }

    location @server{
        proxy_pass http://127.0.0.1:9090;
    }

    location @server_test{
        proxy_pass http://127.0.0.1:8080;
    }

    error_page   500 502 503 504 404  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

dep.lua配置

 clientIP = ngx.req.get_headers()["X-Real-IP"]
if clientIP == nil then
    clientIP = ngx.req.get_headers()["x_forwarded_for"]
end
if clientIP == nil then
    clientIP = ngx.var.remote_addr
end
    local memcached = require "resty.memcached"
    local memc, err = memcached:new()
    if not memc then
        ngx.say("failed to instantiate memc: ", err)
        return
    end
    local ok, err = memc:connect("127.0.0.1", 11211)
    if not ok then
        ngx.say("failed to connect: ", err)
        return
    end
    local res, flags, err = memc:get(clientIP)
    ngx.say("value key: ",res,clientIP)
    if err then
        ngx.say("failed to get clientIP ", err)
        return
    end
    if  res == "1" then
        ngx.exec("@server_test")
        return
    end
    ngx.exec("@server")

猜你喜欢

转载自blog.csdn.net/c_ym_ww/article/details/88179325
今日推荐