HashtagFollowService.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. namespace App\Services;
  3. use Illuminate\Support\Facades\Cache;
  4. use Illuminate\Support\Facades\Redis;
  5. use App\Hashtag;
  6. use App\StatusHashtag;
  7. use App\HashtagFollow;
  8. class HashtagFollowService
  9. {
  10. const FOLLOW_KEY = 'pf:services:hashtag-follows:v1:';
  11. const CACHE_KEY = 'pf:services:hfs:byHid:';
  12. const CACHE_WARMED = 'pf:services:hfs:wc:byHid';
  13. public static function getPidByHid($hid)
  14. {
  15. if(!self::isWarm($hid)) {
  16. return self::warmCache($hid);
  17. }
  18. return self::get($hid);
  19. }
  20. public static function unfollow($hid, $pid)
  21. {
  22. return Redis::zrem(self::CACHE_KEY . $hid, $pid);
  23. }
  24. public static function add($hid, $pid)
  25. {
  26. return Redis::zadd(self::CACHE_KEY . $hid, $pid, $pid);
  27. }
  28. public static function rem($hid, $pid)
  29. {
  30. return Redis::zrem(self::CACHE_KEY . $hid, $pid);
  31. }
  32. public static function get($hid)
  33. {
  34. return Redis::zrange(self::CACHE_KEY . $hid, 0, -1);
  35. }
  36. public static function count($hid)
  37. {
  38. return Redis::zcard(self::CACHE_KEY . $hid);
  39. }
  40. public static function warmCache($hid)
  41. {
  42. foreach(HashtagFollow::whereHashtagId($hid)->lazyById(20, 'id') as $h) {
  43. if($h) {
  44. self::add($h->hashtag_id, $h->profile_id);
  45. }
  46. }
  47. self::setWarm($hid);
  48. return self::get($hid);
  49. }
  50. public static function isWarm($hid)
  51. {
  52. return Redis::zcount(self::CACHE_KEY . $hid, 0, -1) ?? Redis::zscore(self::CACHE_WARMED, $hid) != null;
  53. }
  54. public static function setWarm($hid)
  55. {
  56. return Redis::zadd(self::CACHE_WARMED, $hid, $hid);
  57. }
  58. }