varnish,squid,apache,nginx缓存文件比较

一,测试环境

1,硬件是奔腾双核,机子三年前买的。系统是archlinux

2,测试varnish和squid的时候,web服务用的apache

3,测试apache的时候,启动了5个进程,不过随着压力的增加,进程会增加的。

4,测试nginx的时候,启动了十个nginx进程,20个php-cgi进程

 

5,varnish,squid,nginx用的是反向代理的形势,也就是说访问图片的时候,要先透过缓存工具

二,测试

1,varnish

[root@BlackGhost bin]# /usr/local/bin/webbench -c 100 -t 20 http://127.0.0.1:8080/00/01/RwGowEtWvcQAAAAAAAAWHH0Rklg81.gif
Webbench – Simple Web Benchmark 1.5
Copyright (c) Radim Kolar 1997-2004, GPL Open Source Software.

Benchmarking: GET http://127.0.0.1:8080/00/01/RwGowEtWvcQAAAAAAAAWHH0Rklg81.gif
100 clients, running 20 sec.

Speed=476508 pages/min, 47258114 bytes/sec.
Requests: 158836 susceed, 0 failed.

访问了这么次,没有缓存只有一次,效率真的很高。

2,squid

[root@BlackGhost bin]# /usr/local/bin/webbench -c 100 -t 20 http://localhost:9000/00/01/RwGowEtWvcQAAAAAAAAWHH0Rklg81.gif
Webbench – Simple Web Benchmark 1.5
Copyright (c) Radim Kolar 1997-2004, GPL Open Source Software.

Benchmarking: GET http://localhost:9000/00/01/RwGowEtWvcQAAAAAAAAWHH0Rklg81.gif
100 clients, running 20 sec.

Speed=133794 pages/min, 7475018 bytes/sec.
Requests: 44598 susceed, 0 failed.

从测试效果来说,squid挺让我失望的,在测试前,我心里是这样估计的,缓存最好的是varnish,其次是squid,然后nginx,最后是apache,现在呢,squid是最差的。后来我看了一下log文件,发现正常情况下,缓存和没有缓存的比率不是1:2,如果在高压力下,缓存和没有缓存的比率更小。

3,apache

[root@BlackGhost conf]# /usr/local/bin/webbench -c 100 -t 20 http://localhost/00/01/RwGowEtWvcQAAAAAAAAWHH0Rklg81.gif
Webbench – Simple Web Benchmark 1.5
Copyright (c) Radim Kolar 1997-2004, GPL Open Source Software.

Benchmarking: GET http://localhost/00/01/RwGowEtWvcQAAAAAAAAWHH0Rklg81.gif
100 clients, running 20 sec.

Speed=160890 pages/min, 15856005 bytes/sec.
Requests: 53630 susceed, 0 failed.

4,nginx

[root@BlackGhost conf]# /usr/local/bin/webbench -c 100 -t 20 http://localhost:10000/00/01/RwGowEtWvcQAAAAAAAAWHH0Rklg81.gif
Webbench – Simple Web Benchmark 1.5
Copyright (c) Radim Kolar 1997-2004, GPL Open Source Software.

Benchmarking: GET http://localhost:10000/00/01/RwGowEtWvcQAAAAAAAAWHH0Rklg81.gif
100 clients, running 20 sec.

Speed=304053 pages/min, 30121517 bytes/sec.
Requests: 101351 susceed, 0 failed.

从上面的测试结果我们可以发现,varnish > nginx > apache > squid,我想这个结果,根大家预期的结果有点出入,因为squid做老牌文件缓存工具怎么会这么差呢,squid的命中率低,我在网上查了一下,很多人都是这样的,这个可能根个人配置有关系,也许真正的高手,才能让squid发挥最大功力。

原文地址:http://blog.51yip.com/server/1032.html

初步试用Squid的替代产品──Varnish Cache网站加速器

Varnish是一款高性能的开源HTTP加速器,挪威最大的在线报纸 Verdens Gang (vg.no) 使用3台Varnish代替了原来的12台squid,性能比以前更好。

Varnish的作者Poul-Henning Kamp是FreeBSD的内核开发者之一,他认为现在的计算机比起1975年已经复杂许多。在1975年时,储存媒介只有两种:内存与硬盘。但现在计算机系统的内存除了主存外,还包括了cpu内的L1、L2,甚至有L3快取。硬盘上也有自己的快取装置,因此squid cache自行处理物件替换的架构不可能得知这些情况而做到最佳化,但操作系统可以得知这些情况,所以这部份的工作应该交给操作系统处理,这就是Varnish cache设计架构。

Varnish可以在FreeBSD 6.0和Linux 2.6内核上运行。

1、编译安装varnish HTTP加速器:

引用
wget http://blog.s135.com/soft/linux/varnish/varnish-1.1.1.tar.gz
tar zxvf varnish-1.1.1.tar.gz
cd varnish-1.1.1
./configure –prefix=/usr/local/varnish
make && make install

2、简单启动varnish守护进程,用本机80端口去反向代理加速127.0.0.1:81上的Apache服务器:

引用
/usr/local/varnish/sbin/varnishd -a :8080 -b 127.0.0.1:81 -p thread_pool_max=1500 -p thread_pools=5 -p listen_depth=512 -p client_http11=on -w 1,10000,120

Varnish官方网站:http://www.varnish-cache.org/

另有一份PDF文档,说明Varnish原理的:http://ishare.iask.sina.com.cn/cgi-bin/fileid.cgi?fileid=2163384

我测试了一下,在同等配置环境下,Varnish的性能确实要超过Squid,稳定性也不错,值得继续去深入研究。

 

原文地址:http://blog.s135.com/post/290/

使用Varnish代替Squid做网站缓存加速器的详细解决方案

今天写的这篇关于Varnish的文章,已经是一篇可以完全替代Squid做网站缓存加速器的详细解决方案了。网上关于Varnish的资料很少,中文资料更是微乎其微,希望本文能够吸引更多的人研究、使用Varnish。
在我看来,使用Varnish代替Squid的理由有三点:
1、Varnish采用了“Visual Page Cache”技术,在内存的利用上,Varnish比Squid具有优势,它避免了Squid频繁在内存、磁盘中交换文件,性能要比Squid高。
2、Varnish的稳定性还不错,我管理的一台图片服务器运行Varnish已经有一个月,没有发生过故障,而进行相同工作的Squid服务器就倒过几次。
3、通过Varnish管理端口,可以使用正则表达式快速、批量地清除部分缓存,这一点是Squid不能具备的。

点击在新窗口中浏览此图片


下面来安装Varnish网站缓存加速器(Linux系统):
1、创建www用户和组,以及Varnish缓存文件存放目录(/var/vcache):

/usr/sbin/groupadd www -g 48
/usr/sbin/useradd -u 48 -g www www
mkdir -p /var/vcache
chmod +w /var/vcache
chown -R www:www /var/vcache

2、创建Varnish日志目录(/var/logs/):

mkdir -p /var/logs
chmod +w /var/logs
chown -R www:www /var/logs

3、编译安装varnish:

wget http://blog.s135.com/soft/linux/varnish/varnish-1.1.2.tar.gz
tar zxvf varnish-1.1.2.tar.gz
cd varnish-1.1.2
./configure –prefix=/usr/local/varnish
make && make install

4、创建Varnish配置文件:

vi /usr/local/varnish/vcl.conf

输入以下内容:

引用
backend myblogserver {
set backend.host = “192.168.0.5”;
set backend.port = “80”;
}

acl purge {
“localhost”;
“127.0.0.1”;
“192.168.1.0”/24;
}

sub vcl_recv {
if (req.request == “PURGE”) {
if (!client.ip ~ purge) {
error 405 “Not allowed.”;
}
lookup;
}

if (req.http.host ~ “^blog.s135.com”) {
set req.backend = myblogserver;
if (req.request != “GET” && req.request != “HEAD”) {
pipe;
}
else {
lookup;
}
}
else {
error 404 “Zhang Yan Cache Server”;
lookup;
}
}

sub vcl_hit {
if (req.request == “PURGE”) {
set obj.ttl = 0s;
error 200 “Purged.”;
}
}

sub vcl_miss {
if (req.request == “PURGE”) {
error 404 “Not in cache.”;
}
}

sub vcl_fetch {
if (req.request == “GET” && req.url ~ “\.(txt|js)$”) {
set obj.ttl = 3600s;
}
else {
set obj.ttl = 30d;
}
}

这里,我对这段配置文件解释一下:
(1)、Varnish通过反向代理请求后端IP为192.168.0.5,端口为80的web服务器;
(2)、Varnish允许localhost、127.0.0.1、192.168.0.***三个来源IP通过PURGE方法清除缓存;
(3)、Varnish对域名为blog.s135.com的请求进行处理,非blog.s135.com域名的请求则返回“Zhang Yan Cache Server”;
(4)、Varnish对HTTP协议中的GET、HEAD请求进行缓存,对POST请求透过,让其直接访问后端Web服务器。之所以这样配置,是因为POST请求一般是发送数据给服务器的,需要服务器接收、处理,所以不缓存;
(5)、Varnish对以.txt和.js结尾的URL缓存时间设置1小时,对其他的URL缓存时间设置为30天。

5、启动Varnish

ulimit -SHn 51200
/usr/local/varnish/sbin/varnishd -n /var/vcache -f /usr/local/varnish/vcl.conf -a 0.0.0.0:80 -s file,/var/vcache/varnish_cache.data,1G -g www -u www -w 30000,51200,10 -T 127.0.0.1:3500 -p client_http11=on

6、启动varnishncsa用来将Varnish访问日志写入日志文件:

/usr/local/varnish/bin/varnishncsa -n /var/vcache -w /var/logs/varnish.log &

7、配置开机自动启动Varnish

vi /etc/rc.local

在末尾增加以下内容:

引用
ulimit -SHn 51200
/usr/local/varnish/sbin/varnishd -n /var/vcache -f /usr/local/varnish/vcl.conf -a 0.0.0.0:80 -s file,/var/vcache/varnish_cache.data,1G -g www -u www -w 30000,51200,10 -T 127.0.0.1:3500 -p client_http11=on
/usr/local/varnish/bin/varnishncsa -n /var/vcache -w /var/logs/youvideo.log &

8、优化Linux内核参数

vi /etc/sysctl.conf

在末尾增加以下内容:

引用
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_keepalive_time = 300
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 1
net.ipv4.ip_local_port_range = 5000    65000

 


再看看如何管理Varnish:
1、查看Varnish服务器连接数与命中率:

/usr/local/varnish/bin/varnishstat

点击在新窗口中浏览此图片

2、通过Varnish管理端口进行管理:
用help看看可以使用哪些Varnish命令:

/usr/local/varnish/bin/varnishadm -T 127.0.0.1:3500 help

 

引用
Available commands:
ping [timestamp]
status
start
stop
stats
vcl.load
vcl.inline
vcl.use
vcl.discard
vcl.list
vcl.show
param.show [-l] []
param.set
help [command]
url.purge
dump.pool

3、通过Varnish管理端口,使用正则表达式批量清除缓存:
(1)、例:清除类似http://blog.s135.com/a/zhangyan.html的URL地址):

/usr/local/varnish/bin/varnishadm -T 127.0.0.1:3500 url.purge /a/

(2)、例:清除类似http://blog.s135.com/tech的URL地址:

/usr/local/varnish/bin/varnishadm -T 127.0.0.1:3500 url.purge w*$

(3)、例:清除所有缓存:

/usr/local/varnish/bin/varnishadm -T 127.0.0.1:3500 url.purge *$

4、一个清除Squid缓存的PHP函数(清除Varnish缓存同样可以使用该函数,无需作任何修改,十分方便):

  1. <?php
  2. function purge($ip, $url)
  3. {
  4.     $errstr = ”;
  5.     $errno = ”;
  6.     $fp = fsockopen ($ip, 80, $errno, $errstr, 2);
  7.     if (!$fp)
  8.     {
  9.          return false;
  10.     }
  11.     else
  12.     {
  13.         $out = “PURGE $url HTTP/1.1\r\n”;
  14.         $out .= “Host:blog.s135.com\r\n”;
  15.         $out .= “Connection: close\r\n\r\n”;
  16.         fputs ($fp, $out);
  17.         $out = fgets($fp , 4096);
  18.         fclose ($fp);
  19.         return true;
  20.     }
  21. }
  22. purge(“192.168.0.4”, “/index.php”);
  23. ?>

附1:Varnish官方网站:http://www.varnish-cache.org/

附2:2007年12月10日,我写了一个每天0点运行,按天切割Varnish日志,生成一个压缩文件,同时删除上个月旧日志的脚本(/var/logs/cutlog.sh):
/var/logs/cutlog.sh文件内容如下:

引用
#!/bin/sh
# This file run at 00:00
date=$(date -d “yesterday” +”%Y-%m-%d”)
pkill -9 varnishncsa
mv /var/logs/youvideo.log /var/logs/${date}.log
/usr/local/varnish/bin/varnishncsa -n /var/vcache -w /var/logs/youvideo.log &
mkdir -p /var/logs/youvideo/
gzip -c /var/logs/${date}.log > /var/logs/youvideo/${date}.log.gz
rm -f /var/logs/${date}.log
rm -f /var/logs/youvideo/$(date -d “-1 month” +”%Y-%m*”).log.gz

设置在每天00:00定时执行:

/usr/bin/crontab -e

或者

vi /var/spool/cron/root

输入以下内容:

引用
0 0 * * * /bin/sh /var/logs/cutlog.sh

 

 

原文地址:http://blog.s135.com/post/313/

CentOS 6正式发布,免费的企业级Linux

CentOS 6 正式版已于7月9日发布。

CentOS(Community ENTerprise Operating System)是Linux发行版之一,它是来自于Red Hat Enterprise Linux依照开放源代码规定释出的源代码所编译而成。由于出自同样的源代码,因此有些要求高度稳定性的服务器以CentOS替代商业版的Red Hat Enterprise Linux使用。两者的不同在于,CentOS并不包含封闭源代码软件。

CentOS 6.0 基于上游的 Red Hat Enterprise Linux 6.0 制作,同时基本包含了所有的上游软件包。CentOS 完全遵守上游供应商的再发行政策,并且以百分之百的软件兼容性为目标,但相对于 RHEL ,CentOS 最主要的改变是去除了上游供应商的商标及美工图。

CentOS 6上游版本发行注记和文档:Red Hat Enterprise Linux 6

CentOS 6相对于上游版本 RHEL 6,修改、删除和新增了部分组件,详细情况参阅:发行注记

官方网站:http://www.centos.org/

下载页面:http://www.centos.org/modules/tinycontent/index.php?id=15

Bash 小技巧:给目录加上书签,快速切换目录

原文地址:http://www.zhuoqun.net/html/y2011/1635.html

当我们在命令行下面做开发的时候,很大一部分时间都浪费在了目录切换上面,相信不少人每天敲 “cd” 都敲得想吐。如果目录层次多一点,Tab 键也会饱受摧残。虽然 Bash 有内置的 “cd -”, “pushd” 和 “popd” 命令,但用起来都不是很顺手。

昨天在 Twitter 上看到了 Huy Nguyen 的一篇文章:Quick Bash Tip : Directory Bookmarks,用几行简单的 Bash 脚本巧妙地给目录加上了书签,这样你就可以给最常用的那几个工作目录加上书签,不需要每次都敲 cd 了。

昨天 Huy Nguyen 的这篇文章被发布到了 Hacker News 上,然后引来了很多人评论,其中不少评论都是非常有价值的,甚至还有人直接在评论里对 Huy Nguyen 的脚本做了改进。Huy Nguyen 看到评论之后也修改了自己最初写的脚本,并放到了 github 上(https://github.com/huyng/bashmarks),你可以用 git clone 命令把那个脚本下载下来,或者直接把源码复制到你的 ~/.bashrc 中。

这个脚本只有三个命令:

s – 给当前目录加上书签,书签名为 bookmark_name
g – 跳到名为 bookmark_name 的书签
l – 列出所有的书签

如果想要删除已经保存的书签,请直接编辑 $HOME/.sdirs 文件删除相应的行。

评论中也有人推荐了另外一个功能更为强大的名为 z 的脚本,这个脚本也在 github 上(https://github.com/rupa/z),有兴趣的可以试用一下。

BTW, 经常在国外很多技术文章下面看到很多精彩评论,有些甚至比文章本身更加精彩,所以我很多时候都把每个评论仔细看完。评论里没有人说“沙发”,没有人说“傻 逼,这都不懂”,没有人说“菜鸟,早就有人写出同样的东西了!连z都没听说过,我只用它!”,大家都很礼貌,即使是有反对意见也都是逻辑清晰地列出自己的 理由。这让我非常惊诧和羡慕。

作者发布一篇文章,读者提供反馈,然后作者改进原文,文章的改动历史和评论都成为文章不可分割的一部分,作者和读者都可以不断思考和获益。反过来 说,也正是因为这样的氛围才使得很多人敢于分享自己的看法,敢于写出自己的观点,敢于否认自己最初的看法并不断修正。真希望国内在别人文章下面评论的人也 可以有那样的耐心和礼貌,以及与作者对话的逻辑和才能。至少,要把别人的文章看完再发言。

 

Ruby on Rails with Nginx on CentOS 5

Ruby on Rails is a popular rapid development web framework that allows web designers and developers to implement fully featured dynamic web applications using the Ruby programming language. This guide describes the required process for deploying Ruby on Rails with Passenger and the nginx web server on CentOS 5.

 

These instructions work with the Linode platform. If you don’t have a Linode yet, sign up for a Linux VPS and get started today.

Contents
Install Required Packages
Install Passenger and Nginx
Set up an Init Script for Nginx
Install MySQL Support (optional)
More Information
License

Install Required Packages

Make sure your system is up to date by issuing the following command:

yum update

Issue the following series of commands to install packages required for Ruby on Rails.

yum groupinstall "Development Tools"
yum install zlib-devel wget openssl-devel pcre pcre-devel make gcc gcc-c++ curl-devel

The version of Ruby in the CentOS repositories is fairly old; we’ll need to download and compile it ourselves. Check the Ruby language siteExternal Link for a link to the newest stable version and substitute it for the link shown below. Execute the following sequence of commands to get Ruby installed.

cd /opt
wget ftp://ftp.ruby-lang.org/pub/ruby/1.9/ruby-1.9.1-p376.tar.gz
tar -zxvf ruby-1.9.1-p376.tar.gz
cd ruby-1.9.1-p376
./configure --bindir=/usr/bin --sbindir=/usr/sbin/
make -j3
make install

Now we’ll need to install gems. Issue the following series of commands to download and install a fresh version. You may wish to check the RubyForge files pageExternal Link for the most recent version.

cd /opt
wget http://production.cf.rubygems.org/rubygems/rubygems-1.5.1.tgz
tar -zxvf rubygems-1.5.1.tgz
cd /opt/rubygems-1.5.1/
ruby setup.rb

Update rubygems:

gem update --system

Install the rakerack, and fastthread gems:

gem install rake rack
gem install fastthread --no-rdoc --no-ri

Install Passenger and Nginx

Proceed to the Phusion PassengerExternal Link site and locate the link for the current source code tarball. Download it as follows (substitute the link for the current version):

cd /opt
wget http://rubyforge.org/frs/download.php/73563/passenger-3.0.1.tar.gz
tar xzvf passenger-3.0.1.tar.gz

Run the Phusion Passenger installer for Nginx:

cd /opt/passenger-3.0.1/bin
./passenger-install-nginx-module

You’ll be greeted by the Phusion Passenger Nginx installer program. Press “Enter” to continue with the installation.

Phusion Passenger Nginx installer program running on CentOS 5.When prompted for the Nginx installation method, we recommend you choose “1” to allow the installer to automatically download, compile, and install Nginx for you. Unless you have specific needs that would necessitate passing custom options to Nginx at compile time, this is the safest way to proceed.

Please do not remove the Passenger files from opt after the install. They need to stay in place or your install will not function correctly.

Set up an Init Script for Nginx

Nginx is now installed in /opt/nginx, but there are no “init” scripts to control this process. Issue the following sequence of commands to download a script, move it to the proper directory, set the proper permissions and set system startup links:

cd /opt
wget https://library.linode.com/frameworks/ruby-on-rails-nginx/reference/init-rpm.sh
mv /opt/init-deb.sh /etc/rc.d/init.d/nginx
chmod +x /etc/rc.d/init.d/nginx
chkconfig --add nginx
chkconfig nginx on

You can now start, stop, and restart Nginx just like any other server daemon. For example, to start the server, issue the following command:

/etc/init.d/nginx start

You can now start, stop, and restart Nginx just like any other server daemon. For example, to start the server, issue the following command:

/etc/rc.d/init.d/nginx start

If you haven’t already configured your firewall to allow inbound HTTP connections, run the following command to do so now:

system-config-securitylevel-tui

The configuration file for Nginx is located at /opt/nginx/conf/nginx.conf. This is the file you’ll need to edit to add support for your Rails applications. A default server is already configured in this file, and it also contains examples for alternate virtual host and SSL configurations.

Install MySQL Support (optional)

If your application uses MySQL, install the database server by following our MySQL on CentOS 5 guide. Once it’s installed and configured properly, issue the following commands:

yum install mysql-devel
gem install mysql --no-rdoc --no-ri -- --with-mysql-dir=/usr/bin --with-mysql-lib=/usr/lib/mysql --with-mysql-include=/usr/include/mysql

 

More Information

You may wish to consult the following resources for additional information on this topic. While these are provided in the hope that they will be useful, please note that we cannot vouch for the accuracy or timeliness of externally hosted materials.

 

received event “button/power PWRF 00000080 00000001”

今天其中一台服務器無緣無故重啓了。問了機房的人,沒有人去操作。只有清潔工進過機房。

無耐,只好查看系統日誌。/var/log/acpid 發現以下內容。時間跟服務器重啓時間敏合。初步推薦是電源按扭被按了。

[Wed Mar 23 10:44:38 2011] received event “button/power PWRF 00000080 00000001”

[Wed Mar 23 10:44:38 2011] notifying client 4187[68:68]

[Wed Mar 23 10:44:38 2011] notifying client 4380[0:0]

[Wed Mar 23 10:44:38 2011] executing action “/bin/ps awwux | /bin/grep gnome-power-manager | /bin/grep -qv grep || /sbin/shutdown -h now”[Wed Mar 23 10:44:38 2011] BEGIN HANDLER MESSAGES

[Wed Mar 23 10:44:38 2011] END HANDLER MESSAGES

[Wed Mar 23 10:44:38 2011] action exited with status 0

[Wed Mar 23 10:44:38 2011] completed event “button/power PWRF 00000080 00000001”

 

不知道是誰。還是把這個電源按扭事件屏蔽比較安全一些。因爲不知道什麽時候又被“按”了。

# vi /etc/acpi/events/power.conf

# ACPID config to power down machine if powerbutton is pressed, but only if
# no gnome-power-manager is running

event=button/power.*
action=/bin/ps awwux | /bin/grep gnome-power-manager | /bin/grep -qv grep || /sbin/shutdown -h now

看到這裏,已經很肯定是電源按扭被按了。

把最後2行注釋掉:

# ACPID config to power down machine if powerbutton is pressed, but only if
# no gnome-power-manager is running

#event=button/power.*
#action=/bin/ps awwux | /bin/grep gnome-power-manager | /bin/grep -qv grep || /sbin/shutdown -h now

 

bash下利用trap捕捉信号

我在之前的文章里写了myisam读数据压缩的情况,最近决定把它用在生产环境上,所以避免不了写一个“安全”的处理脚本放在DB服务器上,这就引入了本文所讨论的话题。

我希望这个bash脚本在退出的时候做一些事情,包括:

  1. 它启动的切到后台的job需要被杀死;
  2. 一些临时文件的清理。

在这个脚本里我用到了trap这个命令,关于它,你可以man一下,我这里就不啰嗦了。直接上示例代码:

$ cat test_trap.sh

declare -i run_terminate=0

trap "run_terminate=1" SIGINT SIGTERM

# 启动io监控,IO较大时不进行压缩
vmstat 1 &gt;&gt; ./a.log &amp;

while [ ${run_terminate} -eq 0 ]
do
    # 核心代码
    sleep 30
done

for pid in $(ps -ef | awk -v p=${$} '{if ($3 == p){print $2}}')
do
    kill -9 ${pid} &gt; /dev/null
done

rm -f ./a.log
echo "Terminated."

在上面的代码中,我们捕捉INT信号(CTRL+C)和TERM信号(kill产生)。运行程序:

$ /bin/bash test_trap.sh

^C

按照我们预期的,当我CTRL+C退出程序,或者kill进程时,上面的脚本应该停掉vmstat进程,并且删除a.log,输出“Terminated”后退出。

但是,CTRL+C确实按照我们的设想进行了。可kill之后程序并没有任何反应,这是为何?

Google了一遍,天下文章一大抄,相似的例子,却没有人抛出这个问题。思索了半天,幡然醒悟:

  1. kill(killall)命令只是发出一个TERM信号(15),至于这个信号是否被对应进程捕捉并处理了,它并不管;
  2. kill发出的时候,test_trap.sh正在sleep——这个时间有点长(30秒)。

也就是说,等它“睡醒”了,它自然会处理TERM信号的。不信,你多等一会。

 

nginx+resin 使用中文域名解决方案。

xxx中文域名.中国

这样的域名在resin下会出错:

[15:34:31.628] {hmux-127.0.0.1:6801-5} java.lang.StringIndexOutOfBoundsException: String index out of range: 9[15:34:31.628] {hmux-127.0.0.1:6801-5}  at java.lang.String.charAt(String.java:687)[15:34:31.628] {hmux-127.0.0.1:6801-5}  at com.caucho.server.host.DomainName.decode(DomainName.java:205)[15:34:31.628] {hmux-127.0.0.1:6801-5}  at com.caucho.server.host.DomainName.fromAscii(DomainName.java:86)[15:34:31.628] {hmux-127.0.0.1:6801-5}  at com.caucho.server.host.HostContainer.buildInvocation(HostContainer.java:305)[15:34:31.628] {hmux-127.0.0.1:6801-5}  at com.caucho.server.cluster.Server.buildInvocation(Server.java:915)[15:34:31.628] {hmux-127.0.0.1:6801-5}  at com.caucho.server.dispatch.DispatchServer.buildInvocation(DispatchServer.java:209)[15:34:31.628] {hmux-127.0.0.1:6801-5}  at com.caucho.server.hmux.HmuxRequest.handleRequest(HmuxRequest.java:427)[15:34:31.628] {hmux-127.0.0.1:6801-5}  at com.caucho.server.port.TcpConnection.run(TcpConnection.java:603)[15:34:31.628] {hmux-127.0.0.1:6801-5}  at com.caucho.util.ThreadPool$Item.runTasks(ThreadPool.java:721)[15:34:31.628] {hmux-127.0.0.1:6801-5}  at com.caucho.util.ThreadPool$Item.run(ThreadPool.java:643)[15:34:31.628] {hmux-127.0.0.1:6801-5}  at java.lang.Thread.run(Thread.java:619)[15:34:31.628] {hmux-127.0.0.1:6801-5} java.lang.RuntimeException: java.lang.StringIndexOutOfBoundsException: String index out of range: 9[15:34:31.628] {hmux-127.0.0.1:6801-5}  at com.caucho.server.host.DomainName.fromAscii(DomainName.java:109)[15:34:31.628] {hmux-127.0.0.1:6801-5}  at com.caucho.server.host.HostContainer.buildInvocation(HostContainer.java:305)[15:34:31.628] {hmux-127.0.0.1:6801-5}  at com.caucho.server.cluster.Server.buildInvocation(Server.java:915)[15:34:31.628] {hmux-127.0.0.1:6801-5}  at com.caucho.server.dispatch.DispatchServer.buildInvocation(DispatchServer.java:209)[15:34:31.628] {hmux-127.0.0.1:6801-5}  at com.caucho.server.hmux.HmuxRequest.handleRequest(HmuxRequest.java:427)[15:34:31.628] {hmux-127.0.0.1:6801-5}  at com.caucho.server.port.TcpConnection.run(TcpConnection.java:603)[15:34:31.628] {hmux-127.0.0.1:6801-5}  at com.caucho.util.ThreadPool$Item.runTasks(ThreadPool.java:721)[15:34:31.628] {hmux-127.0.0.1:6801-5}  at com.caucho.util.ThreadPool$Item.run(ThreadPool.java:643)[15:34:31.628] {hmux-127.0.0.1:6801-5}  at java.lang.Thread.run(Thread.java:619)[15:34:31.628] {hmux-127.0.0.1:6801-5} Caused by: java.lang.StringIndexOutOfBoundsException: String index out of range: 9[15:34:31.628] {hmux-127.0.0.1:6801-5}  at java.lang.String.charAt(String.java:687)[15:34:31.628] {hmux-127.0.0.1:6801-5}  at com.caucho.server.host.DomainName.decode(DomainName.java:205)[15:34:31.628] {hmux-127.0.0.1:6801-5}  at com.caucho.server.host.DomainName.fromAscii(DomainName.java:86)[15:34:31.628] {hmux-127.0.0.1:6801-5}  … 8 more

 

 

原因是中文域名做了“转码”,不知道是什么鬼东西。反正就出错了。要解决。

分析一下中文域名转码后是怎样的?

例如 中文域名.中国   转码后   xn--wlqpfy8in9c9zd3hc50a.xn--io0a7i

原来这样:当resin接收 到host时,用正常的域名去解释这个地址,由于这个地址不符合正规的域名格式,所以出错。

解决思路,能不能在nginx转发时,改变host呢?查一查nginx说明文档,有一条这样写:

proxy_set_header Host $host;

应该就是这条了。将后面的$host改为 一个英文域名

proxy_set_header Host www.youdomain.com;

 

问题解决了。哈。。。大家加油。

 

 

Nginx源码分析-内存池

Nginx的内存池实现得很精巧,代码也很简洁。总的来说,所有的内存池基本都一个宗旨:申请大块内存,避免“细水长流”。

一、创建一个内存池

nginx内存池主要有下面两个结构来维护,他们分别维护了内存池的头部和数据部。此处数据部就是供用户分配小块内存的地方。

//该结构用来维护内存池的数据块,供用户分配之用。
typedef struct {
    u_char               *last; 	//当前内存分配结束位置,即下一段可分配内存的起始位置
    u_char               *end;  	//内存池结束位置
    ngx_pool_t           *next; 	//链接到下一个内存池
    ngx_uint_t            failed; 	//统计该内存池不能满足分配请求的次数
} ngx_pool_data_t;
//该结构维护整个内存池的头部信息。
struct ngx_pool_s {
    ngx_pool_data_t       d; 		//数据块
    size_t                max;		//数据块的大小,即小块内存的最大值
    ngx_pool_t           *current;	//保存当前内存池
    ngx_chain_t          *chain;	//可以挂一个chain结构
    ngx_pool_large_t     *large;	//分配大块内存用,即超过max的内存请求
    ngx_pool_cleanup_t   *cleanup;	//挂载一些内存池释放的时候,同时释放的资源。
    ngx_log_t            *log;
};

有了上面的两个结构,就可以创建一个内存池了,nginx用来创建一个内存池的接口是:ngx_pool_t *ngx_create_pool(size_t size, ngx_log_t *log)(位于src/core/ngx_palloc.c中);调用这个函数就可以创建一个大小为size的内存池了。这里,我用内存池的结构图来展示,就不做具体的代码分析了。

ngx_create_pool接口函数就是分配上图这样的一大块内存,然后初始化好各个头部字段(上图中的彩色部分)。红色表示的四个字段就是来自于上述的第一个结构,维护数据部分,由图可知:last是用户从内存池分配新内存的开始位置,end是这块内存池的结束位置,所有分配的内存都不能超过end。蓝色表示的max字段的值等于整个数据部分的长度,用户请求的内存大于max时,就认为用户请求的是一个大内存,此时需要在紫色表示的large字段下面单独分配;用户请求的内存不大于max的话,就是小内存申请,直接在数据部分分配,此时将会移动last指针。

二、分配小块内存(size <= max)

上面创建好了一个可用的内存池了,也提到了小块内存的分配问题。nginx提供给用户使用的内存分配接口有:
void *ngx_palloc(ngx_pool_t *pool, size_t size);
void *ngx_pnalloc(ngx_pool_t *pool, size_t size);
void *ngx_pcalloc(ngx_pool_t *pool, size_t size);
void *ngx_pmemalign(ngx_pool_t *pool, size_t size, size_t alignment);

ngx_palloc和ngx_pnalloc都是从内存池里分配size大小内存,至于分得的是小块内存还是大块内存,将取决于size的大小;他们的不同之处在于,palloc取得的内存是对齐的,pnalloc则否。ngx_pcalloc是直接调用palloc分配好内存,然后进行一次0初始化操作。ngx_pmemalign将在分配size大小的内存并按alignment对齐,然后挂到large字段下,当做大块内存处理。下面用图形展示一下分配小块内存的模型:

上图这个内存池模型是由上3个小内存池构成的,由于第一个内存池上剩余的内存不够分配了,于是就创建了第二个新的内存池,第三个内存池是由于前面两个内存池的剩余部分都不够分配,所以创建了第三个内存池来满足用户的需求。由图可见:所有的小内存池是由一个单向链表维护在一起的。这里还有两个字段需要关注,failed和current字段。failed表示的是当前这个内存池的剩余可用内存不能满足用户分配请求的次数,即是说:一个分配请求到来后,在这个内存池上分配不到想要的内存,那么就failed就会增加1;这个分配请求将会递交给下一个内存池去处理,如果下一个内存池也不能满足,那么它的failed也会加1,然后将请求继续往下传递,直到满足请求为止(如果没有现成的内存池来满足,会再创建一个新的内存池)。current字段会随着failed的增加而发生改变,如果current指向的内存池的failed达到了4的话,current就指向下一个内存池了。猜测:4这个值应该是作者的经验值,或者是一个统计值。

三、大块内存的分配(size > max)

大块内存的分配请求不会直接在内存池上分配内存来满足,而是直接向操作系统申请这么一块内存(就像直接使用malloc分配内存一样),然后将这块内存挂到内存池头部的large字段下。内存池的作用在于解决小块内存池的频繁申请问题,对于这种大块内存,是可以忍受直接申请的。同样,用图形展示大块内存申请模型:

注意每块大内存都对应有一个头部结构(next&alloc),这个头部结构是用来将所有大内存串成一个链表用的。这个头部结构不是直接向操作系统申请的,而是当做小块内存(头部结构没几个字节)直接在内存池里申请的。这样的大块内存在使用完后,可能需要第一时间释放,节省内存空间,因此nginx提供了接口函数:ngx_int_t ngx_pfree(ngx_pool_t *pool, void *p);此函数专门用来释放某个内存池上的某个大块内存,p就是大内存的地址。ngx_pfree只会释放大内存,不会释放其对应的头部结构,毕竟头部结构是当做小内存在内存池里申请的;遗留下来的头部结构会作下一次申请大内存之用。

四、cleanup资源


可以看到所有挂载在内存池上的资源将形成一个循环链表,一路走来,发现链表这种看似简单的数据结构却被频繁使用。由图可知,每个需要清理的资源都对应有一个头部结构,这个结构中有一个关键的字段handler,handler是一个函数指针,在挂载一个资源到内存池上的时候,同时也会注册一个清理资源的函数到这个handler上。即是说,内存池在清理cleanup的时候,就是调用这个handler来清理对应的资源。比如:我们可以将一个开打的文件描述符作为资源挂载到内存池上,同时提供一个关闭文件描述的函数注册到handler上,那么内存池在释放的时候,就会调用我们提供的关闭文件函数来处理文件描述符资源了。

五、内存的释放

nginx只提供给了用户申请内存的接口,却没有释放内存的接口,那么nginx是如何完成内存释放的呢?总不能一直申请,用不释放啊。针对这个问题,nginx利用了web server应用的特殊场景来完成;一个web server总是不停的接受connection和request,所以nginx就将内存池分了不同的等级,有进程级的内存池、connection级的内存池、request级的内存池。也就是说,创建好一个worker进程的时候,同时为这个worker进程创建一个内存池,待有新的连接到来后,就在worker进程的内存池上为该连接创建起一个内存池;连接上到来一个request后,又在连接的内存池上为request创建起一个内存池。这样,在request被处理完后,就会释放request的整个内存池,连接断开后,就会释放连接的内存池。因而,就保证了内存有分配也有释放。

总结:通过内存的分配和释放可以看出,nginx只是将小块内存的申请聚集到一起申请,然后一起释放。避免了频繁申请小内存,降低内存碎片的产生等问题