Memcached Notes and summaries (9) Memcached and Session

Source: Internet
Author: User
Tags memcached

First, Memcached storage Session

Because Memcached is a distributed memory object caching system, it can be used to implement Session synchronization: Combine the memory in the WEB server into a "memory pool", regardless of which server generates Sessoin can be put into this "memory pool", the other web Servers are available. The advantage of using Memcached to synchronize sessions is that it does not add to the burden of the database and is more secure than a Cookie, putting the session into memory and reading faster than other processing methods.

The custom session class can refer to the thinkphp 3.2.3 full to use Memcached to process session information and to work with the user-defined session_set_save_handler(). Session class in version (\thinkphp\library\think\session\driver\memcache.class.php)

Note: The PHP extension used is memcache 1.4.24, the server environment is Windows7 + PHP 5.3.10 + Apache 2.2.21

memcached.class.php

<?PHPclassmemcachesession {protected Static $lifeTime= 3600; protected Static $handle=NULL;  Public functionStart (Memcache$mem) { self::$handle=$mem; Self::$lifeTime=Ini_get(' Session.gc_maxlifetime '); Session_set_save_handler(            Array(__class__, ' open '),Array(__class__, ' close '),Array(__class__, ' read '),Array(__class__, ' write '),Array(__class__, ' Destroy '),Array(__class__, ' GC ')        ); Session_Start(); }    /** * Open Session * @access private * @param string $savePath * @param mixed $sessName*/    Private Static functionOpen$savePath,$sessName) {        return true; }    /** * Close Session * @access Public*/     Public Static functionClose () { self:: GC (self::$lifeTime); Self::$handle-Close (); Self::$handle=NULL; return true; }    /** * Read session * @access private * @param string $sessID*/    Private Static functionRead$sessID) {        returnSelf::$handle->get ($sessID); }    /** * Write session * @access public * @param string $sessID * @param string $sessData*/     Public Static functionWrite$sessID,$sessData) {        returnSelf::$handle->set ($sessID,$sessData, 0, Self::$lifeTime); }    /** * Delete session * @access private * @param string $sessID*/    Private Static functionDestroy$sessID) {        returnSelf::$handle->delete ($sessID); }    /** * Session garbage Collection * @access private * @param string $sessMaxLifeTime*/    Private Static functiongc$sessMaxLifeTime) {        return true; }  }

Using memcached.class.php

session.php

<?PHPHeader(' content-type:text/html; Charset=utf-8 ');require' Memcache.class.php ';$mem=NewMemcache ();$mem->connect (' 127.0.0.1 ', 11211);$memclass=Newmemcachesession ();$memclass->start ($mem);$_session[' username '] = ' Dee ';Echo' <a href= ' get.php ' target= ' _blank ' > Jump </a> ';Echo' <pre> '; Print_r($_session); Echo session_id(), ' <br/> ';

get.php

 <? php  require  ' memcache.class.php '   $mem  = new   Memcache ();   $mem ->connect (' 127.0.0.1 ', 11211  $memclass  = new   Memcachesession ();   $memclass ->start ( $mem  ); echo  ' <pre> '  print_r  ($_session  );  echo  session_id  ();

Second, Memcached Cluster realizes Session sharing

Simulates opening two Memcached servers (127.0.0.1:11211 and 127.0.0.1:11212), introducing the Memcached Session class, and modifying the configuration in php.ini

Ini_set (' memcache.hash_strategy ', ' consistent '); // using a consistent hash algorithm Ini_set (' Session.save_path ', ' tcp://127.0.0.1:11211?weight=10,tcp://127.0.0.1:11212 ');

Now look at the Phpinfo information:

Set Session

cluster_session_set.php

<?PHPHeader(' content-type:text/html; Charset=utf-8 ');require' Memcache.class.php ';Ini_set(' memcache.hash_strategy ', ' consistent ');Ini_set(' Session.save_path ', ' tcp://127.0.0.1:11211?weight=10,tcp://127.0.0.1:11212 ');$mem=NewMemcache ();$mem->addserver ("127.0.0.1", 11211) or die("Could not add server 11211"); $mem->addserver ("127.0.0.1", 11212) or die("Could not add server 11212"); $memclass=Newmemcachesession ();$memclass->start ($mem);$_session[' username '] = "Deathmask"; Echo session_id(); Echo' <pre> ';Print_r($_session);Echo' <a href= ' cluster_session_get.php ' target= ' _blank ' > Jump </a> ';

Output:

Print Session

cluster_session_get.php

<?PHPrequire' Memcache.class.php ';Ini_set(' memcache.hash_strategy ', ' consistent ');Ini_set(' Session.save_path ', ' tcp://127.0.0.1:11211?weight=10,tcp://127.0.0.1:11212 ');$mem=NewMemcache ();$mem->addserver ("127.0.0.1", 11211) or die("Could not add server 11211"); $mem->addserver ("127.0.0.1", 11212) or die("Could not add server 11212"); $memclass=Newmemcachesession ();$memclass->start ($mem);Echo session_id(); Echo' <pre> ';Print_r($_session);

Output:

Use the Telnet client to connect 127.0.0.1:11211 and 127.0.0.1:11212 respectively to get the value for session_id:

127.0.0.1:11211

127.0.0.1:11212

Third,the disadvantage of Memcached storage Session

①memcached memory into many kinds of storage blocks (chunk), this way determines that Memcached can not fully utilize the memory, will produce memory fragmentation, if the storage block is insufficient, but also generate memory overflow;

② when a Memcached cluster fails (such as a memory overflow) or maintenance (such as upgrading, increasing, or reducing the server), the user will not be able to log in or be kicked off the line;

The ③memcached recovery mechanism (lru,least recently used least recently used algorithm) may cause users to fall out of line for no reason.

The solution is to use Memcached + MySQL:

A. When the user logs in, the Session "set" to Memcached, and write to the database;

B. Add a field to the session to identify when the session was last written to the database;

C. When each page loads, it takes precedence to read the Session from Memcached, followed by reading from the database;

D. After each load N or Y minutes, the Session is written to the database again;

E. Getting the expired Session from the database, giving priority to getting the latest data from the Memcached

or use Redeis to store the Session with Redis persistence.

Reference:

Using memcached to realize session sharing in clusters

Why can't I store session with memcached

3 Methods of session synchronization in Web cluster

How to Strictly set the session expiration time in PHP

Use memcached to do session sharing

The session variable cannot be transferred to the next page. Resolution: Session.use_trans_sid = 1

Using Memcache to store session details based on PHP

PHP module Memcache and memcached difference analysis

About Memcache distributed consistent hash

memcached Memory allocations (slab and chunk)

Memcached Notes and summaries (9) Memcached and Session

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.