16 Aralık 2022 Cuma

AWS S3 API AmazonS3ClientBuilder Sınıfı

Giriş
Şu satırı dahil ederiz
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
withEndpointConfiguration metodu
Localstack ile kullanılır

Örnek
Şöyle yaparız
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;

public AmazonS3 amazonS3() {
  AmazonS3 s3client = AmazonS3ClientBuilder
    .standard()
    .withCredentials(new AWSStaticCredentialsProvider(credentials()))
    .withEndpointConfiguration(
      getEndpointConfiguration("http://s3.localhost.localstack.cloud:4566"))
    .build();
    return s3client;
}

public AWSCredentials credentials() {
  ...
}

private AwsClientBuilder.EndpointConfiguration getEndpointConfiguration(String url) {
  return new AwsClientBuilder.EndpointConfiguration(url, Regions.US_EAST_1.getName());
}
withRegion metodu
Örnek
Şöyle yaparız
import com.amazonaws.auth.AWSCredentials
import com.amazonaws.auth.AWSStaticCredentialsProvider
import com.amazonaws.auth.BasicAWSCredentials
import com.amazonaws.services.s3.AmazonS3
import com.amazonaws.services.s3.AmazonS3ClientBuilder

@Configuration public class AmazonConfig {     
  @Value("${AWS_SECRET}")     
  private String awsSecret;     
  @Value("${AWS_KEY}")     
  private String awsKey;     
  
  @Bean     
  public AmazonS3 s3() {         
    AWSCredentials awsCredentials = new BasicAWSCredentials(awsKey,awsSecret);         
    return AmazonS3ClientBuilder.standard()                 
      .withCredentials(new AWSStaticCredentialsProvider(awsCredentials))
      .withRegion("PUT_YOUR_REGION_HERE")                 
      .build();     
  } 
}
withCredentials metodu - AWSStaticCredentialsProvider
Örnek
Şöyle yaparız
@Configuration
public class AwsS3Config {
    @Value("${amazon.aws.access-key}")
    private String accessKeyId;

    @Value("${amazon.aws.secret-key}")
    private String accessKeySecret;

    @Value("${amazon.aws.region}")
    private String s3RegionName;

  @Bean
  public AmazonS3 getAmazonS3Client() {
    final BasicAWSCredentials basicAwsCredentials = 
      new BasicAWSCredentials(accessKeyId, accessKeySecret);
    // Get Amazon S3 client and return the S3 client object
    return AmazonS3ClientBuilder
      .standard()
      .withCredentials(new AWSStaticCredentialsProvider(basicAwsCredentials))
      .withRegion(s3RegionName)
      .build();
    }
}

Hiç yorum yok:

Yorum Gönder