我一直在尝试在Java中实现一个GetAttributeRequest,它具有与以下C#代码类似的功能。
try
{
long epochWindowTime = ToEpochTimeInMilliseconds(DateTime.UtcNow.Subtract(this.SQSWindow));
int numberOfMessages = 0;
// 1st query to determine the # of Messages available in the queue
using (AmazonSQSClient client = new AmazonSQSClient(
this.AWSAccessKey, this.AWSSecretAccessKey,
ew AmazonSQSConfig() { ServiceURL = this.AWSSQSServiceUrl }))
{
// get the NumberOfMessages to optimize how to Receive all of the messages from the queue
GetQueueAttributesRequest attributesRequest = new GetQueueAttributesRequest();
attributesRequest.QueueUrl = this.QueueUrl;
attributesRequest.AttributeName.Add("ApproximateNumberOfMessages");
numberOfMessages = client.GetQueueAttributes(attributesRequest).GetQueueAttributesResult.ApproximateNumberOfMessages;
}
我对Java实现的尝试如下所示,
try
{
long epochWindowTime;
int numberOfMessages = 0;
Map<String, String> attributes;
// Setup the SQS client
AmazonSQS client = new AmazonSQSClient(new
ClasspathPropertiesFileCredentialsProvider());
client.setEndpoint(this.AWSSQSServiceUrl);
// get the NumberOfMessages to optimize how to
// Receive all of the messages from the queue
GetQueueAttributesRequest attributesRequest =
new GetQueueAttributesRequest();
attributesRequest.setQueueUrl(this.QueueUrl);
//attributesRequest.setAttributeNames();
attributes = client.getQueueAttributes(attributesRequest).
getAttributes();
numberOfMessages = Integer.valueOf(attributes.get(
"ApproximateNumberOfMessages")).intValue();
}catch (AmazonServiceException ase){
ase.printStackTrace();
}catch (AmazonClientException ace) {
ace.printStackTrace();
}
因为添加属性名称的Java AmazonSQS实现需要作为Collection我不明白我将如何正确添加“ApproximateNumberOfMessages”。
我也很好奇是否有更好的替代
new AmazonSQSClient(new ClasspathPropertiesFileCredentialsProvider());
更接近C#实现?原因是此方法旨在用作SDK的一部分,AWSAccessKey和AWSSecretAccessKey将作为单独配置文件的一部分。我是创建自己的AWSCredentialsProvider的唯一选择吗?
答案 0 :(得分:2)
withAttributeNames
接受vararg属性列表。
String attr = "ApproximateNumberOfMessages";
Map<String, String> attributes = client.getQueueAttributes(new GetQueueAttributesRequest(this.QueueUrl).withAttributeNames(attr)).getAttributes();
int count = Integer.parseInt(attributes.get(attr));
Java SDK有多种构造凭据的方法。如果您可以随时使用密钥,则使用BasicAWSCredentials
是最快的。
AmazonSQS client = new AmazonSQSClient(new BasicAWSCredentials("accessKey", "secretKey"));