目錄
這裏實現個簡單的負載均衡,只做功能展示(實際業務比這複雜高,單臺服務器無法滿足需求的情況下,纔會進行負載均衡)
OpenResty
用Openresty實現日誌功能
Openresty 服務配置文件
lua 文件
-- 引入lua json庫
local cjson = require "cjson"
-- 獲取請求參數
local request_args_tab = ngx.req.get_uri_args()
-- 獲取系統時間
local time = os.date("%Y%m%d",unixtime)
-- 創建file對象
local file = io.open("ho-data/ho-".. time ..".log","a")
-- 創建json對象
local log_json = {}
-- 將請求參數轉爲json
for k,v in pairs(request_args_tab) do
log_json[k] = v
end
-- json數據寫入文件,並\n換行
file:write(cjson.encode(log_json),"\n")
file:flush()
nginx.conf 文件
worker_processes 1;
error_log logs/error.log;
events {
worker_connections 1024;
}
http {
server {
client_header_buffer_size 512m;
large_client_header_buffers 4 512m;
lua_need_request_body on;
lua_code_cache off;
listen 12199;
location /log.gif {
#internal;
default_type image/gif;
access_log off;
log_by_lua_file 'conf/log_conf.lua';
empty_gif;
}
location /jast {
log_by_lua_file conf/jast_conf.lua;
content_by_lua '
#用三臺服務器做測試,調用接口後使用jast_conf.lua處理數據,處理完成並返回對應服務器標識
ngx.say("hello,89")
#ngx.say("hello,44")
#ngx.say("hello,121")
';
}
}
}
啓動Openresty服務
/usr/local/openresty/nginx/sbin/nginx -p /root/openresty/openresty-1.15.8.2/jast_log -c conf/nginx.conf
測試調用接口
[root@ecs-001 jast]# curl 172.16.0.89:12199/jast?userid=123&action=read&date=160000000
hello,89
[root@ecs-002 jast]# curl 172.16.0.121:12199/jast?userid=123&action=read&date=160000000
hello,121
[root@ecs-002 jast]# curl 172.16.0.44:12199/jast?userid=123&action=read&date=160000000
hello,44
Nginx 負載均衡服務
nginx 配置文件
worker_processes 4;
error_log logs/error.log;
events {
worker_connections 1024;
}
http {
upstream jast.loadBalance{
server 172.16.0.44:12199 weight=1;
server 172.16.0.121:12199 weight=1;
server 172.16.0.89:12199 weight=1;
}
server {
client_header_buffer_size 512k;
large_client_header_buffers 4 512k;
lua_need_request_body on;
lua_code_cache off;
listen 2199;
location / {
proxy_pass http://jast.loadBalance;
}
}
}
啓動服務
/usr/local/openresty/nginx/sbin/nginx -p /root/openresty/openresty-1.15.8.2/jast -c conf/nginx.conf
實現功能
調用2199端口,自動負載均衡到44:12199,121:12199,89:12199三臺服務器的服務中
測試結果
測試調用2199端口,我們只有2199開通了外網端口
返回結果如下,說明我們自動將請求分發了
第1次請求 Hello,121
第2次請求 Hello,44
第3次請求 hello,89
第4次請求 Hello,121
第5次請求 Hello,44
第6次請求 hello,89
第7次請求 Hello,121
第8次請求 Hello,44
第9次請求 hello,89
第10次請求 Hello,121
第11次請求 Hello,44
第12次請求 hello,89
第13次請求 Hello,121
第14次請求 Hello,44
第15次請求 hello,89
第16次請求 Hello,121
第17次請求 Hello,44
第18次請求 hello,89
第19次請求 Hello,121
第20次請求 Hello,44
這個網站有些基本介紹:https://moonbingbing.gitbooks.io/openresty-best-practices