RedisService.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. <?php
  2. namespace app\admin\service;
  3. use app\common\library\Redis;
  4. use think\Log;
  5. use think\exception\HttpException;
  6. class RedisService
  7. {
  8. const REDIS_KEY_SHORT_URL = 'SU:';
  9. public function __construct()
  10. {
  11. }
  12. /**
  13. * 获取客服消息自增id
  14. * @return int
  15. */
  16. public function getAutoCustomId()
  17. {
  18. $redisAuto = Redis::instanceAuto();
  19. $newCustomId = $redisAuto->incr('ACID');
  20. if (!$newCustomId) {
  21. $strErr = '客服消息自增ID获取失败!';
  22. Log::error($strErr);
  23. throw new HttpException(500, $strErr);
  24. }
  25. return $newCustomId;
  26. }
  27. /**
  28. * 获取模板消息自增id
  29. * @return int
  30. */
  31. public function getTemplateMessageId()
  32. {
  33. $redisAuto = Redis::instanceAuto();
  34. $newTemplateMessageId = $redisAuto->incr('TMID');
  35. if (!$newTemplateMessageId) {
  36. $strErr = '模板消息自增ID获取失败';
  37. Log::error($strErr);
  38. throw new HttpException(500, $strErr);
  39. }
  40. return $newTemplateMessageId;
  41. }
  42. /**
  43. * 获取推广链接自增id
  44. * @return int
  45. */
  46. public function getAutoReferralId()
  47. {
  48. $redisAuto = Redis::instanceAuto();
  49. $newReferralId = $redisAuto->incr('RFID');
  50. if (!$newReferralId) {
  51. $strErr = '推广链接自增ID获取失败!';
  52. Log::error($strErr);
  53. throw new HttpException(500, $strErr);
  54. }
  55. return $newReferralId;
  56. }
  57. /**
  58. * 获取短链接自增id
  59. * @return int
  60. */
  61. public function getAutoShortUrlId()
  62. {
  63. $redisAuto = Redis::instanceAuto();
  64. $newShortUrlId = $redisAuto->incr('SUID');
  65. if (!$newShortUrlId) {
  66. $strErr = '短链接自增ID获取失败!';
  67. Log::error($strErr);
  68. throw new HttpException(500, $strErr);
  69. }
  70. return $newShortUrlId;
  71. }
  72. #region 短链接
  73. /**
  74. * 获取短链接redis-key
  75. * @param $id
  76. * @return string
  77. */
  78. private function _getShortUrlKey($id)
  79. {
  80. return self::REDIS_KEY_SHORT_URL . $id;
  81. }
  82. /**
  83. * 从redis获取短链接
  84. * @param $id
  85. * @return bool|string
  86. */
  87. public function getShortUrl($id)
  88. {
  89. $redis = Redis::instance();
  90. $key = $this->_getShortUrlKey($id);
  91. return $redis->get($key);
  92. }
  93. /**
  94. * 设置redis短链接
  95. * @param $id
  96. * @param $url
  97. * @return bool
  98. * @throws \Exception
  99. */
  100. public function setShortUrl($id, $url)
  101. {
  102. $redis = Redis::instance();
  103. $key = $this->_getShortUrlKey($id);
  104. $result = $redis->set($key, $url, 3600);
  105. if (!$result) {
  106. throw new \Exception('设置短连接redis失败');
  107. }
  108. return $result;
  109. }
  110. #endregion
  111. }