inotify+unison双向同步环境部署

在网上搜寻了不少方案,在liux下作文件同步,有以下几种方式: html

一、nfs实现web数据共享
二、rsync +inotify实现web数据同步
三、rsync+sersync更快更节约资源实现web数据同步
四、unison+inotify实现web数据双向同步 linux

在这里详细介绍第四种方案,前几种都有些各自的不足。只有第四种方案支持双向实时同步,且当其中一台服务器宕机,也不会影响web的访问。(ps:以前一直喜欢nfs,配置很是简单,可是其有个致命的缺点就是其中一台web服务挂掉以后,会直接致使web页面没法访问)。 web


环境部署,有以下两台服务器须要作双向同步 shell

192.168.10.1是server1, bash

192.168.10.2是server2 服务器


第一步,保证两台服务器之间能够经过ssh无密码访问,操做以下(这里以root用户为例): ssh

分别在server1和server2下,建立秘钥 测试

mkdir ~/.ssh
chmod 700 ~/.ssh
生成RSA密钥
ssh-keygen -t rsa 
(而后连续三次回车)
加密

添加密钥到受权密钥文件中
spa

cd ~/.ssh
ssh "-p 22" 192.168.10.1 cat /root/.ssh/id_rsa.pub >> authorized_keys  #小写p
ssh "-p 22" 192.168.10.2 cat /root/.ssh/id_rsa.pub >> authorized_keys
scp  -P 22 authorized_keys 192.168.10.2:/root/.ssh/  #大写P

chmod 600 /root/.ssh/authorized_keys
在服务器server2上操做
chmod 600 /root/.ssh/authorized_keys
分别在两台机器上执行以下测试
ssh -p 22 192.168.10.1 date
ssh -p 22 192.168.10.2 date

至此用户受权完成。

第二步,软件安装,server1和server2都得安装

安装unison
首先安装ocaml,版本至少为3.07或更高
下载地址:http://caml.inria.fr/pub/distrib/ocaml-3.10/
tar xf ocaml-3.10.2.tar.gz
cd ocaml-3.10.2
./configure
make world opt
make install
cd ..


安装unison

下载地址:http://www.seas.upenn.edu/~bcpierce/unison//download/releases/unison-2.13.16/
tar xvf unison-2.13.16.tar.gz
cd unison-2.13.16
make UISTYLE=text THREADS=true STATIC=true
cp unison /usr/local/bin
cd ..


安装inotify

下载地址:http://inotify-tools.sourceforge.net
tar xvf inotify-tools-3.14.tar.gz
cd inotify-tools-3.14
./configure
make
make install
cd ..


到此所需的软件都已安装完毕,能够在server1服务器上执行这个命令,来查看两台服务器之间是否能够同步文件,unison -batch /home/server1/ ssh://192.168.10.2//home/server2 ,若是这时候抱以下错误:


/usr/local/bin/inotifywait: error while loading shared libraries: libinotify
能够执行下这个命令:



ln -sv /usr/local/lib/libinotify* /usr/lib/

执行成功后,看目录下的文件是否同步。


第三步,建立.sh脚原本执行同步

1)server1上建立脚本/root/inotify.sh(chmod a+x /root/inotify.sh):


#/bin/bash
ip2="192.168.10.2"
src2="/home/server1/"
dst2="/home/server2/"
/usr/local/bin/inotifywait -mrq -e create,delete,modify,move $src2 | while read line; do
/usr/local/bin/unison -batch $src2 ssh://$ip2/$dst2
echo -n "$line " >> /var/log/inotify.log
echo `date | cut -d " " -f1-4` >> /var/log/inotify.log
done

1)server2上建立脚本/root/inotify.sh(chmod a+x /root/inotify.sh):

#/bin/bash 
ip1="192.168.10.1"
src1="/home/server2/"
dst1="/home/server1/"
/usr/local/bin/inotifywait -mrq -e create,delete,modify,move $src1 | while read line; do
/usr/local/bin/unison -batch $src1 ssh://$ip1/$dst1
echo -n "$line " >> /var/log/inotify.log
echo `date | cut -d " " -f1-4` >> /var/log/inotify.log
done
最后分别在server1和server2上执行上面两个脚本,这样两台服务器的目录会保持相互实时同步了!!!
相关文章
相关标签/搜索