Reputation: 77
I am trying to create multiple Redis connection in Laravel Command. It just let me create one connection in it and for others, it fails with error
InvalidArgumentException : Redis connection [redis_db] not configured.
at /vendor/laravel/framework/src/Illuminate/Redis/RedisManager.php:116
My database.php
looks like
'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),
],
],
The connection that I am creating in my command file looks like:
/**
* Create a new command instance.
*/
public function __construct()
{
parent::__construct();
$this->redis = Redis::connection('psh');
$this->redisAbTest = Redis::connection('redis_db');
}
I have already added Redis in my .env
file
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
Redis is "predis/predis": "^1.1",
and laravel is 5.8.17
Upvotes: 1
Views: 782
Reputation: 9586
You need multiple redis connections you need to open a new service provider for each connection and add service providers to config/app.php
. Then you can use like
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'];
}
}
When you need another one, open another service provider replace psh
with other connection name.
'providers' => [
// other providers
App\Providers\RedisPshProvider::class,
];
Upvotes: 2