分享

inotify+unison双向同步环境部署

 zjycy 2017-01-26

 在网上搜寻了很多方案,在liux下做文件同步,有如下几种方式:

1、nfs实现web数据共享
2、rsync +inotify实现web数据同步
3、rsync+sersync更快更节约资源实现web数据同步
4、unison+inotify实现web数据双向同步

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


环境部署,有如下两台服务器需要做双向同步

192.168.10.1是server1,

192.168.10.2是server2


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

分别在server1和server2下,创建秘钥

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

添加密钥到授权密钥文件中

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./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./~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.
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上执行上面两个脚本,这样两台服务器的目录会保持相互实时同步了!!!



    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多