首先提下memcached 是守护进程,memcache是PHP扩展这点大家知道,别搞错了 !
操作系统:centos
服务器WEB:192.168.210
服务器WEB:192.168.209
- 第一部分:安装PHP扩展memcache (两台)
- tar -zxf memcache-2.2.6.tgz
- cd memcache-2.2.6
- /usr/local/php/bin/phpize
- ./configure --with-php-config=/usr/local/php/bin/php-config
- make
- make install
- vi /usr/local/php/etc/php.ini
- extension_dir = "/usr/local/php/lib/php/extensions/no-debug-non-zts-20090626" #no-debug-non-zts-20090626这个目录跟据你自己实际得到名称修改
extension = "memcache.so"
- 第二部分:安装memcached (两台二选1)
- tar -zxf memcached-1.4.14.tar.gz
- cd memcached-1.4.14
- ./configure
- make
- make install
- /usr/local/bin/memcached -m 32m -p 11211 -d -u root -P /var/run/memcached.pid -c 256 #启动服务,具体参数值自行修改,注意打开防火墙端口
- 第三部分:测试(重要)
- vi /usr/local/php/etc/php.ini
- session.save_handler = "memcache" #存储方式
- session.save_path = "tcp://192.168.1.210:11211" #session 存储路经
- 另一种方式就是 PHP程序里面写入
- ini_set("session.save_handler", "memcache");
ini_set("session.save_path", "tcp://192.168.1.210:11211"); - 此程序是网上摘录
- vi session.php #进入192.168.2.210 输入
- <?php
session_start();
if (!isset($_SESSION['TEST'])) {
$_SESSION['TEST'] = time();
} - $_SESSION['TEST3'] = time();
- print $_SESSION['TEST'];
print "<br><br>";
print $_SESSION['TEST3'];
print "<br><br>";
print session_id();
?> - 运行结果如下
- 1346805490
1346805568
c0o46kuhnaokd70g6677ta76 #把这串数值输入到如下程序内 - vi get.php #进入192.168.2.209 输入
- <?php
$memcache = memcache_connect('192.168.2.210', 11211);
var_dump($memcache->get('c0o46kuhnaokd70g6677ta7601'));
?> - 运行结果如下
- string(37) "TEST|i:1346805490;TEST3|i:1346805568;" #证明成功
- bool(false) #出现这句就证成,配置不正确,请仔细检查
- 特别提醒:建义/usr/local/php/bin/php sessin.php | get.php 使用程序直接跑报错信息很详细,方便排查
- 第4部自写的memcached启动脚本
- ./memcache.py stop|start|restart 格式
- 如下源码:
- #!/usr/bin/python
- #
- import sys
- import os
- #This is geting arguments
- AGRV=''.join(sys.argv[1:])
- #The memcache run argument of script
- MEM_BIN='/usr/local/bin/memcached'
- MEM_CACHE= '32m'
- MEM_PORT='11211'
- MEM_USER='root'
- MEM_PID='/var/run/'
- MEM_PID_FILE='memcached.pid'
- MEM_THREAD='256'
- MEM_STOP='daemon kill -9 `cat /var/run/memcached.pid`'
- #The memcache commands
- MEM_EXEC='daemon %s -m %s -p %s -d -u %s -P %s -c %s'%(MEM_BIN,MEM_CACHE,MEM_PORT,MEM_USER,MEM_PID+MEM_PID_FILE,MEM_THREAD)
- #Source function library.
- FUN_LIB='. /etc/rc.d/init.d/functions&&'
- #Starting memcahce function.
- def start():
- if os.path.isfile(MEM_PID+MEM_PID_FILE):
- print "memcache already is runing ...."
- else:
- if os.system(FUN_LIB+MEM_EXEC) == 0:
- print "Starting memcache:"
- def stop():
- if os.system(FUN_LIB+MEM_STOP) == 0:
- os.remove(MEM_PID+MEM_PID_FILE)
- print "Stoping memcache:"
- def restart():
- stop()
- start()
- #The program decide start|stop|restart
- if AGRV.upper() == 'START':
- start()
- elif AGRV.upper() == 'STOP':
- stop()
- elif AGRV.upper() == 'RESTART':
- restart()
- else:
- print 'Please input argument(start|stop|restart)'