Nginx ("engine x") 是一个高性能的 HTTP 和反向代理服务器,也是一个 IMAP/POP3/SMTP 服务器。
主要介绍 Nginx 负载均衡配置,以实例进行说明。
准备材料:nginx(http://nginx.org/),web 项目(此处以 jetty 编写可自定义访问 IP 和端口的项目为例)
关键代码:
HelloWorldHandler.javapublic class HelloWorldHandler extends AbstractHandler {
private static final String name = "alfred";
private String host;
private Integer port;
public HelloWorldHandler() {
}
public HelloWorldHandler(String host, Integer port) {
this.host = host;
this.port = port;
}
@Override
public void handle(String target, Request baseRequest,
HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html;charset=utf-8");
response.setStatus(HttpServletResponse.SC_OK);
baseRequest.setHandled(true);
response.getWriter().println("<h1>Usage " + host + ":"+port+"</h1>"+"<h1>Hello World " + name + "</h1>");
}
}
JettyMain.javapublic class JettyMain {
private static String host = "127.0.0.1";
private static Integer port = 8888;
public static void main(String[] args) throws Exception {
if(args.length != 2) {
args = new String[]{host,port.toString()};
}else{
host = args[0];
port = Integer.parseInt(args[1]);
}
System.out.println("host:"+host+" "+"port:"+port+" start");
Server server = ServerUtil.getServerInstance();
server.addConnector(ConnectorUtil.getSelectChannelConnector(host, port));
server.setHandler(new HelloWorldHandler(host,port));
server.start();
server.join();
}
}
pom.xml<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.alfred.jetty</groupId>
<artifactId>jetty-base</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>Jetty基础</name>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>8.1.19.v20160209</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-webapp</artifactId>
<version>8.1.19.v20160209</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
<version>8.1.19.v20160209</version>
</dependency>
</dependencies>
</project>
nginx 结构:
修改 nginx 配置文件 conf/nginx.conf,http 段添加 upstream 节点,并在 http 段中 server 节点的 location 节点中添加 proxy_pass 配置为:http:// + upstream 名称。
upstreamupstream site {
server 127.0.0.1:8889;
server 127.0.0.1:8887;
}
proxy_passlocation / {
root html;
index index.html index.htm;
proxy_pass http://site;
}
配置完成后,即可启动 nginx(双击 nginx.exe,窗口闪退是正常的,是否正常启动是看是否启动了 nginx 的进程)
配置成功后的 nginx.conf 文件如下:
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;
}
http {
upstream site {
server 127.0.0.1:8889;
server 127.0.0.1:8887;
}
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 on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
server {
listen 8088;
server_name 127.0.0.1;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root html;
index index.html index.htm;
proxy_pass http://site;
}
#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 {
# listen 443 ssl;
# server_name localhost;
# ssl_certificate cert.pem;
# ssl_certificate_key cert.key;
# ssl_session_cache shared:SSL:1m;
# ssl_session_timeout 5m;
# ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_prefer_server_ciphers on;
# location / {
# root html;
# index index.html index.htm;
# }
#}
}
访问地址:http://127.0.0.1:8088/,刷新切换服务器。
以上,最简单的负载均衡完成。
upstream 按照轮询(默认)方式进行负载,每个请求按时间顺序逐一分配到不同的后端服务器,如果后端服务器 down 掉,能自动剔除。虽然这种方式简便、成本低廉。但缺点是:可靠性低和负载分配不均衡。适用于图片服务器集群和纯静态页面服务器集群。
除此之外,upstream 还有其它的分配策略,分别如下:
weight(权重)
指定轮询几率,weight 和访问比率成正比,用于后端服务器性能不均的情况。如下所示,10.0.0.88 的访问比率要比 10.0.0.77 的访问比率高一倍。
upstream site{
server 10.0.0.77 weight=5;
server 10.0.0.88 weight=10;
}
ip_hash(访问ip)
每个请求按访问 ip 的 hash 结果分配,这样每个访客固定访问一个后端服务器,可以解决 session 的问题。
upstream site{
ip_hash;
server 10.0.0.10:8080;
server 10.0.0.11:8080;
}
fair(第三方)
按后端服务器的响应时间来分配请求,响应时间短的优先分配。与 weight 分配策略类似。
upstream site{
server 10.0.0.10:8080;
server 10.0.0.11:8080;
fair;
}
url_hash(第三方)
按访问url的hash结果来分配请求,使每个 url 定向到同一个后端服务器,后端服务器为缓存时比较有效。
upstream site{
server 10.0.0.10:7777;
server 10.0.0.11:8888;
hash $request_uri;
hash_method crc32;
}
注意:在 upstream 中加入 hash 语句,server 语句中不能写入 weight 等其他的参数,hash_method 是使用的 hash 算法。
upstream 还可以为每个设备设置状态值,这些状态值的含义分别如下:
down:表示单前的 server 暂时不参与负载.
weight:默认为1。weight 越大,负载的权重就越大。
max_fails:允许请求失败的次数默认为1.当超过最大次数时,返回 proxy_next_upstream 模块定义的错误.
fail_timeout:max_fails 次失败后,暂停的时间。
backup:其它所有的非 backup 机器 down 或者忙的时候,请求 backup 机器。所以这台机器压力会最轻。
upstream site{ #定义负载均衡设备的Ip及设备状态
ip_hash;
server 10.0.0.11:9090 down;
server 10.0.0.11:8080 weight=2;
server 10.0.0.11:6060;
server 10.0.0.11:7070 backup;
}