佳木斯湛栽影视文化发展公司

主頁 > 知識庫 > PHP使用Redis實現(xiàn)Session共享的實現(xiàn)示例

PHP使用Redis實現(xiàn)Session共享的實現(xiàn)示例

熱門標簽:團購網(wǎng)站 電子圍欄 Mysql連接數(shù)設置 科大訊飛語音識別系統(tǒng) 服務器配置 銀行業(yè)務 Linux服務器 阿里云

前言

小型web服務, session數(shù)據(jù)基本是保存在本地(更多是本地磁盤文件), 但是當部署多臺服務, 且需要共享session, 確保每個服務都能共享到同一份session數(shù)據(jù).

redis 數(shù)據(jù)存儲在內(nèi)存中, 性能好, 配合持久化可確保數(shù)據(jù)完整.

設計方案

1. 通過php自身session配置實現(xiàn)

# 使用 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;

評價

  • 優(yōu)點: 實現(xiàn)簡單, 無需修改php代碼
  • 缺點: 配置不支持多樣化, 只能應用于簡單場景

2. 設置用戶自定義會話存儲函數(shù)

通過 session_set_save_handler() 函數(shù)設置用戶自定義會話函數(shù).

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

在配置完會話存儲函數(shù)后, 再執(zhí)行 session_start() 即可.

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

?php

/*
 * 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;
  }
}

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

您可能感興趣的文章:
  • PHP實現(xiàn)cookie跨域session共享的方法分析
  • PHP實現(xiàn)負載均衡session共享redis緩存操作示例
  • PHP簡單實現(xiàn)HTTP和HTTPS跨域共享session解決辦法
  • php實現(xiàn)session共享的實例方法

標簽:江蘇 大理 萍鄉(xiāng) 廣元 棗莊 蚌埠 衡水 衢州

巨人網(wǎng)絡通訊聲明:本文標題《PHP使用Redis實現(xiàn)Session共享的實現(xiàn)示例》,本文關鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權問題,煩請?zhí)峁┫嚓P信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡,涉及言論、版權與本站無關。
  • 相關文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    锦屏县| 梧州市| 淮安市| 景德镇市| 易门县| 远安县| 封开县| 邵阳市| 荣成市| 沁源县| 内江市| 大理市| 泰安市| 拉萨市| 大名县| 安陆市| 津市市| 宁武县| 海门市| 湘潭市| 佛冈县| 会泽县| 临沧市| 宜良县| 阳江市| 孝昌县| 九江市| 秦皇岛市| 沧源| 永靖县| 普格县| 贵溪市| 砚山县| 宝清县| 灵丘县| 德清县| 丰宁| 沂源县| 广东省| 白玉县| 云龙县|