Trabalhando com S3 e armazenamentos em nuvem em Kotlin: AWS SDK e Ktor S3 Client

Treinador Online de Python para Iniciantes

Aprenda Python facilmente sem sobrecarga teórica. Resolva tarefas práticas com verificação automática e escreva código diretamente no navegador.

Start Course

Trabalhando com S3 e armazenamentos em nuvem em Kotlin



No desenvolvimento moderno com Kotlin, surge frequentemente a necessidade de integração com armazenamentos em nuvem compatíveis com o protocolo Amazon S3 (Simple Storage Service). Estes podem ser AWS S3, MinIO, DigitalOcean Spaces, Yandex Object Storage e outros. Neste artigo, abordaremos duas abordagens principais: o uso do AWS SDK oficial para Kotlin e um cliente leve baseado em Ktor.



1. AWS SDK para Kotlin (aws-sdk-kotlin)



O SDK oficial da Amazon fornece uma API tipada e assíncrona, com suporte total para corrotinas Kotlin. Esta é a solução mais completa para trabalhar com S3.



Adicionando a dependência

Adicione ao build.gradle.kts:

dependencies {    implementation("aws.sdk.kotlin:s3:1.0.0")    implementation("aws.smithy.kotlin:http-client-engine-ktor:1.0.0")}


Inicialização do cliente

import aws.sdk.kotlin.services.s3.S3Clientimport aws.sdk.kotlin.services.s3.model.*

suspend fun createClient(): S3Client = S3Client.fromEnvironment { region = "ru-central1" // Para MinIO ou outros armazenamentos compatíveis com S3: endpointUrl = "https://storage.yandexcloud.net" // Configuração através das variáveis de ambiente AWS_ACCESS_KEY_ID e AWS_SECRET_ACCESS_KEY}


Upload de arquivo (PutObject)

suspend fun uploadFile(client: S3Client, bucket: String, key: String, filePath: String) {    val fileBytes = java.io.File(filePath).readBytes()    client.putObject(        PutObjectRequest {            this.bucket = bucket            this.key = key            this.body = fileBytes.toByteArray()        }    )    println("Arquivo $key enviado para o bucket $bucket")}


Download de arquivo (GetObject)

suspend fun downloadFile(client: S3Client, bucket: String, key: String, savePath: String) {    val response = client.getObject(        GetObjectRequest {            this.bucket = bucket            this.key = key        }    )    val bytes = response.body?.readAll()    if (bytes != null) {        java.io.File(savePath).writeBytes(bytes)        println("Arquivo $key salvo em $savePath")    }}


Listar objetos no bucket

suspend fun listObjects(client: S3Client, bucket: String): List<String> {    val response = client.listObjectsV2(        ListObjectsV2Request {            this.bucket = bucket        }    )    return response.contents?.map { it.key ?: "" } ?: emptyList()}


2. Ktor S3 Client (alternativa leve)



Se você não precisa de toda a potência do AWS SDK, pode usar o Ktor com a biblioteca ktor-client-s3. Isso oferece peso mínimo e controle total sobre as requisições HTTP.



Adicionando dependências

dependencies {    implementation("io.ktor:ktor-client-core:2.3.0")    implementation("io.ktor:ktor-client-cio:2.3.0")    implementation("io.ktor:ktor-client-content-negotiation:2.3.0")    implementation("io.ktor:ktor-serialization-kotlinx-json:2.3.0")    // Para assinatura de requisições S3    implementation("io.ktor:ktor-client-auth:2.3.0")}


Criando um cliente S3 com Ktor

import io.ktor.client.*import io.ktor.client.request.*import io.ktor.client.statement.*import io.ktor.http.*import io.ktor.utils.io.*

class S3KtorClient( private val endpoint: String, private val accessKey: String, private val secretKey: String) { private val client = HttpClient { install(io.ktor.client.plugins.auth.Auth) { basic { credentials { username = accessKey password = secretKey } } } }

suspend fun putObject(bucket: String, key: String, data: ByteArray) { client.put("

Recommendations