使用内存硬盘(tmpfs)来加速你的网站
source link: https://www.laruence.com/2020/02/15/4982.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
博客迁移完腾讯云以后, 又配置好了ssl,一直在调优PHP的性能,中午调整了半天fpm和opcache, 晚上又突然想起来我之前在某个大会上分享过的使用tmpfs(把内存当成硬盘)来加速网站的做法,于是~搞!
重要的事情要说三遍, 开始之前,对你对nginx root目录要备份, 备份, 备份!
腾讯云这台机器是ubuntu的,版本是:
$ cat /etc/issue Ubuntu 18.04.4 LTS \n \l
首先,我们创建一个目录,比如/ramdisk, 然后使用tmpfs命令挂载一部分内存当作硬盘:
mount -t tmpfs -o size=256M tmpfs /ramdisk
此处我挂载了最大256M的内存到/tmp节点,值得注意的是系统不会一下子就会把256M内存占用,而是实际用多少占多少,最大不超过256M。
可以用df来确认是否成功操作:
$ df -h Filesystem Size Used Avail Use% Mounted on ...... tmpfs 256M 0 256M 0% /ramdisk
接下来我们需要用到一个今天才发现的神器(以前还要自己写corntab脚本来做同步:<), Anything-sync-daemon , 它可以自动的把一个指定目录同步到tmpfs,并且能设置按时,或者系统启动时来自动同步,有了个这个工具,这一切都会变得非常简单。
首先下载asd( Anything-sync-daemon ):
wget https://github.com/graysky2/anything-sync-daemon/archive/master.zip
解压缩之后,执行安装:
make install-systemd-all
(这里有个问题,默认的它会把systemd服务安装到/usr/lib/systemd/system, 但不知道为啥在我的这个系统不systemd找不到这个服务,我通过把它的几个服务脚本拷贝到/lib/systemd/system解决)
mv asd-resync.service asd-resync.timer asd.service /lib/systemd/system
然后通知systemd:
systemctl daemon-reload
我的博客的nginx的root是/home/huixinchen/www/htdocs下, 我们现在希望是这个目录能自动同步到tmpfs目录,也就是/ramdisk, 于是我们修改asd.conf文件, 增加:
WHATTOSYNC=('/home/huixinchen/www/htdocs/') //要同步的目录 VOLATILE="/ramdisk" // tmpfs目录
你也可以同步多个文件,只需要逗号分隔写在WHATTOSYNC数组里即可,比如:
WHATTOSYNC=('/home/huixinchen/www/htdocs/', ‘/home/huixinchen/local/xxxx’) //要同步的目录
然后我们设置每天同步一次tmpfs上的变更内容到硬盘,编辑/lib/systemd/system/asd-resync.timer,
[Unit] Description=Timer for Anything-sync-daemon - 1Hour PartOf=asd-resync.service asd.service [Timer] OnUnitActiveSec=24h
然后我们用asd p检查下:
$ asd p Anything-sync-daemon v5.85 on Ubuntu 18.04.4 LTS Daemon pid file is not present. Resync cronjob is not present. Overlayfs technology is currently inactive. Asd will manage the following per /etc/asd.conf settings: owner/group id: huixinchen/1000 target to manage: /home/huixinchen/www/htdocs sync target: /home/huixinchen/www/.htdocs-backup_asd tmpfs target: /ramdisk/asd-huixinchen/home/huixinchen/www/htdocs dir size: 237M recovery dirs: none
asd会把我的
/home/huixinchen/www/htdocs
目录同步到
/ramdisk/asd-huixinchen/home/huixinchen/www/htdocs,
并且会把tmpfs上的更新内容按照时间写回到
/home/huixinchen/www/.htdocs-backup_asd
当我们停止asd的服务的时候,asd会把.htdocs-backup_asd在mv成htdocs,这样就不用担心你的内容会因为服务器突然断电丢失了.
现在,让我们启动asd:
service asd start
现在/home/huixinchen/www/htdocs就会被复制到tmpfs, 并且软链接过去,也就是说nginx我们根本不需要修改, 只需要重启一下fpm, 重置一下opcache的cache即可:
$ ll total 0K lrwxrwxrwx 1 huixinchen huixinchen 50 Feb 15 22:27 htdocs -> /ramdisk/asd-huixinchen/home/huixinchen/www/htdocs/
重启完fpm,一切works out of the box!
PS:关于Asd更多的信息,可以参考: Anything-sync-daemon
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK