ProfileStatusService.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. namespace App\Services;
  3. use DB;
  4. use Illuminate\Support\Facades\Redis;
  5. class ProfileStatusService
  6. {
  7. const CACHE_KEY = 'pf:services:profile-statuses:ids:';
  8. const COLD_CHECK_KEY = 'pf:services:profile-statuses:id-ttl:';
  9. const FALLOFF_LIMIT = 40;
  10. public static function get($id, $start = 0, $stop = 8)
  11. {
  12. $key = self::CACHE_KEY . $id;
  13. if(!Redis::zscore(self::COLD_CHECK_KEY, $id)) {
  14. $res = self::coldFetch($id);
  15. if($res && count($res)) {
  16. return array_slice($res, $start, $stop);
  17. }
  18. }
  19. $ids = Redis::zrevrange($key, $start, $stop - 1);
  20. return $ids;
  21. }
  22. public static function count($id)
  23. {
  24. return Redis::zcount(self::CACHE_KEY . $id, '-inf', '+inf');
  25. }
  26. public static function add($pid, $sid)
  27. {
  28. if(self::count($pid) > self::FALLOFF_LIMIT) {
  29. Redis::zpopmin(self::CACHE_KEY . $pid);
  30. }
  31. return Redis::zadd(self::CACHE_KEY . $pid, $sid, $sid);
  32. }
  33. public static function delete($pid, $sid)
  34. {
  35. return Redis::zrem(self::CACHE_KEY . $pid, $sid);
  36. }
  37. public static function coldFetch($pid)
  38. {
  39. Redis::del(self::CACHE_KEY . $pid);
  40. $ids = DB::table('statuses')
  41. ->select('id', 'profile_id', 'type', 'scope')
  42. ->whereIn('type', ['photo', 'photo:album', 'video'])
  43. ->whereIn('scope', ['public', 'unlisted'])
  44. ->whereProfileId($pid)
  45. ->orderByDesc('id')
  46. ->limit(self::FALLOFF_LIMIT)
  47. ->pluck('id')
  48. ->toArray();
  49. if($ids && count($ids)) {
  50. foreach($ids as $id) {
  51. self::add($pid, $id);
  52. }
  53. }
  54. Redis::zadd(self::COLD_CHECK_KEY, $pid, $pid);
  55. return $ids;
  56. }
  57. }