PHP多服务器环境下Session共享的NFS实现方案
PHP多服务器环境下Session共享的NFS实现方案
此前,开发者Nio提出了关于在多台服务器上保持Session数据一致性的需求,相关讨论详见《PHP实现多服务器共享SESSION数据》一文。
一种可行的解决方案是采用NFS(网络文件系统)来共享Session文件。然而,若Session数据量庞大且全部集中于单一子目录中,可能会引发严重的性能瓶颈,甚至导致服务不可用。本文将深入解析该方案的实施细节及注意事项。
首要步骤是调整php.ini配置文件中的session.save_path参数,配置示例如下:
session.save_path = "2;/tmp/php_sess"
上述配置指示系统将Session数据存储于“/tmp/php_sess”路径下,并构建两级子目录结构。每一级目录默认包含16个子文件夹,这种哈希分布有助于分散文件I/O压力。
假设PHP的安装根目录位于/usr/local/server/php/,需在该路径下新建脚本文件/usr/local/server/php/include/php/ext/session/mod_files.sh,其内容如下:
#! /bin/sh
# NAME
# mod_files.sh - Update of the php-source/ext/session/mod_files.sh
#
# SYNOPSIS
# mod_files.sh basedir depth [numberofsubdirs]
#
# DESCRIPTION
# this script creates the directories tree used by php to store the session files
# (see php.ini - 'session.save_path' option)
#
# Example: if you want php to store the session files in a directory tree
# of 3 levels of depth containing 32 directories in each directory,
# first, put the setting bellow in the php.ini file:
#
# session.save_path = "3;/tmp/session"
#
# Now create the basedir directory: 'mkdir /tmp/session'
#
# Then, call this scrip with the following arguments:
#
# ./mod_files.sh ./mod_files.sh /tmp/session 3 32
if test "$2" = ""; then
echo "usage: $0 basedir depth [numberofsubdirs]"
echo "numberofsubdirs: if unset, defaults to 16. if 32, 32 subdirs, if 64, 64 subdirs."
exit 1
fi
if test "$2" = "0"; then
exit 0
fi
hash_chars="0 1 2 3 4 5 6 7 8 9 a b c d e f"
if [ ! -z $3 ] ; then
if test "$3" -a "$3" -eq "32"; then
hash_chars="$hash_chars g h i j k l m n o p q r s t u v"
if test "$3" -eq "64"; then
hash_chars="$hash_chars w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z - ,"
fi
fi
fi
for i in $hash_chars; do
newpath="$1/$i"
mkdir $newpath || exit 1
sh $0 $newpath `expr $2 - 1` $3
done
赋予该脚本执行权限后,运行以下命令以生成所需的哈希目录结构:
shell>#cd /usr/local/server/php/include/php/ext/session/
shell>#./mod_files.sh /tmp/php_sess 2 16
接下来配置NFS共享服务。假设有三台主机参与集群,IP地址分别为192.168.0.1(主机名svr1)、192.168.0.2(主机名svr2)和192.168.0.3(主机名svr3)。现指定192.168.0.1作为NFS服务端,需在/etc/exports文件中添加如下配置:
/tmp/php_sess/ svr*(rw,no_root_squash)
保存配置后重启NFS服务,即可向其他两台主机提供共享访问。
在svr2和svr3节点上,执行以下命令以挂载NFS共享目录:
shell>#mkdir /tmp/php_sess
shell>#mount svr1:/tmp/php_sess /tmp/php_sess
最后,在这两个客户端主机的php.ini中应用前述的session.save_path设置,并重启Apache服务,即可完成整个Session共享环境的部署。