Amazon web services 在AmazonS3中逐行读取文件?
可以用AmazonS3逐行读取文件吗?我想让人们把大文件上传到某个地方,然后让一些代码(可能在Amazon上运行)逐行读取他们的文件并用它做一些事情,可能是以一种地图简化的多线程方式。或者一次只能加载1000行。。。有什么建议吗?Amazon S3确实支持范围请求,但其设计不是逐行读取文件Amazon web services 在AmazonS3中逐行读取文件?,amazon-web-services,amazon-s3,amazon-ec2,bigdata,Amazon Web Services,Amazon S3,Amazon Ec2,Bigdata,可以用AmazonS3逐行读取文件吗?我想让人们把大文件上传到某个地方,然后让一些代码(可能在Amazon上运行)逐行读取他们的文件并用它做一些事情,可能是以一种地图简化的多线程方式。或者一次只能加载1000行。。。有什么建议吗?Amazon S3确实支持范围请求,但其设计不是逐行读取文件 然而,它看起来可能是一个很好的适合你所寻找的。S3和使用的EC2实例之间的传输将非常快,然后您可以按照自己喜欢的方式分配工作。下面是一个PHP示例片段,它似乎满足了您的要求(获取file.txt中的前1000
然而,它看起来可能是一个很好的适合你所寻找的。S3和使用的EC2实例之间的传输将非常快,然后您可以按照自己喜欢的方式分配工作。下面是一个PHP示例片段,它似乎满足了您的要求(获取file.txt中的前1000行并将它们连接起来)。这有点遗憾,但这个想法可以用其他语言或使用其他技术实现。关键是要像对待windows或linux等任何其他文件系统一样对待S3,唯一的区别是使用S3密钥凭据并将文件路径设置为S3://your_directory\u tree/your_file.txt”:
下面是一个使用PHP 7和Laravel 5的简单示例,介绍如何从Amazon S3逐行读取文件: S3StreamReader.php
<?php
declare(strict_types=1);
namespace App\Helpers\Json;
use App\Helpers\S3StreamFactory;
use Generator;
use SplFileObject;
final class S3StreamReader
{
/**
* @var \App\Helpers\S3StreamFactory
*/
private $streamFactory;
/**
* @param \App\Helpers\S3StreamFactory $s3StreamFactory
*/
public function __construct(S3StreamFactory $s3StreamFactory)
{
$this->streamFactory = $s3StreamFactory;
}
/**
* @param string $filename
* @return \Generator
*/
public function get(string $filename): Generator
{
$file = new SplFileObject($this->streamFactory->create($filename), 'r');
while (!$file->eof()) {
yield $file->fgets();
}
}
}
即使不使用Laravel,也可以使用此代码,因为Laravel只使用包
<?php
declare(strict_types=1);
namespace App\Helpers\Json;
use App\Helpers\S3StreamFactory;
use Generator;
use SplFileObject;
final class S3StreamReader
{
/**
* @var \App\Helpers\S3StreamFactory
*/
private $streamFactory;
/**
* @param \App\Helpers\S3StreamFactory $s3StreamFactory
*/
public function __construct(S3StreamFactory $s3StreamFactory)
{
$this->streamFactory = $s3StreamFactory;
}
/**
* @param string $filename
* @return \Generator
*/
public function get(string $filename): Generator
{
$file = new SplFileObject($this->streamFactory->create($filename), 'r');
while (!$file->eof()) {
yield $file->fgets();
}
}
}
<?php
declare(strict_types=1);
namespace App\Helpers;
use League\Flysystem\AwsS3v3\AwsS3Adapter;
final class S3StreamFactory
{
/**
* @var \League\Flysystem\AwsS3v3\AwsS3Adapter
*/
private $adapter;
/**
* @param \League\Flysystem\AwsS3v3\AwsS3Adapter $adapter
*/
public function __construct(AwsS3Adapter $adapter)
{
$this->adapter = $adapter;
$adapter->getClient()->registerStreamWrapper();
}
/**
* @param string $filename
* @return string
*/
public function create(string $filename): string
{
return "s3://{$this->adapter->getBucket()}/{$filename}";
}
}
$lines = (new S3JsonReader(new S3StreamFactory(Storage::disk('s3')->getAdapter())))->get($sourceFile);
while ($lines->valid()) {
$line = $lines->current();
// do something with the current line...
$lines->next();
}