在 Laravel 命令中创建多个 redis 连接失败

Failed to create multiple redis connections in Laravel command

我正在尝试在 Laravel 命令中创建多个 Redis 连接。它只是让我在其中创建一个连接,对于其他人,它失败并显示错误

InvalidArgumentException  : Redis connection [redis_db] not configured.

at /vendor/laravel/framework/src/Illuminate/Redis/RedisManager.php:116

我的database.php长得像

    'redis' => ['client' => env('REDIS_CLIENT', 'predis'),

    'options' => [
        'cluster' => env('REDIS_CLUSTER', 'predis'),
        'prefix'  => Str::slug(env('APP_NAME', 'laravel'), '_') . '_database_',
    ],

    'psh' => [
        'host'     => env('REDIS_HOST', '127.0.0.1'),
        'password' => env('REDIS_PASSWORD', null),
        'port'     => env('REDIS_PORT', 6379),
        'database' => env('REDIS_CACHE_DB', 5),
    ],

    'redis_db' => [
        'host'     => env('REDIS_HOST', '127.0.0.1'),
        'password' => env('REDIS_PASSWORD', null),
        'port'     => env('REDIS_PORT', 6379),
        'database' => env('REDIS_CACHE_DB', 3),
    ],
],

我在命令文件中创建的连接如下所示:

/**
 * Create a new command instance.
 */
public function __construct()
{
    parent::__construct();
    $this->redis              = Redis::connection('psh');
    $this->redisAbTest        = Redis::connection('redis_db');
}

我已经在我的 .env 文件中添加了 Redis

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

Redis 是 "predis/predis": "^1.1", 并且 laravel 是 5.8.17

您需要多个redis 连接您需要为每个连接打开一个新的服务提供者并将服务提供者添加到config/app.php。然后你可以像

Redis::connection('psh');
class RedisPshProvider extends ServiceProvider
{
    protected $defer = true;

    public function register()
    {
        $this->app->singleton('psh', function ($app) {
            return new RedisManager($app, 'predis', $app['config']['database.psh']);
        });
    }

    public function provides()
    {
        return ['psh'];
    }
}

当您需要另一个时,打开另一个服务提供商将psh替换为其他连接名称。

'providers' => [
    // other providers
    App\Providers\RedisPshProvider::class,
];