定义Redis池

在app/config/beans/base.php增加如下配置

1
2
3
4
'cacheRedis'       => [
'class' => \Swoft\Redis\Redis::class,
'poolName' => 'cacheRedis',
],

定义Redis池配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
namespace App\Pool\Config;

use Swoft\Bean\Annotation\Bean;
use Swoft\Bean\Annotation\Value;
use Swoft\Redis\Pool\Config\RedisPoolConfig;

/**
* CacheRedisPoolConfig
*
* @Bean()
*/
class CacheRedisPoolConfig extends RedisPoolConfig
{
/**
* @Value(name="${config.cache.redis.db}", env="${REDIS_DB}")
* @var int
*/
protected $db = 0;

/**
* @Value(name="${config.cache.redis.prefix}", env="${REDIS_PREFIX}")
* @var string
*/
protected $prefix = '';
}

定义redis池

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
namespace App\Pool;

use Swoft\Bean\Annotation\Inject;
use Swoft\Bean\Annotation\Pool;
use Swoft\Redis\Pool\RedisPool;
use App\Pool\Config\CacheRedisPoolConfig;

/**
* CacheRedisPool
*
* @Pool("cacheRedis")
*/
class CacheRedisPool extends RedisPool
{
/**
* @Inject()
* @var CacheRedisPoolConfig
*/
public $poolConfig;
}

使用注入

此时可以调用所有的redis方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
namespace App\Lib\TpCache;

use Swoft\Bean\Annotation\Inject;

trait Redis
{
/**
* @Inject("cacheRedis")
*/
private $cacheRedis;

/**
* 设置缓存过期时间
*/
private function cacheExpire($name, $ttl)
{
$this->cacheRedis->expire($name, $ttl);
}
}