1. 程式人生 > 其它 >yii2設定session時間_PHP使用Redis實現Session共享

yii2設定session時間_PHP使用Redis實現Session共享

技術標籤:yii2設定session時間

前言

小型web服務, session資料基本是儲存在本地(更多是本地磁碟檔案), 但是當部署多臺服務, 且需要共享session, 確保每個服務都能共享到同一份session資料.

redis 資料儲存在記憶體中, 效能好, 配合持久化可確保資料完整.

設計方案

1. 通過php自身session配置實現

# 使用 redis 作為儲存方案
session.save_handler = redis
session.save_path = "tcp://127.0.0.1:6379"
# 若設定了連線密碼, 則使用如下
session.save_path = "tcp://127.0.0.1:6379?auth=密碼"

測試程式碼

<?php
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>";

輸出 ↓

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

評價

  • 優點: 實現簡單, 無需修改php程式碼
  • 缺點: 配置不支援多樣化, 只能應用於簡單場景

2. 設定使用者自定義會話儲存函式

通過 session_set_save_handler() 函式設定使用者自定義會話函式.

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

在配置完會話儲存函式後, 再執行 session_start() 即可.

具體程式碼略, 以下提供一份 Memcached 的(來自Symfony框架程式碼):

<?php

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

namespace SymfonyComponentHttpFoundationSessionStorageHandler;

/**
 * MemcacheSessionHandler.
 *
 * @author Drak <[email protected]>
 */
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;
    }
}
以上內容希望幫助到大家,很多PHPer在進階的時候總會遇到一些問題和瓶頸,業務程式碼寫多了沒有方向感,不知道該從那裡入手去提升,對此我整理了一些資料,包括但不限於:分散式架構、高可擴充套件、高效能、高併發、伺服器效能調優、TP6,laravel,YII2,Redis,Swoole、Swoft、Kafka、Mysql優化、shell指令碼、Docker、微服務、Nginx等多個知識點高階進階乾貨需要的可以免費分享給大家 ,需要請戳這裡連結 或 者關注咱們下面的知乎專欄
PHP架構師圈子​zhuanlan.zhihu.com 6b78c1e15a0d94b31c2c595669dca227.png