案例需求
代码分发服务器 172.18.20.78
PHP后端分布式服务器所在网段172.18.20.0/24
需要:
1、将代码自动分发到PHP后端服务器
2、其中qcms系统为老系统,需要将其中的上传的图片文件实时同步到负载均衡服务器[nginx](这里和代码分发服务器是同一台)
3、在负载均衡服务器上使用workerman将实时同步过来的老系统图片文件再同步到七牛云,然后删除
4、使用nginx重写将不存在的图片301跳转到七牛云
5、虽然lsyncd是实时发起同步,但毕竟网络同步也需要时间,所以老系统上传图片后立即访问(考虑html在线编辑器上传图片后立即预览的情况)图片时,nginx会发现图片还没有同步过来,造成nginx判断图片已经被workerman同步到了七牛云,从而直接重写到七牛云的情况。所以老系统上传图片成功后需要等待2s再给客户端返回,以便lsyncd完成同步。
一、完成代码分发(代码在/data/www/laravel 和 /data/www/qcms)
代码分发服务器rsync配置
/etc/rsyncd.conf
uid = www
gid = www
port = 873
use chroot = no
max connections = 200
log file = /var/log/rsyncd.log
pid file = /var/run/rsyncd.pid
lock file = /var/run/rsyncd.lock
dont compress = *.gz *.tgz *.zip *.z *.Z *.rpm *.deb *.bz2
[www]
path = /data/www
comment = from source mirror server to backend instance server
ignore errors = yes
read only = no
list = no
timeout = 600
auth users = php
secrets file = /etc/rsyncd.passwd
hosts allow = 172.18.20.0/24
hosts deny = 0.0.0.0/32
systemctl enable rsyncd
systemctl start rsyncd
客户端rsync排除文件配置,排除匹配规则参考:https://www.cnblogs.com/f-ck-need-u/p/7221713.html 中的 INCLUDE/EXCLUDE PATTERN RULES章节
vi /data/www/rsync.exclude
laravel/storage/
laravel/bootstrap/cache/
Public/uploads/
Data/Cache/
*.pid
*.log
客户端rsync crontab配置
* * * * * rsync -rltuvz php@172.18.20.78::www/rsync.exclude /data/www/rsync.exclude --password-file=/etc/rsync.passwd
* * * * * rsync -rltuvz --exclude-from='/data/www/rsync.exclude' php@172.18.20.78::www /data/www/ --password-file=/etc/rsync.passwd
二、客户端系统上传文件实时同步到网关
yum install lsyncd -y
lsyncd 配置,vi /etc/lsyncd.conf
settings {
logfile = "/var/log/lsyncd/lsyncd.log",
statusFile = "/var/log/lsyncd/lsyncd.status",
inotifyMode = "CloseWrite",
maxProcesses = 4,
}
sync {
default.rsync,
source = "/data/www/xxx1",
target = "php@172.18.20.78::www/xxx1",
delete= false,
excludeFrom = "/data/www/lsyncd.exclude",
delay = 0,
rsync = {
binary = "/usr/bin/rsync",
archive = true,
compress = true,
verbose = true,
password_file = "/etc/rsync.passwd",
_extra = {"--bwlimit=200"}
}
}
sync {
default.rsync,
source = "/data/www/xxx2",
target = "php@172.18.20.78::www/xxx2",
delete= false,
excludeFrom = "/data/www/lsyncd.exclude",
delay = 0,
rsync = {
binary = "/usr/bin/rsync",
archive = true,
compress = true,
verbose = true,
password_file = "/etc/rsync.passwd",
_extra = {"--bwlimit=200"}
}
}
多个任务就写多个sync配置即可
如果同步之后需要做其他动作,参考:https://axkibe.github.io/lsyncd/faq/postscript/
文件排除,排除规则写法与原生rsync有点不同,更为简单:
监控路径里的任何部分匹配到一个文本,都会被排除,例如foo可以匹配路径/bin/foo/bar
如果规则以斜线/开头,则从头开始要匹配全部
如果规则以/结尾,则要匹配监控路径的末尾
?匹配任何字符,但不包括/
*匹配0或多个字符,但不包括/
**匹配0或多个字符,可以是/
vi /data/lsyncd.exclude
storage/
bootstrap/cache/
Data/
*.pid
*.log
启动服务
systemctl enable lsyncd
systemctl start lsyncd
如果启动lsyncd,报错 rsync error: error in socket IO (code 10),可尝试重启代码分发服务器rsyncd服务