RedisDataServer.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. <?php
  2. namespace App\Servers\Common;
  3. use Illuminate\Support\Facades\Redis;
  4. /**
  5. * Redis数据缓存类
  6. */
  7. class RedisDataServer
  8. {
  9. /**
  10. * 单列对象
  11. * @var
  12. */
  13. private static $server;
  14. private function __construct()
  15. {
  16. }
  17. /**
  18. * 创建对象
  19. * @return RedisDataServer
  20. */
  21. static function creatServer()
  22. {
  23. if (empty(self::$server)) {
  24. self::$server = new RedisDataServer();
  25. }
  26. return self::$server;
  27. }
  28. /**
  29. * 获取缓存数据
  30. * @param $key
  31. * @param string $type
  32. * @return mixed
  33. */
  34. function getData($key, $type = 'str')
  35. {
  36. $value = Redis::get($key);
  37. if ($type == 'json') {
  38. $value = json_decode($value, true);
  39. }
  40. return $value;
  41. }
  42. /**
  43. * 设置缓存数据
  44. * @param $key
  45. * @param $value
  46. * @param string $type
  47. * @param int $time
  48. * @param $random
  49. */
  50. function setData($key, $value, $type = 'str', $time = 10, $random = true)
  51. {
  52. if (!empty($value)) {
  53. if ($type == 'json') {
  54. $value = json_encode($value);
  55. }
  56. if ($time > 1 && $random) $time += $this->getRandom();
  57. Redis::setex($key, $time, $value);
  58. }
  59. }
  60. /**
  61. * 长时间存放数据
  62. * @param $key
  63. * @param $value
  64. * @param string $type
  65. */
  66. function setLongData($key, $value, $type = 'str')
  67. {
  68. if (!empty($value)) {
  69. if ($type == 'json') {
  70. $value = json_encode($value);
  71. }
  72. Redis::set($key, $value);
  73. }
  74. }
  75. /**
  76. * 更新数据
  77. * @param $key
  78. * @param $value
  79. * @param string $type
  80. * @param int $start_num
  81. */
  82. function setSetrange($key, $value, $type = 'str', $start_num = 0)
  83. {
  84. if (!empty($value)) {
  85. if ($type == 'json') {
  86. $value = json_encode($value);
  87. }
  88. Redis::setrange($key, $start_num, $value);
  89. }
  90. }
  91. /**
  92. * 删除Redis数据
  93. * @param $key
  94. */
  95. function delData($key)
  96. {
  97. Redis::del($key);
  98. }
  99. /**
  100. * 获取随机数
  101. * @return int
  102. */
  103. private function getRandom()
  104. {
  105. return mt_rand(1, 10);
  106. }
  107. /**
  108. * 获取过期时间
  109. * @param $key
  110. * @return mixed
  111. */
  112. function getTime($key)
  113. {
  114. $key_num = Redis::ttl($key);
  115. return $key_num;
  116. }
  117. /**
  118. * 缓存清除
  119. * @return mixed
  120. */
  121. function flushdb()
  122. {
  123. return Redis::flushdb();
  124. }
  125. }