如何用Azure SDK for Go获取存储账户容量及容器配置?
使用Azure SDK for Go获取存储账户容量与容器配置信息
你当前的代码通过旧版Azure Storage SDK for Go(github.com/Azure/azure-storage-go)成功列出了容器,但ListContainers接口本身不会返回存储账户或容器的容量数据,需要通过以下两种方式分别获取:
一、获取存储账户的总容量与已使用量
存储账户的容量配额(总容量)和已使用量属于账户级别的管理数据,需要使用Azure Resource Manager(ARM)的Storage Accounts管理API,而非Blob服务API。
实现步骤:
- 安装新版ARM存储管理SDK和身份认证SDK:
go get github.com/Azure/azure-sdk-for-go/sdk/azidentity go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage
- 编写获取账户容量的代码(使用Azure AD身份认证,推荐生产环境使用):
import ( "context" "log" "os" "github.com/Azure/azure-sdk-for-go/sdk/azidentity" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage" ) func GetStorageAccountCapacity(subscriptionID, storageAccountName, resourceGroupName string) (*armstorage.AccountProperties, error) { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { return nil, err } client, err := armstorage.NewStorageAccountsClient(subscriptionID, cred, nil) if err != nil { return nil, err } resp, err := client.GetProperties(context.TODO(), resourceGroupName, storageAccountName, nil) if err != nil { return nil, err } return resp.AccountProperties, nil }
调用该函数后,可通过properties.SKU.Tier判断账户类型(如Standard_LRS),通过properties.Usage获取已使用容量(usage.Value为已用字节数,usage.Unit为存储单位)。
二、获取单个容器的已使用容量
对于容器级别的已使用容量,可通过旧版SDK的GetContainerProperties接口获取:
修改你原有的代码:
在遍历容器的循环中,新增获取容器属性的逻辑:
for _, container := range containerListResponse.Containers { // 获取容器属性(包含已使用容量) containerProps, err := containerSvc.GetContainerProperties(container.Name) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{ "Erro ao obter propriedades do container ": container.Name, "Erro": err, }) continue } // 容器已使用容量(字节) usedBytes := containerProps.Properties.Usage.Bytes c.JSON(http.StatusOK, gin.H{ "ContainerNome": container.Name, "Propriedades": container.Properties, "CapacidadeUsada": usedBytes, }) }
注意事项
- 你当前使用的
github.com/Azure/azure-storage-go是旧版SDK,微软现已推荐使用新版的azblobSDK(github.com/Azure/azure-sdk-for-go/sdk/storage/azblob),新版API更简洁且支持更多特性。 - 获取账户容量需要对应的ARM权限(如
Storage Account Reader角色),确保你的认证主体具备相应权限。
内容的提问来源于stack exchange,提问作者Guilherme Rodrigues
相关产品推荐
相关产品推荐

