InitKeyword.php
3.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
<?php
namespace App\Console\Commands;
use App\Models\Com\NoticeLog;
use App\Models\Product\Keyword;
use App\Models\RouteMap\RouteMap;
use App\Services\ProjectServer;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
/**
* Class InitKeyword
* @package App\Console\Commands
*/
class InitKeyword extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'init_keyword';
/**
* The console command description.
*
* @var string
*/
protected $description = '批量导入关键字生成路由';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* @return bool
*/
public function handle()
{
while (true){
$notice_id = $this->getTask();
if (empty($notice_id)) {
sleep(30);
continue;
}
try {
$this->output(' taskID: ' . $notice_id . ' start');
$this->bind($notice_id);
$this->output(' taskID: ' . $notice_id . ' end');
} catch (\Exception $e) {
$this->output(' taskID: ' . $notice_id . ', error: ' . $e->getMessage());
}
sleep(2);
}
return true;
}
/**
* 处理子任务
* @param $notice_id
* @return bool
* @throws \Exception
*/
public function bind($notice_id)
{
$notice = NoticeLog::where(['id' => $notice_id])->first();
if (empty($notice) || $notice->type != NoticeLog::TYPE_INIT_KEYWORD || $notice->status != NoticeLog::STATUS_PENDING){
return true;
}
ProjectServer::useProject($notice['data']['project_id']);
$keyword = Keyword::whereNull('route')->get();
foreach ($keyword as $val) {
$this->output(' keywordID: ' . $val->id . ', title: ' . $val->title);
try {
$route = RouteMap::setRoute($val['title'],RouteMap::SOURCE_PRODUCT_KEYWORD, $val->id, $notice['data']['project_id']);
$val->route = $route;
$val->save();
} catch (\Exception $e) {
$this->output(' keywordID: ' . $val->id . ', title: ' . $val->title . ', error: ' . $e->getMessage());
}
}
$notice->status = NoticeLog::STATUS_SUCCESS;
$notice->save();
DB::disconnect('custom_mysql');
return true;
}
/**
* 获取需要处理的任务
* @return mixed
*/
public function getTask()
{
$key = 'notice_log_type_keyword';
$notice_id = Redis::rpop($key);
if ($notice_id){
return $notice_id;
}
$ids = NoticeLog::where('type', NoticeLog::TYPE_INIT_KEYWORD)->where('status', NoticeLog::STATUS_PENDING)->limit(100)->pluck('id');
foreach ($ids as $id) {
Redis::lpush($key, $id);
}
$notice_id = Redis::rpop($key);
return $notice_id;
}
/**
* 输出message
* @param $message
*/
public function output($message)
{
echo date('Y-m-d H:i:s') . ' ' . $message . PHP_EOL;
}
}