Redis.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. namespace App\libs\cache\redis;
  3. use App\libs\PreInstall;
  4. use Illuminate\Support\Env;
  5. use Illuminate\Support\Facades\Config;
  6. class Redis
  7. {
  8. private $host = '127.0.0.1';
  9. private $port = 6379;
  10. private $redis;
  11. private static $instance;
  12. private function __construct()
  13. {
  14. $redis = new \Redis();
  15. $config = [
  16. 'host' => Env::get('redis.host', $this->host),
  17. 'port' => Env::get('redis.port', $this->port),
  18. 'pwd' => Env::get('redis.pwd', '')
  19. ];
  20. $config = array_merge($config, PreInstall::config('redis'));
  21. $redis->connect($config['host'], $config['port']);
  22. if (!empty($config['pwd'])) {
  23. $redis->auth($config['pwd']);
  24. }
  25. $this->redis = $redis;
  26. $this->redis->select(Config::get('lc.redis.db'));
  27. }
  28. public static function instance()
  29. {
  30. if (!self::$instance) {
  31. self::$instance = new self();
  32. }
  33. return self::$instance;
  34. }
  35. /**
  36. * 同步锁
  37. * 上锁成功返回true
  38. * 当存在锁(即上锁失败)返回false
  39. * @param string $key 锁定的标识
  40. * @param string $value 锁定值
  41. * @param int $ex 锁释放时间,超时自动释放锁
  42. * @return bool
  43. */
  44. public function lock($key, $value, $ex = 3)
  45. {
  46. return $this->redis->set($key, $value, ['nx', 'ex' => $ex]);
  47. }
  48. public function __call($name, $arguments)
  49. {
  50. return call_user_func_array([$this->redis, $name], $arguments);
  51. }
  52. }