Home Backend Development PHP Tutorial php之session最优将信息写下memcache中管理

php之session最优将信息写下memcache中管理

Jun 13, 2016 pm 12:16 PM
handler memcache session static

php之session最优将信息写入memcache中管理

前面也讲到了用memcache存储数据信息缓存的方法和好处,这样能够减少访问数据库的次数,减少访问量大时对数据库的压力

将session存储到memcache中管理需要了解memcache、session的使用和session_set_save_handler()

同样先编写一个公用的类,当然采用静态的成员方法

memcache 指令用telnet操作



同样现在根目录下建立需要用到的文件


其中memsession.class.php 是公用的memcache存储类文件,one.php、two.php和three.php是测试文件,items.php 是输出数据数组的

session.class.php中:

首先定义连接memcache用到的变量并初始化

<?php class MemSession{    	private static $handler=null;    	private static $lifetime=null;    	private static $time=null;    	const NS=&#39;session_&#39;;  //定义下标     ...    	&#160;...}&#160; &#160; $memcache=new Memcache;&#160; &#160; //连接memcache&#160; &#160; $memcache->connect("localhost",11211) or die("could not connect");    MemSession::start($memcache);
Copy after login



注意的是 NS 为常量,定义下标

 

再初始化方法

    	//初始化方法    	private static function init($handler){    		self::$handler=$handler;    		self::$lifetime=ini_get('session.gc_maxlifetime');    		self::$time=time();    	}
Copy after login


开启session,并定义调用本类中的open、close等方法

    	//开启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();    	}
Copy after login

接下来就是定义上面调用的这些方法

open() 和 close() 只要返回真就可以,但 open() 的参数为 路径(path) 和 名称(name)

    	public static function open($path, $name){    		return true;    	}    	public static function close(){    		return true;    	}
Copy after login

read()  只需要有PHPSESSID参数即可

但要判断传入的out 参数是否有值,有值就返回out的数据

    	public static function read($PHPSESSID){    		$out=self::$handler->get(self::session_key($PHPSESSID));  //得到该下标输出的数据    		if($out===false || $out ==null){    			return '';  //out得到数据没有,返回空    		}    		return $out;  //返回得到的数据    	}
Copy after login

write() :

返回自身的id,数据,和生命时长

    	public static function write($PHPSESSID, $data){    		//判断是否有数据    		$method=$data ? 'set' : 'relpace';    		return self::$handler->$method(self::session_key($PHPSESSID), $data, MEMCACHE_COMPRESSED, self::$lifetime);    	}
Copy after login


destroy() 和 gc() :

destroy()调用自身的delete方法

    	public static function destroy($PHPSESSID){    		return self::$handler->delete(self::session_key($PHPSESSID));  //调用delete方法    	}    	public static function gc($lifetime){    			return true;    	}
Copy after login

接下来需要定义一个传入PHPSESSID的方法

    	private static function session_key($PHPSESSID){    		$session_key=self::NS.$PHPSESSID; //键值为自身和传进来的phpsessid    		return $session_key;    	}
Copy after login



结果显示

如果成功,在telnet中显示





表示session数据信息储存到memcache成功















Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve session failure How to solve session failure Oct 18, 2023 pm 05:19 PM

Session failure is usually caused by the session lifetime expiration or server shutdown. The solutions: 1. Extend the lifetime of the session; 2. Use persistent storage; 3. Use cookies; 4. Update the session asynchronously; 5. Use session management middleware.

Solution to PHP Session cross-domain problem Solution to PHP Session cross-domain problem Oct 12, 2023 pm 03:00 PM

Solution to the cross-domain problem of PHPSession In the development of front-end and back-end separation, cross-domain requests have become the norm. When dealing with cross-domain issues, we usually involve the use and management of sessions. However, due to browser origin policy restrictions, sessions cannot be shared by default across domains. In order to solve this problem, we need to use some techniques and methods to achieve cross-domain sharing of sessions. 1. The most common use of cookies to share sessions across domains

How to use Memcache in PHP development? How to use Memcache in PHP development? Nov 07, 2023 pm 12:49 PM

In web development, we often need to use caching technology to improve website performance and response speed. Memcache is a popular caching technology that can cache any data type and supports high concurrency and high availability. This article will introduce how to use Memcache in PHP development and provide specific code examples. 1. Install Memcache To use Memcache, we first need to install the Memcache extension on the server. In CentOS operating system, you can use the following command

What are the differences between JavaScript and PHP cookies? What are the differences between JavaScript and PHP cookies? Sep 02, 2023 pm 12:29 PM

JavaScriptCookies Using JavaScript cookies is the most effective way to remember and track preferences, purchases, commissions and other information. Information needed for a better visitor experience or website statistics. PHPCookieCookies are text files that are stored on client computers and retained for tracking purposes. PHP transparently supports HTTP cookies. How do JavaScript cookies work? Your server sends some data to your visitor's browser in the form of a cookie. Browsers can accept cookies. If present, it will be stored on the visitor's hard drive as a plain text record. Now, when a visitor reaches another page on the site

PHP Session cross-domain and AJAX asynchronous communication optimization PHP Session cross-domain and AJAX asynchronous communication optimization Oct 12, 2023 am 09:22 AM

Optimization of asynchronous communication between PHPSession across domains and AJAX With the development of the Internet, cross-domain access and asynchronous communication have become common requirements in modern web application development. This article will focus on how to use PHPSession to achieve cross-domain access, and provide some optimization methods to improve the asynchronous communication efficiency of AJAX. 1. The problem of cross-domain access In Web development, when the browser initiates an HTTP request from a web page of one domain name, and then returns the response data belonging to another domain name, it will occur.

How to use Memcache for efficient data reading and writing operations in PHP development? How to use Memcache for efficient data reading and writing operations in PHP development? Nov 07, 2023 pm 03:48 PM

In PHP development, using the Memcache caching system can greatly improve the efficiency of data reading and writing. Memcache is a memory-based caching system that can cache data in memory to avoid frequent reading and writing of the database. This article will introduce how to use Memcache in PHP for efficient data reading and writing operations, and provide specific code examples. 1. Install and configure Memcache First, you need to install the Memcache extension on the server. able to pass

What are the reasons for session failure? What are the reasons for session failure? Oct 17, 2023 pm 05:01 PM

Reasons for session failure include session timeout, session number limit, session integrity check, server restart, browser or device problems, etc. Detailed introduction: 1. Session timeout: The server sets a default timeout for the Session. When the user does not interact with the server for a period of time, the Session will automatically expire; 2. Session number limit: The server has a number of Sessions for each user. A limit is set. When the number of Sessions created by a user exceeds this limit, the latest one will overwrite the oldest one and so on.

What is the function and usage of static in C language What is the function and usage of static in C language Jan 31, 2024 pm 01:59 PM

The role and usage of static in C language: 1. Variable scope; 2. Life cycle; 3. Internal function; 4. Modify global variables; 5. Modify function; 6. Other uses; Detailed introduction: 1. Variable scope, when If there is the static keyword before a variable, then the scope of the variable is limited to the file in which it is declared. In other words, the variable is a "file-level scope", which is very useful for preventing the "duplicate definition" problem of variables; 2. Life cycle, static variables are initialized once when the program starts executing, and destroyed when the program ends, etc.

See all articles