我在 amazon 存储桶中有一个文件夹,其中包含一些对象。
如何获取最早添加的对象?
public FileMetaData Poll()
{
var config = new AmazonS3Config();
config.ServiceURL = "s3.amazonaws.com";
config.CommunicationProtocol = Protocol.HTTP;
string bucketName = "bucketname1";
string accessKey = "accesskey1";
string secretKey = "secretkey1";
Amazon.S3.AmazonS3 client = AWSClientFactory.CreateAmazonS3Client(accessKey,
secretKey,
config);
var request = new GetObjectRequest();
request.WithBucketName(bucketName);
// how to get the oldest object?
GetObjectResponse response = client.GetObject(request);
// todo
return null;
}
我已经尝试了下面的代码,它工作正常,但问题是它加载所有对象然后找到最旧的,我认为这是一个糟糕的做法:
var request = new ListObjectsRequest()
.WithBucketName(bucketName)
.WithPrefix(this._folderPath);
ListObjectsResponse response = client.ListObjects(request);
S3Object s3Object = response.S3Objects
.Where(p => !p.Key.EndsWith("_$folder$"))
.OrderBy(k => k.LastModified).FirstOrDefault();
var getObjectRequest = new GetObjectRequest()
.WithBucketName(bucketName)
.WithKey(s3Object.Key);
GetObjectResponse getObjectResponse = client.GetObject(getObjectRequest);
// provider
string provider = getObjectResponse.Metadata.Get("x-amz-meta-provider");
string site = getObjectResponse.Metadata.Get("x-amz-meta-sitename");
string identifier = s3Object.Key.Remove(0, this._folderPath.Length);
string xmlData = new StreamReader(getObjectResponse.ResponseStream, true).ReadToEnd();
return new FileMetaData()
{
Identifier = identifier,
Provider = provider,
SiteName = site,
XmlData = xmlData
};
您的代码看起来不错。您只会为“列出对象请求”损失几秒钟,但据我所知这是强制性的。
我在您的代码中看到的一个问题是您没有处理每个请求返回的最大键数为 1000 的事实。如果您的键数可能多于此数量,那么您必须检查列表是否被截断,将请求标记更改为下一个并发出更多请求。
var request = new ListObjectsRequest()
.WithBucketName(bucketName)
.WithPrefix(this._folderPath);
ListObjectsResponse response;
S3Object s3Object = null;
do
{
response = client.ListObjects(request);
S3Object tempS3Object = response.S3Objects
.Where(p => !p.Key.EndsWith("_$folder$"))
.OrderBy(k => k.LastModified).FirstOrDefault();
if (s3Object != null)
{
if (s3Object.LastModified < tempS3Object.LastModified)
s3Object = tempS3Object;
}
else s3Object = tempS3Object;
request.Marker = response.NextMarker;
} while (response.IsTruncated);
var getObjectRequest = new GetObjectRequest()
.WithBucketName(bucketName)
.WithKey(s3Object.Key);
GetObjectResponse getObjectResponse = client.GetObject(getObjectRequest);
// provider
string provider = getObjectResponse.Metadata.Get("x-amz-meta-provider");
string site = getObjectResponse.Metadata.Get("x-amz-meta-sitename");
string identifier = s3Object.Key.Remove(0, this._folderPath.Length);
string xmlData = new StreamReader(getObjectResponse.ResponseStream, true).ReadToEnd();
return new FileMetaData()
{
Identifier = identifier,
Provider = provider,
SiteName = site,
XmlData = xmlData
};
我是一名优秀的程序员,十分优秀!