2013-06-10 2 views
1

Я пытаюсь реализовать GetAttributeRequest в Java, который имеет схожие функции со следующим кодом C#.Создание GetAttributeRequest в Java

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 добавления имен атрибутов требует в качестве коллекции я не понимаю, как я хотел бы добавить «ApproximateNumberOfMessages» правильно.

Я также любопытно, если есть лучшая альтернатива к

new AmazonSQSClient(new ClasspathPropertiesFileCredentialsProvider()); 

, что ближе к реализации C#? Причина этого заключается в том, что этот метод предназначен для использования как часть SDK, а AWSAccessKey и AWSSecretAccessKey будут частью отдельного файла конфигурации. Является ли мой единственный способ создать свой собственный AWSCredentialsProvider?

+0

Является GetQueueAttributesRequest.withAttributeNames (...) правильная альтернатива attributesRequest.AttributeName.Add ("ApproximateNumberOfMessages") ;? – JME

ответ

1

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"));