Linux 服务器集群下同步目录文件 - rsync

时间:2022-07-22
本文章向大家介绍Linux 服务器集群下同步目录文件 - rsync,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

rsync 地址: https://www.samba.org/ftp/rsync/rsync.html

简介: remote synchronize是一个远程数据同步工具,可通过 LAN/WAN 快速同步多台主机之间的文件。也可以使用 rsync 同步本地硬盘中的不同目录。 rsync 是用于替代 rcp 的一个工具,rsync 使用所谓的 rsync算法 进行数据同步,这种算法只传送两个文件的不同部分,而不是每次都整份传送,因此速度相当快。

rsync 基于inotify 开发

一、客户端 - 主动拉取文件(不实时)

1. 安装

两端安装

yum install -y rsync

2. 服务端配置

创建密码文件

vi /etc/rsync.password
或者
echo "hello:123" > /etc/rsync.password
# 账号:密码

hello:123

修改密码文件权限

chmod 600 /etc/rsync.password

修改配置文件

vi /etc/rsyncd.conf
uid = root
gid = root
use chroot = no
max connections = 200
hosts allow = *
timeout = 600
log file = /var/log/rsyncd.log
pid file = /var/run/rsyncd.pid
lock file = /var/run/rsync.lock
ignore errors
read only = false
list = false
host deny = 0.0.0.0/32
# rsyncd 权限用户
auth users = hello
secrets file = /etc/rsync.password
transfer logging = yes
#Module definitions
    
# 映射路径编号 拉取时需要 编号
[www]
path = /usr/local/openresty/nginx/html/

创建监控目录

mkdir -p /data/www

启动服务

rsync --daemon

3. 客户端配置

创建密码文件(客户端只需要密码)

vi /etc/rsync.password
或者
echo "123" > /etc/rsync.password

修改密码文件权限

chmod 600 /etc/rsync.password

客户端同步数据

# hello 为服务端用户名
# 192.0.0.110 为服务端地址
# www 为服务端 文件路径编号

rsync -zvaP --password-file=/etc/rsync.password hello@192.0.0.110::www /usr/local/openresty/nginx/html/

二、主服务器 - 主动推送至客户端(实时同步)

实时同步

rsync + inotify-tools 或 rsync+sersync

1. 安装

两端安装

yum install -y rsync

2. 客户端配置

创建密码文件

vi /etc/rsync.password
或者
echo "hello:123" > /etc/rsync.password
# 账号:密码

hello:123

修改密码文件权限

chmod 600 /etc/rsync.password

修改配置文件

vi /etc/rsyncd.conf
uid = root
gid = root
use chroot = no
max connections = 200
hosts allow = *
timeout = 600
log file = /var/log/rsyncd.log
pid file = /var/run/rsyncd.pid
lock file = /var/run/rsync.lock
ignore errors
read only = false
list = false
host deny = 0.0.0.0/32
# rsyncd 权限用户
auth users = hello
secrets file = /etc/rsync.password
transfer logging = yes
#Module definitions
    
# 映射路径编号 拉取时需要 编号
[www]
path = /usr/local/openresty/nginx/html/

启动服务

rsync --daemon

3. 服务端配置

sersync 的方式监控目录中变化的数据,通过rsync客户端推送给rsync daemon

在数据源创建密码文件

vi /etc/rsync.password 

密码 123

或 echo “123” > /etc/rsync.password

chmod 600  /etc/rsync.password

下载sersync 并解压

wget https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/sersync/sersync2.5.4_64bit_binary_stable_final.tar.gz

tar xf sersync2.5.4_64bit_binary_stable_final.tar.gz 

cd GNU-Linux-x86/

mkdir -p  /opt/sersync/{logs,conf,bin}
cp sersync2 /opt/sersync/bin
cp confxml.xml /opt/sersync/conf/
cd /opt/sersync/conf/

编辑sersync 配置文件

vi confxml.xml 

xml中:
    <localpath watch="需要监控的目录" >
	<remote ip="IP地址" name=“客户端 路径编号 即 www ” />
   	... 可 remote 多个
    <auth start="true" users="客户端rsync用户名 即 hello" passwordfile="服务端密码文件路径" />

启动sersync

/opt/sersync/bin/sersync2 -d -r -o ./confxml.xml 

测试

cd /需要监控的目录
touch {1,2,3,4,5,6}