Session caching (redis), DB, and sessionredis_PHP tutorial

Source: Internet
Author: User
Session is put into the cache (redis), DB, and sessionredis. Session is stored in the cache (redis) and DB. Why does sessionredis store the SESSION in the cache? for php, the session supported by the language itself is saved to the disk file as a file, save session to cache (redis), DB, and sessionredis
Why save the SESSION in the cache?

For php, Sessions supported by the language itself are stored as files in disk files and saved in the specified folder, you can set the saved path in the configuration file or use the session_save_path () function in the program. However, this method has drawbacks,

First, it is saved to the file system, which is less efficient. when used to the session, it will find the specified sessionid from many files, which is very inefficient.

Second, when multiple servers are used, session loss may occur (in fact, they are stored on other servers ).

Of course, saving in the cache can solve the above problem. if you use the session function of php, you can use the session_set_save_handler () function to conveniently re-control the session processing process. If you do not need php session functions, you can write a similar session function by yourself. this is also the project I am working on, hash is used as the sessionId based on the user's mid and logon time. the sessionId must be added for each request to be valid (this is not required during the first login, and sessionId will be created at this time, return to the client), which is convenient, concise, and efficient. Of course, I am mainly talking about "hands and feet" in the php SESSION ".

SESSION stored in cache

Php saves the cache to redis. you can use the configuration file to modify the processing and saving of the session. of course, you can also use the ini_set () function in the program to modify it, this is very convenient for testing. I will use this method here. of course, we recommend that you use the configuration file in the production environment.

 

Set session here. the save_handler mode is redis and session. the save_path is the address and port of apsaradb for redis. refresh the settings and check redis later. the sessionId generated in apsaradb for redis is the same as that requested by the browser,

Open (string $ savePath, string $ sessionName); // open is similar to the constructor. it is called when the session starts. for example, after the session_start () function is used

Close (); // similar to the class destructor. it is called after the write function is called and executed after session_write_close ().

Read (string $ sessionId); // called when the session is read

Write (string $ sessionId, string $ data); // call

Destory ($ sessionId); // when the session is destroyed (session_destory () or session_regenerate_id (), it is called

Gc ($ lifeTime); // The Garbage collection function to clear expired and expired data.

The main method is to implement these methods. you can set different methods based on different storage Drivers. I have implemented the mysql database and redis two session-saving drivers, if needed, you can expand it by yourself, which is very convenient and easy to scale.

Below is the implementation of my redis (db and redis are similar, redis code is few, post out ):

I used the interface, which is more convenient to expand. I wanted to use memcached that day, just add it directly.

 Null, // database connection handle 'host' => null, 'port' => null, 'lifetime' => null ,); /*** constructor ** @ param $ options sets the information array */public function _ construct ($ options = array () {if (! Class_exists ("redis", false) {die ("redis extensions must be installed");} if (! Isset ($ options ['lifetime']) | $ options ['lifetime'] <= 0) {$ options ['lifetime'] = ini_get ('session. gc_maxlifetime');} $ this-> _ options = array_merge ($ this-> _ options, $ options );} /*** start to use the driver's session */public function begin () {if ($ this-> _ options ['host'] === null | $ this-> _ options ['port'] === null | $ this-> _ options ['lifetime'] = null) {return false;} // sets the session processing function session_set_save_handler (Array ($ this, 'open'), array ($ this, 'close'), array ($ this, 'read'), array ($ this, 'write '), array ($ this, 'destory '), array ($ this, 'gc');}/*** automatically starts session or session_start () the first called function * is similar to the role of the constructor * @ param $ savePath default save path * @ param $ sessionName default parameter name, PHPSESSID */public function open ($ savePath, $ sessionName) {if (is_resource ($ this-> _ options ['handler']) return true; // Connect to redis $ redisHandle = new Re Dis (); $ redisHandle-> connect ($ this-> _ options ['host'], $ this-> _ options ['port']); if (! $ RedisHandle) {return false;} $ this-> _ options ['handler'] = $ redisHandle; $ this-> gc (null); return true ;} /*** similar to the destructor, it is called after write or after session_write_close () function */public function close () {return $ this-> _ options ['handler']-> close ();} /*** read session information ** @ param $ sessionId uniquely identifies the corresponding session data through this Id * @ return session information/empty string */public function read ($ sessionId) {return $ this-> _ options ['handler']-> get ($ session Id);}/*** write or modify session data * @ param $ sessionId: id of the session to which data is to be written * @ param $ sessionData the data to be written, */public function write ($ sessionId, $ sessionData) {return $ this-> _ options ['handler']-> setex ($ sessionId, $ this-> _ options ['lifetime'], $ sessionData );} /*** actively destroys the session * @ param $ sessionId the unique id of the session to be destroyed */public function destory ($ sessionId) {return $ this-> _ options ['handler']-> delete ($ sessionId )> = 1? True: false;}/*** clear expired data in the painting * @ param validity period */public function gc ($ lifeTime) {// Obtain all sessionids, release expired $ this-> _ options ['handler']-> keys ("*"); return true ;}}

Look at the simple factory model

Class session {/*** driver handle save */private static $ _ handler = null;/*** create session driver */public static function getSession ($ type, $ options) {// Singleton if (isset ($ handler) {return self: $ _ handler;} switch ($ type) {case 'DB ': // database-driven session type include_once _ DIR __. "/driver/dbSession. php "; $ handler = new dbSession ($ options); break; case 'redis': // redis driver session type include_once _ DIR __. "/driver/redisSession. php "; $ handler = new redisSession ($ options); break; default: return false; break;} return self ::$ _ handler = $ handler ;}}

The call is also very simple,

session::getSession('redis',array(        'host' => "localhost",        'port' => "6379",    ))->begin();session_start();

The database version can be configured easily. you can download it here if necessary.Full version and demo

The copyright of this article is owned by the author iforever (luluyrt@163.com), without the author's consent to prohibit any form of Reprint, repost the article must be in the obvious position on the article page to give the author and the original connection, otherwise, you are entitled to pursue legal liability.

Why should SESSION (redis), DB, and sessionredis be stored in the cache? for php, the session supported by the language itself is saved to the disk file as a file...

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.