jessecascio / spider
MySQL 并行查询库
Requires
- php: >=5.4.0
- monolog/monolog: 1.11.0
- psr/log: ~1.0
Requires (Dev)
- phpunit/phpunit: ~3.7.0
This package is not auto-updated.
Last update: 2024-09-28 16:31:09 UTC
README
Spider 是一个PHP库,提供异步MySQL查询功能。虽然还有其他方法可以实现这一点,例如mysqlnd或pthread,但Spider的设计是为了除了与MySQL数据库的连接外,不依赖任何外部库。
使用方法
使用composer require jessecascio/spider安装最新版本
<?php use Spider\Connection; use Spider\Component; // build an array of queries $queries = array(); $queries[] = "SELECT SLEEP(FLOOR(0 + (RAND() * 1)))"; $queries[] = "SELECT SLEEP(FLOOR(0 + (RAND() * 1)))"; $queries[] = "SELECT SLEEP(FLOOR(0 + (RAND() * 1)))"; // create a MySQL Connection $connection = new Connection\MySQL($dbname, $usr, $pwd, $host, $port); // execute $web = new Component\Web($connection); $web->queries($queries); $web->crawl(); // proceed $web->results();
概念
由于PHP本身不支持线程或并行执行,Spider将查询放在自己的进程中进行处理。查询执行后,它被放置在临时存储中,直到所有查询完成。一旦所有查询完成,结果将返回到调用进程。
文档
配置
使用多个进程时,控制进程的数量和大小变得非常重要。此外,通过定义日志输出,可以在进程失败期间正确记录错误。
use Spider\Component; $config = new Component\Config(); $config->processes(5); $config->memory(100); // MB $config->trace('/path/to/log'); $web = new Component\Web($connection, $config);
或者可以从.ini文件中加载这些配置,以允许在不同环境中使用不同的设置。
use Spider\Component; $config = new Component\Config(); $config->parse('/path/to/file.ini');
存储
默认情况下,Spider将结果存储在临时MySQL表中。然而,还有其他Storage对象。例如,如果您希望结果存储在Memcached中,只需实例化正确的Storage对象即可。
use Spider\Component; use Spider\Storage; $memcached = new Storage\Memcached($host, $port); $config = new Component\Config(); $config->storage($memcached);
回调
通常,在查询完成后立即处理查询是有益的,而不是等待所有查询完成。这可以通过对所有查询应用单个回调或为查询键映射特定回调来实现。
// single callback $web->crawl(function($data) { // do work return $data; }); // multiple callbacks $queries = array(); $queries['users'] = "SELECT * FROM users"; $queries['orders'] = "SELECT * FROM orders" $web->queries($queries); $web->crawl([ 'users' => function ($data) { // do work on users data return $data; }, 'orders' => function ($data) { // do work on orders data return $data; } ])
注意事项
需要特别考虑运行进程的数量和大小。由于大多数Web服务器在资源上有限,您需要确保Spider不会启动太多进程,并且这些进程不会变得太大。这可以通过使用Component\Config对象来完成。
以这种方式运行查询会有额外的开销。不仅包括启动和监控进程的成本,还包括所有额外的临时存储读取和写入操作。通常,除非您的总查询时间超过1秒,否则Spider不会非常有用。Spider的一些良好用例包括查询大型水平星形表,其中每个组件都可以单独查询并返回给PHP进行聚合构建,或者跨多个分片进行查询。
应进行测试以确定最佳进程数/大小以及批量查询的典型返回时间。