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


Posted in PHP onMay 12, 2019

前言

小型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 <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;
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

PHP 相关文章推荐
PHP 开源框架22个简单简介
Aug 24 PHP
php 中文和编码判断代码
May 16 PHP
第七章 php自定义函数实现代码
Dec 30 PHP
解析PHP跳出循环的方法以及continue、break、exit的区别介绍
Jul 01 PHP
ThinkPHP的L方法使用简介
Jun 18 PHP
PHP实现简单搜歌的方法
Jul 28 PHP
Java中final关键字详解
Aug 10 PHP
php 遍历目录,生成目录下每个文件的md5值并写入到结果文件中
Dec 12 PHP
PHP echo()函数讲解
Feb 15 PHP
基于thinkphp5框架实现微信小程序支付 退款 订单查询 退款查询操作
Aug 17 PHP
PhpStorm 2020.3:新增开箱即用的PHP 8属性(推荐)
Oct 30 PHP
PHP接入支付宝接口失效流程详解
Nov 10 PHP
如何让PHP编码更加好看利于阅读
May 12 #PHP
Yii2处理密码加密及验证的方法
May 12 #PHP
php和asp语法上的区别总结
May 12 #PHP
Laravel推荐使用的十个辅助函数
May 10 #PHP
PHP下载大文件失败并限制下载速度的实例代码
May 10 #PHP
PHP 7.4 新语法之箭头函数实例详解
May 09 #PHP
PHP文件类型检查及fileinfo模块安装使用详解
May 09 #PHP
You might like
初探PHP5
2006/10/09 PHP
PHP操作数组的一些函数整理介绍
2011/07/17 PHP
PHP session文件独占锁引起阻塞问题解决方法
2015/05/12 PHP
php接口技术实例详解
2016/12/07 PHP
php实现微信企业号支付个人的方法详解
2017/07/26 PHP
jquery的颜色选择插件实例代码
2008/10/02 Javascript
JS面向对象编程浅析
2011/08/28 Javascript
js变量以及其作用域详解
2020/07/18 Javascript
jQuery中parents()和parent()的区别分析
2014/10/28 Javascript
使用JavaScript链式编程实现模拟Jquery函数
2014/12/21 Javascript
实现音乐播放器的代码(html5+css3+jquery)
2015/08/04 Javascript
JS+CSS实现的经典tab选项卡效果代码
2015/09/16 Javascript
js中的触发事件对象event.srcElement与event.target详解
2017/03/15 Javascript
Angular2.js实现表单验证详解
2017/06/23 Javascript
React实践之Tree组件的使用方法
2017/09/30 Javascript
简述JS控制台的使用
2018/07/15 Javascript
小程序图片长按识别功能的实现方法
2018/08/30 Javascript
mpvue项目中使用第三方UI组件库的方法
2018/09/30 Javascript
微信小程序MUI侧滑导航菜单示例(Popup弹出式,左侧不动,右侧滑动)
2019/01/23 Javascript
微信小程序中限制激励式视频广告位显示次数(实现思路)
2019/12/06 Javascript
微信小程序wx.navigateTo方法里的events参数使用详情及场景
2020/01/07 Javascript
python数据结构之二叉树的建立实例
2014/04/29 Python
Python使用htpasswd实现基本认证授权的例子
2014/06/10 Python
tensorflow入门之训练简单的神经网络方法
2018/02/26 Python
Python获取二维矩阵每列最大值的方法
2018/04/03 Python
python简单操作excle的方法
2018/09/12 Python
python 动态生成变量名以及动态获取变量的变量名方法
2019/01/20 Python
python mysql断开重连的实现方法
2019/07/26 Python
利用python实现汉字转拼音的2种方法
2019/08/12 Python
pytorch 获取tensor维度信息示例
2020/01/03 Python
Python实现桌面翻译工具【新手必学】
2020/02/12 Python
大学生求职工作的自我评价
2014/02/13 职场文书
检查接待方案
2014/02/27 职场文书
2014年五四青年节演讲比赛方案
2014/04/22 职场文书
2016婚礼主持词开场白
2015/11/24 职场文书
世界十大评分最高的动漫,CLANNAD上榜,第八赚足人们眼泪
2022/03/18 日漫