Azure Tablosu ile Go için Azure SDK'sını kullanma

ŞUNLAR IÇIN GEÇERLIDIR: Tablo

İpucu

Bu makaledeki içerik, Azure Tablo depolama ve Tablo için Azure Cosmos DB için geçerlidir. Tablo için API, aktarım hızı için iyileştirilmiş tablolar, genel dağıtım ve otomatik ikincil dizinler sunan, tablo depolamaya yönelik premium bir tekliftir.

Bu makalede, Go için Azure SDK ile Azure Tabloları ve Tablo varlıklarını oluşturmayı, listelemeyi ve silmeyi öğreneceksiniz.

Azure Tablosu, şemasız tasarıma sahip bir anahtar öznitelik deposu sağlayarak yapılandırılmış NoSQL verilerini bulutta depolamanıza olanak tanır. Azure Tablo depolama şemasız olduğundan, verilerinizi uygulamalarınızın gelişen gereksinimlerine uyarlamak kolaydır. Tablonun verilerine ve API'sine erişim, birçok uygulama için hızlı ve uygun maliyetli bir çözümdür.

Web uygulamaları için kullanıcı verileri, adres defterleri, cihaz bilgileri gibi esnek veri kümelerini depolamak için Tablo depolama alanını veya Azure Cosmos DB'yi kullanabilirsiniz. Veya hizmetinizin gerektirdiği diğer meta veri türleri. Bir tabloda istediğiniz kadar varlık depolayabilirsiniz ve bir depolama hesabı kapasite limitini dolduracak kadar tablo içerebilir.

Go için Azure SDK'sını kullanarak Azure Tablo depolamayı yönetmeyi öğrenmek için bu makaleyi izleyin.

Önkoşullar

Ortamınızı ayarlama

Bu öğreticiyi takip etmek için bir Azure kaynak grubuna, depolama hesabına ve tablo kaynağına ihtiyacınız vardır. Ortamınızı ayarlamak için aşağıdaki komutları çalıştırın:

  1. Azure kaynak grubu oluşturun.

    az group create --name myResourceGroup --location eastus
    
  2. Ardından yeni Azure Tablonuz için bir Azure depolama hesabı oluşturun.

    az storage account create --name <storageAccountName> --resource-group myResourceGroup --location eastus --sku Standard_LRS
    
  3. Tablo kaynağı oluşturun.

    az storage table create --account-name <storageAccountName> --account-key 'storageKey' --name mytable
    

Paketleri yükleme

Go ile Azure Tablosunu yönetmek için iki paket gerekir; azidentity ve aztables. Paket, azidentity Azure'da kimlik doğrulaması yapmanız için size bir yol sağlar. Paketler size aztables Azure'daki tablo kaynağını yönetme olanağı sağlar. Bu paketleri yüklemek için aşağıdaki Go komutlarını çalıştırın:

go get github.com/Azure/azure-sdk-for-go/sdk/data/aztables
go get github.com/Azure/azure-sdk-for-go/sdk/azidentity

Azure'da kimlik doğrulaması yapmanın yolları hakkında daha fazla bilgi edinmek için Go için Azure SDK ile Azure kimlik doğrulaması makalesine bakın.

Örnek uygulamayı oluşturma

Paketleri yükledikten sonra, Azure Tablosunu yönetmek için Go için Azure SDK'sını kullanan bir örnek uygulama oluşturursunuz. go mod adlı azTableSampleyeni bir modül oluşturmak için komutunu çalıştırın.

go mod init azTableSample

Ardından adlı main.gobir dosya oluşturun ve aşağıdaki dosyayı içine kopyalayın:

package main

import (
    "context"
    "encoding/json"
    "fmt"
    "os"

    "github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
    "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
    "github.com/Azure/azure-sdk-for-go/sdk/data/aztables"
)

type InventoryEntity struct {
    aztables.Entity
    Price       float32
    Inventory   int32
    ProductName string
    OnSale      bool
}

type PurchasedEntity struct {
    aztables.Entity
    Price float32
    ProductName string
    OnSale bool
}

func getClient() *aztables.Client {
    accountName, ok := os.LookupEnv("AZURE_STORAGE_ACCOUNT")
    if !ok {
        panic("AZURE_STORAGE_ACCOUNT environment variable not found")
    }

    tableName, ok := os.LookupEnv("AZURE_TABLE_NAME")
    if !ok {
        panic("AZURE_TABLE_NAME environment variable not found")
    }

    cred, err := azidentity.NewDefaultAzureCredential(nil)
    if err != nil {
        panic(err)
    }
    serviceURL := fmt.Sprintf("https://%s.table.core.windows.net/%s", accountName, tableName)
    client, err := aztables.NewClient(serviceURL, cred, nil)
    if err != nil {
        panic(err)
    }
    return client
}

func createTable(client *aztables.Client) {
    //TODO: Check access policy, Storage Blob Data Contributor role needed
    _, err := client.Create(context.TODO(), nil)
    if err != nil {
        panic(err)
    }
}

func addEntity(client *aztables.Client) {
    myEntity := InventoryEntity{
        Entity: aztables.Entity{
            PartitionKey: "pk001",
            RowKey:       "rk001",
        },
        Price:       3.99,
        Inventory:   20,
        ProductName: "Markers",
        OnSale:      false,
    }

    marshalled, err := json.Marshal(myEntity)
    if err != nil {
        panic(err)
    }

    _, err = client.AddEntity(context.TODO(), marshalled, nil) // TODO: Check access policy, need Storage Table Data Contributor role
    if err != nil {
        panic(err)
    }
}

func listEntities(client *aztables.Client) {
    listPager := client.List(nil)
    pageCount := 0
    for listPager.More() {
        response, err := listPager.NextPage(context.TODO())
        if err != nil {
            panic(err)
        }
        fmt.Printf("There are %d entities in page #%d\n", len(response.Entities), pageCount)
        pageCount += 1
    }
}

func queryEntity(client *aztables.Client) {
    filter := fmt.Sprintf("PartitionKey eq '%v' or RowKey eq '%v'", "pk001", "rk001")
    options := &aztables.ListEntitiesOptions{
        Filter: &filter,
        Select: to.StringPtr("RowKey,Price,Inventory,ProductName,OnSale"),
        Top:    to.Int32Ptr(15),
    }

    pager := client.List(options)
    for pager.More() {
        resp, err := pager.NextPage(context.Background())
        if err != nil {
            panic(err)
        }
        for _, entity := range resp.Entities {
            var myEntity PurchasedEntity 
            err = json.Unmarshal(entity, &myEntity)
            if err != nil {
                panic(err)
            }
            fmt.Println("Return custom type [PurchasedEntity]")
            fmt.Printf("Price: %v; ProductName: %v; OnSale: %v\n", myEntity.Price, myEntity.ProductName, myEntity.OnSale)
        }
    }
}

func deleteEntity(client *aztables.Client) {
    _, err := client.DeleteEntity(context.TODO(), "pk001", "rk001", nil)
    if err != nil {
        panic(err)
    }
}

func deleteTable(client *aztables.Client) {
    _, err := client.Delete(context.TODO(), nil)
    if err != nil {
        panic(err)
    }
}

func main() {

    fmt.Println("Authenticating...")
    client := getClient()

    fmt.Println("Creating a table...")
    createTable(client)

    fmt.Println("Adding an entity to the table...")
    addEntity(client)

    fmt.Println("Calculating all entities in the table...")
    listEntities(client)

    fmt.Println("Querying a specific entity...")
    queryEntity(client) 

    fmt.Println("Deleting an entity...")
    deleteEntity(client) 

    fmt.Println("Deleting a table...")
    deleteTable(client)
}

Önemli

Kimlik doğrulaması yaptığınız hesabın Azure depolama hesabınızı yönetmek için uygun accces ilkesine sahip olduğundan emin olun. Yukarıdaki kodu çalıştırmak için hesabınızın en az Depolama Blob Verileri Katkıda Bulunanı rolüne ve Depolama Tablo Verileri Katkıda Bulunanı rolüne sahip olması gerekir.

Kod örnekleri

İstemcinin kimliğini doğrulama

// Lookup environment variables
accountName, ok := os.LookupEnv("AZURE_STORAGE_ACCOUNT")
if !ok {
  panic("AZURE_STORAGE_ACCOUNT environment variable not found")
}

tableName, ok := os.LookupEnv("AZURE_TABLE_NAME")
if !ok {
  panic("AZURE_TABLE_NAME environment variable not found")
}

// Create a credential
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
  panic(err)
}

// Create a table client
serviceURL := fmt.Sprintf("https://%s.table.core.windows.net/%s", accountName, tableName)
client, err := aztables.NewClient(serviceURL, cred, nil)
if err != nil {
  panic(err)
}

Tablo oluştur

// Create a table and discard the response
_, err := client.Create(context.TODO(), nil)
if err != nil {
  panic(err)
}

Varlık oluşturma

// Define the table entity as a custom type
type InventoryEntity struct {
    aztables.Entity
    Price       float32
    Inventory   int32
    ProductName string
    OnSale      bool
}

// Define the entity values
myEntity := InventoryEntity{
    Entity: aztables.Entity{
        PartitionKey: "pk001",
        RowKey:       "rk001",
    },
    Price:       3.99,
    Inventory:   20,
    ProductName: "Markers",
    OnSale:      false,
}

// Marshal the entity to JSON
marshalled, err := json.Marshal(myEntity)
if err != nil {
    panic(err)
}

// Add the entity to the table
_, err = client.AddEntity(context.TODO(), marshalled, nil) // needs Storage Table Data Contributor role
if err != nil {
    panic(err)
}

Varlık alma

// Define the new custom type
type PurchasedEntity struct {
    aztables.Entity
    Price       float32
    ProductName string
    OnSale      bool
}

// Define the query filter and options
filter := fmt.Sprintf("PartitionKey eq '%v' or RowKey eq '%v'", "pk001", "rk001")
options := &aztables.ListEntitiesOptions{
    Filter: &filter,
    Select: to.StringPtr("RowKey,Price,Inventory,ProductName,OnSale"),
    Top:    to.Int32Ptr(15),
}

// Query the table for the entity
pager := client.List(options)
for pager.More() {
    resp, err := pager.NextPage(context.Background())
    if err != nil {
        panic(err)
    }
    for _, entity := range resp.Entities {
        var myEntity PurchasedEntity
        err = json.Unmarshal(entity, &myEntity)
        if err != nil {
            panic(err)
        }
        fmt.Println("Return custom type [PurchasedEntity]")
        fmt.Printf("Price: %v; ProductName: %v; OnSale: %v\n", myEntity.Price, myEntity.ProductName, myEntity.OnSale)
    }
}

Varlığı silme

_, err := client.DeleteEntity(context.TODO(), "pk001", "rk001", nil)
if err != nil {
  panic(err)
}

Tablo silme

_, err := client.Delete(context.TODO(), nil)
if err != nil {
  panic(err)
}

Kodu çalıştırma

Geriye kalan tek şey uygulamayı çalıştırmaktır. Ancak bunu gerçekleştirmeden önce ortam değişkenlerinizi ayarlamanız gerekir. aşağıdaki komutları kullanarak iki ortam değişkeni oluşturun ve bunları uygun değere ayarlayın:

export AZURE_STORAGE_ACCOUNT=<YourStorageAccountName> 
export AZURE_TABLE_NAME=<YourAzureTableName>

Ardından aşağıdaki komutu çalıştırarak go run uygulamayı çalıştırın:

go run main.go

Kaynakları temizleme

Kaynak grubunu ve kalan tüm kaynaklarını silmek için aşağıdaki komutu çalıştırın:

az group delete --resource-group myResourceGroup

Sonraki adımlar

Bu hızlı başlangıçta Azure Cosmos DB hesabı oluşturmayı, Veri Gezgini'ni kullanarak tablo oluşturmayı ve bir uygulamayı çalıştırmayı öğrendiniz. Artık Tablo API'sini kullanarak verilerinizi sorgulayabilirsiniz.