| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170 |
- <?php
- namespace App\Servers;
- use Illuminate\Support\Facades\Redis;
- /**
- * Redis服务
- */
- class RedisDataServer
- {
- /**
- * 错误信息
- * @var string
- */
- private $errorMsg = '';
- static private $server = null;
- private function __construct()
- {
- }
- /**
- * 创建对象
- * @return RedisDataServer
- */
- static function creatServer()
- {
- if (empty(self::$server)) self::$server = new RedisDataServer();
- return self::$server;
- }
- /**
- * 获取随机数
- * @return int
- */
- private function getRandom()
- {
- return mt_rand(1, 10);
- }
- /**
- * 获取缓存数据
- * @param $key
- * @param string $type
- * @return mixed
- */
- function getData($key, $type = 'str')
- {
- $value = Redis::get($key);
- if (!empty($value) && $type == 'json') {
- $value = json_decode($value, true);
- }
- return $value;
- }
- /**
- * 设置缓存数据
- * @param $key
- * @param $value
- * @param string $type
- * @param int $time
- * @param $random
- */
- function setData($key, $value, $type = 'str', $time = 10, $random = true)
- {
- if (!empty($value)) {
- if ($type == 'json') {
- $value = json_encode($value);
- }
- if ($time > 1 && $random) $time += $this->getRandom();
- Redis::setex($key, $time, $value);
- }
- }
- /**
- * 删除Redis数据
- * @param $key
- */
- function delData($key)
- {
- Redis::del($key);
- }
- /**
- * 添加序号
- * @param $key
- * @param $num
- * @return false|int
- */
- function addQueue($key, $num)
- {
- return Redis::lpush($key, ...$num);
- }
- function addOneQueue($key, $num)
- {
- return Redis::lpush($key, $num);
- }
- /**
- * 弹出队列数据
- * @param $key
- * @return false
- */
- function getQueue($key)
- {
- $key_num = Redis::rpop($key);
- if (empty($key_num)) $key_num = false;
- return $key_num;
- }
- /**
- *
- * 获取队列数据长度
- * @param $key
- * @return false|int
- */
- function getQueueList($key)
- {
- return Redis::llen($key);
- }
- /**
- * 设置自增
- * @param $key
- * @return void
- */
- function setIncr($key)
- {
- Redis::incr($key);
- }
- /**
- * key加锁
- * @param $key
- * @param $value
- * @param int $time
- * @return mixed
- */
- function lockKey($key,$value,$time = 10){
- return Redis::set($key, $value, 'px', $time, 'nx');//以毫秒为单位
- // return Redis::set($key, $value, 'ex', $time, 'nx');//以秒为单位
- }
- /**
- * 解锁
- * @param $key
- * @param $value
- * @return mixed
- */
- function unLockKey($key, $value)
- {
- $res = $this->getData($key);
- if ($res == $value) {
- return Redis::del($key);
- }
- }
- }
|