您的位置 首页 php

php手把手教你做网站(二十七)nginx 负载均衡配置

本地测试:可以使用IP+不同端口作为不同服务器进行测试

1、配置nginx/conf

 http {

    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;


    upstream urlbox {
        ip_hash;#同一个ip访问一个站点,可以注释掉
        server 127.0.0.1:8812 weight=1 max_fails=2 fail_timeout=30s;
        server 127.0.0.1 weight=2 max_fails=2 fail_timeout=30s;
    }
    server {
        listen       80;#端口
        server_name  localhost;#解析的域名
        location / {
            proxy_pass 
        }
        #error_page  404              /404.html;
        error_page   500 502 503 504  /50x.html;

        location = /50x.html {
            root   html;
        }
    }  

说明:

  1. weight出现的几率,默认为1,配置高的服务器可以设置得高一些;
  2. server 127.0.0.1:8812 weight=1; 正规服务器这里127.0.0.1:8812,要换成服务器的局域网地址,192.168..;
  3. upstream urlbox,这里的 urlbox 可以换成任意的;
  4. proxy_pass 反向代理;3、4的 urlbox 是对应的;
  5. ip_hash; 是只同一个IP访问一个站点;
  6. max_fails失败次数;
  7. fail_timeout失败时间;
  8. max_fails,fail_timeout 不添加默认即可;

2、A,B两台服务器作为代理,用于展示网站内容

  1. A(127.0.0.1:8812)127.0.0.1:8812这个网址要可以访问到展示的网站;
  2. B(127.0.0.1)同A也要访问到网站;
  3. 数据库放到链接C服务器(127.0.0.1:8800),A、B2个网站数据库地址都使用C服务器的;
  4. C服务器,用于添加信息,所上传的图片、压缩包等附件,需要填写完整的网址,不能是public/这样的,A、B网站没法显示附件,要使用http://网址/public/图片地址;

3、存储用户登陆信息

  1. 如果upstream urlbox 不加入 ip_hash(用于一个IP访问一个站点),需要使用redis存储用户登陆信息,防止一个服务器出问题切换到另一个的时候用户退出了登陆;
  2. 如果不想使用redis,也可以使用文件存储的方式在C服务器存储用户的登陆信息,使用curl读取C服务器的用户信息,判断是否已经超时;

redis存储读取示例:

 <?php
   $redis = new Redis();
   $redis->connect('192.168.100.2', 6379);//192.168.100.2为安装redis的IP
   $redis->auth('cms168');//redis.windows.conf  443行requirepass 设置的密码
   $username='ttt';
   $redis->set('user_'.$username,time(),15);//15为设置的有效期 15秒
   if(!$redis->get('user_'.$username)){
      echo '已经退出登录';  
   }
?>  

redis存储数组信息:

由于不能直接存储数组信息,可以使用序列化和反序列化转换

 <?php
   $redis = new Redis();
   $redis->connect('192.168.100.2', 6379);
   $redis->auth('cms168');
   
   $lgninfo=serialize(array('username'=>'ttt','lgntime'=>time()));
   $redis->set("ulogin", $lgninfo,15);

   var_dump( unserialize($redis->get('ulogin')));
?>  

文章来源:智云一二三科技

文章标题:php手把手教你做网站(二十七)nginx 负载均衡配置

文章地址:https://www.zhihuclub.com/80019.shtml

关于作者: 智云科技

热门文章

网站地图