Skynet

---------- ---------- 我的新 blog : liukaiyi.cublog.cn ---------- ----------

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  112 Posts :: 1 Stories :: 49 Comments :: 0 Trackbacks

2010年1月31日 #


作者:NetSeek  http://www.linuxtone.org (IT运维专家网|集群架构|性能调优)
欢迎转载,转载时请务必以超链接形式标明文章原始出处和作者信息及本声明.
首发时间: 2008-11-25     更新时间:2009-1-14

目 录
一、        Nginx 基础知识
二、        Nginx 安装及调试
三、        Nginx Rewrite
四、        Nginx Redirect
五、        Nginx 目录自动加斜线:
六、        Nginx Location
七、        Nginx expires
八、        Nginx 防盗链
九、        Nginx 访问控制
十、        Nginx日志处理
十一、     Nginx Cache
十二、     Nginx负载均衡
十三、       Nginx简单优化      
十四、        如何构建高性能的LEMP环境
十五、        Nginx服务监控
十六、        常见问题与错误处理.
十七、        相关资源下载

【前言】:
编写此技术指南在于推广普及NGINX在国内的使用,更方便的帮助大家了解和掌握NGINX的一些使用技巧。本指南很多技巧来自于网络和工作中或网络上朋友们问我的问题.在此对网络上愿意分享的朋友们表示感谢和致意!欢迎大家和我一起丰富本技术指南提出更好的建议!请朋友们关注: http://www.linuxtone.org 技术分享社区! 互想学习共同进步!

一、 Nginx 基础知识
1、简介
   Nginx ("engine x") 是一个高性能的 HTTP 和 反向代理 服务器,也是一个 IMAP/POP3/SMTP 代理服务器。 Nginx 是由 Igor Sysoev 为俄罗斯访问量第二的 Rambler.ru 站点开发的,它已经在该站点运行超过两年半了。Igor 将源代码以类BSD许可证的形式发布。尽管还是测试版,但是,Nginx 已经因为它的稳定性、丰富的功能集、示例配置文件和低系统资源的消耗而闻名了。
更多的请见官方wiki: http://wiki.codemongers.com/

2、 Nginx的优点
nginx做为HTTP服务器,有以下几项基本特性:
1)        处理静态文件,索引文件以及自动索引;打开文件描述符缓冲.
2)        无缓存的反向代理加速,简单的负载均衡和容错.
3)        FastCGI,简单的负载均衡和容错.
4)        模块化的结构。包括gzipping, byte ranges, chunked responses, 以及 SSI-filter等filter。如果由FastCGI或其它代理服务器处理单页中存在的多个SSI,则这项处理可以并行运行,而不需要相互等待。
5)        支持SSL 和 TLS SNI

Nginx专为性能优化而开发,性能是其最重要的考量, 实现上非常注重效率 。它支持内核Poll模型,能经受高负载的考验, 有报告表明能支持高达 50,000 个并发连接数。
Nginx具有很高的稳定性。其它HTTP服务器,当遇到访问的峰值,或者有人恶意发起慢速连接时,也很可能会导致服务器物理内存耗尽频繁交换,失去响应,只能重启服务器。例如当前apache一旦上到200个以上进程,web响 应速度就明显非常缓慢了。而Nginx采取了分阶段资源分配技术,使得它的CPU与内存占用率非常低。nginx官方表示保持10,000个没有活动的连 接,它只占2.5M内存,所以类似DOS这样的攻击对nginx来说基本上是毫无用处的。就稳定性而言, nginx比lighthttpd更胜一筹。
Nginx支持热部署。它的启动特别容易, 并且几乎可以做到7*24不间断运行,即使运行数个月也不需要重新启动。你还能够在不间断服务的情况下,对软件版本进行进行升级。
Nginx采用master-slave模型, 能够充分利用SMP的优势,且能够减少工作进程在磁盘I/O的阻塞延迟。当采用select()/poll()调用时,还可以限制每个进程的连接数。
Nginx 代码质量非常高,代码很规范, 手法成熟, 模块扩展也很容易。特别值得一提的是强大的Upstream与Filter链。 Upstream为诸如reverse proxy, 与其他服务器通信模块的编写奠定了很好的基础。而Filter链最酷的部分就是各个filter不必等待前一个filter执行完毕。它可以把前一个 filter的输出做为当前filter的输入,这有点像Unix的管线。这意味着,一个模块可以开始压缩从后端服务器发送过来的请求,且可以在模块接收 完后端服务器的整个请求之前把压缩流转向客户端。
Nginx采用了一些os提供的最新特性如对sendfile (Linux 2.2+),accept-filter (FreeBSD 4.1+),TCP_DEFER_ACCEPT (Linux 2.4+) 的支持,从而大大提高了性能

二、 Nginx 安装及调试
1、Pcre 安装

  1. ./configure
  2.   make && make install
  3.   cd ../
复制代码

2.        nginx 编译安装

  1. ./configure --user=www --group=www --prefix=/usr/local/nginx/ --with-http_stub_status_module --with-openssl=/usr/local/openssl
  2. make && make install
复制代码

更详细的模块定制与安装请参照官方wiki.

3、Nginx 配置文件测试:

  1. # /usr/local/nginx/sbin/nginx -t  //Debug 配置文件的关键命令需要重点撑握.
  2. 2008/12/16 09:08:35 [info] 28412#0: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
  3. 2008/12/16 09:08:35 [info] 28412#0: the configuration file /usr/local/nginx/conf/nginx.conf was tested successfully
复制代码

3、Nginx 启动:

  1. # /usr/local/nginx/sbin/nginx
复制代码

4、Nginx 配置文件修改重新加载:

  1. # kill -HUP `cat /usr/local/nginx/logs/nginx.pid
复制代码

`
三、Nginx Rewrite

1.  Nginx Rewrite 基本标记(flags)
last - 基本上都用这个Flag。
※相当于Apache里的[L]标记,表示完成rewrite,不再匹配后面的规则
break - 中止Rewirte,不再继续匹配
redirect - 返回临时重定向的HTTP状态302
permanent - 返回永久重定向的HTTP状态301
      ※原有的url支持正则  重写的url不支持正则

2.  正则表达式匹配,其中:
    * ~         为区分大小写匹配
    * ~*       为不区分大小写匹配
    * !~和!~*   分别为区分大小写不匹配及不区分大小写不匹配

3. 文件及目录匹配,其中:
   * -f和!-f用来判断是否存在文件
    * -d和!-d用来判断是否存在目录
    * -e和!-e用来判断是否存在文件或目录
    * -x和!-x用来判断文件是否可执行


3.  Nginx 的一些可用的全局变量,可用做条件判断:

  1. $args
  2. $content_length
  3. $content_type
  4. $document_root
  5. $document_uri
  6. $host
  7. $http_user_agent
  8. $http_cookie
  9. $limit_rate
  10. $request_body_file
  11. $request_method
  12. $remote_addr
  13. $remote_port
  14. $remote_user
  15. $request_filename
  16. $request_uri
  17. $query_string
  18. $scheme
  19. $server_protocol
  20. $server_addr
  21. $server_name
  22. $server_port
  23. $uri
复制代码

四、 Nginx Redirect
将所有linuxtone.org与netseek.linuxtone.org域名全部自跳转到http://www.linuxtone.org

  1. server
  2. {
  3. listen 80;
  4. server_name linuxtone.org netseek.linuxtone.org;
  5. index index.html index.php;
  6. root /data/www/wwwroot;
  7. if ($host !~ "^www.linxtone.org$") {
  8. rewrite ^(.*) http://www.linuxtone.org$1 redirect;
  9. }
  10. ........................
  11. }
复制代码

五、 Nginx 目录自动加斜线:

  1. if (-d $request_filename){
  2.            rewrite ^/(.*)([^/])$ http://$host/$1$2/ permanent;
  3.      }
复制代码

六  Nginx Location

1.基本语法:[和上面rewrite正则匹配语法基本一致]
location [=|~|~*|^~] /uri/ { … }
    * ~  为区分大小写匹配
    * ~* 为不区分大小写匹配
    * !~和!~*分别为区分大小写不匹配及不区分大小写不匹配

示例1:
location = / {
# matches the query / only.
# 只匹配 / 查询。
}
匹配任何查询,因为所有请求都已 / 开头。但是正则表达式规则和长的块规则将被优先和查询匹配

示例2:
location ^~ /images/ {
# matches any query beginning with /images/ and halts searching,
# so regular expressions will not be checked.
# 匹配任何已 /images/ 开头的任何查询并且停止搜索。任何正则表达式将不会被测试。

示例3:
location ~* .(gif|jpg|jpeg)$ {
# matches any request ending in gif, jpg, or jpeg. However, all
# requests to the /images/ directory will be handled by
}
# 匹配任何已 gif、jpg 或 jpeg 结尾的请求。


七、 Nginx expires

1.根据文件类型expires

  1. # Add expires header for static content
  2. location ~* .(js|css|jpg|jpeg|gif|png|swf)$ {
  3.     if (-f $request_filename) {
  4.        root /data/www/wwwroot/bbs;
  5.        expires      1d;
  6.        break;
  7.     }
  8. }
复制代码

2、根据判断某个目录

  1. # serve static files
  2. location ~ ^/(images|javascript|js|css|flash|media|static)/  {
  3. root    /data/www/wwwroot/down;
  4.         expires 30d;
  5.   }
复制代码

八、  Nginx 防盗链

1.        针对不同的文件类型

  1. #Preventing hot linking of images and other file types
  2. location ~* ^.+.(gif|jpg|png|swf|flv|rar|zip)$ {
  3.         valid_referers none blocked server_names *.linuxtone.org linuxtone.org http://localhost baidu.com;
  4. if ($invalid_referer) {
  5.       rewrite   ^/   ;
  6.      # return   403;
  7.       }
  8. }
复制代码

2.        针对不同的目录

  1. location /img/ {
  2.     root /data/www/wwwroot/bbs/img/;
  3.     valid_referers none blocked server_names *.linuxtone.org http://localhost baidu.com;
  4.     if ($invalid_referer) {
  5.                    rewrite  ^/  ;
  6.                    #return   403;
  7.     }
  8. }
复制代码

3.        同实现防盗链和expires的方法

  1. #Preventing hot linking of images and other file types
  2. location ~* ^.+.(gif|jpg|png|swf|flv|rar|zip)$ {
  3.         valid_referers none blocked server_names *.linuxtone.org linuxtone.org http://localhost ;
  4. if ($invalid_referer) {
  5.       rewrite   ^/   ;
  6.                      }
  7.      access_log off;
  8.      root /data/www/wwwroot/bbs;
  9. expires 1d;
  10.      break;
  11. }
复制代码

九、 Nginx 访问控制

1.        Nginx 身份证验证

  1. #cd /usr/local/nginx/conf
  2. #mkdir htpasswd
  3. /usr/local/apache2/bin/htpasswd -c /usr/local/nginx/conf/htpasswd/tongji linuxtone
  4. #添加用户名为linuxtone
  5. New password:   (此处输入你的密码)
  6. Re-type new password:   (再次输入你的密码)
  7. Adding password for user
  8. http://count.linuxtone.org/tongji/data/index.html(目录存在/data/www/wwwroot/tongji/data/目录下)
  9. 将下段配置放到虚拟主机目录,当访问http://count.linuxtone/tongji/即提示要密验证:
  10. location ~ ^/(tongji)/  {
  11.                 root    /data/www/wwwroot/count;
  12.                         auth_basic              "LT-COUNT-TongJi";
  13.                         auth_basic_user_file  /usr/local/nginx/conf/htpasswd/tongji;
  14.                 }
复制代码

2.        Nginx 禁止访问某类型的文件.
如,Nginx下禁止访问*.txt文件,配置方法如下.

  1. location ~* .(txt|doc)$ {
  2.    if (-f $request_filename) {
  3.    root /data/www/wwwroot/linuxtone/test;
  4.    #rewrite …..可以重定向到某个URL
  5.    break;
  6.    }
  7. }
复制代码

方法2:

  1. location ~* .(txt|doc)${
  2.         root /data/www/wwwroot/linuxtone/test;
  3.         deny all;
  4. }
复制代码

实例:
禁止访问某个目录

  1. location ~ ^/(WEB-INF)/ {
  2.             deny all;
  3. }  
复制代码

3.        使用ngx_http_access_module限制ip访问

  1. location / {
  2.     deny    192.168.1.1;
  3.     allow   192.168.1.0/24;
  4.     allow   10.1.1.0/16;
  5.     deny    all;
  6. }
复制代码

详细参见wiki: http://wiki.codemongers.com/NginxHttpAccessModule#allow

4.        Nginx 下载限制并发和速率

  1. limit_zone   linuxtone  $binary_remote_addr  10m;
  2. server
  3.        {
  4.                listen       80;
  5.                server_name  down.linuxotne.org;
  6.                index index.html index.htm index.php;
  7.                root   /data/www/wwwroot/down;
  8.                #Zone limit
  9.                location / {
  10.                    limit_conn   linuxtone  1;
  11.                    limit_rate  20k;
  12.                }
  13. ..........
  14.        }
复制代码

只允许客房端一个线程,每个线程20k.
【注】limit_zone   linuxtone  $binary_remote_addr  10m; 这个可以定义在主的


5.        Nginx 实现Apache一样目录列表

  1. location  /  {
  2.     autoindex  on;
  3. }
复制代码

6.        上文件大小限制
主配置文件里加入如下,具体大小根据你自己的业务做调整。
client_max_body_size 10m;                                                         

十、        Nginx 日志处理

1.Nginx 日志切割
#contab -e
59 23 * * * /usr/local/sbin/logcron.sh /dev/null 2>&1
[root@count ~]# cat /usr/local/sbin/logcron.sh

  1. #!/bin/bash
  2. log_dir="/data/logs"
  3. time=`date +%Y%m%d`  
  4. /bin/mv  ${log_dir}/access_linuxtone.org.log ${log_dir}/access_count.linuxtone.org.$time.log
  5. kill -USR1 `cat  /var/run/nginx.pid`
复制代码

更多的日志分析与处理就关注(同时欢迎你参加讨论):http://bbs.linuxtone.org/forum-8-1.html

2.利用AWSTATS分析NGINX日志
  设置好Nginx日志格式,仍后利用awstats进行分析.
请参考: http://bbs.linuxtone.org/thread-56-1-1.html

3.        Nginx 如何不记录部分日志
日志太多,每天好几个G,少记录一些,下面的配置写到server{}段中就可以了
location ~ .*.(js|jpg|JPG|jpeg|JPEG|css|bmp|gif|GIF)$
{
     access_log off;
}

十一、Nginx Cache服务配置

如果需要将文件缓存到本地,则需要增加如下几个子参数:

  1. proxy_store on;
  2. proxy_store_access user:rw group:rw all:rw;
  3. proxy_temp_path 缓存目录;
复制代码

其中,
proxy_store on用来启用缓存到本地的功能,
proxy_temp_path用来指定缓存在哪个目录下,如:proxy_temp_path html;

在经过上一步配置之后,虽然文件被缓存到了本地磁盘上,但每次请求仍会向远端拉取文件,为了避免去远端拉取文件,必须修改

  1. proxy_pass:
  2. if ( !-e $request_filename) {
  3.     proxy_pass  http://mysvr;
  4. }
复制代码

即改成有条件地去执行proxy_pass,这个条件就是当请求的文件在本地的proxy_temp_path指定的目录下不存在时,再向后端拉取。

   
更多更高级的应用可以研究ncache,详细请参照http://bbs.linuxtone.org 里ncache相关的贴子.

十二、Nginx 负载均衡
1. Nginx 负载均衡基础知识
nginx的upstream目前支持4种方式的分配
1)、轮询(默认)
每个请求按时间顺序逐一分配到不同的后端服务器,如果后端服务器down掉,能自动剔除。
2)、weight
指定轮询几率,weight和访问比率成正比,用于后端服务器性能不均的情况。
2)、ip_hash
每个请求按访问ip的hash结果分配,这样每个访客固定访问一个后端服务器,可以解决session的问题。
3)、fair(第三方)
按后端服务器的响应时间来分配请求,响应时间短的优先分配。
4)、url_hash(第三方)

2.        Nginx 负载均衡实例1

  1. upstream bbs.linuxtone.org {#定义负载均衡设备的Ip及设备状态
  2.     server 127.0.0.1:9090 down;
  3.     server 127.0.0.1:8080 weight=2;
  4.     server 127.0.0.1:6060;
  5.     server 127.0.0.1:7070 backup;
  6. }
复制代码

在需要使用负载均衡的server中增加
proxy_pass http://bbs.linuxtone.org/;

每个设备的状态设置为:
a)        down 表示单前的server暂时不参与负载
b)        weight 默认为1.weight越大,负载的权重就越大。
c)        max_fails :允许请求失败的次数默认为1.当超过最大次数时,返回proxy_next_upstream 模块定义的错误
d)        fail_timeout:max_fails次失败后,暂停的时间。
e)        backup: 其它所有的非backup机器down或者忙的时候,请求backup机器。所以这台机器压力会最轻。

nginx支持同时设置多组的负载均衡,用来给不用的server来使用。

client_body_in_file_only 设置为On 可以讲client post过来的数据记录到文件中用来做debug
client_body_temp_path 设置记录文件的目录 可以设置最多3层目录
location 对URL进行匹配.可以进行重定向或者进行新的代理 负载均衡


3.        Nginx 负载均衡实例 2
按访问url的hash结果来分配请求,使每个url定向到同一个后端服务器,后端服务器为缓存时比较有效,也可以用作提高Squid缓存命中率.

简单的负载均等实例:
#vi nginx.conf  //nginx主配置文件核心配置

  1. ……….
  2. #loadblance my.linuxtone.org
  3.        upstream  my.linuxtone.org  {
  4.        ip_hash;
  5.        server   127.0.0.1:8080;
  6.        server   192.168.169.136:8080;
  7.        server   219.101.75.138:8080;
  8.        server   192.168.169.117;
  9.        server   192.168.169.118;
  10.        server   192.168.169.119;
  11.      }
  12. …………..
  13. include          vhosts/linuxtone_lb.conf;
  14. ………
  15. # vi proxy.conf
  16. proxy_redirect off;
  17. proxy_set_header Host $host;
  18. proxy_set_header X-Real-IP $remote_addr;
  19. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  20. client_max_body_size 50m;
  21. client_body_buffer_size 256k;
  22. proxy_connect_timeout 30;
  23. proxy_send_timeout 30;
  24. proxy_read_timeout 60;
  25. proxy_buffer_size 4k;
  26. proxy_buffers 4 32k;
  27. proxy_busy_buffers_size 64k;
  28. proxy_temp_file_write_size 64k;
  29. proxy_next_upstream error timeout invalid_header http_500 http_503 http_404;
  30. proxy_max_temp_file_size 128m;
  31. proxy_store on;
  32. proxy_store_access   user:rw  group:rw  all:r;
  33. #nginx cache               
  34. #client_body_temp_path  /data/nginx_cache/client_body 1 2;
  35. proxy_temp_path /data/nginx_cache/proxy_temp 1 2;
复制代码

#vi  linuxtone_lb.conf

  1. server
  2.     {
  3.         listen  80;
  4.         server_name my.linuxtone.org;
  5.         index index.php;
  6.         root /data/www/wwwroot/mylinuxtone;
  7.         if (-f $request_filename) {
  8.             break;
  9.            }
  10.         if (-f $request_filename/index.php) {
  11.           rewrite (.*) $1/index.php break;
  12.         }
  13.         error_page 403 http://my.linuxtone.org/member.php?m=user&a=login;
  14.         location / {
  15.            if ( !-e $request_filename) {
  16.                proxy_pass http://my.linuxtone.org;
  17.                break;
  18.            }
  19.            include /usr/local/nginx/conf/proxy.conf;
  20.         }
  21. }
复制代码



十三、Nginx简单优化


1.        减小nginx编译后的文件大小 (Reduce file size of nginx)
默认的nginx编译选项里居然是用debug模式(-g)的(debug模式会插入很多跟踪和ASSERT之类),编译以后一个nginx有好几兆。去掉nginx的debug模式编译,编译以后只有几百K
在 auto/cc/gcc,最后几行有:
# debug

  1. CFLAGS=”$CFLAGS -g”
复制代码

注释掉或删掉这几行,重新编译即可。

2.        修改Nginx的header伪装服务器
1)        修改nginx.h

  1. #vi nginx-0.7.30/src/core/nginx.h
  2. #define NGINX_VERSION      "1.8"
  3. #define NGINX_VER          "LTWS/" NGINX_VERSION
  4. #define NGINX_VAR          "NGINX"
  5. #define NGX_OLDPID_EXT     ".oldbin"
复制代码

2) 修改nginx_http_header_filter_module
#vi nginx-0.7.30/src/http/ngx_http_header_filter_module.c
将如下

  1. static char ngx_http_server_string[] = "Server: nginx" CRLF;
复制代码

修改为

  1. static char ngx_http_server_string[] = "Server: LTWS" CRLF;
复制代码

a)        修改nginx_http_header_filter_module
#vi nginx-0.7.30/src/http/ngx_http_special_response.c
将如下:

  1. static u_char ngx_http_error_full_tail[] =
  2. "<hr><center>" NGINX_VER "</center>" CRLF
  3. "</body>" CRLF
  4. "</html>" CRLF
  5. ;
复制代码
  1. static u_char ngx_http_error_tail[] =
  2. "<hr><center>nginx</center>" CRLF
  3. "</body>" CRLF
  4. "</html>" CRLF
  5. ;
复制代码

修改为:

  1. static u_char ngx_http_error_full_tail[] =
  2. "<center> "NGINX_VER" </center>" CRLF
  3. "<hr><center>http://www.linuxtone.org</center>" CRLF
  4. "</body>" CRLF
  5. "</html>" CRLF
  6. ;
  7. static u_char ngx_http_error_tail[] =
  8. "<hr><center>LTWS</center>" CRLF
  9. "</body>" CRLF
  10. "</html>" CRLF
  11. ;
复制代码

修改后重新编译一下环境,
404错误的时候显示效果图(如果没有指定错误页的话):
404.png

利用curl命令查看服务器header
curl.png



 

3.为特定的CPU指定CPU类型编译优化.
默认nginx使用的GCC编译参数是-O
需要更加优化可以使用以下两个参数
--with-cc-opt='-O3'
--with-cpu-opt=opteron
使得编译针对特定CPU以及增加GCC的优化.
此方法仅对性能有所改善并不会有很大的性能提升,供朋友们参考.
CPUD类型确定: # cat /proc/cpuinfo | grep "model name"
编译优化参数参考:http://en.gentoo-wiki.com/wiki/Safe_Cflags


4.Tcmalloc优化Nginx 性能

  1. # wget http://download.savannah.gnu.org/releases/libunwind/libunwind-0.99-alpha.tar.gz
  2. # tar zxvf libunwind-0.99-alpha.tar.gz
  3. # cd libunwind-0.99-alpha/
  4. # CFLAGS=-fPIC ./configure
  5. # make CFLAGS=-fPIC
  6. # make CFLAGS=-fPIC install
  7. # wget http://google-perftools.googlecode.com/files/google-perftools-0.98.tar.gz
  8. # tar zxvf google-perftools-0.98.tar.gz
  9. # cd google-perftools-0.98/
  10. # ./configure
  11. # make && make install
  12. # echo "/usr/local/lib" > /etc/ld.so.conf.d/usr_local_lib.conf
  13. # ldconfig
  14. # lsof -n | grep tcmalloc
复制代码

编译nginx 加载google_perftools_module:
./configure --with-google_perftools_module
在主配置文件加入nginx.conf 添加:
google_perftools_profiles /path/to/profile;

5.内核参数优化
# vi /etc/sysctl.conf   #在末尾增加以下内容:

  1. net.ipv4.tcp_fin_timeout = 30
  2. net.ipv4.tcp_keepalive_time = 300
  3. net.ipv4.tcp_syncookies = 1
  4. net.ipv4.tcp_tw_reuse = 1
  5. net.ipv4.tcp_tw_recycle = 1
  6. net.ipv4.ip_local_port_range = 5000 65000
复制代码

#使配置立即生效
/sbin/sysctl -p

十四、如何构建高性的LEMP
请参见: http://www.linuxtone.org/lemp/lemp.pdf
1、提供完整的配置脚本下载:http://www.linuxtone.org/lemp/scripts.tar.gz
2、提供NGINX常见配置范例含(虚拟主机,防盗链,Rewrite,访问控制,负载均衡
Discuz相关程序静态化及等等),你只要稍稍修改即可线上应用。 3、将原版的xcache替换成EA,并提供相关简单调优脚本及配置文件。
更多的及更新资料请关注: http://www.linuxtone.org

十五、Nginx监控
1、        RRDTOOL+Perl脚本画图监控
先安装好rrdtool ,关于rrdtool本文不作介绍,具体安装请参照linuxtone监控版块.
#cd /usr/local/sbnin
#wget http://blog.kovyrin.net/files/mrtg/rrd_nginx.pl.txt
#mv rrd_nginx.pl.txt rrd_nginx.pl
#chmod a+x rrd_nginx.pl

#vi rrd_nginx.pl   //配置脚本文件设置好路径
#!/usr/bin/perl
use RRDs;
use LWP::UserAgent;

# define location of rrdtool databases
my $rrd = '/data/www/wwwroot/nginx/rrd';
# define location of images
my $img = '/data/www/wwwroot/nginx/html';
# define your nginx stats URL
my $URL = "http://219.232.244.13/nginx_status";
…………
【注】根据自己具体的状况修改相应的路径.
#crontab –e //加入如下
* * * * * /usr/local/sbin/rrd_nginx.pl
重启crond后,通过配置nginx虚拟主机指到/data/www/wwwroot/nginx/html目录,通过crond自动执行perl脚本会生成很多图片.
http://xxx/connections-day.png即可看到服务器状态图。

2、        官方Nginx-rrd 监控服务(多虚拟主机)(推荐)
网址:http://www.nginx.eu/nginx-rrd.html
此解决方案其实是基于上述监控方案的一个改进和增强,同样先安装好rrdtool这个画图工具和相应的perl模块再做如下操作:
# yum install perl-HTML*
先建立好生成的库存和图片存放录

  1. #mkdir -p /data/www/wwwroot/nginx/{rrd,html}
  2. #cd /usr/local/sbin
  3. #wget http://www.nginx.eu/nginx-rrd/nginx-rrd-0.1.4.tgz
  4. #tar zxvf nginx-rrd-0.1.4.tgz
  5. #cd nginx-rrd-0.1.4
  6. #cd etc/
  7. #cp nginx-rrd.conf /etc
  8. #cd etc/cron.d
  9. #cp nginx-rrd.cron /etc/cron.d
  10. #cd /usr/local/src/nginx-rrd-0.1.4/html
  11. # cp index.php /data/www/wwwroot/nginx/html/
  12. #cd /usr/local/src/nginx-rrd-0.1.4/usr/sbin
  13. #cp * /usr/sbin/
复制代码

#vi /etc/nginx-rrd.conf

  1. #####################################################
  2. #
  3. # dir where rrd databases are stored
  4. RRD_DIR="/data/www/wwwroot/nginx/rrd";
  5. # dir where png images are presented
  6. WWW_DIR="/data/www/wwwroot/nginx/html";
  7. # process nice level
  8. NICE_LEVEL="-19";
  9. # bin dir
  10. BIN_DIR="/usr/sbin";
  11. # servers to test
  12. # server_utl;server_name
  13. SERVERS_URL="http://219.32.205.13/nginx_status;219.32.205.13  http://www.linuxtone.org/nginx_status;www.linuxtone.org""
复制代码

//根据你的具体情况做调整.
SEVERS_URL 格式 http://domain1/nginx_status;domain1 http://domain2/nginx_status;domain2
这种格式监控多虚拟主机连接状态:
重点启crond服务,仍后通过http://219.32.205.13/nginx/html/ 即可访问。配置过程很简单!

3、        CACTI模板监控Nginx
利用Nginx_status状态来画图实现CACTI监控
nginx编译时允许http_stub_status_module

# vi /usr/local/nginx/conf/nginx.conf

  1. location /nginx_status {
  2. stub_status on;
  3. access_log off;
  4. allow 192.168.1.37;
  5. deny all;
  6. }
复制代码
  1. # kill -HUP `cat /usr/local/nginx/logs/nginx.pid`
  2. # wget http://forums.cacti.net/download.php?id=12676
  3. # tar xvfz cacti-nginx.tar.gz
  4. # cp cacti-nginx/get_nginx_socket_status.pl /data/cacti/scripts/
  5. # cp cacti-nginx/get_nginx_clients_status.pl /data/cacti/scripts/
  6. # chmod 755 /data/cacti/scripts/get_nginx*
复制代码

检测插件

  1. # /data/cacti/scripts/get_nginx_clients_status.pl http://192.168.1.37/nginx_status
复制代码

在cacti管理面板导入
cacti_graph_template_nginx_clients_stat.xml
cacti_graph_template_nginx_sockets_stat.xml

十六、常见问题与错误处理
1、400 bad request错误的原因和解决办法
配置nginx.conf相关设置如下.
client_header_buffer_size 16k;
large_client_header_buffers 4 64k;
根据具体情况调整,一般适当调整值就可以。

2、Nginx 502 Bad Gateway错误
proxy_next_upstream error timeout invalid_header http_500 http_503;
或者尝试设置:
large_client_header_buffers 4 32k;


3、Nginx出现的413 Request Entity Too Large错误
这个错误一般在上传文件的时候会出现,
编辑Nginx主配置文件Nginx.conf,找到http{}段,添加
client_max_body_size 10m; //设置多大根据自己的需求作调整.
如果运行php的话这个大小client_max_body_size要和php.ini中的如下值的最大值一致或者稍大,这样就不会因为提交数据大小不一致出现的错误。
post_max_size = 10M
upload_max_filesize = 2M

4、解决504 Gateway Time-out(nginx)
遇到这个问题是在升级discuz论坛的时候遇到的
一般看来, 这种情况可能是由于nginx默认的fastcgi进程响应的缓冲区太小造成的, 这将导致fastcgi进程被挂起, 如果你的fastcgi服务对这个挂起处理的不好, 那么最后就极有可能导致504 Gateway Time-out
现在的网站, 尤其某些论坛有大量的回复和很多内容的, 一个页面甚至有几百K。
默认的fastcgi进程响应的缓冲区是8K, 我们可以设置大点
在nginx.conf里, 加入: fastcgi_buffers 8 128k
这表示设置fastcgi缓冲区为8×128k
当然如果您在进行某一项即时的操作, 可能需要nginx的超时参数调大点,例如设置成60秒:send_timeout 60;
只是调整了这两个参数, 结果就是没有再显示那个超时, 可以说效果不错, 但是也可能是由于其他的原因, 目前关于nginx的资料不是很多, 很多事情都需要长期的经验累计才有结果, 期待您的发现哈!

5、如何使用Nginx Proxy
朋友一台服务器运行tomcat 为8080端口,IP:192.168.1.2:8080,另一台机器IP:192.168.1.8. 朋友想通过访问http://192.168.1.8即可访问tomcat服务.配置如下:
在192.168.1.8的nginx.conf上配置如下:

  1. server {
  2. listen 80;
  3. server_name java.linuxtone.org
  4. location / {
  5. proxy_pass http://192.168.1.2:8080;
  6. include /usr/local/nginx/conf/proxy.conf;
  7. }
  8. }
复制代码

6、如何关闭Nginx的LOG
access_log /dev/null; error_log /dev/null;

十七、相关资源下载

1.nginx配置示例及脚本下载:
# wget http://www.linuxtone.org/lemp/scripts.tar.gz #此脚本范例定期更新.


相关话题 (查看更多知识库搜索

其中以下这项挺值得留意的。
Tcmalloc 不单可用于 Mysql 的优化,还能应用于 Nginx
虽说 Nginx 本身的性能跟系统占用已经做到很优秀。

4.Tcmalloc优化Nginx 性能

  1. # wget http://download.savannah.gnu.org/releases/libunwind/libunwind-0.99-alpha.tar.gz
  2. # tar zxvf libunwind-0.99-alpha.tar.gz
  3. # cd libunwind-0.99-alpha/
  4. # CFLAGS=-fPIC ./configure
  5. # make CFLAGS=-fPIC
  6. # make CFLAGS=-fPIC install
  7. # wget http://google-perftools.googlecode.com/files/google-perftools-0.98.tar.gz
  8. # tar zxvf google-perftools-0.98.tar.gz
  9. # cd google-perftools-0.98/
  10. # ./configure
  11. # make && make install
  12. # echo "/usr/local/lib" > /etc/ld.so.conf.d/usr_local_lib.conf
  13. # ldconfig
  14. # lsof -n | grep tcmalloc




posted @ 2010-01-31 23:08 刘凯毅 阅读(1031) | 评论 (0)编辑 收藏

2010年1月18日 #

     摘要: tabBar.vim 这个插件实现了类似UltraEdit中的标签页的功能,而且能通过Alt-<n>来切换, 安装: 拷贝文件到[你的gvim的安装目录]"vimfiles"plugin"中即可! 下载: http://www.vim.org/scripts/script.php?script_id=1338 C:/Program Files/Vim/_v...  阅读全文
posted @ 2010-01-18 13:45 刘凯毅 阅读(1938) | 评论 (0)编辑 收藏

2010年1月5日 #


学习:
http://blog.chinaunix.net/u1/59571/showart_2077664.html

个人对上面文章做的 笔记共享出来 和大家分享!


posted @ 2010-01-05 11:21 刘凯毅 阅读(2136) | 评论 (0)编辑 收藏

2009年12月20日 #

python easy_install moin 或 下载 moin-1.9.0 编译
设置 path 中有 moin.py
#我这 参考
path = $PATH:/Python25/moin-1.9.0/MoinMoin/script

# wikiconfig.py 下面我点下 参数 ,大家看代码 就知道了
vi  /Python25/moin-1.9.0/wiki/config/wikiconfig.py
#instance_dir = '/where/ever/your/instance/is'
instance_dir = wikiconfig_dir+'/../'

# Where your own wiki pages are (make regular backups of this directory):
data_dir = os.path.join(instance_dir, 'data-1'''# path with trailing /


navi_bar 
= [
        
# If you want to show your page_front_page here:
        #u'%(page_front_page)s',
        u'标题',
        u
'FindPage',
        u
'HelpContents',
    ]

language_default 
= 'zh'

在修改linux 时不起作用 :
修改/root/tools/moin-1.9.0/MoinMoin/script/server/standalone.py 全局先


运行:
$>moin  server standalone --config-dir=/root/wiki/mywiki/config/ --hostname=192.168.102.207 --port=18081
命令是可调参数:
#/root/tools/moin-1.9.0/MoinMoin/script/server/standalone.py
class PluginScript(MoinScript):
    
def __init__(self, argv, def_values):
        MoinScript.
__init__(self, argv, def_values)
        self.parser.add_option(
            
"--docs", dest="docs",
            help
="Set the documents directory. Default: use builtin MoinMoin/web/static/htdocs"
        )
        self.parser.add_option(
            
"--user", dest="user",
            help
="Set the user to change to. UNIX only. Default: Don't change"
        )
        self.parser.add_option(
            
"--group", dest="group",
            help
="Set the group to change to. UNIX only. Default: Don't change"
        )
        self.parser.add_option(
            
"--port", dest="port", type="int",
            help
="Set the port to listen on. Default: 8080"
        )
        self.parser.add_option(
            
"--hostname""--interface", dest="hostname",
            help
="Set the ip/hostname to listen on. Use \"\" for all interfaces. Default: localhost"
        )
        self.parser.add_option(
            
"--start", dest="start", action="store_true",
            help
="Start server in background."
        )
        self.parser.add_option(
            
"--stop", dest="stop", action="store_true",
            help
="Stop server in background."
        )
        self.parser.add_option(
            
"--pidfile", dest="pidfile",
            help
="Set file to store pid of moin daemon in. Default: moin.pid"
        )
        self.parser.add_option(
            
"--debug", dest="debug",
            help
="Debug mode of server. off: no debugging (default), web: for browser based debugging, external: for using an external debugger."
        )


#成功运行 后
2009-12-20 23:31:31,796 WARNING MoinMoin.log:139 using logging configuration read from built-in fallback in MoinMoin.log module!

2009-12-20 23:31:32,515 INFO werkzeug:106  * Running on http://192.168.1.100:8080/


一些简单的语法介绍『其中 HelpOnDrawings 的功能 有“惊艳”的效果!!呵呵,自己搭建个自己的wiki 出来 看吧』






posted @ 2009-12-20 23:34 刘凯毅 阅读(2176) | 评论 (0)编辑 收藏

2009年12月11日 #



定义:
灰羊群   (无主见的用户群体)
黑羊   ( 对自己需要什么有明确的认识,我们一般称为专家用户。  )


1. 区分 灰(无主见) 黑 羊群

2.
user session 关联 #当 关联关系维护使用 用户的会话ID(用户不同心情,起始在数据中就应该是不同分类的)
user 推荐         # 而推荐出产品 还是 跟 用户唯一编号有关
#在推荐中需要描述  用户的多角度 问题

3.
蛮力推荐( 全数据 ;描述初期清洗后的数据 ) 适合 产品关联 
清洗后期的数据(包含用户多维度描述) 适合   用户关联


4.
专家跟随推荐
描述:
  用户分类 找到黑绵羊  
  找到 一群灰绵羊 和 一只黑绵羊的关联关系
  让 一群灰绵羊 可以看 黑绵羊 动作



posted @ 2009-12-11 16:20 刘凯毅 阅读(385) | 评论 (2)编辑 收藏




1,负重深蹲,仰卧起坐,慢跑,主要练习心肺功能(腿部锻炼很重要,如果深蹲完了没体力,慢跑可以改成慢走放松)

2,卧推,仰卧飞鸟,站立飞鸟,仰卧起坐,慢跑,主要练习胸部和肩部(飞鸟就是侧举,仰卧的时候用的是胸的力量,站立时用的是肩)

3,引体向上,划船,曲臂,主要练习背部和胳膊,最后加上固定的项目:仰卧起坐和慢跑放松


1的消耗最大,要自己状态最好的时候去
2主要是练习和“推,举”相关的肌群
3是“拉,收”相关的肌群

而且有个原则,就是先练大项目,再练小项目。


 深蹲、卧推、引体向上,这3个是最基本的,别的其实都可有可无
另外,适当慢跑也是必要的,是很好的放松和有氧运动,促进代谢。当然,如果有条件可以去户外跑,宁可跑马路,也别在健身房里跑,空气不理想

做动作也是要循序渐进,每次从很轻的重量开始,逐步加大负荷



posted @ 2009-12-11 11:52 刘凯毅 阅读(328) | 评论 (0)编辑 收藏

2009年12月8日 #

下面介绍的排序都为:非比较排序法

这里个人认为在某些特定的地方非比较排序的速度非常明显;
比如 : 对待排数据中有顺序分类,使用鸽巢总体分类,然后对不同类别的待排小数据集合采用 插入,快排等排序方式


Counting sort :计数排序
描述:迭代待排序数组出元素x,确定小于此元素[z]个数,然后把x放到它在的最终输出数组[z]上。
特性:与待排值有关;稳定的排序算法;待排序数据要求过于严格,无实际用处;
算法的步骤如下:
   1. 找出待排序的数组中最大和最小的元素
   2. 统计数组中每个值为i的元素出现的次数,存入数组C的第i项
   3. 对所有的计数累加(从C中的第一个元素开始,每一项和前一项相加)
   4. 反向填充目标数组:将每个元素i放在新数组的第C(i)项,每放一个元素就将C(i)减去1


Radix sort:基数排序
描述:将所有待比较数值(正整数)统一为同样的数位长度,数位较短的数前面补零. 然后, 从最低位开始, 依次进行一次排序.这样从最低位排序一直到最高位排序完成以后, 数列就变成一个有序序列.
排序方式:LSD 由右向左排;MSD 由左向右排
特性:非比较排序;待排数据需要统一格式;
假设需排序数列的取值范围从1...k,我们于是建一个K+1元的数组 a[],并赋初值为0,然后便开始排序工作:
算法的步骤如下:
   1. 按输入顺序读入数列,如果所读的元素为i(1<=i<=k),我们就将a[i]的值加一,这样直到读完所有的元素。
   2. 读出元素并排序:我们遍历整个数组,如果a[i]=j(j>=0),我们就输出j次i(表示元素i在原先数列中出现了j次),这样输出的序列就是已排序的。
   3. 由于一般排序算法涉及到元素之间的比较,如果化成比较树可以知道,这样的排序算法复杂度的下限是O(N*lnN),而计数排序没有比较元素,所以所需排序时间就少了,我们可以看到计数排序的复杂度为O(n*k),其中k(k的定义同上)为合并排列所需的时间,是个常数。
   4. 此算法适合所需排列的元素取值范围不大的情况下,否则会造成空间的消耗,比如,一共100个元素,其取值范围从1-100000,显然这个时候用基数排序是不合适的。



Bucket sort:桶排序
描述:工作的原理是将阵列分到有限数量的桶子里。每个桶子再个别排序(有可能再使用别的排序算法或是以递回方式继续使用桶排序进行排序)。
桶排序以下列程序进行:
   1. 设置一个定量的阵列当作空桶子。
   2. 寻访序列,并且把项目一个一个放到对应的桶子去。
   3. 对每个不是空的桶子进行排序。
   4. 从不是空的桶子里把项目再放回原来的序列中。



Pigeonhole sort:鸽巢排序
描述:是一种时间复杂度为O(n)且在不可避免遍历每一个元素并且排序的情况下效率最好的一种排序算法. 但它只有在差值(或者可被映射在差值)很小的范围内的数值排序的情况下实用.
算法的步骤如下:与桶排同



posted @ 2009-12-08 14:21 刘凯毅 阅读(1738) | 评论 (1)编辑 收藏

2009年12月7日 #


date demo:
实例:
$
>date
Mon Dec  
7 15:43:39 CST 2009

#格式化输出
$> date +"%Y-%m-%d"
2009-12-07

#时间游走 当前时间 2009-12-07
# year , month , day ,hour , minute,second  - ago
#昨天输出

$> date  -"1 day ago" +"%Y-%m-%d"
2009-12-06

#2秒后输出
$> date  -"2 second" +"%Y-%m-%d %H:%M.%S"
2009-12-07 15:50.04

#传说中的 1234567890 秒
$>date -"1970-01-01  1234567890 seconds"  +"%Y-%m-%d %H:%m:%S"
2009-02-13 23:02:30

#其他格式的转换
date -"$(echo "03/Nov/2009 11:04:28" |perl -ne 'print "$2 $1 $3 $4\n" if /(.*?)"/(.*?)"/(.*?) (.*)/;') " +%Y-%m-%d
2009-11-03

#普通 转格式
$> date -"2009-12-12" +"%Y/%m/%d %H:%M.%S"
2009/12/12 00:00.00

#apache 格式转换
$>date  -"Dec 5, 2009 12:00:37 AM" +"%Y-%m-%d %H:%M.%S"
2009-12-05 00:00.37

#格式转换 后时间 游走
$>date  -"Dec 5, 2009 12:00:37 AM 2 year ago" +"%Y-%m-%d %H:%M.%S"
2007-12-05 00:00.37


#时间差
#一小时 3600
#一天 86400 秒

$>st=$(date  -"Dec 5, 2009 12:00:37 AM 1 day ago 1 hour ago " +"%s")
$
>et=$(date  -"Dec 5, 2009 12:00:37 AM" +"%s")
$
>echo "时间差$[($et-$st)/86400]天,$[($et-$st)/3600%24]小时"
时间差1天,1小时





date --help
Usage: date [OPTION] [+FORMAT]
  or
:  date [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]]
Display the current 
time in the given FORMAT, or set the system date.

  
-d, --date=STRING         display time described by STRING, not `now'
  -f, --file=DATEFILE       like --date once for each line of DATEFILE
  -r, --reference=FILE      display the last modification time of FILE
  -R, --rfc-2822            output date and time in RFC 2822 format
      --rfc-3339=TIMESPEC   output date and time in RFC 3339 format.
                            TIMESPEC=`date
', `seconds', or `ns' for
                            date and 
time to the indicated precision.
  
-s, --set=STRING          set time described by STRING
  
-u, --utc, --universal    print or set Coordinated Universal Time
      
--help     display this help and exit
      
--version  output version information and exit














posted @ 2009-12-07 16:14 刘凯毅 阅读(2408) | 评论 (0)编辑 收藏



工具为  dist/myImg.exe


工具使用:
在 dist 中
myImg.exe Ratio  c:/需要等比压缩图片/*.jpg  d:/等比后路径   等比款width  等比高height
myImg.exe Watermark c:/水印图片/x.png  c:/需要加水印图片/*.jpg  d:/添加水印后图片   加水印width处  加水印height处

等比压缩实例:
myImg.exe Ratio  
    "C:"Documents and Settings"lky"My Documents"My Dropbox"tools"img"src"python"dist"test"img"*.jpg"
    "C:"Documents and Settings"lky"My Documents"MyDropbox"tools"img"src"python"dist"test"toimg2"
    600 400
结果在  ../dist"test"toimg  目录下 生成 等比图片 testratio_600_400.jpg


水印添加实例:
myImg.exe Watermark
    "C:"Documents and Settings"lky"My Documents"My Dropbox"tools"img"src"python"dist"test"img"logo.png"   
    "C:"Documents and Settings"lky"My Documents"My Dropbox"tools"img"src"python"dist"test"toimg2"*.jpg"
    "C:"Documents and Settings"lky"My Documents"My Dropbox"tools"img"src"python"dist"test"toimg3"
    100 220
结果在  ../dist"test"toimg3  目录下 生成 等比图片 test_ratio_600_400_watermark_100_220.jpg



安装 python PIL 包
和安装 python py2exe

工具脚本 py


工具编译过程:
python setup.py py2exe



import sys

def imgRatio(imgpath,tpath='.',width=600,height=400):
    
import Image,os
    im 
= Image.open( imgpath )
    im.thumbnail( (width,height) )
    imgpath 
= os.path.split(imgpath)[1]
    
if not os.path.exists(tpath) : os.makedirs(tpath)
    im.save( tpath
+'/'+imgpath.split('.')[0]+'_ratio_'+str(width)+'_'+str(height)+'.jpg' )


def imgWatermark(imgwate,imgpath,sw=100,sh=50,tpath='.'):
    
import Image,os
    baseim 
= Image.open( imgpath )
    floatim 
= Image.open( imgwate )
    baseim.paste( floatim, (sw,sh ) )
    imgpath 
= os.path.split(imgpath)[1]
    
if not os.path.exists(tpath) : os.makedirs(tpath)
    baseim.save( tpath
+'/'+imgpath.split('.')[0]+'_watermark_'+str(sw)+'_'+str(sh)+'.jpg' )
    

args 
= sys.argv
import glob,os

# Ratio  /path/*.jpg  /tpath   width  height  
if args[1== 'Ratio' :
    
for img in glob.glob(args[2]) :
        imgRatio(os.path.abspath(img),args[
3],int(args[4]),int(args[5]))
# Watermark /path/x.png  /path/*.jpg  /tpath   width  height 
if args[1== 'Watermark' :
    
for img in glob.glob(args[3]) :
        imgWatermark(args[
2],img,int(args[5]),int(args[6]),args[4])




py2exe
#!/usr/bin/python
#
 -*- coding: utf-8 -*-
#
  py2exe file
#
 1.install py2exe application
#
 2.python setup.py py2exe
from distutils.core import setup
import py2exe
setup(console
=['myImg.py'])


posted @ 2009-12-07 15:12 刘凯毅 阅读(645) | 评论 (0)编辑 收藏

2009年12月3日 #


# 快排 和 分治 很像 都是分而治之 ,但他们却是 相反的 方式排序 :
分治 是想拆分完成后,合并以有序的小段进行 排序 ,而快排是直接由原始的“拆分”来排序


#encoding=utf-8
#
从 大 到 小
def partition(A,p,r):
    tmp
=A[p]
    
while True :
        
while p+1<and A[p] > tmp : p+=1
        
while r-1>and A[r] <= tmp : r-=1    
    
if A[p]<=A[r]: A[p],A[r]=A[r],A[p]
    
if r-1<=p : return p


def quickSort(A,p,r):
    
if p<r:
        q
=partition(A,p,r)
        quickSort(A,p,q)
        quickSort(A,q
+1,r)

A
=[9,61,7,14,-1,7,667,3,6,8]
print A
quickSort(A,0,len(A)
-1)
print A
# 结果
[667, 61, 14, 9, 8, 7, 7, 6, 3, -1]



图解:
一次迭代过程描述 (从小到大):
1. 以 A[0] 为切分点 用临时变量 记录 这里是 切分点 = [5]
2. 分别起 2枚指针 [切分起左,右]
3. 分别向中间 靠拢 , 当左指针指向值大于 切分点 停止 左 , 右指针指向值 小于 切分点 停止 右 。
4. 判断 是否是  停止点 上 左值 小于 右值 是:交换两指针值 !

第一次迭代后 : 
  以初始分隔 [5]  就已经切分好了 小于 5 的左 ,大于等于5 的右


posted @ 2009-12-03 17:11 刘凯毅 阅读(1595) | 评论 (0)编辑 收藏