CAddJob.Class.php 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. namespace Jobs\Controller;
  3. use Mall\Framework\Factory;
  4. use Mall\Framework\Core\ErrorCode;
  5. use Jobs\Controller\CJobObject;
  6. use Jobs\Controller\BaseController;
  7. use Jobs\Model\MQueue;
  8. use think\Error;
  9. class CAddJob extends BaseController
  10. {
  11. private $objMQueue;
  12. public function __construct()
  13. {
  14. parent::__construct();
  15. $config = Factory::config()->all();
  16. $this->config = $config;
  17. $this->logger = Factory::logs($this->config['logPath'] ?:'', $this->config['logSaveFileApp'] ?:'', $this->config['app_name'] ?:'');
  18. $this->objMQueue = MQueue::getQueue($this->config['job']['queue'], $this->logger);
  19. if(!is_object($this->objMQueue)){
  20. exit('初始化队列失败');
  21. }
  22. $this->objMQueue->setTopics($this->config['job']['topics']);
  23. }
  24. /**
  25. * 统一的添加队列任务入口
  26. */
  27. public function add()
  28. {
  29. /*$params['topicName'] = 'MyJob'; // 推送到那个队列主题中
  30. $params['topicClass'] = 'Jobs\Model\MTopic\Log\MLog'; // 往队列中添加得任务脚本类文件
  31. $params['topicMethon'] = 'push'; // 需要触发的类文件中的入口函数
  32. $params['topicMethonParams'] = [
  33. 'userCenterId' => 1,
  34. 'enterpriseId' => 15,
  35. 'createTime' => time(),//操作时间
  36. 'no' => 'Y12455f4545', // 来源:
  37. 'actionType'=> '新增订单', // 操作类型:登录/注册
  38. 'operationData' => [
  39. "goodsId"=>12,
  40. "name"=>"商品名称"
  41. ], //本次操作请求的数据(可空) json格式
  42. ]; // 携带过去的参数*/
  43. //接收参数
  44. $params['topicName'] = $this->request->param('topicName');
  45. $params['topicClass'] = $this->request->param('topicClass');
  46. $params['topicMethon'] = $this->request->param('topicMethon');
  47. $params['topicMethonParams'] = $this->request->param('topicMethonParams');
  48. foreach ($params as $key => $value){
  49. if(empty($value)){
  50. parent::sendOutput('参数'.$key.'值为空', ErrorCode::$paramError);
  51. }
  52. }
  53. $jobExtras = [ // 指定在队列中的执行优先级(redis版本队列不支持,带上就行)
  54. 'delay' => mt_rand(0, 100) * 1000,
  55. 'priority' => 1,
  56. ];
  57. if(!is_array($params['topicMethonParams'])){
  58. $params['topicMethonParams'] = json_decode(htmlspecialchars_decode($params['topicMethonParams'], ENT_QUOTES), true);
  59. }
  60. $job = new CJobObject($params['topicName'], $params['topicClass'], $params['topicMethon'], $params['topicMethonParams'], $jobExtras);
  61. $result = $this->objMQueue->push($params['topicName'], $job);
  62. if($result) {
  63. parent::sendOutput('添加队列成功');
  64. }
  65. parent::sendOutput('添加队列失败',ErrorCode::$redisWriteError);
  66. }
  67. }