nginx实现读写分离

      测试环境

             OS: rhel6

             A服务器: 配置nginx实现负载均衡和方向代理功能

             B服务器: 简单的web服务器,没做其他配置,读服务器

             C服务器: 简单的web服务器,没做其他配置,写服务器

       部署: A服务器实现前端负载均衡和方向代理功能,后端有两台web服务器,B服务器只进行读操作,C服务器只进行写操作,而B和C服务器之间通过rsync+inotify实现数据的同步这样就简单的实现了nginx的读写分离功能。

配置之前先来了解一下什么是WebDAV??

       WebDAV (Web-based Distributed Authoring and Versioning) 一种基于 HTTP1.1协议的通信协议。它扩展了HTTP 1.1,在GET、POST、HEAD等几个HTTP标准方法以外添加了一些新的方法,使应用程序可直接对Web Server直接读写,并支持写文件锁定(Locking)及解锁(Unlock),还可以支持文件的版本控制。

       Web 分布式创作和版本管理 (WebDAV) 扩展了 HTTP/1.1 协议,允许客户端发布、锁定和管理 Web 上的资源。

1.在A服务器上配置负载均衡和方向代理功能

   # vim /etc/nginx/nginx.conf

proxy_cache_path /nginx/cache/first levels=1:2 keys_zone=first:20m max_size=1g;
####读服务器组  B
upstream read {
      #ip_hash;
      server 192.168.20.121 weight=2 max_fails=2 fail_timeout=2;
      server 192.168.20.123 weight=2 max_fails=2 fail_timeout=2;
   }
####写服务器组  A
upstream write {  
      #ip_hash;
      server 192.168.20.122 weight=2 max_fails=2 fail_timeout=2;
      server 192.168.20.124 weight=2 max_fails=2 fail_timeout=2;
      server 127.0.0.1:8080 backup;
   }

server {
      location / {
           root   html;
           index  index.html index.htm;
           proxy_cache first;
           proxy_cache_valid 200 10m;
           proxy_pass  http://read;
           if($request_method = "POST"){    ####在这里判断用户是否执行的是写操作
                      proxy_pass http://write;
           }
           proxy_set_header Host $host;
           proxy_set_header X-Real-IP $remote_addr;
      }
}

2.A服务器上重新启动服务

   # service nginx restart

3.在B,C服务器上开启httpd的WebDAV功能

   # vim /etc/httpd/conf/httpd.conf

        Dav on   ####在<Directory  "/var/www/html/">标签里添加

4.在B,C服务器上重启httpd服务

   # service httpd retstart

5.在A服务器上用curl命令测试下是否能正常访问B,C服务器上的web服务

   # curl  http://192.168.20.121 

6.用curl命令的T参数实现http协议中的put方法上传文件 (A服务器)

   # curl  -T  /etc/issue  http://192.168.20.121  ###往读服务器上传文件会报405的错误,因为没开启WebDAV功能

   # curl  -T  /etc/issue  http://192.168.20.122  ###往写服务器上传文件会报403的错误,禁止访问权限不够

7.下面我们给apache用户授权

   # setfacl -m u:apache:rwx /var/www/html/

8.最后再测试下看是否可以往写服务器上传文件

   # curl  -T  /etc/issue  http://192.168.20.122

9.验证上传是否成功

   # cd /var/www/html