Redis.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: zhengmingwei
  5. * Date: 2020/3/1
  6. * Time: 6:13 PM
  7. */
  8. namespace addons\unishop\extend;
  9. use think\Env;
  10. use think\Exception;
  11. /**
  12. * Class Redis
  13. * @package addons\unishop\extend
  14. *
  15. */
  16. class Redis
  17. {
  18. public $handler = null;
  19. private $options = [];
  20. /**
  21. * 构造函数
  22. * @param array $options 缓存参数
  23. * @access public
  24. */
  25. public function __construct($options = [])
  26. {
  27. self::available();
  28. $this->options = array_merge([
  29. 'host' => Env::get('redis.host', '127.0.0.1'),
  30. 'port' => Env::get('redis.port', 6379),
  31. 'password' => Env::get('redis.password', ''),
  32. 'select' => Env::get('redis.select', 2), // 默认使用2数据库索引, 因为fastadmin请缓存会清掉1的
  33. 'timeout' => Env::get('redis.timeout', 0),
  34. 'expire' => Env::get('redis.expire', 0),
  35. 'persistent' => Env::get('redis.persistent', false),
  36. 'prefix' => Env::get('redis.prefix', ''),
  37. ], $options);
  38. try {
  39. $this->handler = new \Redis;
  40. if ($this->options['persistent']) {
  41. $this->handler->pconnect($this->options['host'], $this->options['port'], $this->options['timeout'], 'persistent_id_' . $this->options['select']);
  42. } else {
  43. $this->handler->connect($this->options['host'], $this->options['port'], $this->options['timeout']);
  44. }
  45. if ('' != $this->options['password']) {
  46. $this->handler->auth($this->options['password']);
  47. }
  48. if (0 != $this->options['select']) {
  49. $this->handler->select($this->options['select']);
  50. }
  51. } catch (\RedisException $e) {
  52. throw new Exception($e->getMessage().': redis');
  53. }
  54. }
  55. public static function available()
  56. {
  57. if (!extension_loaded('redis')) {
  58. throw new Exception('not support: redis');
  59. }
  60. }
  61. }