当前位置:首页 > PHP教程 > php高级应用 > 列表

PHP使用Redis实现Session共享的实现示例

发布:smiling 来源: PHP粉丝网  添加日期:2021-11-22 14:53:14 浏览: 评论:0 

这篇文章主要介绍了PHP使用Redis实现Session共享的实现示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考,一起跟随小编过来看看吧。

前言

小型web服务, session数据基本是保存在本地(更多是本地磁盘文件), 但是当部署多台服务, 且需要共享session, 确保每个服务都能共享到同一份session数据.

redis 数据存储在内存中, 性能好, 配合持久化可确保数据完整.

设计方案

1. 通过php自身session配置实现

  1. # 使用 redis 作为存储方案 
  2. session.save_handler = redis 
  3. session.save_path = "tcp://127.0.0.1:6379" 
  4. # 若设置了连接密码, 则使用如下 
  5. session.save_path = "tcp://127.0.0.1:6379?auth=密码" 

测试代码

  1. <?php 
  2. ini_set("session.save_handler", "redis"); 
  3. ini_set("session.save_path", "tcp://127.0.0.1:6379"); 
  4.  
  5. session_start(); 
  6. echo "<pre>"; 
  7. $_SESSION['usertest'.rand(1,5)]=1; 
  8. var_dump($_SESSION); 
  9.  
  10. echo "</pre>"; 

输出 ↓

  1. array(2) { 
  2.   ["usertest1"]=> 
  3.   int(88) 
  4.   ["usertest3"]=> 
  5.   int(1) 
  6. } 
  7. usertest1|i:1;usertest3|i:1; 

评价

优点: 实现简单, 无需修改php代码

缺点: 配置不支持多样化, 只能应用于简单场景

2. 设置用户自定义会话存储函数

通过 session_set_save_handler() 函数设置用户自定义会话函数.

  1. 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 
  2.     
  3. # >= php5.4 
  4. session_set_save_handler ( object $sessionhandler [, bool $register_shutdown = TRUE ] ) : bool 

在配置完会话存储函数后, 再执行 session_start() 即可.

具体代码略, 以下提供一份 Memcached 的(来自Symfony框架代码):

  1. <?php 
  2.  
  3. /* 
  4.  * This file is part of the Symfony package. 
  5.  * 
  6.  * (c) Fabien Potencier <fabien@symfony.com> 
  7.  * 
  8.  * For the full copyright and license information, please view the LICENSE 
  9.  * file that was distributed with this source code. 
  10.  */ 
  11.  
  12. namespace Symfony\Component\HttpFoundation\Session\Storage\Handler; 
  13.  
  14. /** 
  15.  * MemcacheSessionHandler. 
  16.  * 
  17.  * @author Drak <drak@zikula.org> 
  18.  */ 
  19. class MemcacheSessionHandler implements \SessionHandlerInterface 
  20. { 
  21.   /** 
  22.    * @var \Memcache Memcache driver. 
  23.    */ 
  24.   private $memcache; 
  25.  
  26.   /** 
  27.    * @var int Time to live in seconds 
  28.    */ 
  29.   private $ttl; 
  30.  
  31.   /** 
  32.    * @var string Key prefix for shared environments. 
  33.    */ 
  34.   private $prefix; 
  35.  
  36.   /** 
  37.    * Constructor. 
  38.    * 
  39.    * List of available options: 
  40.    * * prefix: The prefix to use for the memcache keys in order to avoid collision 
  41.    * * expiretime: The time to live in seconds 
  42.    * 
  43.    * @param \Memcache $memcache A \Memcache instance 
  44.    * @param array   $options An associative array of Memcache options 
  45.    * 
  46.    * @throws \InvalidArgumentException When unsupported options are passed 
  47.    */ 
  48.   public function __construct(\Memcache $memcache, array $options = array()) 
  49.   { 
  50.     if ($diff = array_diff(array_keys($options), array('prefix', 'expiretime'))) { 
  51.       throw new \InvalidArgumentException(sprintf( 
  52.         'The following options are not supported "%s"', implode(', ', $diff) 
  53.       )); 
  54.     } 
  55.  
  56.     $this->memcache = $memcache; 
  57.     $this->ttl = isset($options['expiretime']) ? (int) $options['expiretime'] : 86400; 
  58.     $this->prefix = isset($options['prefix']) ? $options['prefix'] : 'sf2s'; 
  59.   } 
  60.  
  61.   /** 
  62.    * {@inheritdoc} 
  63.    */ 
  64.   public function open($savePath, $sessionName) 
  65.   { 
  66.     return true; 
  67.   } 
  68.  
  69.   /** 
  70.    * {@inheritdoc} 
  71.    */ 
  72.   public function close() 
  73.   { 
  74.     return $this->memcache->close(); 
  75.   } 
  76.  
  77.   /** 
  78.    * {@inheritdoc} 
  79.    */ 
  80.   public function read($sessionId) 
  81.   { 
  82.     return $this->memcache->get($this->prefix.$sessionId) ?: ''; 
  83.   } 
  84.  
  85.   /** 
  86.    * {@inheritdoc} 
  87.    */ 
  88.   public function write($sessionId, $data) 
  89.   { 
  90.     return $this->memcache->set($this->prefix.$sessionId, $data, 0, time() + $this->ttl); 
  91.   } 
  92.  
  93.   /** 
  94.    * {@inheritdoc} 
  95.    */ 
  96.   public function destroy($sessionId) 
  97.   { 
  98.     return $this->memcache->delete($this->prefix.$sessionId); 
  99.   } 
  100.  
  101.   /** 
  102.    * {@inheritdoc} 
  103.    */ 
  104.   public function gc($maxlifetime) 
  105.   { 
  106.     // not required here because memcache will auto expire the records anyhow. 
  107.     return true; 
  108.   } 
  109.  
  110.   /** 
  111.    * Return a Memcache instance 
  112.    * 
  113.    * @return \Memcache 
  114.    */ 
  115.   protected function getMemcache() 
  116.   { 
  117.     return $this->memcache; 
  118.   } 
  119. }

Tags: Redis Session

分享到: