数据库配置
config/database.php
'app' => [
'client' => env('REDIS_CLIENT', 'predis'),
'options' => [
'cluster' =>'redis',
'prefix' => 'app:',
],
'default' => [
'url' => env('APP_REDIS_URL'),
'host' => env('APP_REDIS_HOST', '127.0.0.1'),
'password' => env('APP_REDIS_PASSWORD', null),
'port' => env('APP_REDIS_PORT', 6379),
'database' => env('APP_REDIS_DB', 2),
],
],
缓存配置
config/cache.php
'app' => [
'driver' => 'app',
'connection' => 'default',
'prefix' => '',
],
服务容器注册
Providers/AppServiceProvider
/**
* 运行于所有应用.
*
* @return void
*/
public function boot()
{
Cache::extend('app', function ($config) {
$redis = $this->app['app-redis'];
$connection = $config['connection'] ?? 'default';
return $this->repository(new RedisStore($redis, $config['prefix'] ?? '', $connection));
});
}
/**
* 注册服务提供.
*
* @return void
*/
public function register()
{
// 前后端共享的缓存驱动
$this->app->singleton('app-redis', function ($app) {
$config = $app->make('config')->get('database.app', []);
return new RedisManager($app, Arr::pull($config, 'client', 'phpredis'), $config);
});
}
用法
// 缓存
cache()->store('app')->get($key);
// redis
$redis = cache()->store('app')->getRedis();
$redis->sadd($key, 1);