Redis 缓存

目前支持文件缓存、redis 缓存,实现代码如下:

  1. namespace FastD\Pool;
  2. use Symfony\Component\Cache\Adapter\AbstractAdapter;
  3. use Symfony\Component\Cache\Adapter\RedisAdapter;
  4. /**
  5. * Class CachePool.
  6. */
  7. class CachePool implements PoolInterface
  8. {
  9. /**
  10. * @var AbstractAdapter[]
  11. */
  12. protected $caches = [];
  13. /**
  14. * @var array
  15. */
  16. protected $config;
  17. /**
  18. * Cache constructor.
  19. *
  20. * @param array $config
  21. */
  22. public function __construct(array $config)
  23. {
  24. $this->config = $config;
  25. }
  26. /**
  27. * @param $key
  28. *
  29. * @return AbstractAdapter
  30. */
  31. public function getCache($key)
  32. {
  33. if (!isset($this->caches[$key])) {
  34. if (!isset($this->config[$key])) {
  35. throw new \LogicException(sprintf('No set %s cache', $key));
  36. }
  37. $config = $this->config[$key];
  38. switch ($config['adapter']) {
  39. case RedisAdapter::class:
  40. $this->caches[$key] = new RedisAdapter(
  41. RedisAdapter::createConnection($config['params']['dsn']),
  42. isset($config['params']['namespace']) ? $config['params']['namespace'] : '',
  43. isset($config['params']['lifetime']) ? $config['params']['lifetime'] : ''
  44. );
  45. break;
  46. default:
  47. $this->caches[$key] = new $config['adapter'](
  48. isset($config['params']['namespace']) ? $config['params']['namespace'] : '',
  49. isset($config['params']['lifetime']) ? $config['params']['lifetime'] : '',
  50. isset($config['params']['directory']) ? $config['params']['directory'] : app()->getPath().'/runtime/cache'
  51. );
  52. }
  53. }
  54. return $this->caches[$key];
  55. }
  56. /**
  57. * {@inheritdoc}
  58. */
  59. public function initPool()
  60. {
  61. foreach ($this->config as $name => $config) {
  62. $this->getCache($name);
  63. }
  64. }
  65. }

使用 Redis 配置

缓存此处使用 dsn 形式进行配置,因此写法需要按照规范进行填写,如: redis://user:pass@host:port/db

  1. <?php
  2. return [
  3. 'default' => [
  4. 'adapter' => \Symfony\Component\Cache\Adapter\RedisAdapter::class,
  5. 'params' => [
  6. 'dsn' => 'redis://localhost:3306/db',
  7. ],
  8. ],
  9. ];

通过配置完以上配置,框架会自动切换到 redis 驱动中进行数据缓存。无论是文件缓存或者其他不一样驱动的缓存,写法上保持一致。