使用 Azure CLI 创建 Azure Cache for Redis

本方案介绍如何创建 Azure Redis 缓存。 然后,了解如何获取 Azure Cache for Redis 实例的详细信息,包括预配状态、主机名、端口和 Azure Cache for Redis 实例密钥。 最后,了解如何删除缓存。

如果没有 Azure 订阅,可在开始前创建一个试用帐户

先决条件

  • 如需在本地运行 CLI 参考命令,请安装 Azure CLI。 如果在 Windows 或 macOS 上运行,请考虑在 Docker 容器中运行 Azure CLI。 有关详细信息,请参阅如何在 Docker 容器中运行 Azure CLI

    • 如果使用的是本地安装,请使用 az login 命令登录到 Azure CLI。 若要完成身份验证过程,请遵循终端中显示的步骤。 有关其他登录选项,请参阅使用 Azure CLI 登录

    • 出现提示时,请在首次使用时安装 Azure CLI 扩展。 有关扩展详细信息,请参阅使用 Azure CLI 的扩展

    • 运行 az version 以查找安装的版本和依赖库。 若要升级到最新版本,请运行 az upgrade

示例脚本

登录 Azure

使用以下脚本通过其他订阅登录,将 <Subscription ID> 替换为 Azure 订阅 ID。 如果没有 Azure 试用版订阅,请在开始前创建一个试用版订阅

az cloud set -n AzureChinaCloud
az login

subscription="<subscriptionId>" # add subscription here

az account set -s $subscription # ...or use 'az login'

有关详细信息,请参阅设置有效的订阅登录

运行脚本


# Variable block
let "randomIdentifier=$RANDOM*$RANDOM"
location="China North 2"
resourceGroup="msdocs-redis-cache-rg-$randomIdentifier"
tag="create-manage-cache"
cache="msdocs-redis-cache-$randomIdentifier"
sku="basic"
size="C0"

# Create a resource group
echo "Creating $resourceGroup in "$location"..."
az group create --resource-group $resourceGroup --location "$location" --tags $tag

# Create a Basic C0 (256 MB) Redis Cache
echo "Creating $cache"
az redis create --name $cache --resource-group $resourceGroup --location "$location" --sku $sku --vm-size $size

# Get details of an Azure Cache for Redis
echo "Showing details of $cache"
az redis show --name "$cache" --resource-group $resourceGroup 

# Retrieve the hostname and ports for an Azure Redis Cache instance
redis=($(az redis show --name "$cache" --resource-group $resourceGroup --query [hostName,enableNonSslPort,port,sslPort] --output tsv))

# Retrieve the keys for an Azure Redis Cache instance
keys=($(az redis list-keys --name "$cache" --resource-group $resourceGroup --query [primaryKey,secondaryKey] --output tsv))

# Display the retrieved hostname, keys, and ports
echo "Hostname:" ${redis[0]}
echo "Non SSL Port:" ${redis[2]}
echo "Non SSL Port Enabled:" ${redis[1]}
echo "SSL Port:" ${redis[3]}
echo "Primary Key:" ${keys[0]}
echo "Secondary Key:" ${keys[1]}

# Delete a redis cache
echo "Deleting $cache"
az redis delete --name "$cache" --resource-group $resourceGroup -y

# echo "Deleting all resources"
az group delete --resource-group $resourceGroup -y

清理资源

使用 az group delete 命令删除资源组以及与其关联的所有资源 - 除非你持续需要这些资源。 其中一些资源在创建和删除时可能要稍等片刻。

az group delete --reourceg $resourceGroup

示例参考

此脚本使用以下命令创建资源组和 Azure Redis 缓存。 表中的每条命令均链接到特定于命令的文档。

命令 说明
az group create 创建用于存储所有资源的资源组。
az redis create 创建 Azure Redis 缓存实例。
az redis show 检索 Azure Redis 缓存实例的详细信息。
az redis list-keys 检索 Azure Redis 缓存实例的访问密钥。
az redis 删除 删除 Azure Redis 缓存实例。

后续步骤

有关 Azure CLI 的详细信息,请参阅 Azure CLI 文档

有关通过群集创建高级 Azure Cache for Redis 的 Azure Cache for Redis CLI 脚本示例,请参阅借助群集的高级 Azure Cache for Redis