Jak używać zestawu Azure SDK dla języka Go z tabelą platformy Azure

DOTYCZY: Tabeli

Napiwek

Zawartość tego artykułu dotyczy usług Azure Table Storage i Azure Cosmos DB for Table. Interfejs API dla tabel to oferta premium dla magazynu tabel, która oferuje tabele zoptymalizowane pod kątem przepływności, dystrybucję globalną i automatyczne indeksy pomocnicze.

W tym artykule dowiesz się, jak tworzyć, wyświetlać i usuwać jednostki tabel i tabel platformy Azure przy użyciu zestawu Azure SDK dla języka Go.

Tabela platformy Azure umożliwia przechowywanie ustrukturyzowanych danych NoSQL w chmurze, zapewniając magazyn atrybutów klucza z projektem bez schematu. Ponieważ usługa Azure Table Storage jest bez schematu, łatwo dostosować dane do zmieniających się potrzeb aplikacji. Dostęp do danych i interfejsu API tabeli to szybkie i ekonomiczne rozwiązanie dla wielu aplikacji.

Usługi Table Storage lub Azure Cosmos DB można używać do przechowywania elastycznych zestawów danych, takich jak dane użytkownika dla aplikacji internetowych, książek adresowych, informacji o urządzeniu. Lub inne typy metadanych, których wymaga usługa. W tabeli można przechowywać dowolną liczbę jednostek, a konto magazynu może zawierać dowolną liczbę tabel w granicach pojemności konta magazynu.

Postępuj zgodnie z tym artykułem, aby dowiedzieć się, jak zarządzać usługą Azure Table Storage przy użyciu zestawu Azure SDK dla języka Go.

Wymagania wstępne

Konfigurowanie środowiska

Aby wykonać czynności opisane w tym samouczku, musisz mieć grupę zasobów platformy Azure, konto magazynu i zasób tabeli. Uruchom następujące polecenia, aby skonfigurować środowisko:

  1. Utwórz grupę zasobów platformy Azure.

    az group create --name myResourceGroup --location eastus
    
  2. Następnie utwórz konto usługi Azure Storage dla nowej tabeli platformy Azure.

    az storage account create --name <storageAccountName> --resource-group myResourceGroup --location eastus --sku Standard_LRS
    
  3. Utwórz zasób tabeli.

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

Instalowanie pakietów

Do zarządzania tabelą platformy Azure za pomocą języka Go potrzebne są dwa pakiety. azidentity i aztables. Pakiet azidentity zapewnia sposób uwierzytelniania na platformie Azure. aztables Pakiety umożliwiają zarządzanie zasobem tabel na platformie Azure. Uruchom następujące polecenia języka Go, aby zainstalować następujące pakiety:

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

Aby dowiedzieć się więcej na temat sposobów uwierzytelniania na platformie Azure, zapoznaj się z tematem Uwierzytelnianie platformy Azure za pomocą zestawu Azure SDK dla języka Go.

Tworzenie przykładowej aplikacji

Po zainstalowaniu pakietów utworzysz przykładową aplikację, która używa zestawu Azure SDK dla języka Go do zarządzania tabelą platformy Azure. Uruchom polecenie , go mod aby utworzyć nowy moduł o nazwie azTableSample.

go mod init azTableSample

Następnie utwórz plik o nazwie main.go, a następnie skopiuj poniższy plik do niego:

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)
}

Ważne

Upewnij się, że uwierzytelnione konto ma odpowiednie zasady dostępu do zarządzania kontem usługi Azure Storage. Aby uruchomić powyższy kod, musisz mieć co najmniej rolę Współautor danych obiektu blob usługi Storage i rolę Współautor danych tabeli magazynu.

Przykłady kodu

Uwierzytelnianie użytkownika

// 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)
}

Utwórz tabelę

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

Tworzenie encji

// 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)
}

Pobieranie jednostki

// 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)
    }
}

Usuwanie encji

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

Usuń tabelę

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

Uruchamianie kodu

Wystarczy uruchomić aplikację. Jednak zanim to zrobisz, musisz skonfigurować zmienne środowiskowe. Utwórz dwie zmienne środowiskowe i ustaw je na odpowiednią wartość przy użyciu następujących poleceń:

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

Następnie uruchom następujące go run polecenie, aby uruchomić aplikację:

go run main.go

Czyszczenie zasobów

Uruchom następujące polecenie, aby usunąć grupę zasobów i wszystkie pozostałe zasoby:

az group delete --resource-group myResourceGroup

Następne kroki

W tym przewodniku Szybki start wyjaśniono sposób tworzenia konta usługi Azure Cosmos DB, tworzenia tabeli za pomocą Eksploratora danych i uruchamiania aplikacji. Teraz możesz wykonywać zapytania dotyczące danych przy użyciu interfejsu API dla tabeli.