amphp / dns

Async DNS resolution for PHP based on Amp.
https://amphp.org/dns
MIT License
157 stars 32 forks source link

Async example? #111

Closed dragonattack closed 4 months ago

dragonattack commented 1 year ago

Can you please share a link to example of async dns query loop of 500 domains for example.

Of course, simply changing Dns\resolve($domain) in /examples/benchmark.php to:

        $host = Amp\Future\awaitFirst([
            Amp\async(fn() => Dns\resolve($domain, Dns\DnsRecord::A)),
        ]);

doesn't make any difference.

trowski commented 11 months ago

Apologies for the (very) late reply, this issue slipped under my radar.

To perform multiple queries simultaneously (or multiple of any operation which will await I/O), use Amp\async() in conjunction with Amp\Future\await() to await the set of futures created from async().

$listOfDomains = [...]; // List of domain names to query.

$futures = [];
foreach ($listOfDomains as $domain) {
    $futures[$domain] = Amp\async(Dns\resolve(...), $domain);
}

$resolvedRecords = Amp\Future\await($futures);

Note it may not be a good idea to initiate 500 DNS requests simultaneously. As with many simultaneous async operations, it may be a good idea to throttle the number of simultaneous requests in-flight. See amphp/sync and amphp/pipeline for tools to do just this.