保存SESSION到Memcache的Driver类:SessionMemcache.class.php,具体路径在:ThinkPHP/Extend/Driver/Session/SessionMemcache.class.php.模仿SessionDb.class.php来实现保存SESSION数据到Memcache中。
一.配置环境
1、Memcached安装 http://www.2cto.com/os/201205/132641.html
http://up.2cto.com/2012/0522/20120522094758371.rar
2、php.ini的配置:下载php_memcache.dll(如果环境没有,下载好放在php系统文件夹的ext下面),在php.ini中配置加入extension=php_memcache.dll,然后访问phpinfo()页面看是否已开启Memcached成功。
如图:

在ThinkPHP项目的配置文件conf/config.php中配置:
- // 'SESSION_PREFIX' => 'sess_',
- //定义session为memcache
- 'SESSION_TYPE' => 'Memcache',
- //Memcache服务器
- 'MEMCACHE_HOST' => '127.0.0.1',
- //Memcache端口
- 'MEMCACHE_PORT' => 11211,
- //Memcache的session信息有效时间
- //'SESSION_EXPIRE' => 10,
复制代码
- <?php
- // +----------------------------------------------------------------------
- // |
- // +----------------------------------------------------------------------
- // | Copyright (c) 2013-
- // +----------------------------------------------------------------------
- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
- // +----------------------------------------------------------------------
- // | Author: richievoe <richievoe@163.com>
- // +----------------------------------------------------------------------
- /**
- * 自定义Memcache来保存session
- */
- Class SessionMemcache{
- //memcache对象
- private $mem;
- //SESSION有效时间
- private $expire;
- //外部调用的函数
- public function execute(){
- session_set_save_handler(
- array(&$this,'open'),
- array(&$this,'close'),
- array(&$this,'read'),
- array(&$this,'write'),
- array(&$this,'destroy'),
- array(&$this,'gc')
- );
- }
- //连接memcached和初始化一些数据
- public function open($path,$name){
- $this->expire = C('SESSION_EXPIRE') ? C('SESSION_EXPIRE') :ini_get('session.gc_maxlifetime');
- $this->mem = new Memcache;
- return $this->mem->connect(C('MEMCACHE_HOST'), C('MEMCACHE_PORT'));
- }
- //关闭memcache服务器
- public function close(){
- return $this->mem->close();
- }
- //读取数据
- public function read($id){
- $id = C('SESSION_PREFIX').$id;
- $data = $this->mem->get($id);
- return $data ? $data :'';
- }
- //存入数据
- public function write($id,$data){
- $id = C('SESSION_PREFIX').$id;
- //$data = addslashes($data);
- return $this->mem->set($id,$data,0,$this->expire);
- }
- //销毁数据
- public function destroy($id){
- $id = C('SESSION_PREFIX').$id;
- return $this->mem->delete($id);
- }
- //垃圾销毁
- public function gc(){
- return true;
- }
- }
- ?>
http://www.thinkphp.cn/code/361.html
本文介绍如何在ThinkPHP框架中使用Memcache作为Session存储方式。通过配置环境、修改配置文件及自定义SessionMemcache类,实现了高效地利用Memcache进行Session数据的存储与管理。
2174

被折叠的 条评论
为什么被折叠?



