一、反向代理
1.1 Nginx简介
Nginx (engine x) 是一款轻量级的 Web 服务器 、反向代理服务器及电子邮件(IMAP/POP3)代理服务器
什么是反向代理?
反向代理(Reverse Proxy)方式是指以代理服务器来接受 internet 上的连接请求,然后将请求转发给内部网络上的服务器,并将从服务器上得到的结果返回给 internet 上请求连接的客户端,此时代理服务器对外就表现为一个反向代理服务器
1.2 Nginx基本命令
nginx -s stop # 快速关闭Nginx,可能不保存相关信息,并迅速终止web服务。
nginx -s quit # 平稳关闭Nginx,保存相关信息,有安排的结束web服务。
nginx -s reload # 因改变了Nginx相关配置,需要重新加载配置而重载。
nginx -s reopen # 重新打开日志文件。
nginx -c filename # 为 Nginx 指定一个配置文件,来代替缺省的。
nginx -t # 不运行,仅仅测试配置文件。nginx 将检查配置文件的语法的正确性,并尝试打开配置文件中所引用到的文件。
nginx -v # 显示 nginx 的版本。
nginx -V # 显示 nginx 的版本,编译器版本和配置参数。
如果不想每次都敲命令,可以在安装目录下新添一个启动批处理文件D:\openresty-1.21.4.2-win64\startup.bat,双击即可运行。内容如下
@echo off
rem 如果启动前已经启动nginx并记录下pid文件,会kill指定进程
nginx.exe -s stop
rem 测试配置文件语法正确性
nginx.exe -t -c conf/nginx.conf
rem 显示版本信息
nginx.exe -v
rem 按照指定配置去启动nginx
nginx.exe -c conf/nginx.conf
1.3 Nginx反向代理实践
nginx.conf 配置文件如下:
#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
# 工作模式及连接数上限
events {
worker_connections 1024; # 单个后台worker process进程的最大并发连接数
}
http {
# 设定mime类型(邮件支持类型),类型由mime.types文件定义
include mime.types;
default_type application/octet-stream;
# 设定日志
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
# sendfile 指令指定 nginx 是否调用 sendfile 函数(zero copy 方式)来输出文件,对于普通应用,必须设为 on, 如果用来进行下载等应用磁盘IO重负载应用,可设置为off,以平衡磁盘与网络I/O处理速度,降低系统的uptime.
sendfile on;
#tcp_nopush on;
# 连接超时时间秒
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
upstream front_server{
# Vue前端本地启动地址,需在vue.config.js的devServer中配置allowedHosts: "all",否则会报Invalid Host header
server 127.0.0.1:8081;
}
upstream api_server{
# 微服务后端启动端口
server 127.0.0.1:8080;
}
server {
listen 80;
server_name localhost;
# 编码格式
charset utf-8;
#access_log logs/host.access.log main;
# 反向代理的路径(和upstream绑定),location 后面设置映射的路径
location ~ ^/ {
proxy_pass http://front_server;
}
# 跨域配置
location ~ ^/api/ {
#include enable-cors.conf;
proxy_pass http://api_server;
rewrite "^/api/(.*)$" /$1 break;
}
location /hello {
default_type 'text/plain';
content_by_lua_block {
ngx.say("Hello, OpenResty!")
}
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;
# location / {
# root html;
# index index.html index.htm;
# }
#}
# HTTPS server
#
#server {
# 监听443端口。443为知名端口号,主要用于HTTPS协议
# listen 443 ssl;
# server_name localhost;
# ssl证书文件位置(常见证书文件格式为:crt/pem)
# ssl_certificate cert.pem;
# ssl_certificate_key cert.key;
# ssl配置参数(选择性配置)
# ssl_session_cache shared:SSL:1m;
# ssl_session_timeout 5m;
# 数字签名,此处使用MD5
# ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_prefer_server_ciphers on;
# location / {
# root html;
# index index.html index.htm;
# }
#}
}
其中enable-cors.conf配置如下
# allow origin list
set $ACAO '*';
# set single origin
# 替换为自己域名
if ($http_origin ~* (localhost)$) {
set $ACAO $http_origin;
}
if ($cors = "trueget") {
add_header 'Access-Control-Allow-Origin' "$http_origin";
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}
if ($request_method = 'OPTIONS') {
set $cors "${cors}options";
}
if ($request_method = 'GET') {
set $cors "${cors}get";
}
if ($request_method = 'POST') {
set $cors "${cors}post";
}
OK, 完毕,已验证可正常反向代理
二、 负载均衡
2.1 负载均衡配置
上篇文章中,代理仅仅指向一个服务器。但是,网站在实际运营过程中,大部分都是以集群的方式运行,这时需要使用负载均衡来分流。nginx 也可以实现简单的负载均衡功能。
假设这样一个应用场景:将应用部署在 192.168.1.11:80、192.168.1.12:80、192.168.1.13:80 三台 linux 环境的服务器上。网站域名叫 www.helloworld.com,公网 IP 为 192.168.1.11。在公网 IP 所在的服务器上部署 nginx,对所有请求做负载均衡处理(下面例子中使用的是加权轮询策略)
nginx.conf 配置如下:
http {
# 设定mime类型,类型由mime.type文件定义
include /etc/nginx/mime.types;
default_type application/octet-stream;
# 设定日志格式
access_log /var/log/nginx/access.log;
# 设定负载均衡的服务器列表
upstream load_balance_server {
# weigth参数表示权值,权值越高被分配到的几率越大
server 192.168.1.11:80 weight=5;
server 192.168.1.12:80 weight=1;
server 192.168.1.13:80 weight=6;
}
# HTTP服务器
server {
# 侦听80端口
listen 80;
# 定义使用www.xx.com访问
server_name www.helloworld.com;
# 对所有请求进行负载均衡请求
location / {
root /root; # 定义服务器的默认网站根目录位置
index index.html index.htm; # 定义首页索引文件的名称
proxy_pass http://load_balance_server ;# 请求转向load_balance_server 定义的服务器列表
# 以下是一些反向代理的配置(可选择性配置)
#proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
# 后端的Web服务器可以通过X-Forwarded-For获取用户真实IP
proxy_set_header X-Forwarded-For $remote_addr;
proxy_connect_timeout 90; # nginx跟后端服务器连接超时时间(代理连接超时)
proxy_send_timeout 90; # 后端服务器数据回传时间(代理发送超时)
proxy_read_timeout 90; # 连接成功后,后端服务器响应时间(代理接收超时)
proxy_buffer_size 4k; # 设置代理服务器(nginx)保存用户头信息的缓冲区大小
proxy_buffers 4 32k; # proxy_buffers缓冲区,网页平均在32k以下的话,这样设置
proxy_busy_buffers_size 64k; # 高负荷下缓冲大小(proxy_buffers*2)
proxy_temp_file_write_size 64k; # 设定缓存文件夹大小,大于这个值,将从upstream服务器传
client_max_body_size 10m; # 允许客户端请求的最大单文件字节数
client_body_buffer_size 128k; # 缓冲区代理缓冲用户端请求的最大字节数
}
}
}
2.2 负载均衡策略
- 轮询
upstream bck_testing_01 {
# 默认所有服务器权重为 1
server 192.168.250.220:8080
server 192.168.250.221:8080
server 192.168.250.222:8080
}
- 加权轮询
upstream bck_testing_01 {
server 192.168.250.220:8080 weight=3
server 192.168.250.221:8080 # default weight=1
server 192.168.250.222:8080 # default weight=1
}
- 最少连接
upstream bck_testing_01 {
least_conn;
# with default weight for all (weight=1)
server 192.168.250.220:8080
server 192.168.250.221:8080
server 192.168.250.222:8080
}
- 加权最少连接
upstream bck_testing_01 {
least_conn;
server 192.168.250.220:8080 weight=3
server 192.168.250.221:8080 # default weight=1
server 192.168.250.222:8080 # default weight=1
}
- IP Hash
upstream bck_testing_01 {
ip_hash;
# with default weight for all (weight=1)
server 192.168.250.220:8080
server 192.168.250.221:8080
server 192.168.250.222:8080
}
- 普通 Hash
upstream bck_testing_01 {
hash $request_uri;
# with default weight for all (weight=1)
server 192.168.250.220:8080
server 192.168.250.221:8080
server 192.168.250.222:8080
}
三、LuaRestyRedisLibrary
3.1 连接需授权的redis
server {
location /redis1 {
content_by_lua_block {
local redis = require "resty.redis"
local red = redis:new()
-- 1秒
red:set_timeout(1000)
local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
ngx.say("failed to connect: ", err)
return
end
-- 请注意这里 auth 的调用过程
local count
count, err = red:get_reused_times()
-- 如果当前连接不是从内建连接池中获取的,该方法总是返回 0 ,也就是说,该连接还没有被使用过
if 0 == count then
ok, err = red:auth("password")
if not ok then
ngx.say("failed to auth: ", err)
return
end
elseif err then
ngx.say("failed to get reused times: ", err)
return
end
ok, err = red:set("doge", "doge coin")
if not ok then
ngx.say("failed to set dog: ", err)
return
end
ngx.say("set result: ", ok)
-- 连接池大小是100个,并且设置最大的空闲时间是 10 秒
local ok, err = red:set_keepalive(10000, 100)
if not ok then
ngx.say("failed to set keepalive: ", err)
return
end
}
}
}
3.2 pipeline 压缩请求数量
server {
location /withpipeline {
content_by_lua_block {
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000) -- 1 sec
-- or connect to a unix domain socket file listened
-- by a redis server:
-- local ok, err = red:connect("unix:/path/to/redis.sock")
local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
ngx.say("failed to connect: ", err)
return
end
red:init_pipeline()
red:set("cat", "CaiCai")
red:set("dog", "doge coin")
red:get("cat")
red:get("dog")
local results, err = red:commit_pipeline()
if not results then
ngx.say("failed to commit the pipelined requests: ", err)
return
end
for i, res in ipairs(results) do
if type(res) == "table" then
if not res[1] then
ngx.say("failed to run command ", i, ": ", res[2])
else
-- process the table value
end
else
-- process the scalar value
end
end
-- put it into the connection pool of size 100,
-- with 10 seconds max idle time
local ok, err = red:set_keepalive(10000, 100)
if not ok then
ngx.say("failed to set keepalive: ", err)
return
end
}
}
}
OpenResty最佳实践作者:曾经某个后台应用,逐个处理大约 100 万条记录需要几十分钟,经过 pileline 压缩请求数量后,最后时间缩小到 20 秒左右