目录
OpenResty
Openresty 服务配置文件
启动Openresty服务
测试调用接口
Nginx 负载均衡服务
nginx 配置文件
启动服务
实现功能
测试结果
这里实现个简单的负载均衡,只做功能展示(实际业务比这复杂高,单台服务器无法满足需求的情况下,才会进行负载均衡)
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