欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

将Session写入Memcache,sessionmemcache_PHP教程

程序员文章站 2022-05-28 09:34:07
...

将Session写入Memcache,sessionmemcache

通过session_set_save_handler()方法自定义Session写入Memcache

 1 php    
 2     class MemSession{
 3         private static $handler = null;
 4         private static $lifetime = null;
 5         private static $time = null;
 6         const MS = 'session';
 7         
 8         private static function init($handler){
 9             self::$handler = $handler;
10             self::$lifetime = ini_get('session.gc_maxlifetime');
11             self::$time = time();
12         }
13         
14         public static function start($memcache){
15             self::init($memcache);
16             //调用类中的方法要用数组,__CLASS__代表本类
17             session_set_save_handler(
18                 array(__CLASS__,'open'),
19                 array(__CLASS__,'close'),
20                 array(__CLASS__,'read'),
21                 array(__CLASS__,'write'),
22                 array(__CLASS__,'destroy'),
23                 array(__CLASS__,'gc')
24             );
25             session_start();
26         }
27         
28         public static function open($path,$name){
29             
30         }
31         public static function close(){
32             
33         }
34         
35         public static function read($PHPSESSID){
36             $val = self::$handler->get(self::session_key($PHPSESSID));
37             
38             if($val===false || $val==null){
39                 return false;
40             }
41             return $val;
42         }
43         public static function write($PHPSESSID,$data){
44             $method = $data? 'set':'replace';
45             return self::$handler->$method(self::session_key($PHPSESSID),$data,MEMCACHE_COMPRESSED,self::$lifetime);
46         }
47         
48         public static function destroy($PHPSESSID){
49             return self::$handle->delete(self::session_key($PHPSESSID));
50         }
51         //memcache本身就有限定时间,数据自动销毁,所以可不使用gc方法
52         public static function gc($lifetime){
53             return true;
54         }
55         
56         //给sessionID加前缀,避免key重复
57         private static function session_key($PHPSESSID){
58             $session_key = self::MS.$PHPSESSID;
59             return $session_key;
60         }        
61     }
62     $mem = new Memcache;
63     $mem->connect("localhost",11211) or die("could not connect");
64     MemSession::start($mem);

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/980027.htmlTechArticle将Session写入Memcache,sessionmemcache 通过session_set_save_handler()方法自定义Session写入Memcache 1 ? php 2 class MemSession{ 3 private static $handler = null ; 4 pri...