资讯专栏INFORMATION COLUMN

PHP使用Redis实现Session共享

Jiavan / 2635人阅读

摘要:年月日前言小型服务数据基本是保存在本地更多是本地磁盘文件但是当部署多台服务且需要共享确保每个服务都能共享到同一份数据数据存储在内存中性能好配合持久化可确保数据完整设计方案通过自身配置实现使用作为存储方案若设置了连接密码则使用如下密码测试代

Last-Modified: 2019年5月10日16:06:36

前言

小型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=密码"

测试代码

";
$_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.4
session_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 SymfonyComponentHttpFoundationSessionStorageHandler;

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

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/31440.html

相关文章

  • 负载均衡中使用Redis实现共享Session

    摘要:最近在研究架构方面的知识,包括数据库读写分离,缓存和队列,集群,以及负载均衡,今天就来先学习下我在负载均衡中遇到的问题,那就是共享的问题。一负载均衡负载均衡把众多的访问量分担到其他的服务器上,让每个服务器的压力减少。 最近在研究Web架构方面的知识,包括数据库读写分离,Redis缓存和队列,集群,以及负载均衡(LVS),今天就来先学习下我在负载均衡中遇到的问题,那就是session共享...

    tainzhi 评论0 收藏0
  • Sessions共享技术设计

    摘要:方法销毁大于给定的所有数据,对本身拥有过期机制的系统如和而言,该方法可以留空。注意事项浏览器标签脚本执行过程中,打开标签访问同一个脚本,会被,直到执行完毕。 概述 分布式session是实现分布式部署的前提, 当前项目由于历史原因未实现分布式session, 但是由于在kubernets中部署多个pod时, 负载均衡的调用链太长, 导致会话不能保持, 所以迫切需要分布式session....

    RdouTyping 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<