Redis.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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 function __call($name, $arguments)
  29. {
  30. return \call_user_func_array([$this->redis, $name], $arguments);
  31. }
  32. public static function instance()
  33. {
  34. if (!self::$instance) {
  35. self::$instance = new self();
  36. }
  37. return self::$instance;
  38. }
  39. /**
  40. * 同步锁
  41. * 上锁成功返回true
  42. * 当存在锁(即上锁失败)返回false.
  43. *
  44. * @param string $key 锁定的标识
  45. * @param string $value 锁定值
  46. * @param int $ex 锁释放时间,超时自动释放锁
  47. *
  48. * @return bool
  49. */
  50. public function lock($key, $value, $ex = 3)
  51. {
  52. return $this->redis->set($key, $value, ['nx', 'ex' => $ex]);
  53. }
  54. }