PHP 将session写入到memcached

 1 <?php
 2 class MemcacheSession
 3 {
 4     // memcache对象
 5     private static $handler = null;
 6     // 过期时间 秒
 7     private static $lifetime = null;
 8     // 当前时间
 9     private static $time = null;
10     // session名前缀
11     private const NS = 'session_';
12 
13     // 初始化
14     private static function init($handler)
15     {
16         self::$handler = $handler;
17         self::$lifetime = 1440;
18         self::$time = time();
19     }
20 
21     // 外部调用初始化
22     public static function start(Memcached $memcached)
23     {
24         self::init($memcached);
25 
26         // 自定义session存储介质
27         session_set_save_handler(
28             array(__CLASS__, 'open'),
29             array(__CLASS__, 'close'),
30             array(__CLASS__, 'read'),
31             array(__CLASS__, 'write'),
32             array(__CLASS__, 'destroy'),
33             array(__CLASS__, 'gc')
34         );
35         if (!headers_sent() && session_id() == '') session_start();
36     }
37 
38     public static function open($path, $name)
39     {
40         return true;
41     }
42 
43     public static function close()
44     {
45         return true;
46     }
47 
48     public static function read($PHPSESSID)
49     {
50         $out = self::$handler->get(self::session_key($PHPSESSID));
51 
52         if ($out === false || $out == null) return '';
53         return $out;
54     }
55 
56     public static function write($PHPSESSID, $data)
57     {
58         return self::$handler->set(self::session_key($PHPSESSID), $data, self::$lifetime);
59     }
60 
61     public static function destroy($PHPSESSID)
62     {
63         return self::$handler->delete(self::session_key($PHPSESSID));
64     }
65 
66     public static function gc($lifetime)
67     {
68         return true;
69     }
70 
71     private static function session_key($PHPSESSID)
72     {
73         $session_key = self::NS . $PHPSESSID;
74         return $session_key;
75     }
76 }
77 
78 $memcached = new Memcached();
79 $memcached->addServer('127.0.0.1', 11211);
80 MemcacheSession::start($memcached);
81 
82 //
83 $_SESSION['aaa'] = '你好世界';
84 //
85 var_dump($_SESSION);

 

posted @ 2021-06-19 16:19  九鹤  阅读(49)  评论(0编辑  收藏  举报