2

ファイルからデータのチャンクを読み取り、それらのチャンクを残りのAPIに送信し、EOFまで続行するループがある状況がありますが、これをループ内で非同期にしたいので、私はAPI が応答して次のチャンクを読み取るまで待つ必要はありません。これに対する解決策が見つからないため、またはこれらのライブラリがどのように使用されることになっているのか理解できないため、Amphp と ReactPHP を調べています。ここに私がやっていることの疑似があります。

<?php

while($file.read()){

   $chunk = getNextChunk();

   sendChunkAsync($chunk);

}

function getNextChunk(){

   echo "reading next chunk";

   // read next chunk of data

}

amphp でのサンプル

function sendChunkAsync($chunk){

Loop::run(function () {

    $uri =  "https://testapi.com/api";

    $client = new DefaultClient;

    try {

            $promises = $client->request($uri);


        $responses = yield $promises;

       echo "chunk processed";

    } catch (Amp\Artax\HttpException $error) {

        // log error

        // $error->getMessage() . PHP_EOL;
    }
});

}

この場合、私は(APIからの応答を取得するよりもチャンクを読み取る方が速い場合)、このようなことを期待します。この文学を取り上げないでください。説明しようとしています。

次のチャンクを読む

次のチャンクを読む

処理されたチャンク

次のチャンクを読む

処理されたチャンク

処理されたチャンク

4

2 に答える 2

1

ライブラリについてはよく知っているので、React を使用しますが、同様の方法で動作します。

編集:更新、コメントを参照

これはファイルを読み取り、データのチャンクを受信するたびに、API 呼び出しを作成してデータを送信します。

<?php

require_once __DIR__ . '/vendor/autoload.php';

function async_send($config, $file, callable $proccessor)
{

    $config['ssl'] = true === $config['ssl'] ? 's' : '';
    $client = new \GuzzleHttp\Client([
        'base_uri' => 'http' . $config['ssl'] . '://' . $config['domain'] . '/rest/all/V1/',
        'verify' => false,
        'http_errors' => false
    ]);
    $loop = \React\EventLoop\Factory::create();
    $filesystem = \React\Filesystem\Filesystem::create($loop);
    $filesystem->getContents($file)->then(function($contents) use ($config, $proccessor, $client) {
        $contents = $proccessor($contents);
        $client->post($config['uri'], ['body' => $contents]);
    });
}

$config = [
    'domain' => 'example.com',
    'ssl' => true
];
//somewhere later
$configp['uri'] = 'products';
async_send($configp, __DIR__ . 'my.csv', function ($contents) {
    return json_encode($contents);
});
于 2018-12-04T18:34:34.853 に答える