伺服器的大使用者量的承載方案

一見藍天發表於2008-06-25

一、前言
二、編譯安裝
三、 安裝MySQL、memcache
四、 安裝Apache、PHP、eAccelerator、php-memcache
五、 安裝Squid
六、後記

一、前言,準備工作
      當前,LAMP開發模式是WEB開發的首選,如何搭建一個高效、可靠、穩定的WEB伺服器一直是個熱門主題,本文就是這個主題的一次嘗試。
我們採用的架構圖如下:

引用
——–               ———-                           ————-                   ———                 ————
| 客戶端 | ===> |負載均衡器| ===> |反向代理/快取| ===> |WEB伺服器| ===> |資料庫伺服器|
——–               ———-                           ————-                   ———                 ————
                              Nginx                     Squid                     Apache,PHP                 MySQL
                                                                              eAccelerator/memcache

準備工作:

引用
伺服器: Intel(R) Xeon(TM) CPU 3.00GHz * 2, 2GB mem, SCISC 硬碟
作業系統:CentOs4.4,核心版本2.6.9-22.ELsmp,gcc版本3.4.4
軟體:
Apache 2.2.3(能使用MPM模式)
PHP 5.2.0(選用該版本是因為5.2.0的引擎相對更高效)
eAccelerator 0.9.5(加速PHP引擎,同時也可以加密PHP源程式)
memcache 1.2.0(用於快取記憶體常用資料)
libevent 1.2a(memcache工作機制所需)
MySQL 5.0.27(選用二進位制版本,省去編譯工作)
Nginx 0.5.4(用做負載均衡器)
squid-2.6.STABLE6(做反向代理的同時提供專業快取功能)

二、編譯安裝
一、) 安裝Nginx
1.) 安裝
Nginx發音為[engine x],是由俄羅斯人Igor Sysoev建立的專案,基於BSD許可。據說他當初是F5的成員之一,英文主頁:http://nginx.net。俄羅斯的一些大網站已經使用它超過兩年多了,一直表現不凡。
Nginx的編譯引數如下:

[root@localhost]#./configure –prefix=/usr/local/server/nginx –with-openssl=/usr/include
–with-pcre=/usr/include/pcre/ –with-http_stub_status_module –without-http_memcached_module
–without-http_fastcgi_module –without-http_rewrite_module –without-http_map_module
–without-http_geo_module –without-http_autoindex_module
在這裡,需要說明一下,由於Nginx的配置檔案中我想用到正則,所以需要 pcre 模組的支援。我已經安裝了 pcre 及 pcre-devel 的rpm包,但是 Ngxin 並不能正確找到 .h/.so/.a/.la 檔案,因此我稍微變通了一下:

[root@localhost]#mkdir /usr/include/pcre/.libs/
[root@localhost]#cp /usr/lib/libpcre.a /usr/include/pcre/.libs/libpcre.a
[root@localhost]#cp /usr/lib/libpcre.a /usr/include/pcre/.libs/libpcre.la
然後,修改 objs/Makefile 大概在908行的位置上,註釋掉以下內容:

./configure –disable-shared
接下來,就可以正常執行 make 及 make install 了。

2.) 修改配置檔案 /usr/local/server/nginx/conf/nginx.conf
以下是我的 nginx.conf 內容,僅供參考:

#執行使用者
user   nobody nobody;
#啟動程式
worker_processes   2;
#全域性錯誤日誌及PID檔案
error_log   logs/error.log notice;
pid         logs/nginx.pid;
#工作模式及連線數上限
events {
use epoll;
worker_connections       1024;
}
#設定http伺服器,利用它的反向代理功能提供負載均衡支援
http {
#設定mime型別
include       conf/mime.types;
default_type   application/octet-stream;
#設定日誌格式
log_format main         `$remote_addr – $remote_user [$time_local] `
`”$request” $status $bytes_sent `
`”$http_referer” “$http_user_agent” `
`”$gzip_ratio”`;
log_format download `$remote_addr – $remote_user [$time_local] `
`”$request” $status $bytes_sent `
`”$http_referer” “$http_user_agent” `
`”$http_range” “$sent_http_content_range”`;
#設定請求緩衝
client_header_buffer_size     1k;
large_client_header_buffers   4 4k;
#開啟gzip模組
gzip on;
gzip_min_length   1100;
gzip_buffers     4 8k;
gzip_types       text/plain;
output_buffers   1 32k;
postpone_output   1460;
#設定access log
access_log   logs/access.log   main;
client_header_timeout   3m;
client_body_timeout     3m;
send_timeout           3m;
sendfile                 on;
tcp_nopush               on;
tcp_nodelay             on;
keepalive_timeout   65;
#設定負載均衡的伺服器列表
upstream mysvr {
#weigth參數列示權值,權值越高被分配到的機率越大
#本機上的Squid開啟3128埠
server 192.168.8.1:3128 weight=5;
server 192.168.8.2:80   weight=1;
server 192.168.8.3:80   weight=6;
}
#設定虛擬主機
server {
listen           80;
server_name     192.168.8.1 www.yejr.com;
charset gb2312;
#設定本虛擬主機的訪問日誌
access_log   logs/www.yejr.com.access.log   main;
#如果訪問 /img/*, /js/*, /css/* 資源,則直接取本地檔案,不通過squid
#如果這些檔案較多,不推薦這種方式,因為通過squid的快取效果更好
location ~ ^/(img|js|css)/   {
root     /data3/Html;
expires 24h;
}
#對 “/” 啟用負載均衡
location / {
proxy_pass       http://mysvr;
proxy_redirect           off;
proxy_set_header         Host $host;
proxy_set_header         X-Real-IP $remote_addr;
proxy_set_header         X-Forwarded-For $proxy_add_x_forwarded_for;
client_max_body_size     10m;
client_body_buffer_size 128k;
proxy_connect_timeout   90;
proxy_send_timeout       90;
proxy_read_timeout       90;
proxy_buffer_size       4k;
proxy_buffers           4 32k;
proxy_busy_buffers_size 64k;
proxy_temp_file_write_size 64k;
}
#設定檢視Nginx狀態的地址
location /NginxStatus {
stub_status             on;
access_log               on;
auth_basic               “NginxStatus”;
auth_basic_user_file   conf/htpasswd;
}
}
}
備註:conf/htpasswd 檔案的內容用 apache 提供的 htpasswd 工具來產生即可,內容大致如下:
3.) 檢視 Nginx 執行狀態
輸入地址 http://192.168.8.1/NginxStatus/,輸入驗證帳號密碼,即可看到類似如下內容:
Active connections: 328
server accepts handled requests
9309     8982         28890
Reading: 1 Writing: 3 Waiting: 324

第一行表示目前活躍的連線數
第三行的第三個數字表示Nginx執行到當前時間接受到的總請求數,如果快達到了上限,就需要加大上限值了。
第四行是Nginx的佇列狀態

三、 安裝MySQL、memcache

1.) 安裝MySQL,步驟如下:
[root@localhost]#tar zxf mysql-standard-5.0.27-linux-i686.tar.gz -C /usr/local/server
[root@localhost]#mv /usr/local/server/mysql-standard-5.0.27-linux-i686 /usr/local/server/mysql
[root@localhost]#cd /usr/local/server/mysql
[root@localhost]#./scripts/mysql_install_db –basedir=/usr/local/server/mysql
–datadir=/usr/local/server/mysql/data –user=nobody
[root@localhost]#cp /usr/local/server/mysql/support-files/my-large.cnf
/usr/local/server/mysql/data/my.cnf

2.) 修改 MySQL 配置,增加部分優化引數,如下:
[root@localhost]#vi /usr/local/server/mysql/data/my.cnf

主要內容如下:
[mysqld]
basedir = /usr/local/server/mysql
datadir = /usr/local/server/mysql/data
user     = nobody
port     = 3306
socket   = /tmp/mysql.sock
wait_timeout     = 30
long_query_time=1
#log-queries-not-using-indexes = TRUE
log-slow-queries=/usr/local/server/mysql/slow.log
log-error = /usr/local/server/mysql/error.log
external-locking = FALSE
key_buffer_size = 512M
back_log         = 400
table_cache     = 512
sort_buffer_size = 2M
join_buffer_size = 4M
read_buffer_size = 2M
read_rnd_buffer_size     = 4M
myisam_sort_buffer_size = 64M
thread_cache_size       = 32
query_cache_limit       = 2M
query_cache_size         = 64M
thread_concurrency       = 4
thread_stack     = 128K
tmp_table_size   = 64M
binlog_cache_size       = 2M
max_binlog_size = 128M
max_binlog_cache_size   = 512M
max_relay_log_size       = 128M
bulk_insert_buffer_size = 8M
myisam_repair_threads   = 1
skip-bdb
#如果不需要使用innodb就關閉該選項
#skip-innodb
innodb_data_home_dir     = /usr/local/server/mysql/data/
innodb_data_file_path   = ibdata1:256M;ibdata2:256M:autoextend
innodb_log_group_home_dir       = /usr/local/server/mysql/data/
innodb_log_arch_dir     = /usr/local/server/mysql/data/
innodb_buffer_pool_size = 512M
innodb_additional_mem_pool_size = 8M
innodb_log_file_size     = 128M
innodb_log_buffer_size   = 8M
innodb_lock_wait_timeout         = 50
innodb_flush_log_at_trx_commit   = 2
innodb_file_io_threads   = 4
innodb_thread_concurrency       = 16
innodb_log_files_in_group       = 3

以上配置引數請根據具體的需要稍作修改。執行以下命令即可啟動 MySQL 伺服器:
/usr/local/server/mysql/bin/mysqld_safe
–defaults-file=/usr/local/server/mysql/data/my.cnf &

由於 MySQL 不是安裝在標準目錄下,因此必須要修改 mysqld_safe 中的 my_print_defaults 檔案所在位置,才能通過
mysqld_safe 來啟動 MySQL 伺服器。
3.) memcache + libevent 安裝編譯安裝:
[root@localhost]#cd libevent-1.2a
[root@localhost]#./configure –prefix=/usr/ && make && make install
[root@localhost]#cd ../memcached-1.2.0
[root@localhost]#./configure –prefix=/usr/local/server/memcached –with-libevent=/usr/
[root@localhost]#make && make install

備註:如果 libevent 不是安裝在 /usr 目錄下,那麼需要把 libevent-1.2a.so.1 拷貝/連結到 /usr/lib 中,否則
memcached 無法正常載入。執行以下命令來啟動 memcached:
[root@localhost]#/usr/local/server/memcached/bin/memcached
-l 192.168.8.1 -d -p 10000 -u nobody -m 128

表示用 daemon 的方式啟動 memcached,監聽在 192.168.8.1 的 10000 埠上,執行使用者為 nobody,為其分配
128MB 的記憶體。

四、 安裝Apache、PHP、eAccelerator、php-memcache

四、) 安裝Apache、PHP、eAccelerator、php-memcache由於Apache
2下的php靜態方式編譯十分麻煩,因此在這裡採用動態模組(DSO)方式。1.) 安裝Apache 2.2.3
[root@localhost]#./configure –prefix=/usr/local/server/apache –disable-userdir –disable-actions
–disable-negotiation –disable-autoindex –disable-filter –disable-include –disable-status
–disable-asis –disable-auth –disable-authn-default –disable-authn-file –disable-authz-groupfile
–disable-authz-host –disable-authz-default –disable-authz-user –disable-userdir
–enable-expires –enable-module=so

備註:在這裡,取消了一些不必要的模組,如果你需要用到這些模組,那麼請去掉部分引數。
2.) 安裝PHP 5.2.0
[root@localhost]#./configure –prefix=/usr/local/server/php –with-mysql
–with-apxs2=/usr/local/server/apache/bin/apxs –with-freetype-dir=/usr/ –with-png-dir=/usr/
–with-gd=/usr/ –with-jpeg-dir=/usr/ –with-zlib –enable-magic-quotes –with-iconv
–without-sqlite –without-pdo-sqlite –with-pdo-mysql –disable-dom –disable-simplexml
–enable-roxen-zts
[root@localhost]#make && make install

備註:如果不需要gd或者pdo等模組,請自行去掉。
3.) 安裝eAccelerator-0.9.5
[root@localhost]#cd eAccelerator-0.9.5
[root@localhost]#export PHP_PREFIX=/usr/local/server/php
[root@localhost]#$PHP_PREFIX/bin/phpize
[root@localhost]#./configure –enable-eaccelerator=shared –with-php-config=$PHP_PREFIX/bin/php-config
[root@localhost]#make && make install

4.) 安裝memcache模組
[root@localhost]#cd memcache-2.1.0
[root@localhost]#export PHP_PREFIX=/usr/local/server/php
[root@localhost]#$PHP_PREFIX/bin/phpize
[root@localhost]#./configure –enable-eaccelerator=shared –with-php-config=$PHP_PREFIX/bin/php-config
[root@localhost]#make && make install

5.) 修改 php.ini 配置然後修改 php.ini,修改/加入類似以下內容:
extension_dir = “/usr/local/server/php/lib/”
extension=”eaccelerator.so”
eaccelerator.shm_size=”32″       ;設定eaccelerator的共享記憶體為32MB
eaccelerator.cache_dir=”/usr/local/server/eaccelerator”
eaccelerator.enable=”1″
eaccelerator.optimizer=”1″
eaccelerator.check_mtime=”1″
eaccelerator.debug=”0″
eaccelerator.filter=”*.php”
eaccelerator.shm_max=”0″
eaccelerator.shm_ttl=”0″
eaccelerator.shm_prune_period=”3600″
eaccelerator.shm_only=”0″
eaccelerator.compress=”1″
eaccelerator.compress_level=”9″
eaccelerator.log_file = “/usr/local/server/apache/logs/eaccelerator_log”
eaccelerator.allowed_admin_path = “/usr/local/server/apache/htdocs/ea_admin”
extension=”memcache.so”

在這裡,最好是在apache的配置中增加預設檔案型別的cache機制,即利用apache的expires模組,新增類似如下幾行:
ExpiresActive On
ExpiresByType text/html “access plus 10 minutes”
ExpiresByType text/css “access plus 1 day”
ExpiresByType image/jpg “access 1 month”
ExpiresByType image/gif “access 1 month”
ExpiresByType image/jpg “access 1 month”
ExpiresByType application/x-shockwave-flash “access plus 3 day”

這麼設定是由於我的這些靜態檔案通常很少更新,因此我選擇的是”access”規則,如果更新相對比較頻繁,可以改用”modification”規則;或者也可以用”access”規則,但是在檔案更新的時候,執行一下”touch”命令,把檔案的時間重新整理一下即可。

五、 安裝Squid

五、) 安裝Squid
[root@localhost]#./configure –prefix=/usr/local/server/squid –enable-async-io=100 –disable-delay-pools –disable-mem-gen-trace –disable-useragent-log –enable-kill-parent-hack –disable-arp-acl –enable-epoll –disable-ident-lookups –enable-snmp –enable-large-cache-files –with-large-files
[root@localhost]#make && make install

或使用如下安裝方法:
[root@localhost]#yum install squid

如果是2.6的核心,才能支援epoll的IO模式,舊版本的核心則只能選擇poll或其他模式了;另外,記得帶上支援大檔案的選項,否則在access
log等檔案達到2G的時候就會報錯。設定 squid 的配置大概如下內容:
#設定快取目錄為 /var/cache1 和 /var/lib/squid,每次處理快取大小為128MB,當快取空間使用達到95%時
#新的內容將取代舊的而不直接新增到目錄中,直到空間又下降到90%才停止這一活動
#/var/cache1 最大1024MB,/var/lib/squid 最大 5000MB,都是 16*256 級子目錄
cache_dir aufs /var/cache1 1024 16 256
cache_dir aufs /var/lib/squid 5000 16 256
cache_mem 128 MB
cache_swap_low 90
cache_swap_high 95
#設定儲存策略等
maximum_object_size 4096 KB
minimum_object_size 0 KB
maximum_object_size_in_memory 80 KB
ipcache_size 1024
ipcache_low 90
ipcache_high 95
cache_replacement_policy lru
memory_replacement_policy lru
#設定超時策略
forward_timeout 20 seconds
connect_timeout 15 seconds
read_timeout 3 minutes
request_timeout 1 minutes
persistent_request_timeout 15 seconds
client_lifetime 15 minutes
shutdown_lifetime 5 seconds
negative_ttl 10 seconds
#限制一個ip最大隻能有16個連線
acl OverConnLimit maxconn 16
http_access deny OverConnLimit
#限制baidu spider訪問
#acl AntiBaidu req_header User-Agent Baiduspider
#http_access deny AntiBaidu
#常規設定
visible_hostname cache.yejr.com
cache_mgr webmaster@yejr.com
client_persistent_connections off
server_persistent_connections on
cache_effective_user nobody
cache_effective_group nobody
tcp_recv_bufsize 65535 bytes
half_closed_clients off
#設定不快取的規則
hierarchy_stoplist cgi-bin
acl QUERY urlpath_regex cgi-bin
cache deny QUERY
#不要相信ETag 因為有gzip
acl apache rep_header Server ^Apache
broken_vary_encoding allow apache
#設定access log,並且令其格式和apache的格式一樣,方便awstats分析
emulate_httpd_log   on
logformat apache %>a %ui %un [%tl] “%rm %ru HTTP/%rv” %Hs %

初始化和啟動squid
[root@localhost]#/usr/local/server/squid/sbin/squid -z
[root@localhost]#/usr/local/server/squid/sbin/squid

第一條命令是先初始化squid快取雜湊子目錄,只需執行一次即可。

六、後記

六、後記一、)想要啟用squid所需的改變想要更好的利用squid的cache功能,不是把它啟用了就可以的,我們需要做以下幾個調整:
1、啟用apache的 mod_expires 模組,修改 httpd.conf,加入以下內容:
#expiresdefault “modification plus 2 weeks”expiresactive
onexpiresbytype text/html “access plus 10 minutes”expiresbytype
image/gif “modification plus 1 month”expiresbytype image/jpeg “modification
plus 1 month”expiresbytype image/png “modification plus 1
month”expiresbytype text/css “access plus 1 day”expiresbytype
application/x-shockwave-flash “access plus 3 day”
以上配置的作用是規定各種型別檔案的cache規則,對那些圖片/flash等靜態檔案總是cache起來,可根據各自的需要做適當調整。
2、修改 php.ini 配置,如下:
session.cache_limiter = nocache
以上配置的作用是預設取消php中的cache功能,避免不正常的cache產生。
3、修改應用程式例如,有一個php程式頁面static.php,它存放著某些查詢資料庫後的結果,並且資料更新並不頻繁,於是,我們就可以考慮對其cache。只需在static.php中加入類似如下程式碼:
header(`Cache-Control: max-age=86400
,must-revalidate`);header(`Pragma:`);header(`Last-Modified: ` .
gmdate(`D, d M Y H:i:s`) . ` GMT` );header(“Expires: ” .gmdate (`D, d M Y
H:i:s`, time() + `86400` ). ` GMT`);
以上程式碼的意思是,輸出一個http頭部資訊,讓squid知道本頁面預設快取時長為一天。
二、)squidclient簡要介紹
*取得squid執行狀態資訊: squidclient -p 80 mgr:info
*取得squid記憶體使用情況: squidclient -p 80 mgr:mem
*取得squid已經快取的列表: squidclient -p 80 mgr:objects. use it carefully,it may crash
*取得squid的磁碟使用情況: squidclient -p 80 mgr:diskd
*強制更新某個url:squidclient -p 80 -m PURGE http://www.yejr.com/static.php
*更多的請檢視:squidclient-h 或者 squidclient -p 80 mgr:

http://www.unixtech.cn/read.php?tid=1179  


相關文章