Nginx系列:Nginx解决跨域和负载均衡 | 八月更文挑战

3,580

这是我参与8月更文挑战的第26天,活动详情查看:8月更文挑战

前言

心态好了,就没那么累了。心情好了,所见皆是明媚风景。

“一时解决不了的问题,那就利用这个契机,看清自己的局限性,对自己进行一场拨乱反正。”正如老话所说,一念放下,万般自在。如果你正被烦心事扰乱心神,不妨学会断舍离。断掉胡思乱想,社区垃圾情绪,离开负面能量。心态好了,就没那么累了。心情好了,所见皆是明媚风景。


Nginx正向代理

正向代理:是一个位于客户端和目标服务器之间的服务器,为了从目标服务器取得内容,客户端向代理发送一个请 求并指定目标(目标服务器),然后代理向目标服务器转交请求并将获得的内容返回给客户端。客户端必须要进行 一些特别的设置才能使用正向代理。(例如:我们访问谷歌网站,由于其他原因无法访问到,但是我们通过访问其 它的服务器最终访问到谷歌网站了,此时就是一个正向代理的过程)


Nginx反向代理

反向代理:在计算机世界里,由于单个服务器的处理客户端(用户)请求能力有一个极限,当用户的接入请求蜂拥 而入时,会造成服务器忙不过来的局面,可以使用多个服务器来共同分担成千上万的用户请求,这些服务器提供相 同的服务,对于用户来说,根本感觉不到任何差别。实际上是通过反向代理服务器接受客户端的请求,然后把请求 分发给具体的服务器进行处理,然后再将服务器的响应结果返回给代理服务器,由代理服务器反馈给客户端。 (例如:拨打10086客服电话,一个省的10086客服估计有成千上万个,实际上我们并不关心有多个客服,我们关心 的是只要拨通了10086 的号码能够有客服为我们提供服务就可以了。其实10086总机号码就是我们说的反向代理)


反向代理示例

我们通过nginx来代理访问该项目。我们只需要修改配置文件nginx.conf即可,具体修改如下:(下面截图中如weight = 3中间的空格记得去掉,我这个是格式化了不去掉会报错哦....)

在这里插入图片描述

重新启动nginx服务器(nginx -s reload),然后在浏览器中访问网址:http://localhost:8086/chenOne或者chenTwo 即可看到效果(会分别访问upstream配置下的路径)。


什么是负载均衡

当一台服务器在单位时间内的访问量越大时,服务器压力就越大,大到超过自身承受能力时,服务器就会崩 溃。为了避免服务器崩溃,让用户有更好的体验,我们通过负载均衡的方式来分担服务器压力。
我们可以建立很多很多服务器,组成一个服务器集群,当用户访问网站时,先访问一个中间服务器,让这个中 间服务器在服务器集群中选择一个压力较小的服务器,然后将该访问请求引入该服务器中。如此以来,用户的每次 访问,都会保证服务器集群中的每个服务器压力趋于平衡,分担了服务器压力,避免了服务器崩溃的情况。如下:

    # 配置负载均衡的服务器Ip和负载均衡方式(此处为权重轮询)并且允许请求失败次数 max_fails 为3次以及 fail_timeout 请求3次失败后,暂停的时间。
	upstream tomcate_server {
		server localhost:3010 weight=2 max_fails=3  fail_timeout=10s;
		server localhost:3011 weight=2 max_fails=3 fail_timeout=10s;
		server localhost:3012 weight=2 max_fails=3 fail_timeout=10s;
		# backup 不能和 ip_hash 关键字一起使用
		server localhost:3100 max_fails=3 fail_timeout=10s backup;# 其它所有的非backup机器down或者忙的时候,请求backup机器。所以这台机器压力会最轻。
	}
	
	# 配置负载均衡的服务器Ip和负载均衡方式(此处为权重轮询)并且允许请求失败次数 max_fails 为3次以及 fail_timeout 请求3次失败后,暂停的时间。
	upstream tomcate_serverTwo {
		server localhost:4010 weight=2 max_fails=3 fail_timeout=10s;
		server localhost:4011 weight=2 max_fails=3 fail_timeout=10s;
		server localhost:4012 weight=2 max_fails=3 fail_timeout=10s;
		# backup 不能和 ip_hash 关键字一起使用
		server localhost:4100 max_fails=3 fail_timeout=10s backup;# 其它所有的非backup机器down或者忙的时候,请求backup机器。所以这台机器压力会最轻。
	}

故障转移

在使用负载均衡时,假如集群中的某台服务器挂掉了,那么当访问到该服务器时会有很长的响应超时时间, 响应失败后才会去访问集群中正常的服务器,这样的话用户的体验就非常差了,那么如何来解决这个问题 呢,实际上可以通过在nginx服务器上配置故障转移来解决这个问题。 打开nginx/conf目录下 nginx.conf文件进行编辑。如下:

        # 超过超时时间则进行故障转移
        location /chenOne {
			# 放置静态资源的地方
            root   static;# (d:/nginx/static)
			# 访问的首页
            index  index.html index.htm;
			# 进行负载均衡的配置指向地址
			proxy_pass http://tomcate_server;
			proxy_connect_timeout 3;#默认单位是秒 
			proxy_read_timeout 3; 
			proxy_send_timeout 3;
        }
		
		# 超过超时时间则进行故障转移
		location /chenTwo {
			# 放置静态资源的地方
            root   static;# (d:/nginx/static)
			# 访问的首页
            index  index.html index.htm;
			# 进行负载均衡的配置指向地址
			proxy_pass http://tomcate_serverTwo;
			proxy_connect_timeout 3;#默认单位是秒 
			proxy_read_timeout 3; 
			proxy_send_timeout 3;
        }

编辑完成后保存文件,重启nginx服务器nginx -s reload。停掉集群中的一台服务器,然后进行测试。在浏览器中访问:http://localhost:8086/,则可看到当访问停止的服务器时,访问不成功,3秒后则自动转移访问另一个正常运行的服务器。


代理用法完整配置:解决跨域、负载均衡和故障转移(请注意看下面配置的注释)

  • 同域:简单的解释就是相同域名、端口号和协议。
  • 跨域问题:跨域问题的产生是因为浏览器对于javascript的同源策略的限制导致的,例如a.com下面的js不能 调用b.com中的 js、对象或数据,因为a.com和b.com是不同域,所以想要调用就出现了跨域问题。
  • 同源策略:请求的url地址必须与浏览器上url地址处于同域上,也就是域名、端口号、协议相同。配置如下:
http {
    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;

   # 配置负载均衡的服务器Ip和负载均衡方式(此处为权重轮询)并且允许请求失败次数 max_fails 为3次以及 fail_timeout 请求3次失败后,暂停的时间。
	upstream tomcate_server {
		server localhost:3010 weight=2 max_fails=3  fail_timeout=10s;
		server localhost:3011 weight=2 max_fails=3 fail_timeout=10s;
		server localhost:3012 weight=2 max_fails=3 fail_timeout=10s;
		# backup 不能和 ip_hash 关键字一起使用
		server localhost:3100 max_fails=3 fail_timeout=10s backup;# 其它所有的非backup机器down或者忙的时候,请求backup机器。所以这台机器压力会最轻。
	}
	
	# 配置负载均衡的服务器Ip和负载均衡方式(此处为权重轮询)并且允许请求失败次数 max_fails 为3次以及 fail_timeout 请求3次失败后,暂停的时间。
	upstream tomcate_serverTwo {
		server localhost:4010 weight=2 max_fails=3 fail_timeout=10s;
		server localhost:4011 weight=2 max_fails=3 fail_timeout=10s;
		server localhost:4012 weight=2 max_fails=3 fail_timeout=10s;
		# backup 不能和 ip_hash 关键字一起使用
		server localhost:4100 max_fails=3 fail_timeout=10s backup;# 其它所有的非backup机器down或者忙的时候,请求backup机器。所以这台机器压力会最轻。
	}

    server {
        listen       8086;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;
        
        # 超过超时时间则进行故障转移
        location /chenOne {
			# 放置静态资源的地方
            root   static;# (d:/nginx/static)
			# 访问的首页
            index  index.html index.htm;
			# 进行负载均衡的配置指向地址
			proxy_pass http://tomcate_server;
        }
		
		# 超过超时时间则进行故障转移
		location /chenTwo {
			# 放置静态资源的地方
            root   static;# (d:/nginx/static)
			# 访问的首页
            index  index.html index.htm;
			# 进行负载均衡的配置指向地址
			proxy_pass http://tomcate_serverTwo;
        }
        #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://tomcate_serverhttp://tomcate_serverTwo 两个服务器上的数据就全 都出现在了http://loaclhost:8086服务器上,从而解决了跨域的问题。


🎉总结:

  • 更多参考精彩博文请看这里:《陈永佳的博客》

  • 喜欢博主的小伙伴可以加个关注、点个赞哦,持续更新嘿嘿!