【问题标题】:Session sweeping lottery届会大抽奖
【发布时间】:2016-05-29 04:51:04
【问题描述】:

谁能解释一下什么是全场抽奖?我已经附加了 Laravel 框架的默认会话配置文件。

问题:1. 它说一些会话驱动程序必须手动扫描他们的 存储位置。有人可以描述这个过程以及为什么会这样吗 必要的?哪些会话驱动程序需要此操作? 2. 为什么需要抽奖?如果说某种形式的存储(数据库) 满了,为什么一定要随机?为什么框架不能 当它检测到驱动程序已满时扫描旧会话?

/*
|--------------------------------------------------------------------------
| Session Sweeping Lottery
|--------------------------------------------------------------------------
|
| Some session drivers must manually sweep their storage location to get
| rid of old sessions from storage. Here are the chances that it will
| happen on a given request. By default, the odds are 2 out of 100.
|
*/

'lottery' => array(2, 100),

【问题讨论】:

    标签: php laravel session


    【解决方案1】:

    因此,会话是在服务器上存储一定时间的一段数据。

    想象一下使用包含文件的文件夹来存储会话。必须有一个时刻应该清除旧会话。因为无法每隔 x 小时自动检查一次文件,所以会根据某些请求检查会话文件。
    此设置是此检查发生的机会。在这种情况下,每个请求 100 个中有 2 个。

    我认为目前唯一需要这个的会话驱动程序是数据库驱动程序。

    如果您在存储空间已满时对其进行清扫,则有可能在清扫存储空间之前无法启动新会话。
    如果您对每个请求都清空存储,那么您的所有请求都会变得非常慢。

    【讨论】:

    • 这是一个会话中的 100 个请求中的 2 个,还是来自多个会话的 100 个请求中的 2 个?如果是后者,那么对于任何流量不错的网站来说,100 次中的 2 次似乎过于频繁,对吗?
    • 我理解扫描数据库驱动程序的必要性,因为我认为不同数据类型存在存储限制。如果我将文件会话驱动程序的扫描频率降低到极低,您能预见到任何问题吗?例如(2 of 1000000)
    • 100 个请求中有 2 个不会发生扫描。对于每个请求,扫描发生的变化是 2 out of 100。
    • 只要你有足够的访问者让扫描每天发生一次,我看不出有什么问题。
    • 您的存储空间将开始填满。 :)
    【解决方案2】:

    我完全同意 Jerodev 的回答。

    对于现在正在寻找这个的任何人,从 Laravel 8 开始,以下是来自以下的方法:

    \vendor\laravel\framework\src\Illuminate\Session\Middleware\StartSession.php:

    /**
     * Remove the garbage from the session if necessary.
     *
     * @param  \Illuminate\Contracts\Session\Session  $session
     * @return void
     */
    protected function collectGarbage(Session $session)
    {
        $config = $this->manager->getSessionConfig();
    
        // Here we will see if this request hits the garbage collection lottery by hitting
        // the odds needed to perform garbage collection on any given request. If we do
        // hit it, we'll call this handler to let it delete all the expired sessions.
        if ($this->configHitsLottery($config)) {
            $session->getHandler()->gc($this->getSessionLifetimeInSeconds());
        }
    }
    
    /**
     * Determine if the configuration odds hit the lottery.
     *
     * @param  array  $config
     * @return bool
     */
    protected function configHitsLottery(array $config)
    {
        return random_int(1, $config['lottery'][1]) <= $config['lottery'][0];
    }
    

    config/session.php中的默认值是[2, 100]。

    因此 configHitsLottery() 将计算一个介于 1 和 100 之间的 random integer 并将其与 2 进行比较,如下所示:

    return random_int(1, 100) <= 2;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-25
      • 1970-01-01
      • 2021-03-10
      • 2013-07-09
      • 1970-01-01
      • 1970-01-01
      • 2012-11-27
      • 1970-01-01
      相关资源
      最近更新 更多