1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- <?php
- namespace App\libs\cache\redis;
- use App\libs\PreInstall;
- use Illuminate\Support\Env;
- use Illuminate\Support\Facades\Config;
- class Redis
- {
- private $host = '127.0.0.1';
- private $port = 6379;
- private $redis;
- private static $instance;
- private function __construct()
- {
- $redis = new \Redis();
- $config = [
- 'host' => Env::get('redis.host', $this->host),
- 'port' => Env::get('redis.port', $this->port),
- 'pwd' => Env::get('redis.pwd', '')
- ];
- $config = array_merge($config, PreInstall::config('redis'));
- $redis->connect($config['host'], $config['port']);
- if (!empty($config['pwd'])) {
- $redis->auth($config['pwd']);
- }
- $this->redis = $redis;
- $this->redis->select(Config::get('lc.redis.db'));
- }
- public static function instance()
- {
- if (!self::$instance) {
- self::$instance = new self();
- }
- return self::$instance;
- }
- /**
- * 同步锁
- * 上锁成功返回true
- * 当存在锁(即上锁失败)返回false
- * @param string $key 锁定的标识
- * @param string $value 锁定值
- * @param int $ex 锁释放时间,超时自动释放锁
- * @return bool
- */
- public function lock($key, $value, $ex = 3)
- {
- return $this->redis->set($key, $value, ['nx', 'ex' => $ex]);
- }
- public function __call($name, $arguments)
- {
- return call_user_func_array([$this->redis, $name], $arguments);
- }
- }
|