golang aws-sdk-go 之 s3 服務

hatlonely發表於2018-03-04

s3 是 aws 提供的分散式檔案服務,價格比較優惠,經常被用來作為日誌的持久化儲存,大資料處理結果的輸入輸出等

s3 服務提供命令列工具,可以很方便地上傳、下載、刪除檔案,普通 golang 程式如果需要訪問 s3 上檔案,一種簡單方式可以先將 s3 上檔案下載到本地,然後直接訪問本地檔案即可,但是這種方式需要一個額外的步驟,下載到本地,有額外的運維成本,需要額外的磁碟空間,使用上面不是很靈活,此外,微服務應該儘可能地降低對本地資料的依賴,這種設計也不符合微服務的設計思想

使用 aws-sdk-go 可以直接訪問 s3 服務,實現檔案的上傳和讀取

以下使用的程式碼:https://github.com/hatlonely/hellogolang/blob/master/internal/aws-sdk-go/s3_test.go

建立會話

首先需要建立一個會話,後續的訪問都可以通過這個會話進行,如果訪問的服務需要授權,也可以在 config 裡面指定授權檔案

sess := session.Must(session.NewSession(&aws.Config{
    Region: aws.String(endpoints.ApSoutheast1RegionID),
}))
service := s3.New(sess)

這裡必須指定 s3 桶所在的地區

上傳檔案

fp, err := os.Open("s3_test.go")
So(err, ShouldBeNil)
defer fp.Close()

ctx, cancel := context.WithTimeout(context.Background(), time.Duration(30)*time.Second)
defer cancel()

_, err = service.PutObjectWithContext(ctx, &s3.PutObjectInput{
    Bucket: aws.String("hatlonely"),
    Key:    aws.String("test/s3_test.go"),
    Body:   fp,
})
So(err, ShouldBeNil)

使用 PutObjectWithContext 實現檔案的上傳,這裡只能實現檔案的上傳,不能實現檔案的寫入,所以只能先將檔案寫入到本地,然後再整個上傳

可以通過 context 設定訪問超時時間

下載檔案

ctx, cancel := context.WithTimeout(context.Background(), time.Duration(30)*time.Second)
defer cancel()

out, err := service.GetObjectWithContext(ctx, &s3.GetObjectInput{
    Bucket: aws.String("hatlonely"),
    Key: aws.String("test/s3_test.go"),
})
So(err, ShouldBeNil)
defer out.Body.Close()
scanner := bufio.NewScanner(out.Body)
for scanner.Scan() {
    Println(scanner.Text())
}

使用 GetObjectWithContext 介面讀取檔案,檔案的內容在 out.Body 中,可以使用 scanner 介面,不斷地按行讀取檔案內容

最後要記得呼叫 out.Body.Close(),釋放資源

遍歷目錄

var objkeys []string

ctx, cancel := context.WithTimeout(context.Background(), time.Duration(30)*time.Second)
defer cancel()

out, err := service.ListObjectsWithContext(ctx, &s3.ListObjectsInput{
    Bucket: aws.String("hatlonely"),
    Prefix: aws.String("test/"),
})
So(err, ShouldBeNil)
for _, content := range out.Contents  {
    objkeys = append(objkeys, aws.StringValue(content.Key))
}
Println(objkeys)

大資料一般都是併發輸出,每個節點都會輸出一個檔案,到一個指定的目錄下面,所以有時候我們需要去獲取一個目錄下面到底有哪些檔案,可以使用 ListObjectsWithContext 遍歷一個目錄下所有的檔案,這個函式是遞迴的

var objkeys []string

ctx, cancel := context.WithTimeout(context.Background(), time.Duration(30)*time.Second)
defer cancel()

err := service.ListObjectsPagesWithContext(ctx, &s3.ListObjectsInput{
    Bucket: aws.String("hatlonely"),
    Prefix: aws.String("test/"),
}, func(output *s3.ListObjectsOutput, b bool) bool {
    for _, content := range output.Contents {
        objkeys = append(objkeys, aws.StringValue(content.Key))
    }
    return true
})
So(err, ShouldBeNil)
Println(objkeys)

也可以使用 ListObjectsPagesWithContext 傳入一個回撥函式,用於處理每個檔案

參考連結

轉載請註明出處 本文連結:http://hatlonely.github.io/2018/03/04/golang-aws-sdk-go-%E4%B9%8B-s3-%E6%9C%8D%E5%8A%A1/

相關文章