- 反向代理
1.1 使用nginx实现反向代理
Nginx只做请求的转发,后台有多个http服务器提供服务,nginx的功能就是把请求转发给后面的服务器,决定把请求转发给谁。
1.2 安装tomcat
在一个虚拟机上创建两个tomcat实例,模拟多个服务器。
1.3 需求
通过访问不同的域名访问运行在不同端口的tomcat
8080.xiaoyin.com 访问运行8080端口的tomcat
8081.xiaoyin.com 访问运行8081端口的tomcat
1.4 域名需要配置host文件:
1.5 Nginx的配置文件
upstream tomcatserver1{
server 192.168.6.131:8080
}
upstream tomcatserver2{
server 192.168.6.131:8081;
}
server {
listen 80;
server_name 8080.xiaoyin.com;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
#root html-xiaoyin;
proxy_pass http://tomcatserver1;
index index.html index.htm;
}
}
server {
listen 80;
server_name 8081.xiaoyin.com;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
#root html-xiaoyin;
proxy_pass http://tomcatserver2;
index index.html index.htm;
}
}
2. 负载均衡
2.1 什么是负载均衡
负载均衡 建立在现有网络结构之上,它提供了一种廉价有效透明的方法扩展网络设备和服务器的带宽、增加吞吐量、加强网络数据处理能力、提高网络的灵活性和可用性。
负载均衡,英文名称为Load Balance,其意思就是分摊到多个操作单元上进行执行,例如Web服务器、FTP服务器、企业关键应用服务器和其它关键任务服务器等,从而共同完成工作任务。
2.2 需求
nginx作为负载均衡服务器,用户请求先到达nginx,再由nginx根据负载配置将请求转发至 tomcat服务器。
nginx负载均衡服务器:192.168.6.131
tomcat1服务器:192.168.6.131:8080
tomcat2服务器:192.168.6.131:8081
2.3 配置nginx的负载均衡
upstream tomcatserver1{
server 192.168.6.131:8080 weight=2;
server 192.168.6.131:8081 weight=1;
}
upstream tomcatserver2{
server 192.168.6.131:8081;
}
server {
listen 80;
server_name 8080.xiaoyin.com;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
#root html-xiaoyin;
proxy_pass http://tomcatserver1;
index index.html index.htm;
}
}
server {
listen 80;
server_name 8081.xiaoyin.com;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
#root html-xiaoyin;
proxy_pass http://tomcatserver2;
index index.html index.htm;
}
}
#定义负载均衡设备的 Ip及设备状态
upstream myServer {
server 127.0.0.1:9090 down;
server 127.0.0.1:8080 weight=2;
server 127.0.0.1:6060;
server 127.0.0.1:7070 backup;
}
upstream 每个设备的状态:
down 表示单前的server暂时不参与负载
weight 默认为1.weight越大,负载的权重就越大。
max_fails :允许请求失败的次数默认为1.当超过最大次数时,返回proxy_next_upstream模块定义的错误
fail_timeout:max_fails 次失败后,暂停的时间。
backup: 其它所有的非backup机器down或者忙的时候,请求backup机器。所以这台机器压力会最轻。