LoginSignup
2

More than 3 years have passed since last update.

LaravelでRedisにキャッシュしたキー一覧を取得する

Posted at

環境

  • Laravel Framework 6.0.3
  • Redis 4.0.14 (非クラスタモード)

背景

LaravelのCacheAPIではRedisを利用できますが、全てのRedisのコマンドが実装されているわけではありません。

どんなキーをキャッシュしたかキー一覧を取得したくても、KEYSコマンドが実装されていないため、GETコマンド等のように直感的に呼び出すことはできません。

>>> use Illuminate\Support\Facades\Cache;
>>> Cache::put('key','value');
=> true
>>> Cache::get('key');
=> "value"
>>> Cache::keys('*');
PHP Error:  Call to undefined method Illuminate/Cache/RedisStore::keys() in /var/www/vendor/laravel/framework/src/Illuminate/Cache/Repository.php on line 636

方法

## キーを複数登録
>>> Cache::put('key1','value');
=> true
>>> Cache::put('key2','value');
=> true
>>> Cache::put('key3','value');
=> true

## Redisインスタンス経由でKEYSコマンドを叩く
>>> $redis = Cache::getRedis();
=> Illuminate\Redis\RedisManager {#493}
>>> $redis->keys('*');
=> [
     "key2",
     "key1",
     "key3",
   ]
>>>
>>> $redis->keys('*3');
=> [
     "key3",
   ]
>>>

補足

  • 他のコマンドにも応用可です

参考記事

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2