侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

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

Redis  /  管理员 发布于 5年前   237

前言

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

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

设计方案

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

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

测试代码

";$_SESSION['usertest'.rand(1,5)]=1;var_dump($_SESSION);echo "
";

输出 ↓

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

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

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

 * * 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  */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实现cookie跨域session共享的方法分析
  • PHP实现负载均衡session共享redis缓存操作示例
  • PHP简单实现HTTP和HTTPS跨域共享session解决办法
  • php实现session共享的实例方法


  • 上一条:
    thinkPHP框架通过Redis实现增删改查操作的方法详解
    下一条:
    thinkphp5框架扩展redis类方法示例
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在Redis中能实现的功能、常见应用介绍(0个评论)
    • 2024年Redis面试题之一(0个评论)
    • 在redis缓存常见出错及解决方案(0个评论)
    • 在redis中三种特殊数据类型:地理位置、基数(cardinality)估计、位图(Bitmap)使用场景介绍浅析(2个评论)
    • Redis 删除 key用 del 和 unlink 有啥区别?(1个评论)
    • 近期文章
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2017-12
    • 2020-03
    • 2020-05
    • 2021-04
    • 2022-03
    • 2022-05
    • 2022-08
    • 2023-02
    • 2023-04
    • 2023-07
    • 2024-01
    • 2024-02
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客