9 Şubat 2023 Perşembe

SpringCloud AWS S3

Maven
Şöyle yaparız
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>io.awspring.cloud</groupId>
            <artifactId>spring-cloud-aws-dependencies</artifactId>
            <version>3.0.1</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
Sonra şöyle yaparız
<dependencies>
  <dependency>
    <groupId>io.awspring.cloud</groupId>
    <artifactId>spring-cloud-aws-starter-s3</artifactId>
  </dependency>
</dependencies>
application.properties
Açıklaması şöyle
There are two ways to communicate with the S3 bucket.

1. Path style URLs.
2. Virtual Hosted style URLs.

The path style URLs were the older mechanism which used the format https://s3.region-code.amazonaws.com/bucket-name.

While the virtual hosted URL uses the format https://bucket-name.s3.region-code.amazonaws.com

The path style URLs will soon be deprecated and LocalStack already supports the virtual hosted style URLs by default.
Örnek
Şöyle yaparız.
spring:
  cloud:
    aws:
      s3:
        endpoint: http://s3.localhost.localstack.cloud:4566
        region: eu-central-1
      credentials:
        access-key: none
        secret-key: none
      region:
        static: eu-central-1
Örnek
Şöyle yaparız. Bizim için bir tane AmazonS3  bean yaratılır
spring.cloud.aws.credentials.access-key=dummy
spring.cloud.aws.credentials.secret-key=dummy
spring.cloud.aws.s3.region=eu-west-1
Örnek
Şöyle yaparız
@RestController
public class WebController {

  @Value("s3://mybucket/samplefile.txt")
  private Resource s3SampleFile;

  @GetMapping("/data")
  public ResponseEntity<String> getData() {
    try {
      return ResponseEntity.ok(s3SampleFile.getContentAsString(StandardCharsets.UTF_8));
    } catch (Exception e) {
      return ResponseEntity.internalServerError()
                    .body("Could not fetch content");
    }
  }

  @PostMapping("/data")
  public ResponseEntity<String> putData(@RequestBody String data) throws IOException {
    try (OutputStream outputStream = ((S3Resource) s3SampleFile).getOutputStream()) {
      outputStream.write(data.getBytes(StandardCharsets.UTF_8));
    }
    return ResponseEntity.ok(data);
  }
}
AmazonS3  Sınıfı
putObject metodu
Örnek
Şöyle yaparız
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.ObjectMetadata;

@Service
@AllArgsConstructor
public class UploadService {

  private final AmazonS3 s3Client;

  public String uploadFile(InputStream file, String fileName) {
    String bucketName = ...;
    s3Client.putObject(bucketName, fileName, file, new ObjectMetadata());
    return s3Client.getUrl(bucketName, fileName).getPath();
  }
}
Unit Test
LocalStackContainer kullanılır

Örnek
Şöyle yaparız
@Testcontainers
@SpringBootTest
@AutoConfigureMockMvc
class SpringBootWithS3ApplicationTests {

  @Autowired
  private MockMvc mockMvc;

  @Value("s3://mybucket/samplefile.txt")
  private Resource s3SampleFile;

  @Container
  private static LocalStackContainer localStackContainer =
    new LocalStackContainer(DockerImageName.parse("localstack/localstack"))
    // to create secrets on startup
    .withCopyFileToContainer(MountableFile.forClasspathResource("script.sh", 0775),
                             "/etc/localstack/init/ready.d/")
    .withServices(LocalStackContainer.Service.S3);

  @BeforeAll
  static void beforeAll() throws IOException, InterruptedException {
    System.setProperty("spring.cloud.aws.s3.endpoint",
      "http://s3.localhost.localstack.cloud:" + localStackContainer.getMappedPort(4566));
    System.setProperty("spring.cloud.aws.s3.region", "eu-central-1");
    System.setProperty("spring.cloud.aws.credentials.access-key", "none");
    System.setProperty("spring.cloud.aws.credentials.secret-key", "none");
  }
 ...
}




Hiç yorum yok:

Yorum Gönder