Примечание
Для доступа к этой странице требуется авторизация. Вы можете попробовать войти или изменить каталоги.
Для доступа к этой странице требуется авторизация. Вы можете попробовать изменить каталоги.
Azure Event Grid is an eventing service for the cloud. In this article, you use Azure PowerShell to subscribe to Blob storage events, trigger an event, and view the result.
Как правило, события отправляются на конечную точку, которая обрабатывает данные событий и выполняет соответствующие действия. However, to simplify this article, you send the events to a web app that collects and displays the messages.
When you're finished, you see that the event data has been sent to the web app.
Настройка
Примечание.
Мы рекомендуем использовать модуль Azure Az PowerShell для взаимодействия с Azure. Сведения о начале работы см. в статье "Установка Azure PowerShell". Чтобы узнать, как перейти на модуль Az PowerShell, см. статью Миграция Azure PowerShell с AzureRM на Az.
This article requires that you're running the latest version of Azure PowerShell. If you need to install or upgrade, see Install and configure Azure PowerShell.
Вход в Azure
Чтобы выполнить проверку подлинности, войдите в подписку Azure с помощью команды Connect-AzAccount
и следуйте инструкциям на экране.
Connect-AzAccount
This example uses westus2 and stores the selection in a variable for use throughout.
$location = "westus2"
Создайте группу ресурсов
Event Grid topics are Azure resources, and must be placed in an Azure resource group. The resource group is a logical collection into which Azure resources are deployed and managed.
Создайте группу ресурсов с помощью команды New-AzResourceGroup.
The following example creates a resource group named gridResourceGroup in the westus2 location.
$resourceGroup = "gridResourceGroup"
New-AzResourceGroup -Name $resourceGroup -Location $location
Создание учетной записи хранения
Blob storage events are available in general-purpose v2 storage accounts and Blob storage accounts. General-purpose v2 storage accounts support all features for all storage services, including Blobs, Files, Queues, and Tables. A Blob storage account is a specialized storage account for storing your unstructured data as blobs (objects) in Azure Storage. Blob storage accounts are like general-purpose storage accounts and share all the great durability, availability, scalability, and performance features that you use today including 100% API consistency for block blobs and append blobs. Дополнительные сведения см. в статье Общие сведения об учетной записи хранения Azure.
Create a Blob storage account with LRS replication using New-AzStorageAccount, then retrieve the storage account context that defines the storage account to be used. When acting on a storage account, you reference the context instead of repeatedly providing the credentials. This example creates a storage account called gridstorage
with locally redundant storage (LRS).
Примечание.
Storage account names are in a global name space so you need to append some random characters to the name provided in this script.
$storageName = "gridstorage"
$storageAccount = New-AzStorageAccount -ResourceGroupName $resourceGroup `
-Name $storageName `
-Location $location `
-SkuName Standard_LRS `
-Kind BlobStorage `
-AccessTier Hot `
-AllowBlobPublicAccess $false
$ctx = $storageAccount.Context
Создание конечной точки сообщения
Before subscribing to the topic, let's create the endpoint for the event message. Как правило, конечная точка выполняет действия на основе данных события. To simplify this quickstart, you deploy a prebuilt web app that displays the event messages. Развернутое решение включает план службы приложений, веб-приложение службы приложений и исходный код из GitHub.
Replace <your-site-name>
with a unique name for your web app. The web app name must be unique because it's part of the DNS entry.
$sitename="<your-site-name>"
New-AzResourceGroupDeployment `
-ResourceGroupName $resourceGroup `
-TemplateUri "https://raw.githubusercontent.com/Azure-Samples/azure-event-grid-viewer/master/azuredeploy.json" `
-siteName $sitename `
-hostingPlanName viewerhost
Развертывание может занять несколько минут. After the deployment has succeeded, view your web app to make sure it's running. In a web browser, navigate to: https://<your-site-name>.azurewebsites.net
Вы увидите сайт, где в настоящий момент не отображаются сообщения.
Enable Event Grid resource provider
If you haven't previously used Event Grid in your Azure subscription, you may need to register the Event Grid resource provider. Выполните следующую команду:
Register-AzResourceProvider -ProviderNamespace Microsoft.EventGrid
It may take a moment for the registration to finish. To check the status, run:
Get-AzResourceProvider -ProviderNamespace Microsoft.EventGrid
Когда состояние RegistrationStatus
изменится на Registered
, вы сможете продолжить работу.
Subscribe to your storage account
You subscribe to a topic to tell Event Grid which events you want to track. The following example subscribes to the storage account you created, and passes the URL from your web app as the endpoint for event notification. The endpoint for your web app must include the suffix /api/updates/
.
$storageId = (Get-AzStorageAccount -ResourceGroupName $resourceGroup -AccountName $storageName).Id
$endpoint="https://$sitename.azurewebsites.net/api/updates"
New-AzEventGridSubscription `
-EventSubscriptionName gridBlobQuickStart `
-Endpoint $endpoint `
-ResourceId $storageId
Просмотрите веб-приложение еще раз и обратите внимание, что событие проверки подписки отправлено в него. Select the eye icon to expand the event data. Сетка событий отправляет событие проверки, чтобы конечная точка удостоверяла, что она хочет получать данные о событии. Веб-приложение содержит код для проверки подписки.
Trigger an event from Blob storage
Now, let's trigger an event to see how Event Grid distributes the message to your endpoint. First, let's create a container and an object. Then, let's upload the object into the container.
$containerName = "gridcontainer"
New-AzStorageContainer -Name $containerName -Context $ctx
echo $null >> gridTestFile.txt
Set-AzStorageBlobContent -File gridTestFile.txt -Container $containerName -Context $ctx -Blob gridTestFile.txt
You've triggered the event, and Event Grid sent the message to the endpoint you configured when subscribing. Просмотрите веб-приложение, чтобы увидеть только что отправленное событие.
[{
"topic": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myrg/providers/Microsoft.Storage/storageAccounts/myblobstorageaccount",
"subject": "/blobServices/default/containers/gridcontainer/blobs/gridTestFile.txt",
"eventType": "Microsoft.Storage.BlobCreated",
"eventTime": "2017-08-16T20:33:51.0595757Z",
"id": "4d96b1d4-0001-00b3-58ce-16568c064fab",
"data": {
"api": "PutBlockList",
"clientRequestId": "Azure-Storage-PowerShell-d65ca2e2-a168-4155-b7a4-2c925c18902f",
"requestId": "4d96b1d4-0001-00b3-58ce-16568c000000",
"eTag": "0x8D4E4E61AE038AD",
"contentType": "application/octet-stream",
"contentLength": 0,
"blobType": "BlockBlob",
"url": "https://myblobstorageaccount.blob.core.windows.net/gridcontainer/gridTestFile.txt",
"sequencer": "00000000000000EB0000000000046199",
"storageDiagnostics": {
"batchId": "dffea416-b46e-4613-ac19-0371c0c5e352"
}
},
"dataVersion": "",
"metadataVersion": "1"
}]
Очистка ресурсов
If you plan to continue working with this storage account and event subscription, don't clean up the resources created in this article. If you don't plan to continue, use the following command to delete the resources you created in this article.
Remove-AzResourceGroup -Name $resourceGroup
Дальнейшие действия
Now that you know how to create topics and event subscriptions, learn more about Blob storage Events and what Event Grid can help you do:
- Реагирование на события хранилища Blob
- An introduction to Azure Event Grid (Общие сведения о службе "Сетка событий Azure")