使用balancer_by_lua_block做應用程式層負載平衡

來源:互聯網
上載者:User

首先感謝章義春大神的openresty,解決了web開發的一些痛點並簡化了web開發的複雜度。

需求:

根據url的一個參數,做負載平衡,使得某一個使用者總是被分配到固定的商務服務器上處理,方便後續的業務處理,做緩衝或單元化架構部署

假設這個參數為dvid,一共有兩個商務服務器, 8088連接埠和8089連接埠,分別返回hello和world

    server{    listen 8088;            location /hello {                content_by_lua '                ngx.say("hello")                ';        }      }    server{    listen 8089;            location /hello {                content_by_lua '                ngx.say("world")                ';        }      }  

upstream  balancer_by_lua_block的配置:

    upstream backend{          server 0.0.0.0;          balancer_by_lua_block {               local balancer = require "ngx.balancer"                local port = {8088, 8089}                local backend = ""              local dvid = ngx.req.get_uri_args()["dvid"] or 0            ngx.log(ngx.ERR, "dvid=", dvid)            local hash = (dvid % 2) + 1               ngx.log(ngx.ERR, "hash=", hash)            backend = port[hash]              ngx.log(ngx.ERR, "backend=", backend)            ngx.log(ngx.ERR, "dvid=", dvid, " hash=", hash, " up=", backend)              local ok, err = balancer.set_current_peer("127.0.0.1", backend)              if not ok then                  ngx.log(ngx.ERR, "failed to set the current peer: ", err)                  return ngx.exit(500)              end              ngx.log(ngx.DEBUG, "current peer ", backend)          }       } 

接收業務請求的server:

    server {        listen       80;        server_name  localhost;        #charset koi8-r;        #access_log  logs/host.access.log  main;        location / {            root   html;            index  index.html index.htm;        }        location /hello {            proxy_pass http://backend;        }           error_page   500 502 503 504  /50x.html;        location = /50x.html {            root   html;        }    }
測試:

http://localhost/hello?dvid=1   返回world

http://localhost/hello?dvid=2   返回hello

測試結果OK


openresty安裝:

https://openresty.org/en/download.html

wget https://openresty.org/download/openresty-1.11.2.2.tar.gz

tar zxf openresty-1.11.2.2.tar.gz

cd openresty-1.11.2.2/

./configure --with-luajit&& make && make install


參考:

http://weibo.com/1834459124/DaEmgBhlD?from=singleweibo&mod=recommand_weibo&type=comment#_rnd1479734607640

http://blog.csdn.net/force_eagle/article/details/52224660

http://www.wtoutiao.com/p/177SJDc.html


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.