2015-12-15 45 views
-1

我在當前項目中使用awssqs。我需要知道如何使用SQSConnectionFactory來設置訪問密鑰和密鑰(從屬性文件讀取)。使用SQSConnectionFactory設置AWS_ACCESS_KEY_ID和AWS_SECRET_KEY的值

請在下面找到我的代碼:

public void createConnectionFactory() throws JMSException{ 
    try { 
     SQSConnectionFactory connectionFactory = SQSConnectionFactory.builder() 
      .withRegion(Region.getRegion(Regions.US_EAST_1)) 
      .withAWSCredentialsProvider(new EnvironmentVariableCredentialsProvider()) 
      .build(); 

      // Create the connection. 
      SQSConnection connection = connectionFactory.createConnection(); 
    } 
    catch (JMSException ex) 
    { 
     throw ex; 
    } 
} 

我試圖尋找,通過它我可以設置方法,但找不到任何。如何從這裏開始?我應該爲基本身份驗證編寫另一種方法並在此處調用它,還是有更好的方法來執行此操作?

回答

0

謝謝,我發現了錯誤!

下面是我做了,現在它的做工精細的變化

private BasicAWSCredentials credentials; 

public void createConnectionFactory() throws JMSException,FileNotFoundException{ 
try { 

     Properties properties = new Properties(); 
     properties.load(new FileInputStream("/src/main/resources/AwsCredentials.properties")); 
     this.credentials = new BasicAWSCredentials(properties.getProperty("accessKey"), 
       properties.getProperty("secretKey")); 

     SQSConnectionFactory connectionFactory = 
       SQSConnectionFactory.builder() 
         .withRegion(Region.getRegion(Regions.US_EAST_1)) 
         .withAWSCredentialsProvider(new EnvironmentVariableCredentialsProvider()) 
         .build(); 

     // Create the connection. 
     SQSConnection connection = connectionFactory.createConnection(credentials.getAWSAccessKeyId(),credentials.getAWSSecretKey()); 

    } 
    catch (JMSException ex) 
    { 
     throw ex; 
    } 
    catch (FileNotFoundException ex) 
    { 
     throw ex; 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
+0

我是新來的StackOverflow,我格式化技能的工作。謝謝您的幫助! –

1

最好是使用默認的憑據提供鏈,它允許supply credentials in multiple ways

總之它允許一個非常靈活的配置包括您的開發團隊以及在多種環境下部署到雲時,以及multi-region setup

可以包含這樣的豆:

<bean id="awsCredentialsProviderBean" class="com.amazonaws.auth.DefaultAWSCredentialsProviderChain"> 
</bean> 
<bean id="awsConnectionFactoryBuilder" class="com.amazon.sqs.javamessaging.SQSConnectionFactory$Builder"> 
    <property name="regionName" value="${aws.region}"/> 
    <property name="numberOfMessagesToPrefetch" value="5"/> 
    <property name="awsCredentialsProvider" ref="awsCredentialsProviderBean"/> 
</bean> 

或用java

@Bean 
public AWSCredentialsProviderChain awsCredentials() { 
    return new DefaultAWSCredentialsProviderChain(); 
} 
+1

請使用代碼塊格式化您的代碼。 :) – GrumpyCrouton