swoole图片下载实践

下载图片文件到本地,上传到阿里云并将记录更新到数据

/**
 * 下载图片文件上传到阿里云并更新数据库
 * @param $imageSrcList
 */
public static function downloadImageFileNew($imageSrcList)
{
#进入的数组格式为{"images":["图片地址1":"排序值2","图片地址2":"排序值1","图片地址3":"排序值3"],"product_id":"id"}
    if (empty($imageSrcList)) {
        return;
    }
    $images = $imageSrcList['images'];
    $productId = $imageSrcList['product_id'];

    self::checkSavePath(); # 检查图片存储位置
    $path = self::getImageSavePath(); # 获取图片存储位置

    $chan = new \Swoole\Coroutine\Channel(50); # 初始化协程channel,设置容量为50,根据业务调整
    $chanListCount = 0; # 通道数量,保证通道全部结束
    foreach ($images as $imageUrl => $sort) {
        if (empty($imageUrl)) {
            continue;
        }

        go(function () use ($imageUrl, $sort, $path, $productId, $chan) {
            $imageType = 'jpg';
            $urlName = md5(md5(time()) . rand(1, 100) . md5($imageUrl));
            $imageName = "{$urlName}.$imageType";
            $savePath = $path . $imageName;
            $imageId = '';
            if ($download = ProductUploadService::downloadFile($imageUrl, $savePath)) { #图片下载到本地
                $imageId = self::uploadFileAliYun($savePath, $imageName); # 图片上传到阿里云
            }
            $chan->push(['complete' => $download, 'image_url' => $imageUrl, 'sort' => $sort, 'imageId' => $imageId]); # 打入通道
        });

            $chanListCount++;
    }

    go(function () use (&$chanListCount, $chan, $productId) {
        $imageList = [];
        while ($chanListCount > 0) { # 从通道中一一取出
            $res = $chan->pop(); # 由数量判断,否则可能造成协程一直等待
            if ($res['imageId']) {
                $imageList[$productId][md5($res['image_url'])] = [
                    'sort'     => $res['sort'],
                    'image_id' => $res['imageId']
                ];
            }
        }
        $imageList = Util::array2dSort($imageList[$productId], 'sort'); # 根据sort排序
        $productUpdateList[] = [
            'id'        => $productId,
            'image_ids' => implode(',', array_column($imageList, "image_id"))
        ];
        $variantList = SailShopProductVariant::find()->select('id,product_id,image_tmp_url')->where(['product_id' => $productId])->asArray()->all();
        $variantUpdateList = [];
        foreach ($variantList as $item) {
            if (empty($item['image_tmp_url'])) continue;
            $key = md5($item['image_tmp_url']);
            $imageId = $imageList[$key]['image_id'] ?? 0;
            if (!$imageId) continue;
            $variantUpdateList[] = [
                'id'       => $item['id'],
                'image_id' => $imageId
            ];
        }
        !empty($productUpdateList) && SailShopProduct::bulkInsertOnDuplicate($productUpdateList);
        !empty($variantUpdateList) && SailShopProductVariant::bulkInsertOnDuplicate($variantUpdateList);
    });
    \swoole_event::wait();
    self::deleteCacheFile(); # 删除本地文件夹
}

 主要练习熟练swoole语法和协程使用。

你可能感兴趣的:(php)