Redis.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Simps.
  5. *
  6. * @link https://simps.io
  7. * @document https://doc.simps.io
  8. * @license https://github.com/simple-swoole/simps/blob/master/LICENSE
  9. */
  10. namespace Simps\DB;
  11. use RuntimeException;
  12. use Swoole\Database\RedisConfig;
  13. use Swoole\Database\RedisPool;
  14. class Redis
  15. {
  16. protected $pools;
  17. protected $config = [
  18. 'host' => 'localhost',
  19. 'port' => 6379,
  20. 'auth' => '',
  21. 'db_index' => 0,
  22. 'time_out' => 1,
  23. 'size' => 64,
  24. ];
  25. private static $instance;
  26. private function __construct(array $config)
  27. {
  28. if (empty($this->pools)) {
  29. $this->config = array_replace_recursive($this->config, $config);
  30. $this->pools = new RedisPool(
  31. (new RedisConfig())
  32. ->withHost($this->config['host'])
  33. ->withPort($this->config['port'])
  34. ->withAuth($this->config['auth'])
  35. ->withDbIndex($this->config['db_index'])
  36. ->withTimeout($this->config['time_out']),
  37. $this->config['size']
  38. );
  39. }
  40. }
  41. public static function getInstance($config = null, $poolName = 'default')
  42. {
  43. if (empty(self::$instance[$poolName])) {
  44. if (empty($config)) {
  45. throw new RuntimeException('redis config empty');
  46. }
  47. if (empty($config['size'])) {
  48. throw new RuntimeException('the size of redis connection pools cannot be empty');
  49. }
  50. self::$instance[$poolName] = new static($config);
  51. }
  52. return self::$instance[$poolName];
  53. }
  54. public function getConnection()
  55. {
  56. return $this->pools->get();
  57. }
  58. public function close($connection = null)
  59. {
  60. $this->pools->put($connection);
  61. }
  62. public function getConfig(): array
  63. {
  64. return $this->config;
  65. }
  66. public function fill(): void
  67. {
  68. $this->pools->fill();
  69. }
  70. }