An overview of the

Distributed session is the premise to realize distributed deployment. The current project has not realized distributed session due to historical reasons. However, when multiple PODS are deployed in Kubernets, the call chain of load balancing is too long, leading to the session cannot be maintained.

Implementation scheme

A. Modify the configuration file php.ini

Configure it directly in PHP, or integrate it in code

session.save_handler = redis
session.save_path = "TCP: / / 127.0.0.1:6379"
Copy the code

B. Dynamic setting in code

ini_set("session.save_handler"."redis");
ini_set("session.save_path"."TCP: / / 127.0.0.1:6379");
Copy the code

C. Implement the SessionHandlerInterface interface

PHP implements session sharing using the SessionHandlerInterface.

/ * * *@see http://php.net/manual/zh/class.sessionhandlerinterface.php
 */
SessionHandlerInterface {
    abstract public bool close ( void )
    abstract public bool destroy ( string $session_id )
    abstract public int gc ( int $maxlifetime )
    abstract public bool open ( string $save_path , string $session_name )
    abstract public string read ( string $session_id )
    abstract public bool write ( string $session_id , string $session_data )
}

/ * * *@see http://php.net/manual/zh/class.sessionhandler.php
 */
MySessionHandler implements SessionHandlerInterface , SessionIdInterface {
    public bool close ( void )
    public string create_sid ( void )
    public bool destroy ( string $session_id )
    public int gc ( int $maxlifetime )
    public bool open ( string $save_path , string $session_name )
    public string read ( string $session_id )
    public bool write ( string $session_id , string $session_data )
}
Copy the code

Here’s how this interface is described in the PHP documentation. Here’s a quick look at some of the methods involved:

methods instructions
open Method is used for file-basedsessionStorage system, which does not place any code in this method and can be set to an empty method.
close Like the open method, it can be ignored and is not used by most drivers.
read Should return and given$sessionIdMatchsessionString version of data.
write I should say given$dataTo the persistent storage system$sessionId destroy
gc Method destruction is greater than the given$lifetimeAll of thesessionData, such as for systems that have their own expiration mechanismMemcachedRedisThe method can be left blank.

Session_set_save_handler is used to register the session driver

$handler = new MySessionHandler();
session_set_save_handler($handler.true); // The following line of code prevents the unexpected behavior that can occur when using objects as session save managers register_shutdown_function('session_write_close'); session_start(); // It can be used now$_SESSIONSave and retrieve dataCopy the code

Warning: After the script is executed, PHP will clear the object internally, so it is possible not to call the write and close callbacks. This may cause unexpected behavior, so you need to avoid this risk by registering the shutdown callback when using an object as a session save manager. Normally, you can register the session_write_close() callback by calling register_shutdown_function()

D. Customize the session driver

You can use memcached, Redis, and DB to implement distributed sessions. Consider implementing the Redis session driver first


      

// Create a custom interface
interface SessionInterface {
    public function set($key, $value, $expire);
    public function get($key);
    public function del($key);
    public function has($key);
    public function all(a);
} 

class RedisSession implements SessionInterface {}Copy the code

As we know, cookies generally store session IDS, so some configuration is required to implement a custom session. The configuration is as follows:

parameter The default value options describe
sess.driver files files/database/redis/memcached/custom The driver used to store sessions
sess.cookie_name my_session [A-Za-z_-] characters only The name of the session cookie
sess.expiration 7200 (2 hours) Time in seconds (integer) The number of seconds you want the session to last if you want the session to not expire (until the browser closes), set it to 0
sess.save_path NULL None Specifies the storage location, depending on the driver used to store the session
sess.time_to_update 300 Time in seconds (integer) This option controls how long it takes to regenerate a new session ID. Setting the session ID to 0 disables the regenerate session ID
sess.regenerate_destroy FALSE TRUE/FALSE (boolean) Whether to destroy the data corresponding to the old session ID when the session ID is automatically generated If the value is set to FALSE, the data will be automatically deleted by the garbage collector

When used, the $_SESSION operation is changed to the RedisSession operation.

Such as:

$_SESSION[‘aa’] = 123; Instead of RedisSession: : set (” aa “, 123); echo $_SESSION[‘aa’]; To echo RedisSession: : get (” aa “);

Redis driver implementation

Warning: Since Redis has no locking mechanism, the locking of this driver is simulated by holding a value of 300 seconds.

Redis is a storage engine, usually used for caching, and has become popular because of its high performance, which is probably why you use the Redis driver.

The downside is that it’s not as common as relational databases, and you need to install the PHpredis PHP extension on your system, which doesn’t come with the PHP program. Chances are, you’re using the Redis driver because you’re already familiar with Redis and you’re using it for other purposes.

Of course, you don’t want to suffer a performance penalty when installing a Phpredis client, so use the Predis package instead

github.com/nrk/predis

As with file and database drivers, you must configure the location to store sessions with the sess.save_path parameter. The format here is a little different and a little more complex, which is well explained in the README file for the Phpredis extension, linked to: github.com/phpredis/ph…

Warning: The Session class doesn’t actually use ‘redis’ session.save_handler, just its path format.

!

Matters needing attention

A. During the script execution of browser TAB A, if you open TAB B to access the same script, the script is pending until the execution of browser A is complete.

The script executes session_start(), and writes to the session after PHP session_start() are exclusive. The session lock can only be released when the script finishes or session_destroy() is explicitly executed.

B. It is not so easy to customize the session driver, and it requires a lot of knowledge to implement it correctly.

Not only do you need to know how sessions work in general, but also how it is implemented in PHP, how its internal storage mechanism works, how to handle concurrency, how to avoid deadlocks (locks can’t be removed), and how to handle potential security issues