1
0

GroupFeedService.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. namespace App\Services;
  3. use App\Models\GroupPost;
  4. use Illuminate\Support\Facades\Redis;
  5. class GroupFeedService
  6. {
  7. const CACHE_KEY = 'pf:services:groups:feed:';
  8. const FEED_LIMIT = 400;
  9. public static function get($gid, $start = 0, $stop = 10)
  10. {
  11. if ($stop > 100) {
  12. $stop = 100;
  13. }
  14. return Redis::zrevrange(self::CACHE_KEY.$gid, $start, $stop);
  15. }
  16. public static function getRankedMaxId($gid, $start = null, $limit = 10)
  17. {
  18. if (! $start) {
  19. return [];
  20. }
  21. return array_keys(Redis::zrevrangebyscore(self::CACHE_KEY.$gid, $start, '-inf', [
  22. 'withscores' => true,
  23. 'limit' => [1, $limit],
  24. ]));
  25. }
  26. public static function getRankedMinId($gid, $end = null, $limit = 10)
  27. {
  28. if (! $end) {
  29. return [];
  30. }
  31. return array_keys(Redis::zrevrangebyscore(self::CACHE_KEY.$gid, '+inf', $end, [
  32. 'withscores' => true,
  33. 'limit' => [0, $limit],
  34. ]));
  35. }
  36. public static function add($gid, $val)
  37. {
  38. if (self::count($gid) > self::FEED_LIMIT) {
  39. if (config('database.redis.client') === 'phpredis') {
  40. Redis::zpopmin(self::CACHE_KEY.$gid);
  41. }
  42. }
  43. return Redis::zadd(self::CACHE_KEY.$gid, $val, $val);
  44. }
  45. public static function rem($gid, $val)
  46. {
  47. return Redis::zrem(self::CACHE_KEY.$gid, $val);
  48. }
  49. public static function del($gid, $val)
  50. {
  51. return self::rem($gid, $val);
  52. }
  53. public static function count($gid)
  54. {
  55. return Redis::zcard(self::CACHE_KEY.$gid);
  56. }
  57. public static function warmCache($gid, $force = false, $limit = 100)
  58. {
  59. if (self::count($gid) == 0 || $force == true) {
  60. Redis::del(self::CACHE_KEY.$gid);
  61. $ids = GroupPost::whereGroupId($gid)
  62. ->orderByDesc('id')
  63. ->limit($limit)
  64. ->pluck('id');
  65. foreach ($ids as $id) {
  66. self::add($gid, $id);
  67. }
  68. return 1;
  69. }
  70. }
  71. }