phplaravelredispredis

Can't use Redis with Laravel


I'm trying to connect to a Redis server I have installed on my local server, from a Laravel app (my final goal is to produce Prometheus metrics).

Redis is alive and kicking (bind on 127.0.0.1 only, without authentication):

# systemctl status redis
[sudo] password for devel: 
● redis-server.service - Advanced key-value store
     Loaded: loaded (/lib/systemd/system/redis-server.service; enabled; vendor preset: enabled)
     Active: active (running) since Wed 2024-05-29 11:14:32 CEST; 1h 18min ago
       Docs: http://redis.io/documentation,
             man:redis-server(1)
   Main PID: 967352 (redis-server)
      Tasks: 4 (limit: 18663)
     Memory: 5.3M
     CGroup: /system.slice/redis-server.service
             └─967352 /usr/bin/redis-server 127.0.0.1:6379
May 29 11:14:32 Ubuntu-2004-services2 systemd[1]: Starting Advanced key-value store...
May 29 11:14:32 Ubuntu-2004-services2 systemd[1]: Started Advanced key-value store.

File .env contains (among other values):

REDIS_CLIENT=predis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

The first endpoint I'm setting up ('/metrics') calls the method \Prometheus\CollectorRegistry::getDefault()->getOrRegisterCounter('', 'some_quick_counter', 'just a quick measurement')->inc();

The error I keep getting in the logs is:

"Call to undefined method Illuminate\Support\Facades\Redis::connect()"

And effectively file /vendor/laravel/framework/src/Illuminate/Support/Facades/Redis.php does not contain a connect() method...

If it can help, I'm on:

Any clues?


Solution

  • It is necessary to correctly initialize the CollectorRegistry, indicating to it which connection to use. That's what ServiceProvider is for.

    In AppServiceProvider::register() you need to configure Redis adapter like this

    public function register(): void
    {
      $this->app->singleton(CollectorRegistry::class, static function () {
            $config = config('database.redis.default');
            $redis = new \Prometheus\Storage\Redis([
                'host'         => $config['host'],
                'port'         => (int) $config['port'],
                'password'     => $config['password'],
                'read_timeout' => (string) ($config['read_timeout'] ?? '1'),
            ]);
        
            return new CollectorRegistry($redis);
        });
    }
    

    And than get CollectorRegistry from container:

    app(CollectorRegistry::class)->getOrRegisterCounter('','some_quick_counter', 'just a quick measurement')->inc()