侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

深入Memcache的Session数据的多服务器共享详解

php  /  管理员 发布于 7年前   174


/**
 *=---------------------------------------------------------------------------=
 *                         MemcacheSession.class.php
 *=---------------------------------------------------------------------------=
 *
 * 实现基于Memcache存储的 Session 功能
 *  (模拟session机制,只是利用memcache将存储媒介换成共享服务器的内存)
 *
 * 缺点:暂时没有引入不同主域的session共享机制的实现策略。即只支持同主域下的实现。
 *
 * Copyright(c) 2008 by guigui. All rights reserved.
 * @author guigui
 * @version $Id: MemcacheSession.class.php, v 1.0 2008/12/22 $
 * @package systen
 * @link http://www.guigui8.com
 */

 
/**
 * class MemcacheSession
 *
 * 1. 设置客户端的Cookie来保存SessionID
 * 2. 把用户的数据保存在服务器端,通过Cookie中的Session Id来确定一个数据是否是用户的
 */
class MemcacheSession
{
   // {{{ 类成员属性定义
   public  $memObject          = null;      //memcache操作对象句柄
   private $_sessId            = '';
   private $_sessKeyPrefix     = 'sess_';
   private $_sessExpireTime    = 86400;  
   private $_cookieDomain      = '.guigui8.com';   //全域cookie域名
   private $_cookieName        = '_PROJECT_MEMCACHE_SESS';
   private $_cookieExpireTime  = '';   

   private $_memServers        = array('192.168.0.3' => 11211, '192.168.0.4' => 11211);
   private $_sessContainer     = array();     //当前用户的session信息
   private static $_instance   = null;      //本类单例对象
   // }}}

 
   /**
    * 单例对象获取的静态方法。
 * (可以顺便提供memcache信息存储的服务器参数)
    *
    * @param string $host   - memcache数据存储的服务器ip
    * @param integer $port  - memcache数据存储的服务器端口号
    * @param bool $isInit   - 是否实例化对象的时候启动Session
    */
   public static function getInstance($host='', $port=11211, $isInit = true) {
     if (null === self::$_instance) {
      self::$_instance = new self($host, $port, $isInit);
     }
     return self::$_instance;
   }

   /**
    * 构造函数
    *
    * @param bool $isInit - 是否实例化对象的时候启动Session
    */
   private function __construct($host='', $port=11211, $isInit = false){
       !empty($host) && $this->_memServers = array(trim($host) => $port);
       $isInit && $this->start();
   }

   /**
  *=-----------------------------------------------------------------------=
  *=-----------------------------------------------------------------------=
 *      Public Methods
  *=-----------------------------------------------------------------------=
  *=-----------------------------------------------------------------------=
  */

   /**
    * 启动Session操作
    *
    * @param int $expireTime - Session失效时间,缺省是0,当浏览器关闭的时候失效, 该值单位是秒
    */
   public function start($expireTime = 0){
       $_sessId = $_COOKIE[$this->_cookieName];
       if (!$_sessId){
           $this->_sessId = $this->_getId();
           $this->_cookieExpireTime = ($expireTime > 0) ? time() + $expireTime : 0;
           setcookie($this->_cookieName, $this->_sessId, $this->_cookieExpireTime, "/", $this->_cookieDomain);
           $this->_initMemcacheObj();

           $this->_sessContainer = array();
           $this->_saveSession();
       } else {
           $this->_sessId = $_sessId;
           $this->_sessContainer = $this->_getSession($_sessId);
       }       
   }

   /**
    * setSessId
    *
    * 自定义的session id,通常没有必要经过cookie操作处理的(所以省略了cookie记录session_id)
    *
    * @param string $sess_id
    * @return boolean
    */
   public function setSessId($sess_id){
       $_sessId = trim($sess_id);
       if (!$_sessId){
           return false;
       } else {
           $this->_sessId = $_sessId;
           $this->_sessContainer = $this->_getSession($_sessId);
       }       
   }

   /**
    * 判断某个Session变量是否注册
    *
    * @param string $varName -
    * @return bool 存在返回true, 不存在返回false
    */
   public function isRegistered($varName){
       if (!isset($this->_sessContainer[$varName])){
           return false;
       }
       return true;
   }   

   /**
    * 注册一个Session变量
    *
    * @param string $varName - 需要注册成Session的变量名
    * @param mixed $varValue - 注册成Session变量的值
    * @return bool - 该变量名已经存在返回false, 注册成功返回true
    */
   public function set($varName, $varValue){
       $this->_sessContainer[$varName] = $varValue;
       $this->_saveSession();
       return true;
   }

   /**
    * 获取一个已注册的Session变量值
    *
    * @param string $varName - Session变量的名称
    * @return mixed - 不存在的变量返回false, 存在变量返回变量值
    */
   public function get($varName){
       if (!isset($this->_sessContainer[$varName])){
           return false;
       }
       return $this->_sessContainer[$varName];
   }   

   /**
    * 销毁一个已注册的Session变量
    *
    * @param string $varName - 需要销毁的Session变量名
    * @return bool 销毁成功返回true
    */
   public function delete($varName){
       unset($this->_sessContainer[$varName]);
       $this->_saveSession();
       return true;
   }

   /**
    * 销毁所有已经注册的Session变量
    *
    * @return 销毁成功返回true
    */
   public function destroy(){
       $this->_sessContainer = array();
       $this->_saveSession();
       return true;   
   }

 
   /**
    * 获取所有Session变量
    *
    * @return array - 返回所有已注册的Session变量值
    */
   public function getAll(){
       return $this->_sessContainer;
   }

   /**
    * 获取当前的Session ID
    *
    * @return string 获取的SessionID
    */
   public function getSid(){
       return $this->_sessId;
   }

   /**
    * 获取Memcache的服务器信息
    *
    * @return array Memcache配置数组信息
    */
   public function getMemServers(){
       return $this->_memServers;
   }

   /**
    * 设置Memcache的服务器信息
    *
    * @param string $host - Memcache服务器的IP
    * @param int $port - Memcache服务器的端口
    */
   public function setMemServers($arr){
       $this->_memServers = $arr;
   }   

   /**
    * 添加Memcache服务器
    *
    * @param string $host - Memcache服务器的IP
    * @param int $port - Memcache服务器的端口
    */
   public function addMemServer($host, $port){
       $this->_memServers[trim($host)] = trim($port);
       $this->memObject->addServer($host, $port);
   }  

   /**
    * 移除Memcache服务器(注意,这个只是移除配置,并不能实际从memcached的连接池移除)
    *
    * @param string $host - Memcache服务器的IP
    * @param int $port - Memcache服务器的端口
    */
   public function removeMemServer($host){
  unset($this->_memServers[trim($host)]);
   }  

   /**
  *=-----------------------------------------------------------------------=
  *=-----------------------------------------------------------------------=
 *      Private Methods
  *=-----------------------------------------------------------------------=
  *=-----------------------------------------------------------------------=
  */

   /**
    * 生成一个Session ID
    *
    * @return string 返回一个32位的Session ID
    */
   private function _getId(){
       return md5(uniqid(microtime()));
   }

   /**
    * 获取一个保存在Memcache的Session Key
    *
    * @param string $_sessId - 是否指定Session ID
    * @return string 获取到的Session Key
    */
   private function _getSessKey($_sessId = ''){
       $sessKey = ($_sessId == '') ? $this->_sessKeyPrefix.$this->_sessId : $this->_sessKeyPrefix.$_sessId;
       return $sessKey;
   }   
   /**
    * 检查保存Session数据的路径是否存在
    *
    * @return bool 成功返回true
    */
   private function _initMemcacheObj(){
       if (!class_exists('Memcache') || !function_exists('memcache_connect')){
           $this->_showMessage('Failed: Memcache extension not install, please from http://pecl.php.net download and install');
       }       
       if ($this->memObject && is_object($this->memObject)){
           return true;
       }
       $this->memObject = new Memcache;
       if (!empty($this->_memServers)) {
          foreach ($this->_memServers as $_host => $_port) {
            $this->memObject->addServer($_host, $_port);
        }
       }

       return true;
   }

   /**
    * 获取Session文件中的数据
    *
    * @param string $_sessId - 需要获取Session数据的SessionId
    * @return unknown
    */
   private function _getSession($_sessId = ''){
       $this->_initMemcacheObj();
       $sessKey = $this->_getSessKey($_sessId);
       $sessData = $this->memObject->get($sessKey);
       if (!is_array($sessData) || empty($sessData)){
         //this must be $_COOKIE['__SessHandler'] error!
         return array();
       }
       return $sessData;
   }

   /**
    * 把当前的Session数据保存到Memcache
    *
    * @param string $_sessId - Session ID
    * @return 成功返回true
    */
   private function _saveSession($_sessId = ''){
       $this->_initMemcacheObj();
       $sessKey = $this->_getSessKey($_sessId);

       if (empty($this->_sessContainer)){
           $ret = @$this->memObject->set($sessKey, $this->_sessContainer, false, $this->_sessExpireTime);
       }else{
           $ret = @$this->memObject->replace($sessKey, $this->_sessContainer, false, $this->_sessExpireTime);
       }

       if (!$ret){
           $this->_showMessage('Failed: Save sessiont data failed, please check memcache server');
       }
       return true;
   }

   /**
    * 显示提示信息
    *
    * @param string $strMessage - 需要显示的信息内容
    * @param bool $isFailed - 是否是失败信息, 缺省是true
    */
   private function _showMessage($strMessage, $isFailed = true){
     return;
       if ($isFailed){
           echo ($strMessage);
       }
       echo $strMessage;
   }   


  • 上一条:
    解决File size limit exceeded 错误的方法
    下一条:
    eAccelerator的安装与使用详解
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • 用Time Warden监控PHP中的代码处理时间(0个评论)
    • 在PHP中使用array_pop + yield实现读取超大型目录功能示例(0个评论)
    • Property Hooks RFC在PHP 8.4中越来越接近现实(0个评论)
    • 近期文章
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2017-06
    • 2017-07
    • 2017-08
    • 2017-09
    • 2017-11
    • 2017-12
    • 2018-01
    • 2018-02
    • 2018-03
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-09
    • 2021-02
    • 2021-03
    • 2021-04
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-11
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-09
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-02
    • 2024-03
    • 2024-04
    • 2024-05
    • 2024-06
    • 2024-07
    • 2024-09
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客