如何在使用redis驱动程序时更改Laravel 4的连接信息


How to change the connection info for Laravel 4 when using the redis driver?

我使用redis作为缓存数据的驱动程序。Laravel的数据库配置能够定义Redis连接信息。

  'redis'       => array(
    'cluster' => true,
    'default' => array(
        'host'     => '127.0.0.1',
        'port'     => 6379,
        'database' => 0,
    ),
),

但是,如果我想定义多个连接,并使用特定的connection用于缓存,我如何在Laravel 4上做到这一点。cache.php上没有连接配置,我可以在其中指定redis连接名称。它当前有一个connection配置,如果缓存驱动程序是database,则将使用该配置。

编辑

我刚刚浏览了Laravel的代码,在初始化Redis驱动程序时,看起来Laravel没有查看连接。我的理解正确吗?

http://laravel.com/api/source-class-Illuminate.Cache.CacheManager.html#63-73

protected function createRedisDriver()
{
    $redis = $this->app['redis'];
    return $this->repository(new RedisStore($redis, $this->getPrefix()));
}
Laravel可以处理多个连接。请参阅此关于添加/使用多个数据库连接的问题/答案。

一旦为redis定义了多个连接,就需要做一些辅助工作来访问代码中的某个地方。这可能看起来像这样:

$redisCache = App::make('cache'); // Assumes "redis" set as your cache
$redisCache->setConnection('some-connection'); // Your redis cache connection
$redisCache->put($key, $value');

编辑

我将在这里添加一点内容,让您了解如何做到这一点,这样您就不需要到处都有连接逻辑:

最简单的是,您可以将redis缓存的实例绑定到应用程序中的某个位置(可能是start.php或其他app/start/*.php文件):

App::singleton('rediscache', function($app){
    $redisCache = $app['cache'];
    $redisCache->setConnection('some-connection'); // Your redis cache connection
    return $redisCache;
});

然后,在你的代码中,你可以这样做来缓存:

$cache = App::make('rediscache');
$cache->put($key, $value); // Or whatever you need to do

如果您有自己的应用程序代码库,也可以创建服务提供商。您可以在其中注册"rediscache",然后在应用程序中以相同的方式使用它。

希望这有助于作为一个开始——还有其他代码体系结构——使用依赖注入,也许还有一个存储库来帮助进一步组织代码。