RedisService.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. <?php
  2. /**
  3. * 缓存服务
  4. * @author wesmiler
  5. */
  6. namespace app\index\service;
  7. use \think\cache\driver\Redis as BaseRedis;
  8. class RedisService
  9. {
  10. public static $redis = null;
  11. public static function instance(){
  12. if(self::$redis){
  13. return self::$redis;
  14. }
  15. $option = config('config.redis');
  16. $redis = new BaseRedis($option);
  17. return $redis;
  18. }
  19. /**
  20. * 设置
  21. * @param $key
  22. * @param $val
  23. * @param int $expire
  24. */
  25. public static function set($key, $val, $expire=0){
  26. $expire = $expire? $expire : 0;
  27. $val = is_array($val)? json_encode($val, 256) : $val;
  28. self::instance()->set($key, $val, $expire);
  29. }
  30. /**
  31. * 获取
  32. * @param $key
  33. * @return bool
  34. */
  35. public static function get($key){
  36. $cacheData = self::instance()->get($key);
  37. $data = $cacheData? json_decode($cacheData, true) : [];
  38. if(empty($data)){
  39. $data = $cacheData;
  40. }
  41. return $data;
  42. }
  43. /**
  44. * 删除
  45. * @param $key
  46. * @return bool
  47. */
  48. public static function del($key){
  49. return self::instance()->rm($key);
  50. }
  51. /**
  52. * 递增
  53. * @param $key
  54. * @return bool
  55. */
  56. public static function inc($key, $step=1){
  57. return self::instance()->inc($key, $step);
  58. }
  59. /**
  60. * 递减
  61. * @param $key
  62. * @return bool
  63. */
  64. public static function dec($key, $step=1){
  65. return self::instance()->dec($key, $step);
  66. }
  67. /**
  68. * 批量删除
  69. * @param $key
  70. * @return bool
  71. */
  72. public static function delByKeys($key){
  73. return self::instance()->rms($key);
  74. }
  75. /**
  76. * 右入队处理
  77. * @param $key
  78. * @param $data
  79. */
  80. public static function rpush($key, $data){
  81. return self::instance()->rpush($key, $data);
  82. }
  83. /**
  84. * 左入出处理
  85. * @param $key
  86. */
  87. public static function lpop($key){
  88. return self::instance()->lpop($key);
  89. }
  90. /**
  91. * 设置有效时间
  92. * @param $key
  93. * @param $expire
  94. * @return mixed
  95. */
  96. public static function expire($key, $expire){
  97. return self::instance()->expire($key, $expire);
  98. }
  99. /**
  100. * 键名是否存在
  101. * @param $key
  102. * @param $expire
  103. * @return mixed
  104. */
  105. public static function exists($key){
  106. return self::instance()->exists($key);
  107. }
  108. }