twn39 / code

:memo: 代码笔记,通过 issue 的方式记录日常遇到的问题和学习笔记
13 stars 1 forks source link

Laravel session mongodb 存储 #47

Open twn39 opened 9 years ago

twn39 commented 9 years ago

将session存储到mongodb,这样可以查看在线人数,并可通过在线人数来优化系统。

twn39 commented 9 years ago

添加mongodb适配器:

<?php namespace App\Handlers;

use Symfony\Component\HttpFoundation\Session\Storage\Handler\MongoDbSessionHandler;

class MongoHandler extends MongoDbSessionHandler
{

}

修改并添加mongodb session 扩展:

<?php namespace App\Providers;

use App\Handlers\MongoHandler;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider {

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        $connection = new \MongoClient();

        \Session::extend('mongo', function($app) use ($connection) {
            $options = array(
                'database' => 'laravel',
                'collection' => 'sessions',
                'expiry_field' => 'expireAt',
            );
            return new MongoHandler($connection, $options);
        });
    }

    /**
     * Register any application services.
     *
     * This service provider is a great spot to register your various container
     * bindings with the application. As you can see, we are registering our
     * "Registrar" implementation here. You can add your own bindings too!
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind(
            'Illuminate\Contracts\Auth\Registrar',
            'App\Services\Registrar'
        );
    }

}

这里为求方便与测试,将mongodb信息硬编码在代码中,应该将其放到配置文件中。

twn39 commented 9 years ago

mongodb支持缓存功能:

db.MySessionCollection.createIndex( { "expireAt": 1 }, { expireAfterSeconds: 120 } )