For small Web services, session data is stored locally (mostly in local disk files). However, when multiple services are deployed and need to share sessions, ensure that each service can share the same session data.

Redis data is stored in memory, with good performance and persistence to ensure data integrity.

Design scheme

  1. This is done through PHP’s own session configuration
Use Redis as the storage solution
session.save_handler = redis
session.save_path = "TCP: / / 127.0.0.1:6379"
# if you have set a connection password, use the following
session.save_path = "TCP: / / 127.0.0.1:6379? Auth = password"
Copy the code

The test code


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

session_start();
echo "<pre>";
$_SESSION['usertest'.rand(1.5)] =1;
var_dump($_SESSION);

echo "</pre>";
Copy the code

Output left

array(2) {["usertest1"] = >int(88)
  ["usertest3"] = >int(1)
}
usertest1|i:1; usertest3|i:1;
Copy the code

evaluation

Advantages: Simple implementation and no need to modify THE PHP code Disadvantages: The configuration does not support diversification and can only be applied to simple scenarios

2. Set the user-defined session storage function. Use the session_set_save_handler() function to set the user-defined session storage function.

session_set_save_handler ( callable $open , callable $close , callable $read , callable $write , callable $destroy , callable $gc [, callable $create_sid [, callable $validate_sid [, callable $update_timestamp]]]) :bool
    
# > = php5.4
session_set_save_handler ( object $sessionhandler [, bool $register_shutdown = TRUE) :bool
Copy the code

After configuring the session storage function, execute session_start().

A copy of Memcached is provided below (from Symfony framework code):


      

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Session\Storage\Handler;

/**
 * MemcacheSessionHandler.
 *
 * @author Drak <drak@zikula.org>
 */
class MemcacheSessionHandler implements \SessionHandlerInterface
{
    / * * *@var \Memcache Memcache driver.
     */
    private $memcache;

    / * * *@var int Time to live in seconds
     */
    private $ttl;

    / * * *@var string Key prefix for shared environments.
     */
    private $prefix;

    /**
     * Constructor.
     *
     * List of available options:
     *  * prefix: The prefix to use for the memcache keys in order to avoid collision
     *  * expiretime: The time to live in seconds
     *
     * @param \Memcache $memcache A \Memcache instance
     * @param array     $options  An associative array of Memcache options
     *
     * @throws \InvalidArgumentException When unsupported options are passed
     */
    public function __construct(\Memcache $memcache.array $options = array())
    {
        if ($diff = array_diff(array_keys($options), array('prefix'.'expiretime'))) {
            throw new \InvalidArgumentException(sprintf(
                'The following options are not supported "%s"', implode(', '.$diff))); }$this->memcache = $memcache;
        $this->ttl = isset($options['expiretime'])? (int) $options['expiretime'] : 86400;
        $this->prefix = isset($options['prefix'])?$options['prefix'] : 'sf2s';
    }

    / * * * {@inheritdoc} * /
    public function open($savePath.$sessionName)
    {
        return true;
    }

    / * * * {@inheritdoc} * /
    public function close()
    {
        return $this->memcache->close();
    }

    / * * * {@inheritdoc} * /
    public function read($sessionId)
    {
        return $this->memcache->get($this->prefix.$sessionId) ?: ' ';
    }

    / * * * {@inheritdoc} * /
    public function write($sessionId.$data)
    {
        return $this->memcache->set($this->prefix.$sessionId.$data.0, time() + $this->ttl);
    }

    / * * * {@inheritdoc} * /
    public function destroy($sessionId)
    {
        return $this->memcache->delete($this->prefix.$sessionId);
    }

    / * * * {@inheritdoc} * /
    public function gc($maxlifetime)
    {
        // not required here because memcache will auto expire the records anyhow.
        return true;
    }

    /**
     * Return a Memcache instance
     *
     * @return \Memcache
     */
    protected function getMemcache()
    {
        return $this->memcache; }}Copy the code

I hope the above content can help you. Many PHPer will encounter some problems and bottlenecks when they are advanced, and they have no sense of direction when writing too many business codes. I have sorted out some information, including but not limited to: Distributed architecture, high scalability, high performance, high concurrency, server performance tuning, TP6, Laravel, Redis, Swoft, Kafka, Mysql optimization, shell scripting, Docker, microservices, Nginx, etc. Many knowledge points can be free to share with you