翻译修改为队列

This commit is contained in:
2025-05-28 09:50:54 +08:00
parent d809b9f666
commit 78843cc244
8 changed files with 206 additions and 0 deletions
+72
View File
@@ -0,0 +1,72 @@
<?php
namespace app\queue\jobs;
use app\model\VehicleAr;
use app\model\VehicleEn;
use app\model\VehicleRu;
use app\service\TranslatorService;
use plugin\admin\app\model\Vehicle;
use support\Log;
class TranslationJob
{
protected array $payload;
public function __construct(array $payload)
{
$this->payload = $payload;
}
public function handle(): void
{
$pt = $this->payload;
$entityType = $pt['entityType'];
$sourceFields = $pt['sourceFields'];
$sourceLang = $pt['sourceLang'];
// $locale = $pt['locale'];
$id = $pt['id'];
$translator = new TranslatorService();
if($entityType == 'location'){
$translationModels = [
'cn' => \app\model\Location::class,
'en' => \app\model\LocationEn::class,
'ar' => \app\model\LocationAr::class,
'ru' => \app\model\LocationRu::class
];
}elseif($entityType == 'vehicle'){
$translationModels = [
'cn' => Vehicle::class,
'en' => VehicleEn::class,
'ar' => VehicleAr::class,
'ru' => VehicleRu::class
];
}
$languages = ['cn' => 'cn', 'en' => 'en', 'ar' => 'ar', 'ru' => 'ru'];
unset($languages[$sourceLang]);
foreach ($languages as $lang => $xflang) {
if($entityType =='location'){
$fields = $translator->location($sourceFields,$lang,$sourceLang);
}else{
$fields = $translator->vehicle($sourceFields,$lang,$sourceLang);
}
$translationModel = $translationModels[$xflang];
if(!empty($id)){
$translation = $translationModel::find($id);
}else{
$translation = new $translationModel();
}
$translation->fill($fields);
$res = $translation->save();
log::info('$languages save', [$res,$fields]);
}
}
}
+40
View File
@@ -0,0 +1,40 @@
<?php
namespace app\queue\redis;
use app\queue\jobs\TranslationJob;
use support\Log;
use Webman\RedisQueue\Consumer;
class Translator implements Consumer
{
// 要消费的队列名
public $queue = 'translator';
// 连接名,对应 plugin/webman/redis-queue/redis.php 里的连接`
public $connection = 'default';
// 消费
public function consume($data)
{
try {
// 无需反序列化
// var_export($data); // 输出 ['to' => 'tom@gmail.com', 'content' => 'hello']
$job = new TranslationJob($data);
$job->handle();
} catch (\Throwable $e) {
Log::error("TranslationService 异步任务异常: ".$e->getMessage());
}
}
// 消费失败回调
public function onConsumeFailure(\Throwable $e, $package)
{
echo "consume failure translator\n";
echo $e->getMessage() . "\n";
// 无需反序列化
var_export($package);
}
}