FollowServiceWarmCache.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. namespace App\Jobs\FollowPipeline;
  3. use Illuminate\Bus\Queueable;
  4. use Illuminate\Contracts\Queue\ShouldBeUnique;
  5. use Illuminate\Contracts\Queue\ShouldQueue;
  6. use Illuminate\Foundation\Bus\Dispatchable;
  7. use Illuminate\Queue\InteractsWithQueue;
  8. use Illuminate\Queue\SerializesModels;
  9. use App\Services\AccountService;
  10. use App\Services\FollowerService;
  11. use Cache;
  12. use DB;
  13. use App\Profile;
  14. class FollowServiceWarmCache implements ShouldQueue
  15. {
  16. use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
  17. public $profileId;
  18. public $tries = 5;
  19. public $timeout = 5000;
  20. public $failOnTimeout = false;
  21. /**
  22. * Create a new job instance.
  23. *
  24. * @return void
  25. */
  26. public function __construct($profileId)
  27. {
  28. $this->profileId = $profileId;
  29. }
  30. /**
  31. * Execute the job.
  32. *
  33. * @return void
  34. */
  35. public function handle()
  36. {
  37. $id = $this->profileId;
  38. $account = AccountService::get($id, true);
  39. if(!$account) {
  40. Cache::put(FollowerService::FOLLOWERS_SYNC_KEY . $id, 1, 604800);
  41. Cache::put(FollowerService::FOLLOWING_SYNC_KEY . $id, 1, 604800);
  42. return;
  43. }
  44. DB::table('followers')
  45. ->select('id', 'following_id', 'profile_id')
  46. ->whereFollowingId($id)
  47. ->orderBy('id')
  48. ->chunk(200, function($followers) use($id) {
  49. foreach($followers as $follow) {
  50. FollowerService::add($follow->profile_id, $id);
  51. }
  52. });
  53. DB::table('followers')
  54. ->select('id', 'following_id', 'profile_id')
  55. ->whereProfileId($id)
  56. ->orderBy('id')
  57. ->chunk(200, function($followers) use($id) {
  58. foreach($followers as $follow) {
  59. FollowerService::add($id, $follow->following_id);
  60. }
  61. });
  62. Cache::put(FollowerService::FOLLOWERS_SYNC_KEY . $id, 1, 604800);
  63. Cache::put(FollowerService::FOLLOWING_SYNC_KEY . $id, 1, 604800);
  64. $profile = Profile::find($id);
  65. if($profile) {
  66. $profile->following_count = DB::table('followers')->whereProfileId($id)->count();
  67. $profile->followers_count = DB::table('followers')->whereFollowingId($id)->count();
  68. $profile->save();
  69. }
  70. AccountService::del($id);
  71. return;
  72. }
  73. }