Chinaunix首页 | 论坛 | 博客
  • 博客访问: 693163
  • 博文数量: 139
  • 博客积分: 7607
  • 博客等级: 少将
  • 技术积分: 1964
  • 用 户 组: 普通用户
  • 注册时间: 2007-11-11 23:43
个人简介

...

文章分类

全部博文(139)

文章存档

2012年(53)

2011年(4)

2010年(29)

2009年(10)

2008年(33)

2007年(10)

分类: LINUX

2012-02-16 19:58:50

varnish是和squid类似的高性能开源HTTP加速器,我这里用来缓存图片,js,css等小文件

varnish cache 192.168.0.15 centos6.0
nagios www后端 192.168.0.11 centos5.3

1.安装varnish

  1. wget
  2. tar zxvf varnish-3.0.0.tar.gz
  3. cd varnish-3.0.0
  4. ./configure --prefix=/opt/varnish-3.0.0
  5. make
  6. make install
  7. ln -s /opt/varnish-3.0.0 /opt/varnish

2.设置权限

  1. cd /opt/varnish
  2. #varnish以www:website来运行
  3. chown -R www:website /opt/varnish/var/varnish/
  4. mkdir /var/log/varnish
  5. chown -R www:website /var/log/varnish
  6. chown -R www:website /opt/varnish/var/varnish/`hostname`
  7. mkdir /opt/varnish/var/varnish/`hostname`

3.配置文件

#查看默认配置文件
cat etc/varnish/default.vcl

#编辑新配置文件
vi etc/vcl.conf

  1. #http请求处理过程
  2. #1,receive请求入口状态,根据vcl判断pass还是lookup本地查询
  3. #lookup,在hash表中查找数据,若找到则进入hit状态,否则进入fetch状态
  4. #pass,选择后台,进入fetch状态
  5. #fetch,对请求进行后端的获取,发送请求,获得数据,并进行本地存储
  6. #deliver,将数据发送给客户端,进入done
  7. #done,处理结束
  8. backend wwwserver {
  9.        .host = "192.168.0.11";
  10.        .port = "80";
  11. }
  12. backend staticserver {
  13.   .host = "192.168.0.11";
  14.   .port = "80";
  15. }
  16. acl purge {
  17.        "localhost";
  18.        "127.0.0.1";
  19.        "192.168.1.0"/24;
  20. }
  21.  
  22. sub vcl_recv {
  23.        if (req.request == "PURGE") {
  24.                if (!client.ip ~ purge) {
  25.                        error 405 "Not allowed.";
  26.                }
  27.                return(lookup);
  28.        }
  29. #去除cookie
  30. if (req.request == "GET" && req.url ~ "^/[^?]+\.(jpeg|jpg|png|gif|ico|swf|js|css|txt|zip|html|htm)(\?.*|)$") {
  31. unset req.http.Cookie;
  32. }
  33. #判断req.http.X-Forwarded-For 如果前端有多重反向代理,这样可以获取客户端IP地址。
  34. if (req.http.x-forwarded-for)
  35. {
  36. set req.http.X-Forwarded-For = req.http.X-Forwarded-For + ", "+ client.ip;
  37. }
  38.         else {
  39. set req.http.X-Forwarded-For = client.ip;
  40. }
  41.  
  42. #浏览器Accept-Encoding兼容
  43. if (req.http.Accept-Encoding) {
  44. if (req.url ~ "\.(jpg|png|gif|jpeg)$") {
  45.     remove req.http.Accept-Encoding;
  46. } elsif (req.http.Accept-Encoding ~ "gzip") {
  47.     set req.http.Accept-Encoding = "gzip";
  48. } elsif (req.http.Accept-Encoding ~ "deflate") {
  49.     set req.http.Accept-Encoding = "deflate";
  50. } else {
  51.     remove req.http.Accept-Encoding;
  52. }
  53. }
  54.  
  55. if (req.http.host ~ "^blog.c1gstudio.com") {
  56.                set req.backend = wwwserver;
  57.                if (req.request != "GET" && req.request != "HEAD") {
  58.                        return(pipe);
  59.                }
  60.        elseif(req.url ~ "\.(php|cgi)($|\?)") {
  61. return(pass);
  62. }
  63.                else {
  64.  
  65.                        return(lookup);
  66.                }
  67.        } elsif (req.http.host ~ "^static.c1gstudio.net") {
  68. #第二个域名
  69. set req.backend = staticserver;
  70.        }else {
  71.                error 404 "Cache Server";
  72.                return(lookup);
  73.        }
  74. }
  75.  
  76. sub vcl_hit {
  77.        if (req.request == "PURGE") {
  78.                set obj.ttl = 0s;
  79.                error 200 "Purged.";
  80.        }
  81. }
  82.  
  83. sub vcl_miss {
  84.        if (req.request == "PURGE") {
  85.                error 404 "Not in cache.";
  86.        }
  87. }
  88.  
  89. sub vcl_fetch {
  90.        if (req.request == "GET" && req.url ~ "\.(jpeg|jpg|png|gif|ico|swf|js|css|txt|zip)$") {
  91.                set beresp.ttl = 600s;
  92. unset beresp.http.set-cookie;
  93.        }
  94.        else {
  95.                set beresp.ttl = 3600s;
  96.        }
  97. }
  98. #显示是否命中
  99. sub vcl_deliver{
  100.         if (obj.hits > 0) {
  101.                 set resp.http.X-Cache = "Server-1-HIT";
  102. set resp.http.X-Cache-Hits = obj.hits;
  103.         } else {
  104.                 set resp.http.X-Cache = "Server-1-MISS";
  105.         }
  106. unset resp.http.X-Varnish;
  107.         set resp.http.Via = "1.1 Xcache";
  108. }

4.启动varnish

  1. /opt/varnish/sbin/varnishd -n /opt/varnish/var/varnish -f /opt/varnish/etc/vcl.conf -a 0.0.0.0:80 -s malloc,1G -g website -u www  -T 127.0.0.1:3200 -p sess_workspace=64768 -p thread_pools=2 -p listen_depth=4096 -p first_byte_timeout=10 -p sess_timeout=15 -w 200,5000,10

#参数说明

  1. -n vcache /                                            #临时文件实例名.如果以"/"开头,就必须是一个可用的路径.
  2.         -a :80 /                                                 #服务所在端口.":80"是默认所有网络都建立80端口,":"前面是服务器IP.
  3.         -T :5000 /                                              #管理端口.
  4.         -s file,/data1/vcache,80g /                        #虚拟内存文件映射类型,路径以及容量. 包括两种类型"malloc"和"file"
  5.         -s file,/data2/vcache,80g /                        #malloc是内存+swap交换模式.很简单.没得说.
  6.         -s file,/data3/vcache,80g /                        #file是mmap的文件内存映射机制.(具体情况,参阅"mmap"函数说明)
  7.         -s file,/data4/vcache,80g /
  8.         -f /usr/local/varnish/etc/varnish.vcl /           #VCL文件路径.
  9.         -P /var/run/varnish.pid /                            #PID文件地址.
  10.         -w 200,5000,10 /                                     #工作进程数.三个参数分别是:,,
  11.         -h classic,16383 /                                    #hash列表类型,以及长度.默认长度是16383.具体用处和调整实际效果要等我看完源代码才知道.
  12.         -p user=www /                                        #"-p"是变量配置参数
  13.         -p group=website/                                    #服务运行用户和用户组配置.
  14.         -p thread_pools=4 /                                  #进程connections pools的个数,数量越多,越耗用cpu和mem,但是处理并发能力越强.
  15.                                                                      #系统手册上说,一个cpu用一个.
  16.         -p listen_depth=4096 /                              #TCP队列长度.默认是1024.
  17.         -p first_byte_timeout=10                           #从后端接受第一个字节的超时时间。默认60秒
  18.         -p between_bytes_timeout=60                    #从后端接收数据后,连接空闲时间,默认60秒
  19.         -p sess_timeout=15                                  #客户端和varnish连接超时时间,默认5秒

5.记录日志
/opt/varnish/bin/varnishncsa -n /opt/varnish/var/varnish -w /var/log/varnish/varnish.log &

#定时切割日志
vi /opt/shell/cutvarnishlog.sh

  1. #!/bin/sh
  2. # 0 0 * * * /bin/sh /opt/shell/cutvarnishlog.sh  > /dev/null 2>&1
  3. date=$(date -d "yesterday" +"%Y%m%d")
  4. pkill -9 varnishncsa
  5. mv /var/log/varnish/varnish.log /var/log/varnish/varnish.${date}.log
  6. /opt/varnish/bin/varnishncsa -n /opt/varnish/var/varnish -w /var/log/varnish/varnish.log &
  7. mkdir -p /var/log/varnish/old
  8. gzip -c /var/log/varnish/varnish.${date}.log > /var/log/varnish/old/varnish.${date}.log.gz
  9. rm -f /var/log/varnish/varnish.${date}.log
  10. rm -f /var/log/varnish/old/varnish$(date -d "-1 month" +"%Y%m*").log.gz

crontab -e

  1. 0 0 * * * /bin/sh /opt/shell/cutvarnishlog.sh  > /dev/null 2>&1

6.查看运行统计
/opt/varnish/bin/varnishstat -n /opt/varnish/var/varnish

  1. 1+01:13:37       /opt/varnish/var/varnish
  2. Hitrate ratio:       10      100      288
  3. Hitrate avg:     0.9987   0.9981   0.9978
  4.  
  5.     22251295       371.40       245.01 client_conn - Client connections accepted
  6.     22250487       371.40       245.00 client_req - Client requests received
  7.     22185321       371.40       244.29 cache_hit - Cache hits
  8.        62904         0.00         0.69 cache_miss - Cache misses
  9.         4615         0.00         0.05 backend_conn - Backend conn. success
  10.           22         0.00         0.00 backend_fail - Backend conn. failures
  11.        59164         0.00         0.65 backend_reuse - Backend conn. reuses
  12.          456         0.00         0.01 backend_toolate - Backend conn. was closed
  13.        59622         0.00         0.66 backend_recycle - Backend conn. recycles
  14.        47470         0.00         0.52 fetch_length - Fetch with Length
  15.        16307         0.00         0.18 fetch_chunked - Fetch chunked
  16.            2         0.00         0.00 fetch_close - Fetch wanted close
  17.         1873          .            .   n_sess_mem - N struct sess_mem
  18.         1834          .            .   n_sess - N struct sess
  19.          655          .            .   n_object - N struct object
  20.          685          .            .   n_objectcore - N struct objectcore
  21.          784          .            .   n_objecthead - N struct objecthead
  22.          405          .            .   n_waitinglist - N struct waitinglist
  23.            2          .            .   n_vbc - N struct vbc
  24.           31          .            .   n_wrk - N worker threads
  25.          381         0.00         0.00 n_wrk_create - N worker threads created
  26.         2584         0.00         0.03 n_wrk_queued - N queued work requests
  27.            2          .            .   n_backend - N backends
  28.        62227          .            .   n_expired - N expired objects
  29.      5365503          .            .   n_lru_moved - N LRU moved objects
  30.         1362         0.00         0.01 losthdr - HTTP header overflows
  31.     18551363       326.47       204.27 n_objwrite - Objects sent with write
  32.     22251295       371.40       245.01 s_sess - Total Sessions
  33.     22250487       371.40       245.00 s_req - Total Requests
  34.          898         0.00         0.01 s_pass - Total pass
  35.        63779         0.00         0.70 s_fetch - Total fetch
  36.   7539848276    127352.96     83022.43 s_hdrbytes - Total header bytes 
  37. 141933911830   2248780.45   1562856.20 s_bodybytes - Total body bytes   
  38.     22251292       371.40       245.01 sess_closed - Session Closed
  39.            1         0.00         0.00 sess_herd - Session herd
  40.    998035729     16610.26     10989.53 shm_records - SHM records
  41.     89193699      1488.60       982.13 shm_writes - SHM writes
  42.       328009         8.99         3.61 shm_cont - SHM MTX contention
  43.          385         0.00         0.00 shm_cycles - SHM cycles through buffer
  44.         1387         0.00         0.02 sms_nreq - SMS allocator requests

7.管理清除缓存
7.1通过Varnish管理端口进行管理
/opt/varnish/bin/varnishadm -T 127.0.0.1:3200 help

  1. CLI connected to 127.0.0.1:3200
  2. help [command]
  3. ping [timestamp]
  4. auth response
  5. quit
  6. banner
  7. status
  8. start
  9. stop
  10. vcl.load
  11. vcl.inline
  12. vcl.use
  13. vcl.discard
  14. vcl.list
  15. vcl.show
  16. param.show [-l] []
  17. param.set
  18. panic.show
  19. panic.clear
  20. storage.list
  21. ban.url
  22. ban [&& ]...
  23. ban.list

通过Varnish管理端口清除缓存,支持正则表达式,1.0时为url.purge参数:
/opt/varnish/bin/varnishadm -T 127.0.0.1:3200 ban.url /shanghai-4.html

例:清除所有缓存:
/opt/varnish/bin/varnishadm -T 127.0.0.1:3200 ban.url *$

7.2通过telnet方式清除

  1. telnet 127.0.0.1 3200
  2. Trying 127.0.0.1 ...
  3. Connected to 127.0.0.1.
  4. Escape character is '^]'.
  5. 200 205     
  6. -----------------------------
  7. Varnish Cache CLI 1.0
  8. -----------------------------
  9. Linux,2.6.32-71.el6.i686,i686,-smalloc,-smalloc,-hcritbit
  10.  
  11. Type 'help' for command list.
  12. Type 'quit' to close CLI session.
  13.  
  14. help
  15. 200 401     
  16. help [command]
  17. ping [timestamp]
  18. auth response
  19. quit
  20. banner
  21. status
  22. start
  23. stop
  24. vcl.load
  25. vcl.inline
  26. vcl.use
  27. vcl.discard
  28. vcl.list
  29. vcl.show
  30. param.show [-l] []
  31. param.set
  32. panic.show
  33. panic.clear
  34. storage.list
  35. ban.url
  36. ban [&& ]...
  37. ban.list
  38.  
  39. #1.0时的方法现在不支持
  40. purge.url /shanghai-4.html
  41. 200 0 101 44     
  42. Unknown request.
  43. Type 'help' for more info.
  44.  
  45. #正确方法
  46. ban.url /shanghai-4.html
  47. 200 0

7.3通过php等其它web请求清除缓存

  1. function purge($ip,$port=80,$domain, $url) 
  2. { 
  3.     $errstr = ''
  4.     $errno = ''
  5.     $fp = fsockopen ($ip, $port, $errno, $errstr, 2)
  6.     if (!$fp) 
  7.     { 
  8.          return false
  9.     } 
  10.     else 
  11.     { 
  12.         $out = "PURGE $url HTTP/1.1\r\n"
  13.         $out .= "Host:$domain\r\n"
  14.         $out .= "Connection: close\r\n\r\n"
  15.         fputs ($fp, $out)
  16.         $out = fgets($fp , 4096)
  17.         fclose ($fp)
  18.         return true
  19.     } 
  20. } 
  21. purge('192.168.0.15','80','blog.c1gstudio.com','/shanghai-4.html');

8.varnish的nginx前端
测试下来nginx和varnish在同一机器上会产生大量time_wait,单独使用没有问题.

  1. upstream mysvr {
  2. server 127.0.0.1:82;
  3.      }
  4.  
  5.      server
  6.      {
  7.              listen       80;
  8.              server_name  static.c1gstudio.net;
  9.              index index.html index.htm index.php;
  10.              root  /opt/lampp/htdocs/web;
  11.  
  12.        location ~/\.ht {
  13.          deny all;
  14.      }
  15.        location ~(favicon.ico) {
  16.                  log_not_found off;
  17. expires 99d;
  18. break;
  19.      }
  20.              location ~ .*\.(php|html|htm)?$
  21.              {
  22. return 403;      
  23.              }
  24.  
  25.      location / {
  26. valid_referers none blocked *.c1gstudio.com *.c1gstudio.net ;
  27. if ($invalid_referer) {
  28.     rewrite ^/
  29.     return 412;
  30.     break;
  31. }
  32.  
  33.   proxy_pass
  34.   proxy_set_header   Host             $host;
  35.   proxy_set_header   X-Real-IP        $remote_addr;
  36.   proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
  37.      }           
  38.  
  39.              access_log  /var/log/nginx/static.c1gstudio.net.log  access;
  40.      }

9.内核优化
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

sysctl -p

varnish服务器运行基本没有负载

  1. top - 15:54:34 up 34 days, 23:49,  1 user,  load average: 0.00, 0.01, 0.00
  2. Tasks: 125 total,   1 running, 124 sleeping,   0 stopped,   0 zombie
  3. Cpu(s):  1.8%us,  1.3%sy,  0.0%ni, 95.0%id,  0.4%wa,  0.0%hi,  1.5%si,  0.0%st
  4. Mem:   2070548k total,  2017996k used,    52552k free,    83556k buffers
  5. Swap:  2097144k total,        0k used,  2097144k free,  1612756k cached
  6.  
  7.   PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND                                                                                                                                 
  8. 26631 www       20   0  228m 134m  81m S  7.6  6.7  74:46.86 varnishd                                                                                                                               
  9.  6070 www       20   0 31852  25m 1000 S  3.3  1.3   7:28.79 nginx                                                                                                                                 
  10.  6071 www       20   0 31076  24m 1000 S  2.0  1.2   7:22.34 nginx                                                                                                                                 
  11.  6068 www       20   0 31356  25m  976 S  1.7  1.3   7:21.36 nginx

tcp状态
netstat -n | awk '/^tcp/ {++S[$NF]} END {for(a in S) print a, S[a]}'

  1. LAST_ACK 9
  2. SYN_RECV 5
  3. CLOSE_WAIT 3
  4. ESTABLISHED 2083
  5. FIN_WAIT1 95
  6. FIN_WAIT2 247
  7. TIME_WAIT 14412
阅读(1253) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~