年年有"余"

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 2213|回复: 0

自定义Session的memcache实现

[复制链接]
  • TA的每日心情
    奋斗
    2022-12-13 21:26
  • 签到天数: 371 天

    [LV.9]以坛为家II

    发表于 2016-1-26 16:00:01 | 显示全部楼层 |阅读模式
    数据库实现参考:www.yusian.com/thread-11084-1-1.html

    [PHP] 纯文本查看 复制代码
    <?php
    	class SASession{
    		private static $mem;
    		public static function start(Memcache $mem){
    			
    			self::$mem = $mem;
    			// 设置session模式为用户模式,也可以在php.ini这个配置文件中修改
    			session_module_name("user");
    			// 注册过程
    			session_set_save_handler(
    									array(__CLASS__, "open"), 
    									array(__CLASS__, "close"), 
    									array(__CLASS__, "read"), 
    									array(__CLASS__, "write"), 
    									array(__CLASS__, "destroy"), 
    									array(__CLASS__, "gc"));	
    									
    			session_start();						
    		}		
    		// 开启
    		public static function open(){
    			return true;
    		}
    		// 关闭
    		public static function close(){
    			return true;
    		}
    		// 读
    		public static function read($sid){
    			$data = self::$mem->get($sid);
    			if(empty($data)) return "";
    			return $data;
    		}
    		// 写
    		public static function write($sid, $data){
    			$lifetime = ini_get("session.gc_maxlifetime");
    			self::$mem->set($sid, $data, MEMCACHE_COMPRESSED, $lifetime);
    		}
    		// 销毁
    		public static function destroy($sid){
    			self::$mem->delete($sid, 0);
    		}
    		// 回收
    		public static function gc($maxlifetime){
    			// memcache有自动回收机制
    			return true;
    		}
    	}
    
    	$mem = new Memcache;
    	$mem->addServer("localhost", 11211);
    	
    	SASession::start($mem);
    

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    手机版|小黑屋|Archiver|iOS开发笔记 ( 湘ICP备14010846号 )

    GMT+8, 2024-4-20 17:41 , Processed in 0.048428 second(s), 18 queries .

    Powered by Discuz! X3.4

    Copyright © 2001-2021, Tencent Cloud.

    快速回复 返回顶部 返回列表