简体   繁体   English

如何在 Spring Boot 应用程序中初始化 AWS SDK?

[英]How to initialize AWS SDK in spring boot application?

I am writing a spring boot application which reads messages from SQS.我正在编写一个从 SQS 读取消息的 Spring Boot 应用程序。 I am able to run the application using environment variables AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY .我能够使用环境变量AWS_ACCESS_KEY_IDAWS_SECRET_ACCESS_KEY运行应用程序。 However, I was wondering it would be simpler to pass this configuration via a file similar to application.properties .但是,我想知道通过类似于application.properties的文件传递此配置会更简单。 How to achieve this?如何实现这一目标?

In spring boot application you can access properties mentioned in application.yml file with @value annotation.在 spring boot 应用程序中,您可以使用@value注释访问application.yml文件中提到的属性。 You can create a service like this:您可以创建这样的服务:

@Service
public class AmazonClient {  
    private AmazonSQS sqsClient;

    @Value("${amazonProperties.accessKey}")
    private String accessKey;
    @Value("${amazonProperties.secretKey}")
    private String secretKey;

    @PostConstruct
    private void initializeAmazon() {
        BasicAWSCredentials awsCredentials = new BasicAWSCredentials(this.accessKey, this.secretKey);
        this.sqsClient = AmazonSQSClientBuilder
                .standard()
                .withCredentials(new AWSStaticCredentialsProvider(awsCredentials))
                .build();

    }
}

In application.yml file:application.yml文件中:

amazonProperties:
   accessKey: <your_access_key>
   secretKey: <your_secret_key>

If you utilise spring cloud AWS with spring boot, some AWS clients (like SQS and SNS) and EC2 meta data can be setup for you via auto-configuration.如果您在 Spring Boot 中使用 Spring Cloud AWS,则可以通过自动配置为您设置一些 AWS 客户端(如 SQS 和 SNS)和 EC2 元数据。 For local testing you can use static providers set via application properties.对于本地测试,您可以使用通过应用程序属性设置的静态提供程序。

Documentation: https://cloud.spring.io/spring-cloud-static/spring-cloud-aws/2.0.1.RELEASE/single/spring-cloud-aws.html#_spring_boot_auto_configuration文档: https : //cloud.spring.io/spring-cloud-static/spring-cloud-aws/2.0.1.RELEASE/single/spring-cloud-aws.html#_spring_boot_auto_configuration

Specifically, you can set properties such as cloud.aws.credentials.accessKey and cloud.aws.region.static .具体来说,您可以设置cloud.aws.credentials.accessKeycloud.aws.region.static等属性。

There are couple of ways you can manage it.有几种方法可以管理它。

  1. You can configure aws configure (on your local or Linux machine) which will be required your secret key and access key then you don't need to pass these in api by default constructor you can create connection as it will pick secret key, etc from system path.您可以配置 aws configure(在您的本地或 Linux 机器上),这将需要您的密钥和访问密钥,然后您不需要在默认构造函数中在 api 中传递这些您可以创建连接,因为它将从中选择密钥等系统路径。

     AmazonSQS sqs = AmazonSQSClientBuilder.defaultClient();

How to configure aws cli 如何配置 aws cli

  1. If you are using AWS EC2 then when you create ec2 instance, make sure assign it a role which has permission to SQS then you don't need to even configure on that machine.如果您使用的是 AWS EC2,那么在创建 ec2 实例时,请确保为其分配一个具有 SQS 权限的角色,那么您甚至不需要在该机器上进行配置。

  2. You can define your ACCESS KEY AND SECRET KEY in application/properties and load in sqs class by @Value .您可以在application/properties定义您的 ACCESS KEY 和 SECRET KEY 并通过@Value在 sqs 类中@Value

  3. You can create aws.keys in your classpath and can load properties from a file.您可以在classpath创建aws.keys并可以从文件加载属性。

  4. Of course you can define them as constant in your Constant class .当然,您可以在Constant class中将它们定义为常量。

Change for aws sdk 2.0 is as follows.. aws sdk 2.0 的变化如下..

    AwsBasicCredentials awsCreds = AwsBasicCredentials.create(this.accessKey, this.secretKey);

    S3Client client = S3Client.builder().region(Region.AP_SOUTH_1)
            .credentialsProvider(StaticCredentialsProvider.create(awsCreds))
            .build();

I avoid using property file, rather use Credential Provider Chain more here, AWS Documentation我避免使用属性文件,而是在这里更多地使用凭证提供者链, AWS 文档

Although, property file can also be overridden by environment variable, but If I always need to do so, why should I even mention it in property file.虽然,属性文件也可以被环境变量覆盖,但是如果我总是需要这样做,我为什么还要在属性文件中提到它。 Also I would also like to avoid from committing keys in code ( in properties file)此外,我还想避免在代码中提交密钥(在属性文件中)

Moreover, when I look at my CI/CD , it makes sense and also easy to just set environment variable for your Spring Boot Environment - specially on cloud.此外,当我查看我的 CI/CD 时,为您的 Spring Boot 环境设置环境变量是有意义且容易的 - 特别是在云上。 If using docker env, even more easier and much more cleaner.如果使用 docker env,则更容易、更干净。

If you are running your service in EC2(mostly non-development environments) then there is no need for configuring the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY , because of EC2ContainerCredentialsProviderWrapper the credentials will be automatically fetched from the AWS container.如果您在 EC2(主要是非开发环境)中运行您的服务,则无需配置AWS_ACCESS_KEY_IDAWS_SECRET_ACCESS_KEY ,因为EC2ContainerCredentialsProviderWrapper将自动从 AWS 容器中获取凭证。

    @Profile({"non-prod", "prod"})
    @Bean("AWSCredentialsProvider")
    public AWSCredentialsProvider amazonAWSCredentialsProvider() {
        return new EC2ContainerCredentialsProviderWrapper();
    }

NOTE: If you decided to use any of below mentioned AWSCredentialsProviderChain then use AWSCredentialsProvider and not AWSStaticCredentialsProvider otherwise you will endup with com.amazonaws.AmazonServiceException: The security token included in the request is expired exception.注意:如果您决定使用AWSCredentialsProviderChain任何AWSCredentialsProviderChain那么请使用AWSCredentialsProvider而不是AWSStaticCredentialsProvider否则您最终会遇到com.amazonaws.AmazonServiceException: The security token included in the request is expired异常。

  • DefaultAWSCredentialsProviderChain DefaultAWSCredentialsProviderChain
  • EnvironmentVariableCredentialsProvider EnvironmentVariableCredentialsProvider
  • SystemPropertiesCredentialsProvider SystemPropertiesCredentialsProvider
  • ProfileCredentialsProvider ProfileCredentialsProvider
  • EC2ContainerCredentialsProviderWrapper EC2ContainerCredentialsProviderWrapper

If the application running outside the AWS then you can use AWSStaticCredentialsProvider with hard coded values of awsAccessKeyId and awsSecretAccessKey如果应用程序在 AWS 之外运行,那么您可以使用AWSStaticCredentialsProviderawsAccessKeyIdawsSecretAccessKey硬编码值

aws.awsAccessKeyId:AWS_ACCESS_KEY_ID
aws.awsSecretAccessKey:AWS_SECRET_ACCESS_KEY
    @Value("${aws.awsAccessKeyId:}")
    private String awsAccessKeyId;

    @Value("${aws.awsSecretAccessKey:}")
    private String awsSecretAccessKey;

    @Profile({"dev", "test"})
    @Bean("AWSCredentialsProvider")
    public AWSStaticCredentialsProvider amazonAWSCredentialsProviderDevelopment() {
        return new AWSStaticCredentialsProvider(new BasicAWSCredentials(
                awsAccessKeyId, awsSecretAccessKey));
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 Spring Boot 应用程序中使用 aws sdk 是一个合理的选择 - Using the aws sdk be a reasonable option in a spring boot application 无法在Spring Boot Application中使用AWS SDK(套接字不是由此工厂创建的) - Cannot use AWS SDK in Spring Boot Application (Socket not created by this factory) 如何使用 Spring 引导应用程序初始化 log4j? - How to initialize log4j with Spring Boot application? 如何将spring boot初始化为项目? - How to initialize spring boot to project? 如何在春季初始化应用程序? - How to Initialize the application in spring? 数据源无法通过Spring Boot应用程序初始化? - Datasource not able to initialize via Spring boot application? 如何将带有自定义.properties文件的Spring Boot应用程序部署到AWS ElasticBeanstalk? - How to deploy a Spring Boot application with custom .properties files to AWS ElasticBeanstalk? 如何将Spring Boot应用程序大战部署到AWS Elastic Beanstalk? - How to deploy Spring Boot application war to AWS Elastic Beanstalk? 如何在我的Spring Boot应用程序中从AWS访问环境变量 - How to access Environment Variable from AWS in my spring boot application 如何使用spring-boot初始化ActiveMQ的SystemUsage? - How to initialize SystemUsage of ActiveMQ with spring-boot?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM