I also talked about the methods and benefits of using memcache to store data information cache, which can reduce the number of database accesses and reduce the pressure on the database when the number of visits is large
To store and manage sessions in memcache, you need to understand the use of memcache, session and session_set_save_handler()
Similarly write a public class first, using static member methods of course
The memcache command is operated by telnet
Similarly create the required files in the root directory
Memsession.class.php is the public memcache storage class file, one.php, two.php and three.php are test files, and items.php is the output data array
session.class.php:
First define the variables used to connect to memcache and initialize them
<!--?php class MemSession{ private static $handler=null; private static $lifetime=null; private static $time=null; const NS='session_'; //定义下标 ...  ... }     $memcache=new Memcache;     //连接memcache     $memcache--->connect("localhost",11211) or die("could not connect"); MemSession::start($memcache);
Note that NS is a constant, define subscript
Reinitialization method
//初始化方法 private static function init($handler){ self::$handler=$handler; self::$lifetime=ini_get('session.gc_maxlifetime'); self::$time=time(); }
Open the session and define calls to open, close and other methods in this class
//开启session public static function start(Memcache $memcache){ //首先将属性初始化 self::init($memcache); //调用handler,以后调用handler时都是用memcache session_set_save_handler( array(__CLASS__,'open'),//调用本类的open方法 array(__CLASS__,'close'), array(__CLASS__,'read'), array(__CLASS__,'write'), array(__CLASS__,'destroy'), array(__CLASS__,'gc') ); //调用session_start() session_start(); }
open() and close() only need to return true, but the parameters of open() are path and name
public static function open($path, $name){ return true; } public static function close(){ return true; }
But it is necessary to determine whether the incoming out parameter has a value, and if it has a value, return the out data
public static function read($PHPSESSID){ $out=self::$handler->get(self::session_key($PHPSESSID)); //得到该下标输出的数据 if($out===false || $out ==null){ return ''; //out得到数据没有,返回空 } return $out; //返回得到的数据 }
Returns its own id, data, and lifespan
public static function write($PHPSESSID, $data){ //判断是否有数据 $method=$data ? 'set' : 'relpace'; return self::$handler->$method(self::session_key($PHPSESSID), $data, MEMCACHE_COMPRESSED, self::$lifetime); }
destroy() and gc():
destroy() calls its own delete method
public static function destroy($PHPSESSID){ return self::$handler->delete(self::session_key($PHPSESSID)); //调用delete方法 } public static function gc($lifetime){ return true; }
private static function session_key($PHPSESSID){ $session_key=self::NS.$PHPSESSID; //键值为自身和传进来的phpsessid return $session_key; }
The results show
If successful, display in telnet
Indicates that the session data information is successfully stored in memcache