Chinaunix

标题: Nginx 巧用Linux内存加速静态文件访问 . [打印本页]

作者: 中关村村草    时间: 2012-02-03 17:59
标题: Nginx 巧用Linux内存加速静态文件访问 .
Nginx 巧用Linux内存加速静态文件访问 .







         nginx 静态文件处理能力是非常棒的,我们能不能进一步优化呢?静态文件的读取,会损耗IO资源。可以考虑把静态文件转移到linux内存中,每次从内存读取资源,效果应该会好很多。不过,系统重启时,内存文件会自动消失。针对这种情况,我们需要做个shell,在系统重启时,把静态文件拷贝到内存中。

        在给出shell示例之前,先做几个假设。nginx.conf中所配置站点的路径是/home/wwwroot/res,站点所对应文件原始存储路径:/opt/web/res

       开始编写拷贝内存initwebres脚本:
  1. [plain] view plaincopyprint?
  2. 01.vim /root/.bin/initwebres.sh  
  3. vim /root/.bin/initwebres.sh
复制代码
脚本内容如下:


[plain] view plaincopyprint?
  1. 01.#! /bin/bash   
  2. 02.  
  3. 03.res_path="/opt/web/res"  
  4. 04.mem_path="/dev/shm/res"  
  5. 05.lk_path="/home/wwwroot/res"  
  6. 06.  
  7. 07.if [ ! -d "$mem_path" ]; then  
  8. 08.        cp -r "$res_path" "$mem_path"  
  9. 09.fi  
  10. 10.  
  11. 11.if [ ! -L "$lk_path" ]; then  
  12. 12.        ln -s "$mem_path" "$lk_path"  
  13. 13.fi  
  14. #! /bin/bash

  15. res_path="/opt/web/res"
  16. mem_path="/dev/shm/res"
  17. lk_path="/home/wwwroot/res"

  18. if [ ! -d "$mem_path" ]; then
  19.         cp -r "$res_path" "$mem_path"
  20. fi

  21. if [ ! -L "$lk_path" ]; then
  22.         ln -s "$mem_path" "$lk_path"
  23. fi
复制代码
脚本写好之后,需要让脚本自启动。假设bash路径/bin/bash,然后在/etc/rc.local末尾添加:


[plain] view plaincopyprint?
  1. 01./bin/bash /root/.bin/initwebres.sh  
  2. /bin/bash /root/.bin/initwebres.sh   
复制代码
通过上述操作,基本搞定一切。不过,更新网站静态文件时,切记要更新内存/dev/shm/中的相应文件哦!
     

     Shell脚本的编写,可以参考以前的blog:   Shell脚本逻辑操作符简介  和 shell脚本比较运算符及逻辑运算符小结


作者: 我是软件狂    时间: 2012-02-03 18:00
谢谢分享
作者: lastfile    时间: 2012-02-04 15:31
内存大的当然可以这样搞了




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2