练习 - 使用 .NET Core 将应用连接到 Azure Cache for Redis

已完成

在本练习中,你将学习如何:

  • 使用 Azure CLI 命令创建新的 Redis 缓存实例。
  • 使用 StackExchange.Redis 包创建 .NET Core 控制台应用,以从缓存中添加和检索值

先决条件

创建 Azure 资源

  1. 登录到门户:https://portal.azure.com 并打开 Cloud Shell,然后选择 Bash 作为 shell

  2. 为 Azure 资源创建资源组。 将 <myLocation> 替换为自己附近的区域。

    az group create --name az204-redis-rg --location <myLocation>
    
  3. 使用 az redis create 命令创建 Azure Cache for Redis 实例。 实例名称必须是唯一的,下面的脚本将尝试为你生成一个名称,并将 <myLocation> 替换为你在上一步中使用的区域。 此命令需要几分钟时间才能完成。

    redisName=az204redis$RANDOM
    az redis create --location <myLocation> \
        --resource-group az204-redis-rg \
        --name $redisName \
        --sku Basic --vm-size c0
    
  4. 在 Azure 门户导航到所创建的新的 Redis 缓存。

  5. 在导航窗格的“设置”部分,选择“访问密钥”并将门户保持为打开状态。 复制主连接字符串 (StackExchange.Redis) 值,以便稍后在应用中使用

创建控制台应用程序

  1. 通过在 Visual Studio Code 终端中运行以下命令来创建控制台应用。

    dotnet new console -o Rediscache
    
  2. 通过选择“文件”>“打开文件夹”并为应用选择文件夹,在 Visual Studio Code 中打开应用

  3. StackExchange.Redis 包添加到项目。

    dotnet add package StackExchange.Redis
    
  4. 删除 Program.cs 文件中的任何现有代码,并在顶部添加以下 using 语句

    using StackExchange.Redis;
    
  5. 将以下变量添加到 using 语句后面,将 <REDIS_CONNECTION_STRING> 替换为门户中的主连接字符串 (StackExchange.Redis)

    // connection string to your Redis Cache    
    string connectionString = "REDIS_CONNECTION_STRING";
    
  6. 在 Program.cs 文件中追加以下代码

    using (var cache = ConnectionMultiplexer.Connect(connectionString))
    {
        IDatabase db = cache.GetDatabase();
    
        // Snippet below executes a PING to test the server connection
        var result = await db.ExecuteAsync("ping");
        Console.WriteLine($"PING = {result.Type} : {result}");
    
        // Call StringSetAsync on the IDatabase object to set the key "test:key" to the value "100"
        bool setValue = await db.StringSetAsync("test:key", "100");
        Console.WriteLine($"SET: {setValue}");
    
        // StringGetAsync retrieves the value for the "test" key
        string getValue = await db.StringGetAsync("test:key");
        Console.WriteLine($"GET: {getValue}");
    }
    
  7. 在 Visual Studio Code 终端中,运行以下命令以生成用于检查错误的应用,然后使用以下命令运行应用

    dotnet build
    dotnet run
    

    输出应如下所示:

    PING = SimpleString : PONG
    SET: True
    GET: 100
    
  8. 返回门户并选择“Azure Cache for Redis”边栏选项卡中的“活动日志”。 你可以在日志中查看操作。

清理资源

不再需要资源时,可以使用 az group delete 命令删除资源组。

az group delete -n az204-redis-rg --no-wait