QueueTrait.php 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace crmeb\traits;
  12. use crmeb\utils\Queue;
  13. use think\facade\Env;
  14. /**
  15. * 快捷加入消息队列
  16. * Trait QueueTrait
  17. * @package crmeb\traits
  18. */
  19. trait QueueTrait
  20. {
  21. /**
  22. * 列名
  23. * @return null
  24. */
  25. protected static function queueName()
  26. {
  27. return null;
  28. }
  29. /**
  30. * 加入队列
  31. * @param $action
  32. * @param array $data
  33. * @param string|null $queueName
  34. * @return mixed
  35. */
  36. public static function dispatch($action, array $data = [], string $queueName = null)
  37. {
  38. if (sys_config('queue_open', 0) == 1 && Env::get('cache.driver', 'file') == 'redis') {
  39. $queue = Queue::instance()->job(__CLASS__);
  40. if (is_array($action)) {
  41. $queue->data(...$action);
  42. } else if (is_string($action)) {
  43. $queue->do($action)->data(...$data);
  44. }
  45. if ($queueName) {
  46. $queue->setQueueName($queueName);
  47. } else if (static::queueName()) {
  48. $queue->setQueueName(static::queueName());
  49. }
  50. return $queue->push();
  51. } else {
  52. $className = '\\' . __CLASS__;
  53. $res = new $className();
  54. if (is_array($action)) {
  55. $res->doJob(...$action);
  56. } else {
  57. $res->$action(...$data);
  58. }
  59. }
  60. }
  61. /**
  62. * 延迟加入消息队列
  63. * @param int $secs
  64. * @param $action
  65. * @param array $data
  66. * @param string|null $queueName
  67. * @return mixed
  68. */
  69. public static function dispatchSecs(int $secs, $action, array $data = [], string $queueName = null)
  70. {
  71. if (sys_config('queue_open', 0) == 1 && Env::get('cache.driver', 'file') == 'redis') {
  72. $queue = Queue::instance()->job(__CLASS__)->secs($secs);
  73. if (is_array($action)) {
  74. $queue->data(...$action);
  75. } else if (is_string($action)) {
  76. $queue->do($action)->data(...$data);
  77. }
  78. if ($queueName) {
  79. $queue->setQueueName($queueName);
  80. } else if (static::queueName()) {
  81. $queue->setQueueName(static::queueName());
  82. }
  83. return $queue->push();
  84. }
  85. }
  86. }