转:http://www.cnblogs.com/vicowong/archive/2011/12/01/2116212.html

一、CentOS 6安装

1.1 使用VMware 虚拟机进行安装,进行安装界面

(分配内存必须大于1G,否则不会显示图型安装界面,网络设置使用“桥接模式” 即"Bridged"模式)

1.2 选择 Install or upgrade an existing system

1.3 在"Disc found" 框 选择 "skip"

1.4 next 选择 "chinese(simplified)(中文(简介 )) next

1.5 选择 "美国英语式" 下一步

1.6 选择 "基本 存储设备" 下一步

1.7 弹出"警告"框时,选择"重新初始化所有"

1.8 主机名可以保留默认,点击”配置网络“ 弹出“网络连接” 双击“System eth0"

1.9 弹出“正在编辑 System eth0" 选择"自动连接" 点击"应用“ ,点击”关闭“ 关闭”网络连接“框 下一步

1.10 不要选择“系统时钟使用UTC时间” 下一步

1.11 输入并确认 ”根密码“ 下一步

1.12 选择"替换现有Linux系统 " 下一步 “将修改写入磁盘"

1.13 选择"Basic Server" 下一步

1.14 大概一共590个软件包,复制安装完成后,点击“重新引导”,重新启动计算机

1.15 (安装完成后,可以将虚拟机内存由1G,改为512M)

 

二、更新centos6

2.1 更新

yum update -y

2.2 查看版本,确认为"CentOS Linux release 6.0 (Final)"

lsb_release -a

2.2 安装编译器

yum install -y gcc gcc-c++

 

三、安装Google-perftools (使用tcmalloc 加速 mysql 和 nginx)

3.1下载需要的文件

下载 libunwind-1.0.1.tar.gz 到 /usr/local/data-original

3.2 安装libunwind

cd /usr/local/data-original/

tar zvxf libunwind-1.0.1.tar.gz

cd libunwind-1.0.1

./configure --enable-shared

make && make install

3.3 安装google-perftools

cd /usr/local/data-original/

tar zvxf google-perftools-1.8.3.tar.gz

cd google-perftools-1.8.3

./configure --enable-shared --enable-frame-pointers

make && make install

3.4 更新,使动态链接库能够被系统共享

echo "/usr/local/lib" > /etc/ld.so.conf.d/usr_local_lib.conf

ldconfig

 

四、安装mysql

4.1.下载文件

下载 ncurses-5.9.tar.gz到/usr/local/data-original
下载 bison-2.5.tar.gz到/usr/local/data-original
下载 cmake-2.8.6.tar.gz到/usr/local/data-original
下载 mysql-5.5.18.tar.gz到/usr/local/data-original

4.2 安装ncurses

yum install ncurses-devel -y

cd /usr/local/data-original/

tar zvxf ncurses-5.9

./configure

make && make install

4.3 安装cmake

cd /usr/local/data-original/

tar zvxf cmake-2.8.6.tar.gz

cd cmake-2.8.6

./bootstrap

make && make install

4.4 安装bison

cd /usr/local/data-original/

tar zvxf bison-2.5.tar.gz

cd bison-2.5

./configure

make && make install

4.5 创建mysql需要的目录、配置用户和用户组

groupadd mysql

useradd -g mysql mysql

mkdir -p /data/mysql

chown -R mysql:mysql /data/mysql

4.6.安装mysql (需要 cmake ncurses-devel bison 库)

4.6.1 安装

cd /usr/local/data-original/

tar zvxf mysql-5.5.18.tar.gz

cd mysql-5.5.18

cmake -DCMAKE_INSTALL_PREFIX=/opt/mysql -DMYSQL_DATADIR=/data/mysql -DWITH_INNOBASE_STORAGE_ENGINE=1 -DWITH_MEMORY_STORAGE_ENGINE=1 -DWITH_MYISAM_STORAGE_ENGINE=1 -DSYSCONFDIR=/etc/ -DWITH_SSL=yes -DDEFAULT_CHARSET=utf8 -DDEFAULT_COLLATION=utf8_general_ci -DWITH_READLINE=on

make && make install

4.6.2 创建软连接

ln -s /opt/mysql/lib/lib* /usr/lib/

4.6.3 配置mysql数据库

cd /opt/mysql
./scripts/mysql_install_db --basedir=/opt/mysql/ --datadir=/data/mysql/ --user=mysql

4.6.4 复制配置文件

cp ./support-files/my-large.cnf /etc/my.cnf

4.6.5 修改配置文件,设置默认使用utf8编码

vim /etc/my.cnf
在[client]下添加一行
default-character-set = utf8
在[mysqld]下添加一行
character-set-server = utf8

4.6.6 设置mysql开机自动启动服务
cp ./support-files/mysql.server /etc/rc.d/init.d/mysqld
chkconfig --add mysqld
chkconfig --level 345 mysqld on

4.6.7 修改服务配置文件
vim /etc/rc.d/init.d/mysqld

根据设定需要,修改mysqld文件中的下面两项
basedir=/opt/mysql
datadir=/data/mysql

4.6.8 启动mysqld服务
service mysqld start

4.6.9 数据库初始化及修改root密码(root初始密码为空)
./bin/mysql_secure_installation
根据提示操作

4.6.10 软连接mysql

ln -s /opt/mysql/bin/mysql /bin

4.6.11 重启centos后,尝试用root连接mysql
mysql -u root -p

成功登录后查看状态

status;

4.6.12 使用tcmalloc优化mysql ( 需要安装google-perftools)

修改MySQL启动脚本(根据你的MySQL安装位置而定)
vim /opt/mysql/bin/mysqld_safe

在# executing mysqld_safe的下一行,加上:
export LD_PRELOAD=/usr/local/lib/libtcmalloc.so

4.6.13 重启服务,查看tcmalloc是否生效 (第二条命令显示即生效)

service mysqld restart

lsof -n | grep tcmalloc

如果显示以下类似的信息,即表示tcmalloc生效

[root@localhost mysql]# lsof -n|grep tcmalloc
mysqld 30347 mysql mem REG 253,0 2177570 544322 /usr/local/lib/libtcmalloc.so.0.2.2

 

五、安装Nginx

5.1.准备安装

下载 pcre-8.20.tar.gz到/usr/local/data-original

下载 nginx-1.0.10.tar.gz到/usr/local/data-original

5.2 更新包

yum install zlib* openssl* -y

 

5.3 安装Pcre

cd /usr/local/data-original/

tar zvxf pcre-8.20.tar.gz

cd pcre-8.20

./configure

make && make install

5.4 创建www用户和组,创建www虚拟主机使用的目录,以及Nginx使用的日志目录,并且赋予他们适当的权限

groupadd www
useradd -g www www

mkdir -p /data/www
chmod +w /data/www
chown -R www:www /data/www

为tcmalloc添加目录,并且赋予适当权限

mkdir -p /tmp/tcmalloc/

chown -R www:www /tmp/tcmalloc/

 

5.1 安装Nginx (需要 pcre google-perftools 库)

5.5.1 安装

cd /usr/local/data-original/

tar zvxf nginx-1.0.10.tar.gz

伪装服务器信息(可以不修改)

cd nginx-1.0.10/data-original/core

vim ./data-original/core/nginx.h

修改NGINX_VERSION为你希望显示的版号

修改NGINX_VER为你希望显示的名称

修改NGINX_VAR 为你希望显示的名称

保存

开始安装

./configure --user=www --group=www --prefix=/opt/nginx --with-http_stub_status_module --with-http_ssl_module --with-google_perftools_module

make && make install

5.4.2 修改 nginx.conf ,令nginx可以 google-perftools实现加速

vim /opt/nginx/conf/nginx.conf

修改前面几行为:

user www www;
worker_processes 8;
error_log logs/error.log crit;
pid logs/nginx.pid;
google_perftools_profiles /tmp/tcmalloc/;
events{
use epoll;
worker_connections 65535;
}

 

5.4.3 测试和运行

cd /opt/nginx

./sbin/nginx -t

如果显示下面信息,即表示配置没问题

nginx: the configuration file /opt/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /opt/nginx/conf/nginx.conf test is successful

输入代码运行nginx服务

./sbin/nginx

ps au|grep nginx

如果显以类似下面的信息,即表示nginx已经启动

root 2013 0.0 0.0 103156 856 pts/0 S+ 03:22 0:00 grep nginx

输入代码检测是否支持加速

lsof -n | grep tcmalloc

如果显示类似下面的信息,即表示支持tcmalloc加速 (mysqld和nginx两个线程都支持)

mysqld 20818 mysql mem REG 253,0 2177570 281050 /usr/local/lib/libtcmalloc.so.0.2.2

nginx 29454 www 25w REG 253,0 0 288399 /tmp/tcmalloc/.29454

nginx 29455 www 27w REG 253,0 0 288403 /tmp/tcmalloc/.29455

 

5.5.4 打开防火墙80端口

写入规则,保存并重启服务

iptables -I INPUT -p tcp --dport 80 -j ACCEPT

/etc/rc.d/init.d/iptables save

/etc/init.d/iptables restart

查看防火墙信息
/etc/init.d/iptables status

如果显示以下类似信息,即表示已经打开了80端口

1 ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:80

5.5.5 编写nginx 启动服务

cd /etc/init.d

vim nginx

输入以下代码并保存

#!/bin/sh
#
# nginx - this script starts and stops the nginx daemon
#
# chkconfig: - 85 15
# description: Nginx is an HTTP(S) server, HTTP(S) reverse \
# proxy and IMAP/POP3 proxy server
# processname: nginx
# config: /etc/nginx/nginx.conf
# config: /etc/sysconfig/nginx
# pidfile: /var/run/nginx.pid

# Source function library.
. /etc/rc.d/init.d/functions

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0

nginx="/opt/nginx/sbin/nginx"
prog=$(basename $nginx)

NGINX_CONF_FILE="/opt/nginx/conf/nginx.conf"

[ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx

lockfile=/var/lock/subsys/nginx

start() {
[ -x $nginx ] || exit 5
[ -f $NGINX_CONF_FILE ] || exit 6
echo -n $"Starting $prog: "
daemon $nginx -c $NGINX_CONF_FILE
retval=$?
echo
[ $retval -eq 0 ] && touch $lockfile
return $retval
}

stop() {
echo -n $"Stopping $prog: "
killproc $prog -QUIT
retval=$?
echo
[ $retval -eq 0 ] && rm -f $lockfile
return $retval
killall -9 nginx
}

restart() {
configtest || return $?
stop
sleep 1
start
}

reload() {
configtest || return $?
echo -n $"Reloading $prog: "
killproc $nginx -HUP
RETVAL=$?
echo
}

force_reload() {
restart
}

configtest() {
$nginx -t -c $NGINX_CONF_FILE
}

rh_status() {
status $prog
}

rh_status_q() {
rh_status >/dev/null 2>&1
}

case "$1" in
start)
rh_status_q && exit 0
$1
;;
stop)
rh_status_q || exit 0
$1
;;
restart|configtest)
$1
;;
reload)
rh_status_q || exit 7
$1
;;
force-reload)
force_reload
;;
status)
rh_status
;;
condrestart|try-restart)
rh_status_q || exit 0
;;
*)
echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"
exit 2
esac

 

保存后,设置权限,并添加到启动服务列表中

chmod 755 /etc/init.d/nginx

chkconfig --add nginx

chkconfig --level 345 nginx on

service nginx start



六、安装PHP

6.1 准备安装

下载php-5.3.6.tar.gz到/usr/local/data-original
下载 libiconv-1.14.tar.gz到/usr/local/data-original
下载 libmcrypt-2.5.8.tar.gz到/usr/local/data-original
下载mcrypt-2.6.8.tar.gz到/usr/local/data-original
下载mhash-0.9.9.9.tar.gz到/usr/local/data-original
下载libmcrypt-2.5.8.tar.gz到/usr/local/data-original

yum -y install autoconf libjpeg libjpeg-devel libpng libpng-devel freetype freetype-devel libxml2 libxml2-devel zlib zlib-devel glibc glibc-devel glib2 glib2-devel bzip2 bzip2-devel ncurses ncurses-devel curl curl-devel e2fsprogs e2fsprogs-devel krb5 krb5-devel libidn libidn-devel openssl openssl-devel openldap openldap-devel nss_ldap openldap-clients openldap-servers libXpm* gcc gcc-c++

 

5.2 安装libiconv (加强系统对支持字符编码转换的功能)

cd /usr/local/data-original/

tar zvxf libiconv-1.14.tar.gz

cd libiconv-1.14

./configure --prefix=/usr/local

make && make install

5.3 安装libmcrypt(加密算法库,PHP扩展mcrypt功能对此库有依耐关系,要使用mcrypt必须先安装此库)

5.3.1 安装libmcrypt

cd /usr/local/data-original/

tar zvxf libmcrypt-2.5.8.tar.gz

cd libmcrypt-2.5.8

./configure

make && make install

5.3.2安装libltdl

cd libltdl/

./configure --enable-ltdl-install

make && make install

5.3.3 更新共享

ln -sf /usr/local/lib/libmcrypt.* /usr/lib64/
ln -sf /usr/local/bin/libmcrypt-config /usr/lib64/
#ln -sf /usr/local/lib/libiconv.so.2 /usr/lib64/

ldconfig

5.4 安装mhash(hash加密算法库)

5.4.1 安装mhash

cd /usr/local/data-original/

tar zvxf mhash-0.9.9.9.tar.gz

cd mhash-0.9.9.9

./configure

make && make install

5.4.2更新共享

ln -sf /usr/local/lib/libmhash.* /usr/lib64/

ldconfig

5.5 安装mcrypt

cd /usr/local/data-original/

tar zvxf mcrypt-2.6.8.tar.gz

cd mcrypt-2.6.8

ldconfig

./configure

make && make install

5.6 安装php

5.6.1 创建mysql软连接、ldap软连接

mkdir -p /opt/mysql/include/mysql
ln -s /opt/mysql/include/* /opt/mysql/include/mysql/

ln -s /usr/lib64/libldap* /usr/lib

5.6.2 安装

cd /usr/local/data-original/

tar zvxf php-5.3.8.tar.gz

cd php-5.3.8

./configure --prefix=/opt/php --with-config-file-path=/opt/php/etc --with-mysql=/opt/mysql --with-mysqli=/opt/mysql/bin/mysql_config --with-iconv-dir=/usr/local --with-freetype-dir --with-jpeg-dir --with-png-dir --with-zlib --with-libxml-dir=/usr --enable-xml --disable-rpath --disable-safe-mode --enable-bcmath --enable-shmop --enable-sysvsem --enable-inline-optimization --with-curl --with-curlwrappers --enable-mbregex --enable-fpm --enable-mbstring --with-mcrypt --with-gd --enable-gd-native-ttf --with-openssl --with-mhash --enable-pcntl --enable-sockets --with-ldap --with-ldap-sasl --with-xmlrpc --enable-zip --enable-soap

make ZEND_EXTRA_LIBS='-liconv'

make install

5.6.3 复制配置文件

cp php.ini-production /opt/php/etc/php.ini

5.6.4 安装memcache扩展(已经安装PHP)

cd /usr/local/data-original/

tar zvxf memcache-2.2.6.tar.gz

cd memcache-2.2.6

/opt/php/bin/phpize

ldconfig

./configure --with-php-config=/opt/php/bin/php-config

make && make install

修改php配置文件,支持memcache

vim /opt/php/etc/php.ini

在文件中搜索extension_dir、extension ,在相应位置添加下面两行
extension_dir = "/opt/php/lib/php/extensions/no-debug-non-zts-20090626/"
extension = "memcache.so"

5.6.5 安装eaccelerator扩展(已经安装PHP)

cd /usr/local/data-original/

tar jxvf eaccelerator-0.9.6.1.tar.bz2

cd eaccelerator-0.9.6.1

/opt/php/bin/phpize

./configure --enable-eaccelerator=shared --with-php-config=/opt/php/bin/php-config

make && make install

修改php配置文件,支持eaccelerator

vim /opt/php/etc/php.ini

在文件尾加入以下代码

[eaccelerator]
zend_extension="/opt/php/lib/php/extensions/no-debug-non-zts-20090626/eaccelerator.so"
eaccelerator.shm_size="32"
eaccelerator.cache_dir="/tmp/eaccelerator"
eaccelerator.enable="1"
eaccelerator.optimizer="1"
eaccelerator.check_mtime="1"
eaccelerator.debug="0"
eaccelerator.log_file = "/opt/php/var/log/eaccelerator_log"
eaccelerator.filter=""
eaccelerator.shm_max="0"
eaccelerator.shm_ttl="3600"
eaccelerator.shm_prune_period="3600"
eaccelerator.shm_only="0"
eaccelerator.compress="1"
eaccelerator.compress_level="9"

增加eaccelerator目录
mkdir -p /tmp/eaccelerator
5.6.5 安装php-fpm

cp /opt/php/etc/php-fpm.conf.default /opt/php/etc/php-fpm.conf
vim /opt/php/etc/php-fpm.conf

修改以下地方
[global]
pid = run/php-fpm.pid-p
error_log = log/php-fpm.log
emergency_restart_threshold = 10
emergency_restart_interval = 1m
process_control_timeout = 5s
pm.start_servers = 20
pm.min_spare_servers = 5
pm.max_spare_servers = 35

[www]
user = www
group = www

5.6.6 修改nginx,支持php

vim /opt/nginx/conf/nginx.conf

找到并修改以下代码

location ~ \.php$ {
root html;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /data/www$fastcgi_script_name;
include fastcgi_params;
}

 

5.6.7将php-fpm 作为服务运行

cd /usr/local/data-original/php-5.3.8
cp ./sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm
chmod 700 /etc/init.d/php-fpm
chkconfig --add php-fpm
chkconfig --level 345 php-fpm on
服务方式启动php-fpm
service php-fpm restart

 

5.6.8 编写测试页面

vim /data/www/index.php

输入代码

<html>
<head><title>hello php</title></head>
<body>
<?php phpinfo();?>
</body>
</html>

5.6.8 打开浏览器进行测试

转:http://blog.csdn.net/xymyeah/article/details/6939544

一、一般来说nginx 配置文件中对优化比较有作用的为以下几项:

1. worker_processes 8;

nginx 进程数,建议按照cpu 数目来指定,一般为它的倍数 (如,2个四核的cpu计为8)。

2. worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000;

为每个进程分配cpu,上例中将8 个进程分配到8 个cpu,当然可以写多个,或者将一
个进程分配到多个cpu。

3. worker_rlimit_nofile 65535;

这个指令是指当一个nginx 进程打开的最多文件描述符数目,理论值应该是最多打开文
件数(ulimit -n)与nginx 进程数相除,但是nginx 分配请求并不是那么均匀,所以最好与ulimit -n 的值保持一致。

现在在linux 2.6内核下开启文件打开数为65535,worker_rlimit_nofile就相应应该填写65535。

这是因为nginx调度时分配请求到进程并不是那么的均衡,所以假如填写10240,总并发量达到3-4万时就有进程可能超过10240了,这时会返回502错误。

查看linux系统文件描述符的方法:

[root@web001 ~]# sysctl -a | grep fs.file

fs.file-max = 789972

fs.file-nr = 510 0 789972

4. use epoll;
使用epoll 的I/O 模型

(

补充说明:

与apache相类,nginx针对不同的操作系统,有不同的事件模型

A)标准事件模型
Select、poll属于标准事件模型,如果当前系统不存在更有效的方法,nginx会选择select或poll
B)高效事件模型
Kqueue:使用于 FreeBSD 4.1+, OpenBSD 2.9+, NetBSD 2.0 和 MacOS X. 使用双处理器的MacOS X系统使用kqueue可能会造成内核崩溃。
Epoll: 使用于Linux内核2.6版本及以后的系统。

/dev/poll:使用于 Solaris 7 11/99+, HP/UX 11.22+ (eventport), IRIX 6.5.15+ 和 Tru64 UNIX 5.1A+。

Eventport:使用于 Solaris 10. 为了防止出现内核崩溃的问题, 有必要安装安全补丁。

)

5. worker_connections 65535;

每个进程允许的最多连接数, 理论上每台nginx 服务器的最大连接数为worker_processes*worker_connections。

6. keepalive_timeout 60;

keepalive 超时时间。

7. client_header_buffer_size 4k;

客户端请求头部的缓冲区大小,这个可以根据你的系统分页大小来设置,一般一个请求头的大小不会超过1k,不过由于一般系统分页都要大于1k,所以这里设置为分页大小。

分页大小可以用命令getconf PAGESIZE 取得。

[root@web001 ~]# getconf PAGESIZE

4096

但也有client_header_buffer_size超过4k的情况,但是client_header_buffer_size该值必须设置为“系统分页大小”的整倍数。

8. open_file_cache max=65535 inactive=60s;

这个将为打开文件指定缓存,默认是没有启用的,max 指定缓存数量,建议和打开文件数一致,inactive 是指经过多长时间文件没被请求后删除缓存。

9. open_file_cache_valid 80s;

这个是指多长时间检查一次缓存的有效信息。

10. open_file_cache_min_uses 1;

open_file_cache 指令中的inactive 参数时间内文件的最少使用次数,如果超过这个数字,文件描述符一直是在缓存中打开的,如上例,如果有一个文件在inactive 时间内一次没被使用,它将被移除。

二、关于内核参数的优化:

net.ipv4.tcp_max_tw_buckets = 6000

timewait 的数量,默认是180000。

net.ipv4.ip_local_port_range = 1024 65000

允许系统打开的端口范围。

net.ipv4.tcp_tw_recycle = 1

启用timewait 快速回收。

net.ipv4.tcp_tw_reuse = 1

开启重用。允许将TIME-WAIT sockets 重新用于新的TCP 连接。

net.ipv4.tcp_syncookies = 1

开启SYN Cookies,当出现SYN 等待队列溢出时,启用cookies 来处理。

net.core.somaxconn = 262144

web 应用中listen 函数的backlog 默认会给我们内核参数的net.core.somaxconn 限制到128,而nginx 定义的NGX_LISTEN_BACKLOG 默认为511,所以有必要调整这个值。

net.core.netdev_max_backlog = 262144

每个网络接口接收数据包的速率比内核处理这些包的速率快时,允许送到队列的数据包的最大数目。

net.ipv4.tcp_max_orphans = 262144

系统中最多有多少个TCP 套接字不被关联到任何一个用户文件句柄上。如果超过这个数字,孤儿连接将即刻被复位并打印出警告信息。这个限制仅仅是为了防止简单的DoS 攻击,不能过分依靠它或者人为地减小这个值,更应该增加这个值(如果增加了内存之后)。

net.ipv4.tcp_max_syn_backlog = 262144

记录的那些尚未收到客户端确认信息的连接请求的最大值。对于有128M 内存的系统而言,缺省值是1024,小内存的系统则是128。

net.ipv4.tcp_timestamps = 0

时间戳可以避免序列号的卷绕。一个1Gbps 的链路肯定会遇到以前用过的序列号。时间戳能够让内核接受这种“异常”的数据包。这里需要将其关掉。

net.ipv4.tcp_synack_retries = 1

为了打开对端的连接,内核需要发送一个SYN 并附带一个回应前面一个SYN 的ACK。也就是所谓三次握手中的第二次握手。这个设置决定了内核放弃连接之前发送SYN+ACK 包的数量。

net.ipv4.tcp_syn_retries = 1

在内核放弃建立连接之前发送SYN 包的数量。

net.ipv4.tcp_fin_timeout = 1

如果套接字由本端要求关闭,这个参数决定了它保持在FIN-WAIT-2 状态的时间。对端可以出错并永远不关闭连接,甚至意外当机。缺省值是60 秒。2.2 内核的通常值是180 秒,3你可以按这个设置,但要记住的是,即使你的机器是一个轻载的WEB 服务器,也有因为大量的死套接字而内存溢出的风险,FIN- WAIT-2 的危险性比FIN-WAIT-1 要小,因为它最多只能吃掉1.5K 内存,但是它们的生存期长些。

net.ipv4.tcp_keepalive_time = 30

当keepalive 起用的时候,TCP 发送keepalive 消息的频度。缺省是2 小时。

三、下面贴一个完整的内核优化设置:

vi /etc/sysctl.conf CentOS5.5中可以将所有内容清空直接替换为如下内容:

net.ipv4.ip_forward = 0
net.ipv4.conf.default.rp_filter = 1
net.ipv4.conf.default.accept_source_route = 0
kernel.sysrq = 0
kernel.core_uses_pid = 1
net.ipv4.tcp_syncookies = 1
kernel.msgmnb = 65536
kernel.msgmax = 65536
kernel.shmmax = 68719476736
kernel.shmall = 4294967296
net.ipv4.tcp_max_tw_buckets = 6000
net.ipv4.tcp_sack = 1
net.ipv4.tcp_window_scaling = 1
net.ipv4.tcp_rmem = 4096 87380 4194304
net.ipv4.tcp_wmem = 4096 16384 4194304
net.core.wmem_default = 8388608
net.core.rmem_default = 8388608
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.core.netdev_max_backlog = 262144
net.core.somaxconn = 262144
net.ipv4.tcp_max_orphans = 3276800
net.ipv4.tcp_max_syn_backlog = 262144
net.ipv4.tcp_timestamps = 0
net.ipv4.tcp_synack_retries = 1
net.ipv4.tcp_syn_retries = 1
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_mem = 94500000 915000000 927000000
net.ipv4.tcp_fin_timeout = 1
net.ipv4.tcp_keepalive_time = 30
net.ipv4.ip_local_port_range = 1024 65000

使配置立即生效可使用如下命令:
/sbin/sysctl -p

四、下面是关于系统连接数的优化

linux 默认值 open files 和 max user processes 为 1024

#ulimit -n

1024

#ulimit –u

1024

问题描述: 说明 server 只允许同时打开 1024 个文件,处理 1024 个用户进程

使用ulimit -a 可以查看当前系统的所有限制值,使用ulimit -n 可以查看当前的最大打开文件数。

新装的linux 默认只有1024 ,当作负载较大的服务器时,很容易遇到error: too many open files 。因此,需要将其改大。

解决方法:

使用 ulimit –n 65535 可即时修改,但重启后就无效了。(注ulimit -SHn 65535 等效 ulimit -n 65535 ,-S 指soft ,-H 指hard)

有如下三种修改方式:

1. 在/etc/rc.local 中增加一行 ulimit -SHn 65535
2. 在/etc/profile 中增加一行 ulimit -SHn 65535
3. 在/etc/security/limits.conf 最后增加:

* soft nofile 65535
* hard nofile 65535
* soft nproc 65535
* hard nproc 65535

具体使用哪种,在 CentOS 中使用第1 种方式无效果,使用第3 种方式有效果,而在Debian 中使用第2 种有效果

# ulimit -n

65535

# ulimit -u

65535

备注:ulimit 命令本身就有分软硬设置,加-H 就是硬,加-S 就是软默认显示的是软限制

soft 限制指的是当前系统生效的设置值。 hard 限制值可以被普通用户降低。但是不能增加。 soft 限制不能设置的比 hard 限制更高。 只有 root 用户才能够增加 hard 限制值。

五、下面是一个简单的nginx 配置文件:

user www www;
worker_processes 8;
worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000
01000000;
error_log /www/log/nginx_error.log crit;
pid /usr/local/nginx/nginx.pid;
worker_rlimit_nofile 204800;
events
{
use epoll;
worker_connections 204800;
}
http
{
include mime.types;
default_type application/octet-stream;
charset utf-8;
server_names_hash_bucket_size 128;
client_header_buffer_size 2k;
large_client_header_buffers 4 4k;
client_max_body_size 8m;
sendfile on;
tcp_nopush on;
keepalive_timeout 60;
fastcgi_cache_path /usr/local/nginx/fastcgi_cache levels=1:2
keys_zone=TEST:10m
inactive=5m;
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
fastcgi_buffer_size 4k;
fastcgi_buffers 8 4k;
fastcgi_busy_buffers_size 8k;
fastcgi_temp_file_write_size 8k;
fastcgi_cache TEST;
fastcgi_cache_valid 200 302 1h;
fastcgi_cache_valid 301 1d;
fastcgi_cache_valid any 1m;
fastcgi_cache_min_uses 1;
fastcgi_cache_use_stale error timeout invalid_header http_500;
open_file_cache max=204800 inactive=20s;
open_file_cache_min_uses 1;
open_file_cache_valid 30s;
tcp_nodelay on;
gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_http_version 1.0;
gzip_comp_level 2;
gzip_types text/plain application/x-javascript text/css application/xml;
gzip_vary on;
server
{
listen 8080;
server_name backup.aiju.com;
index index.php index.htm;
root /www/html/;
location /status
{
stub_status on;
}
location ~ .*\.(php|php5)?$
{
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fcgi.conf;
}
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|js|css)$
{
expires 30d;
}
log_format access ‘$remote_addr — $remote_user [$time_local] “$request” ‘
‘$status $body_bytes_sent “$http_referer” ‘
‘”$http_user_agent” $http_x_forwarded_for’;
access_log /www/log/access.log access;
}
}

六、关于FastCGI 的几个指令:

fastcgi_cache_path /usr/local/nginx/fastcgi_cache levels=1:2 keys_zone=TEST:10minactive=5m;

这个指令为FastCGI 缓存指定一个路径,目录结构等级,关键字区域存储时间和非活动删除时间。

fastcgi_connect_timeout 300;

指定连接到后端FastCGI 的超时时间。

fastcgi_send_timeout 300;

向FastCGI 传送请求的超时时间,这个值是指已经完成两次握手后向FastCGI 传送请求的超时时间。

fastcgi_read_timeout 300;

接收FastCGI 应答的超时时间,这个值是指已经完成两次握手后接收FastCGI 应答的超时时间。

fastcgi_buffer_size 4k;

指定读取FastCGI 应答第一部分需要用多大的缓冲区,一般第一部分应答不会超过1k,由于页面大小为4k,所以这里设置为4k。

fastcgi_buffers 8 4k;

指定本地需要用多少和多大的缓冲区来缓冲FastCGI 的应答。

fastcgi_busy_buffers_size 8k;

这个指令我也不知道是做什么用,只知道默认值是fastcgi_buffers 的两倍。

fastcgi_temp_file_write_size 8k;

在写入fastcgi_temp_path 时将用多大的数据块,默认值是fastcgi_buffers 的两倍。

fastcgi_cache TEST

开启FastCGI 缓存并且为其制定一个名称。个人感觉开启缓存非常有用,可以有效降低CPU 负载,并且防止502 错误。

fastcgi_cache_valid 200 302 1h;
fastcgi_cache_valid 301 1d;
fastcgi_cache_valid any 1m;

为指定的应答代码指定缓存时间,如上例中将200,302 应答缓存一小时,301 应答缓存1 天,其他为1 分钟。

fastcgi_cache_min_uses 1;

缓存在fastcgi_cache_path 指令inactive 参数值时间内的最少使用次数,如上例,如果在5 分钟内某文件1 次也没有被使用,那么这个文件将被移除。

fastcgi_cache_use_stale error timeout invalid_header http_500;

不知道这个参数的作用,猜想应该是让nginx 知道哪些类型的缓存是没用的。以上为nginx 中FastCGI 相关参数,另外,FastCGI 自身也有一些配置需要进行优化,如果你使用php-fpm 来管理FastCGI,可以修改配置文件中的以下值:

60

同时处理的并发请求数,即它将开启最多60 个子线程来处理并发连接。

102400

最多打开文件数。

204800

每个进程在重置之前能够执行的最多请求数。

转:http://apps.hi.baidu.com/share/detail/14819035

如果你打算使用Apache httpd Web服务器,请看这里。

一、系统约定

软件源代码包存放位置 /usr/local/data-original

源码包编译安装位置(prefix) /usr/local/software_name

脚本以及维护程序存放位置 /usr/local/sbin

MySQL 数据库位置 /var/lib/mysql(可按情况设置)

网站根目录 /home/www/wwwroot(可按情况设置)

虚拟主机日志根目录 /home/www/logs(可按情况设置)

运行账户 www:www

二、系统环境部署及调整

1、检查系统是否正常

# more /var/log/messages (检查有无系统级错误信息)

# dmesg (检查硬件设备是否有错误信息)

# ifconfig(检查网卡设置是否正确)

# ping www.163.com (检查网络是否正常)

# cat /proc/cpuinfo (检查CPU频率是否正常)

# top (按1检测CPU核数是否正常,内存大小是否正常)

2、关闭不需要的服务

# ntsysv

以下仅列出需要启动的服务,未列出的服务一律推荐关闭:

atd

crond

irqbalance

microcode_ctl

network

sendmail

sshd

syslog

关闭SElinux:修改/etc/selinux/config文件中的SELINUX= 为 disabled

3、更换yum国内源

# cd /etc/yum.repos.d

# mv CentOS-Base.repo CentOS-Base.repo.save

# wget http://centos.ustc.edu.cn/CentOS-Base.repo.5

# mv CentOS-Base.repo.5 CentOS-Base.repo

# yum clean all

4、服务器时间检查和设置

#data (检查时间是否正确,是否是中国时间CST)

#cp -f /usr/share/zoneinfo/Asia/Shanghai /etc/localtime (如果时区不对,则执行,时间正常的跳过)

#yum -y install ntp (安装ntp对时工具)

#chkconfig ntpd on (让对时服务开机启动)

5、使用 yum 对系统进行更新并且安装必要软件包

#yum update –y

  1. #yum -y install make openssl openssl-devel pcre pcre-devel libpng libpng-devel libjpeg-6b libjpeg-devel-6b freetype freetype-devel gd gd-devel zlib zlib-devel gcc gcc-c++ libXpm libXpm-devel ncurses ncurses-devel libmcrypt libmcrypt-devel libxml2 libxml2-devel imake autoconf automake screen sysstat compat-libstdc++-33 curl curl-devel

复制代码

6. 重新启动系统

# init 6

三、编译安装L.A.M.P环境

1、下载软件(截止到09年10月的最新版本)

# cd /usr/local/data-original

#wget http://sysoev.ru/nginx/nginx-0.7.63.tar.gz

#wget http://download.scientificlinux.net/nginx

#wget http://download.scientificlinux.net/php-fpm.conf

#wget http://download.scientificlinux.net/nginx.conf

#wget http://download.scientificlinux.net/fcgi.conf

#wget http://download.scientificlinux.net/php-5.2.10.tar.gz

#wget http://download.scientificlinux.net/php-5.2.10-fpm-0.5.13.diff.gz

#wget http://download.scientificlinux. ... glibc23-i386.tar.gz (32位系统)

#wget http://download.scientificlinux. ... ibc23-x86_64.tar.gz (64位系统)

#wget http://download.scientificlinux. ... i686-glibc23.tar.gz (32位系统)

#wget http://download.scientificlinux. ... 6_64-glibc23.tar.gz (64位系统)

2、安装MySQL

cd /usr/local/data-original

tar zxvf mysql-5.1.39-linux-i686-glibc23.tar.gz

mv mysql-5.1.39-linux-i686-glibc23 /usr/local/

ln -s /usr/local/mysql-5.1.39-linux-i686-glibc23/ /usr/local/mysql

groupadd mysql

useradd -g mysql mysql

chown -R mysql:mysql /usr/local/mysql

chown -R mysql:mysql /usr/local/mysql-5.1.39-linux-i686-glibc23/

cd /usr/local/mysql

./scripts/mysql_install_db --user=mysql

cp ./support-files/mysql.server /etc/rc.d/init.d/mysqld

chmod 755 /etc/rc.d/init.d/mysqld

chkconfig --add mysqld

chkconfig --level 3 mysqld on

cp ./support-files/my-huge.cnf /etc/my.cnf

mv /usr/local/mysql/data /var/lib/mysql

chown -R mysql:mysql /var/lib/mysql

编辑/etc/my.cnf

在 [mysqld] 段增加

  1. datadir = /var/lib/mysql
  2. skip-innodb
  3. wait-timeout = 10
  4. max_connections = 512
  5. max_connect_errors = 10000000

复制代码

在 [mysqld] 段修改

  1. max_allowed_packet = 16M
  2. thread_cache_size = CPU个数*2

复制代码

将 log-bin 注释

service mysqld start

bin/mysqladmin -u root password 'password_for_root'

其中引号内的password_for_root是要设置的root密码

3、安装Nginx

cd /usr/local/data-original/

tar zxvf nginx-0.7.63.tar.gz

cd nginx-0.7.63

./configure --prefix=/usr/local/nginx --conf-path=/usr/local/nginx/conf/nginx.conf --with-http_realip_module --with-http_addition_module --with-http_gzip_static_module --with-http_random_index_module --with-http_stub_status_module --with-http_sub_module --with-http_dav_module

make

make install

cp /usr/local/data-original/nginx /etc/init.d/nginx

chmod 755 /etc/init.d/nginx

chkconfig --add nginx

chkconfig nginx on

4、安装PHP和Zend

cd /usr/local/data-original

tar zxvf php-5.2.10.tar.gz

gzip -cd php-5.2.10-fpm-0.5.13.diff.gz | patch -d php-5.2.10 -p1

cd php-5.2.10

./configure --prefix=/usr/local/php5 --with-config-file-path=/usr/local/etc/cgi --enable-mbstring --enable-ftp --with-gd --with-jpeg-dir=/usr --with-png-dir=/usr --enable-magic-quotes --with-mysql=/usr/local/mysql --with-pear --enable-sockets --with-ttf --with-freetype-dir=/usr --enable-gd-native-ttf --with-zlib --enable-sysvsem --enable-sysvshm --with-libxml-dir=/usr --enable-force-cgi-redirect --enable-fastcgi --with-xmlrpc --enable-zip --enable-fpm

make

make install

mkdir -p /usr/local/etc/cgi/

cp php.ini-dist /usr/local/etc/cgi/php.ini

mv -f /usr/local/data-original/php-fpm.conf /usr/local/php5/etc/php-fpm.conf

groupadd www

useradd -g www www

echo 'ulimit -SHn 65535' >> /etc/rc.local

echo '/usr/local/php5/sbin/php-fpm start' >> /etc/rc.local

cd /usr/local/data-original

tar zxvf ZendOptimizer-3.3.3-linux-glibc23-i386.tar.gz

cd ZendOptimizer-3.3.3-linux-glibc23-i386

./install

(注意第一个要填的路径是Zend安装路径,第二个是php.ini所在的路径,即/usr/local/etc/cgi)

(不要选重启apache)

5、启动Nginx和php

mv -f /usr/local/data-original/fcgi.conf /usr/local/nginx/conf/

cp -f /usr/local/data-original/nginx.conf /usr/local/nginx/conf/nginx.conf

mkdir -p /home/www/wwwroot

ulimit -SHn 65535

/usr/local/php5/sbin/php-fpm start

service nginx start

在/home/www/wwwroot放入一个index.php,内容为

打开浏览器访问,即可看到phpinfo页面

6、设置系统防火墙

编辑/usr/local/sbin/fw.sh

复制以下内容进去

  1. #!/bin/bash
  2. # Stop iptables service first
  3. service iptables stop
  4. # Load FTP Kernel modules
  5. /sbin/modprobe ip_conntrack_ftp
  6. /sbin/modprobe ip_nat_ftp
  7. # Inital chains default policy
  8. /sbin/iptables -F -t filter
  9. /sbin/iptables -P INPUT DROP
  10. /sbin/iptables -P OUTPUT ACCEPT
  11. # Enable Native Network Transfer
  12. /sbin/iptables -A INPUT -i lo -j ACCEPT
  13. # Accept Established Connections
  14. /sbin/iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
  15. # ICMP Control
  16. /sbin/iptables -A INPUT -p icmp -m limit --limit 1/s --limit-burst 10 -j ACCEPT
  17. # WWW Service
  18. /sbin/iptables -A INPUT -p tcp --dport 80 -j ACCEPT
  19. # FTP Service
  20. /sbin/iptables -A INPUT -p tcp --dport 21 -j ACCEPT
  21. # SSH Service
  22. /sbin/iptables -A INPUT -p tcp --dport 22 -j ACCEPT

复制代码

退出编辑,执行以下命令

# chmod 755 /usr/local/sbin/fw.sh
# echo '/usr/local/sbin/fw.sh' >> /etc/rc.local
# /usr/local/sbin/fw.sh

转:http://zhangxugg-163-com.iteye.com/blog/1153267

我们在生产环境中尝试使用varnish替代squid的主要原因:

 

1. squid不支持多核cpu, 生产环境中大多使用Dell R610系列,这种类型机器配置为2个4核双线程cpu, 操作系统识别为16个,对squid来说,只能利用到一个逻辑cpu, 其它15个逻辑cpu相当于一直浪费!

 

2. squid无法批量清除缓存

 

3. squid3.0目前还无法支持http 1.1, 这对一些管理调整(如gzip压缩,cache-control)带来不必要的麻烦

 

4. 目前我还未找到squid的grace模式(指源站不可到达时,继续使用过期缓存为用户提供服务),而varnish是完全支持的。

 

5. 经过生产环境数个月反复测试,同样访问量情况下,varnish消耗的更少,也没有出现过崩溃情况,而squid因为不支持多核,导致Dell R610机器负载往往超过4,但使用varnish后,机器负载从来没超过1.5

 

经过反复测试,我们已经开始在日独立IP百万级站点中使用varnish替换squid了。

 

但这个过程中,充满太多未知情况,目前我们所遇到的关键问题下:

 

1. 高流量情况下iptables丢包

ip_conntrack: table full, dropping packet.

按网上常规方法,只修改/etc/sysctl.conf是无效的

 

需要以下两步,方可解决之
/boot/grub/grub.conf kernel行中增加参数
ip_conntrack.hashsize=524288
/etc/sysctl.conf中增加
net.ipv4.netfilter.ip_conntrack_max = 2097152

 

注意,上面的操作需要重启机器

 

2. 登录shell ulimit的默认值
/etc/security/limits.conf中加入
* soft nofile 655360
* hard nofile 655360

默认的文件描述符限制为1024, 太小,即使调整成65536,对高负载机器也可能不够,故设置为655360,但也要注意,这个值不能设置过大,否则会导致shell无法登录。

 

修改/etc/security/limits.conf后,只对登录shell有效。对开机运行的程序,一定要注意这个问题(在启动前设置ulimit)

那么,shell级的资源限制来自于/etc/security/limits.conf,那么系统级的资源限制可在哪里修改?

 

3. squid换varnish后流量增加的解决方案:
/etc/security/limits.conf中加入

* soft memlock 1048576
* soft memlock 1048576

或执行 ulimit -HSl 1048576

默认的memlock 只有32K,对varnish来说,太小太小。varnish使用内存块保存日志,故这个值需要调大一些。

上面的值将其调整为1G,即可解决varnish流量高于squid的问题

 

3. varnish运行中频繁出现400,503错误

 

400错误出现,是因为varnish认为客户端请求header行数及长度过大,其默认最大接受的请求header行数为64,最大长度(所有请求header行长度之和)为2048,解决这个问题比较简单,在varnish启动参数中加入:

-p http_max_hdr=256

-p http_req_hdr_len=8192

 

再重启varnish, 即可解决其400错误

 

503错误,这是因为varnish对后端服务器响应header有限制,默认长度是2048,可将其调大一些

-p http_resp_hdr_len=8192

 

再重启之,即可解决这个问题

squid3.0 反向代理 apache2+squid3

我使用的环境CentOS5.5 yum的apache2+PHP5+squid,目前网站已配置成功。

一.APACHE配置
apache(81端口)+squid(80端口)(apache和squid跑在同一个机器上面 要实现反向代理 )我将我的外网域名用abc.com代替了

apache简单配置如下:
Listen 81
NameVirtualHost *
<VirtualHost *>
<Directory "/usr/local/www/">
Options FollowSymLinks
AllowOverride None
Order allow,deny
Allow from all
Satisfy all
</Directory>
ServerName    www.abc.com
ServerAdmin webadmin@abc.com
DocumentRoot "/usr/local/www/"
DirectoryIndex index.jsp
#    ErrorLog "/usr/local/apache/logs/abc-error_log"
#    SetEnvIf Remote_Addr "::1" dontlog
#    CustomLog "/usr/local/apache/logs/abc-access_log" combined env=!dontlog
</VirtualHost>

此时可以通过lsof -i:81查看谁占用81端口

二.SQUID配置
安装    rpm -ivh squid.3.x.rpm

配置    vi /etc/squid/squid.conf

#change for hugwww
visible_hostname www.151051.com

http_port 80 vhost vport

cache_peer 127.0.0.1 parent 81 0 no-query originserver

cache_peer_domain 127.0.0.1 www.151051.com

acl all data-original all

http_access allow all

cache_dir ufs /var/spool/squid 100 16 256

access_log /var/log/squid/access.log squid

cache_log /var/log/squid/cache.log

acl QueryString url_regex \.php?

no_cache deny QueryString

maximum_object_size 320010 KB

maximum_object_size_in_memory 100 KB

dns_nameservers 192.168.0.100

cache_mgr gaojinbo@dayang.com

#/usr/local/squid/sbin/squid -k parse
可以根据这个测试命令用来验证squid.conf的语法和配置(下面是OK的如果不OK会有相应的提示根据提示来修改配置文件)
2008/03/19 15:29:48| Processing Configuration File: /etc/squid.conf (depth 0)

#squid -z
用来Creating Swap Directories

还有测试命令如:squid -CNd1

[root@www ~]# cat /var/log/squid/access.log |grep TCP_MEM_HIT
该指令可以看到在squid运行过程中,有那些文件被squid缓存到内存中,并返回给访问用户

[root@www ~]# cat /var/log/squid/access.log |grep TCP_HIT
该指令可以看到在squid运行过程中,有那些文件被squid缓存到cache目录中,并返回给访问用户

[root@www ~]# cat /var/log/squid/access.log  |grep TCP_MISS
该指令可以看到在squid运行过程中,有那些文件没有被squid缓存,而是现重原始服务器获取并返回给访问用户

可以查看下命中率及其他相关信息
#squidclient -p 80 -h localhost mgr:info

三.配置客户端访问

1.修改HOSTS文件,将svr-ekp.broad-ocean.com的地址设置为192.168.0.193

2.修改DNS记录,将svr-ekp.broad-ocean.com的地址设置为192.168.0.193

3.浏览器访问svr-ekp.broad-ocean.com

注:第一步骤可省略,使用现在WEB服务器.

引自:http://hi.baidu.com/dbaeyes/blog/item/0ab73aed7063f7d8b31cb145.html

mysql 取随机数

--对一个表取任意随机数
SELECT *
FROM TMP_XF_TEST
WHERE ID >= (SELECT FLOOR(RAND() * (SELECT MAX(ID) FROM TMP_XF_TEST)))
order by id LIMIT 1;

--有条件性的取随机数
SELECT *
FROM TMP_XF_TEST
WHERE ID >= (SELECT FLOOR(RAND() * ((SELECT MAX(ID) FROM TMP_XF_TEST WHERE GID = 9) -
(SELECT MIN(ID) FROM TMP_XF_TEST WHERE GID = 9))) +
(SELECT MAX(ID) FROM TMP_XF_TEST WHERE GID = 9))
AND GID = 9
order by id LIMIT 1;

--gid上存在索引

或者
SELECT *
FROM TMP_XF_TEST AS t1 JOIN
(SELECT ROUND(RAND() * ((SELECT MAX(id) FROM TMP_XF_TEST WHERE GID = 9)-(SELECT MIN(id) FROM TMP_XF_TEST WHERE GID = 9))
+(SELECT MIN(id) FROM TMP_XF_TEST WHERE GID = 9)) AS id) AS t2
WHERE t1.id >= t2.id AND t1.GID = 9
ORDER BY t1.id LIMIT 1;

#########
不要用下面的杯具写法

mysql> insert into tmp_xf_test(user_nick,gid,item_id,gmt_create,gmt_modified,memo)
-> select user_nick,gid,item_id,gmt_create,gmt_modified,memo from tmp_xf_test;
Query OK, 165888 rows affected (9.65 sec)
Records: 165888  Duplicates: 0  Warnings: 0

mysql> SELECT *
-> FROM `tmp_xf_test`
-> WHERE id >= (SELECT FLOOR( MAX(id) * RAND()) FROM `tmp_xf_test` )
-> ORDER BY id LIMIT 1;
+-----+-----------+-----+---------+---------------------+---------------------+--------------------+
| id  | user_nick | gid | item_id | gmt_create          | gmt_modified        | memo               |
+-----+-----------+-----+---------+---------------------+---------------------+--------------------+
| 467 | 玄风      |   9 |     123 | 2010-04-26 14:56:39 | 2010-04-26 14:56:39 | 玄风测试使用的数据 |
+-----+-----------+-----+---------+---------------------+---------------------+--------------------+
1 row in set (51.12 sec)

关于session的问题集锦解决方案

1.
错误提示
Warning: Cannot send session cookie - headers already sent
Warning: Cannot send session cache limiter - headers already sent
分析及解决办法
这一类问题,的原因是你在程序中使用session_start()时,之前已经有实际的html内容输出了。或许你说,我没有啊,我只不过是echo或print一条消息了。很抱歉,你的echo或print语句所产生的输出,就是实际的html内容输出。解决此类问题的办法是,将你的session_start()调到程序的第一行。

2.
错误提示
Warning: open(F:/689\php\sessiondata\sess_66a39376b873f4daecf239891edc98b5, O_RDWR) failed
分析及解决方法
出现这样的错误语句一般是因为你的php.ini中关于session.save_path一项没有设置好,解决的方法是将session.save_path和session.cookie_path 设置置为
session_save_path = c:\temp
session.cookie_path = c:\temp
然后在c:\目录下建立一个temp目录,即可

3.
错误提示
Warning: Trying to destroy uninitialized session in
分析及解决方法
出类这样的提示,一般情况都是你直接调session_destroy()函数造成的。很多的朋友认为session_destroy()函数可以独立的运行,其实不然。解决的方法是在你调session_destroy()函数之前,要用session_start()开启session的功能。

4.问题:怎么获得当前session的id值呢?
最简单的方法是:
echo SID;
你会发现的。

5.问题:我的程序,在调用header函数之前没有任何的输出,虽然我include了一个config.php文件,但在config.php文件中也没有任何的输出,为什么session还是会报出与问题1同样的错误呢,是不是因为我在header之前用了session_start()的缘故呢?
答:或许你确实认真的检查了你的php程序,在引用header()之前确实也没有任何的输出,并且在你的include文件中也没有任何的输出!但是你是否用光标键在?>这个PHP代码结束语句后移动检查呢?那么你会发现在?>这个后面,有一个空行或几个空格,你删除了这几个空行或空格,那么问题就解决了。
注:此问题,会出PHP4.1.2中,更高版本,没有测试过。

6.问:用session做登录主页面后,其它页面怎么用session限制登录。。。
答:最简单的方法是
session_start();
if(!session_registered('login') ││ $login != true) {
echo "你没有登陆";
exit;
}

7.问:我用session_register()注册了session变量,可是当我用header或用javascript的重定向语句,那么在一下页面中,我却访问不到session所注册的变量值。请问如何解决?
问题的程序片段:
<?
session_start();
$ok = 'love you';
session_register('ok');
header("location : next.php");
?>

next.php
<?
session_start();
echo $ok;
?>

解决的方法:
当你用header函数或window.location这样的功能后,你上一个页面所注册的session变量,就会容易的丢失,关于这个问题的原因,至今仍没有一个详细的回答。
不过有解决的方法。如下所示
header("Location: next.php" ."?" . SID);
在跳转到下一页面的时候,将session的当前id做为一个参数,传到后一个页面。

8.session如何传数组
session_register('data');
$data=array(1,2,3,4);

方法是先注册后赋值

9.问题9:我是不是可以用像$HTTP_GET_VARS['**']方式来访问session值呢?

回答:可以,你可以使用如下global数组来访问session,以加强网页的安全性
$HTTP_SESSION_VARS
$_SESSION
例程:
<?php
session_start();
$username = 'stangly.wrong';
session_register('username');

echo $HTTP_SESSION_VARS['username'];
echo '<br>';
echo $_SESSION['username'];
?>
请参照此例程修改符合您自己的程序。

问题10:session_unregister() 和 session_destroy() 有何区别?
session_unregister()函数主要作用是注消当前的一个session变量。不过要注意的是,如果你用$HTTP_SESSION_VARS或$_SESSION在当前页面中引用过session变量,那么你可能需要和unset()配合 来注消session变量。
而session_destroy()是清除当前的session环境。意思就是说,当你用session_destroy()函数后,那么你就不可能再用session_is_registered()来检测session的变量了。但是需要注意的是他不能清除global中的session或使用了session cookie的中的session.所以在用session_destroy之前,最好不要用$HTTP_SESSION_VARS $_SESSION来访问session.(译自于php.net)

例程:
if(isset($_COOKIE[session_name()])) {
session_start();
session_destroy();
unset($_COOKIE[session_name()]);
}

转载。