123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144 |
- <?php
- namespace App\Servers\Common;
- use Illuminate\Support\Facades\Redis;
- /**
- * Redis数据缓存类
- */
- class RedisDataServer
- {
- /**
- * 单列对象
- * @var
- */
- private static $server;
- private function __construct()
- {
- }
- /**
- * 创建对象
- * @return RedisDataServer
- */
- static function creatServer()
- {
- if (empty(self::$server)) {
- self::$server = new RedisDataServer();
- }
- return self::$server;
- }
- /**
- * 获取缓存数据
- * @param $key
- * @param string $type
- * @return mixed
- */
- function getData($key, $type = 'str')
- {
- $value = Redis::get($key);
- if ($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);
- }
- }
- /**
- * 长时间存放数据
- * @param $key
- * @param $value
- * @param string $type
- */
- function setLongData($key, $value, $type = 'str')
- {
- if (!empty($value)) {
- if ($type == 'json') {
- $value = json_encode($value);
- }
- Redis::set($key, $value);
- }
- }
- /**
- * 更新数据
- * @param $key
- * @param $value
- * @param string $type
- * @param int $start_num
- */
- function setSetrange($key, $value, $type = 'str', $start_num = 0)
- {
- if (!empty($value)) {
- if ($type == 'json') {
- $value = json_encode($value);
- }
- Redis::setrange($key, $start_num, $value);
- }
- }
- /**
- * 删除Redis数据
- * @param $key
- */
- function delData($key)
- {
- Redis::del($key);
- }
- /**
- * 获取随机数
- * @return int
- */
- private function getRandom()
- {
- return mt_rand(1, 10);
- }
- /**
- * 获取过期时间
- * @param $key
- * @return mixed
- */
- function getTime($key)
- {
- $key_num = Redis::ttl($key);
- return $key_num;
- }
- /**
- * 缓存清除
- * @return mixed
- */
- function flushdb()
- {
- return Redis::flushdb();
- }
- }
|