Redis.php 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. <?php
  2. namespace App\Module\DelayQueue;
  3. use App\Module\DelayQueue\Entity\Queue;
  4. use App\Module\DelayQueue\Job\Job;
  5. class Redis
  6. {
  7. const E_KEY = 'delay_queue';
  8. /**
  9. * 添加队列
  10. *
  11. * @param array $callback
  12. * @param $runParam
  13. * @param int $delay
  14. * @return int
  15. */
  16. static public function addQueue($callback, $runParam, $delay = 3): int
  17. {
  18. if (!is_callable($callback)) {
  19. throw new \Exception('callback is not callable');
  20. }
  21. $key = self::E_KEY . $callback[0] . $callback[1].md5(serialize($runParam));
  22. /**
  23. * @var \Redis $a
  24. */
  25. $a = \Illuminate\Support\Facades\Redis::client();
  26. if ($a->exists($key)) {
  27. return 0;
  28. }
  29. $delay= max(2, $delay);
  30. $a->setex($key, max(1,$delay-1), 1);
  31. $q = new Queue();
  32. $q->create_ts = time();
  33. $q->delay_ts = $delay;
  34. $q->runClass = $callback[0];
  35. $q->runMethod = $callback[1];
  36. $q->runParam = $runParam;
  37. Job::dispatch($q)->delay($delay);
  38. return 1;
  39. }
  40. }