Table of Contents
PHP实现多服务器session共享之memcache共享
Home Backend Development PHP Tutorial PHP兑现多服务器session共享之memcache共享

PHP兑现多服务器session共享之memcache共享

Jun 13, 2016 pm 01:06 PM
memcache return session

PHP实现多服务器session共享之memcache共享

使用基于文件的Session存取瓶颈可能都是在磁盘IO操作上,所以对付小数据量的Session没有问题,但是如果碰到大数据量的Sesstion,那么可能无法胜任,现在利用Memcache来保存Session数据,直接通过内存的方式,效率自然能够提高不少

首先打开php.ini文件,找到session的部分:(分号后面的是注释)

[Session]
; Handler used to store/retrieve data.
session.save_handler = files ; 这个是session的方式,默认的files就可以了,代表用文件储存,

还有两种方式,user和memcache。

user方式指的是你自己(也就是 用户)定义session的句柄,用于session的存取等 ,这个可以把session扩展存到数据库里

memcache方式,需要你配置好memcache ,还要配置session.save_path。

用memcache来作PHP 的session.save_handler

ini_set("session.save_handler", "memcache");
ini_set("session.save_path", "tcp://127.0.0.1:11211,tcp://192.168.1.12:11211");
Copy after login

用memcached 来作PHP 的session.save_handler

ini_set("session.save_handler","memcached");
ini_set("session.save_path","127.0.0.1:11211");
Copy after login

PHP实现多服务器session共享之memcache共享

再自定义一套session处理机制,关于session的实现方法我就不再多讲,直接贴程序了。

<?php /* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
//===========================================
// 程序:   Memcache-Based Session Class
// 功能:   基于Memcache存储的 Session 功能类
// 作者:    yejr
// 网站:    http://imysql.cn
// 时间:    2007-01-05
//===========================================

/**
 * 文件:    MemcacheSession.inc.php
 * 类名:    MemcacheSession Class
 * 功能:    自主实现基于Memcache存储的 Session 功能
 * 描述:    这个类就是实现Session的功能,基本上是通过
 *          设置客户端的Cookie来保存SessionID,
 *          然后把用户的数据保存在服务器端,最后通过
 *          Cookie中的Session Id来确定一个数据是否是用户的,
 *          然后进行相应的数据操作
 *
 *          本方式适合Memcache内存方式存储Session数据的方式,
 *          同时如果构建分布式的Memcache服务器,
 *          能够保存相当多缓存数据,并且适合用户量比较多并发比较大的情况
 *
 * 注意: 本类必须要求PHP安装了Memcache扩展或者必须有Memcache的PHP API
 *       获取Memcache扩展请访问: http://pecl.php.net
 */

//设定 SESSION 有效时间,单位是 秒
define('SESS_LIFTTIME', 3600);

//定义memcache配置信息
define('MEMCACHE_HOST', 'localhost');
define('MEMCACHE_PORT', '10000');

if (!defined('MemcacheSession'))
{
	define('MemcacheSession',    TRUE);
	class MemacheSession
	{
		// {{{ 类成员属性定义
		static  $mSessSavePath;
		static  $mSessName;
		static  $mMemcacheObj;
		// }}}

		// {{{ 初始化构造函数
		/**
     * 构造函数
     *
     * @param string $login_user    登录用户
     * @param int $login_type       用户类型
     * @param string $login_sess    登录Session值
     * @return Esession
     */
		public function __construct()
		{
			//我的memcache是以php模块的方式编译进去的,可以直接调用
			//如果没有,就请自己包含 Memcache-client.php 文件
			if (!class_exists('Memcache') || !function_exists('memcache_connect'))
			{
				die('Fatal Error:Can not load Memcache extension!');
			}

			if (!empty(self::$mMemcacheObj) && is_object(self::$mMemcacheObj))
			{
				return false;
			}

			self::$mMemcacheObj = new Memcache;

			if (!self::$mMemcacheObj->connect(MEMCACHE_HOST , MEMCACHE_PORT))
			{
				die('Fatal Error: Can not connect to memcache host '. MEMCACHE_HOST .':'. MEMCACHE_PORT);
			}

			return TRUE;
		}
		// }}}

	/** {{{ sessOpen($pSavePath, $name)
     *
     * @param   String  $pSavePath
     * @param   String  $pSessName
     *
     * @return  Bool    TRUE/FALSE
     */
		public function sessOpen($pSavePath = '', $pSessName = '')
		{
			self::$mSessSavePath    = $pSavePath;
			self::$mSessName        = $pSessName;
			return TRUE;
		}
		// }}}

	/** {{{ sessClose()
     *
     * @param   NULL
     *
     * @return  Bool    TRUE/FALSE
     */
		public function sessClose()
		{
			return TRUE;
		}
		// }}}

	/** {{{ sessRead($wSessId)
     *
     * @param   String  $wSessId
     *
     * @return  Bool    TRUE/FALSE
     */
		public function sessRead($wSessId = '')
		{
			$wData = self::$mMemcacheObj->get($wSessId);

			//先读数据,如果没有,就初始化一个
			if (!empty($wData))
			{
				return $wData;
			}
			else
			{
				//初始化一条空记录
				$ret = self::$mMemcacheObj->set($wSessId, '', 0, SESS_LIFTTIME);
				if (TRUE != $ret)
				{
					die("Fatal Error: Session ID $wSessId init failed!");
					return FALSE;
				}
				return TRUE;
			}
		}
		// }}}

		/** {{{ sessWrite($wSessId, $wData)
     *
     * @param   String  $wSessId
     * @param   String  $wData
     *
     * @return  Bool    TRUE/FALSE
     */
		public function sessWrite($wSessId = '', $wData = '')
		{
			$ret = self::$mMemcacheObj->replace($wSessId, $wData, 0, SESS_LIFTTIME);
			if (TRUE != $ret)
			{
				die("Fatal Error: SessionID $wSessId Save data failed!");
				return FALSE;
			}
			return TRUE;
		}
		// }}}

	/** {{{ sessDestroy($wSessId)
     *
     * @param   String  $wSessId
     *
     * @return  Bool    TRUE/FALSE
     */
		public function sessDestroy($wSessId = '')
		{
			self::sessWrite($wSessId);
			return FALSE;
		}
		// }}}

	/** {{{ sessGc()
     *
     * @param   NULL
     *
     * @return  Bool    TRUE/FALSE
     */
		public function sessGc()
		{
			//无需额外回收,memcache有自己的过期回收机制
			return TRUE;
		}
		// }}}

	/** {{{ initSess()
     *
     * @param   NULL
     *
     * @return  Bool    TRUE/FALSE
     */
		public function initSess()
		{
			//不使用 GET/POST 变量方式
			ini_set('session.use_trans_sid',    0);

			//设置垃圾回收最大生存时间
			ini_set('session.gc_maxlifetime',   SESS_LIFTTIME);

			//使用 COOKIE 保存 SESSION ID 的方式
			ini_set('session.use_cookies',      1);
			ini_set('session.cookie_path',      '/');
			
			$domain = '.imysql.cn';
			//多主机共享保存 SESSION ID 的 COOKIE
			ini_set('session.cookie_domain',    $domain);

			//将 session.save_handler 设置为 user,而不是默认的 files
			session_module_name('user');

			//定义 SESSION 各项操作所对应的方法名:
			session_set_save_handler(
				array('MemacheSession', 'sessOpen'),   //对应于静态方法 My_Sess::open(),下同。
				array('MemacheSession', 'sessClose'),
				array('MemacheSession', 'sessRead'),
				array('MemacheSession', 'sessWrite'),
				array('MemacheSession', 'sessDestroy'),
				array('MemacheSession', 'sessGc')
			);

			session_start();
			return TRUE;
		}
		// }}}
	}//end class
}//end define

$memSess    = new MemacheSession;
$memSess->initSess();
?>
Copy after login

?然后,在项目程序的头文件中直接包含 MemacheSession.inc.php 即可,并且以前的程序不用做任何改动。
测试 创建一个session

<?php //set_session.php
session_start();
if (!isset($_SESSION['admin'])) {
    $_SESSION['TEST'] = 'wan';
}
print $_SESSION['admin'];
print "/n";
print session_id();
?>
Copy after login

用 sessionid 去 memcached 里查询一下

<?php //get_session.php
$mem = new Memcache;
$mem->connect("127.0.0.1", 11211);
var_dump($mem->get('0935216dbc0d721d629f89efb89affa6'));
?>
Copy after login
?

备注:memcache PECL 未来版本中,可以直接设置 php.ini 来这定自己的 session.save_handler,大致如下:

session.save_handler = memcache
session.save_path = "tcp://host:port?persistent=1&weight=2&timeout=2&retry_interval=15,tcp://host2:port2"
Copy after login

1 楼 any_luf 2012-02-08  
 PHP兑现多服务器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)

Detailed explanation of the usage of return in C language Detailed explanation of the usage of return in C language Oct 07, 2023 am 10:58 AM

The usage of return in C language is: 1. For functions whose return value type is void, you can use the return statement to end the execution of the function early; 2. For functions whose return value type is not void, the function of the return statement is to end the execution of the function. The result is returned to the caller; 3. End the execution of the function early. Inside the function, we can use the return statement to end the execution of the function early, even if the function does not return a value.

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.

See all articles