快速入门:将 Azure Redis 缓存与 .NET Framework 应用程序配合使用Quickstart: Use Azure Cache for Redis with a .NET Framework application

在本快速入门中,会将 Azure Redis 缓存合并到 .NET Framework 应用中,以便能够访问 Azure 中的任何应用程序都可以访问的安全专用缓存。In this quickstart, you incorporate Azure Cache for Redis into a .NET Framework app to have access to a secure, dedicated cache that is accessible from any application within Azure. 你专门在 .NET 控制台应用中将 StackExchange.Redis 客户端与 C# 代码配合使用。You specifically use the StackExchange.Redis client with C# code in a .NET console app.


创建缓存Create a cache

  1. 若要创建缓存,请首先登录到 Azure 门户To create a cache, first sign in to the Azure portal. 然后选择“创建资源” > “数据库” > “用于 Redis 的 Azure 缓存”。Then select Create a resource > Databases > Azure Cache for Redis.

    “新建 Azure Redis 缓存”菜单

  2. 在“新建用于 Redis 的 Azure 缓存” 中,配置新缓存的设置。In New Azure Cache for Redis, configure the settings for your new cache.

    设置Setting 建议的值Suggested value 说明Description
    DNS 名称DNS name 全局唯一名称Globally unique name 缓存名称。The cache name. 必须是 1 到 63 个字符的字符串,只能包含数字、字母和 - 字符。It must be a string between 1 and 63 characters and contain only numbers, letters, and the - character. 缓存名称的开头或末尾不能是 - 字符,并且连续的 - 字符无效。The cache name cannot start or end with the - character, and consecutive - characters are not valid.
    订阅Subscription 你的订阅Your subscription 要在其下创建此新的用于 Redis 的 Azure 缓存实例的订阅。The subscription under which this new Azure Cache for Redis instance is created.
    资源组Resource group TestResources TestResources 要在其中创建缓存的新资源组的名称。Name for the new resource group in which to create your cache. 通过将应用的所有资源都放在一个组中,可以一起管理它们。By putting all the resources for an app in a group, you can manage them together. 例如,删除资源组会删除与该应用关联的所有资源。For example, deleting the resource group deletes all resources that are associated with the app.
    LocationLocation 中国北部China North 选择将使用缓存的其他服务附近的区域Choose a region near to other services that will use your cache.
    定价层Pricing tier 基本 C0(250 MB 缓存)Basic C0 (250 MB Cache) 定价层决定可用于缓存的大小、性能和功能。The pricing tier determines the size, performance, and features that are available for the cache. 有关详细信息,请参阅用于 Redis 的 Azure 缓存概述For more information, see Azure Cache for Redis Overview.
    固定到仪表板Pin to dashboard 选定Selected 将新缓存固定到仪表板,使其容易被找到。Pin the new cache to your dashboard to make it easy to find.

    创建 Azure Redis 缓存

  3. 配置了新缓存设置后,选择“创建” 。After the new cache settings are configured, select Create.

    创建缓存可能耗时几分钟。It can take a few minutes for the cache to be created. 若要检查状态,可以监视仪表板上的进度。To check the status, you can monitor the progress on the dashboard. 缓存在创建后会显示状态为“正在运行” ,可供用户使用。After the cache has been created, it shows the status Running, and is ready for use.

    创建的 Azure Redis 缓存

使用 Azure 门户检索主机名、端口和访问密钥Retrieve host name, ports, and access keys by using the Azure portal

连接到某个 Azure Redis 缓存实例时,缓存客户端需要该缓存的主机名、端口和密钥。When connecting to an Azure Cache for Redis instance, cache clients need the host name, ports, and a key for the cache. 在某些客户端中,这些项的名称可能略有不同。Some clients might refer to these items by slightly different names. 可以在 Azure 门户中检索此信息。You can retrieve this information in the Azure portal.

检索访问密钥和主机名的步骤To retrieve the access keys and host name

  1. 若要使用 Azure 门户检索访问密钥,请转到你的缓存,然后选择“访问密钥” 。To retrieve the access keys by using the Azure portal, go to your cache and select Access keys.

    Azure Redis 缓存密钥

  2. 若要检索主机名和端口,请选择“属性”。 To retrieve the host name and ports, select Properties.

    Azure Redis 缓存属性

在计算机上创建名为 CacheSecrets.config 的文件,将其放到不会连同示例应用程序源代码一起签入的位置。Create a file on your computer named CacheSecrets.config and place it in a location where it won't be checked in with the source code of your sample application. 在本快速入门中,CacheSecrets.config 文件的路径为 C:\AppSecrets\CacheSecrets.configFor this quickstart, the CacheSecrets.config file is located here, C:\AppSecrets\CacheSecrets.config.

编辑 CacheSecrets.config 文件,添加以下内容:Edit the CacheSecrets.config file and add the following contents:

    <add key="CacheConnection" value="<cache-name>.redis.cache.chinacloudapi.cn,abortConnect=false,ssl=true,password=<access-key>"/>

<cache-name> 替换为缓存主机名。Replace <cache-name> with your cache host name.

<access-key> 替换缓存的主密钥。Replace <access-key> with the primary key for your cache.

创建控制台应用Create a console app

在 Visual Studio 中,单击“文件” > “新建” > “项目” 。In Visual Studio, click File > New > Project.

在“Visual C#” 下,单击“Windows 经典桌面” ,然后依次单击“控制台应用” 和“确定” 来创建新的控制台应用程序。Under Visual C#, click Windows Classic Desktop and then click Console App, and OK to create a new console application.

配置缓存客户端Configure the cache client

在本部分中,你将配置控制台应用程序来将 StackExchange.Redis 客户端用于 .NET。In this section, you will configure the console application to use the StackExchange.Redis client for .NET.

在 Visual Studio 中,单击“工具” > “NuGet 包管理器” > “包管理器控制台”,然后从“包管理器控制台”窗口运行以下命令。 In Visual Studio, click Tools > NuGet Package Manager > Package Manager Console, and run the following command from the Package Manager Console window.

Install-Package StackExchange.Redis

安装完成后,StackExchange.Redis 缓存客户端可供用于你的项目。Once the installation is completed, the StackExchange.Redis cache client is available to use with your project.

连接到缓存Connect to the cache

在 Visual Studio 中,打开 App.config 文件,并对其进行更新以包括引用 CacheSecrets.config 文件的 appSettings file 属性。In Visual Studio, open your App.config file and update it to include an appSettings file attribute that references the CacheSecrets.config file.

<?xml version="1.0" encoding="utf-8" ?>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.1" />

    <appSettings file="C:\AppSecrets\CacheSecrets.config"></appSettings>  


在解决方案资源管理器中,右键单击“引用”并单击“添加引用”。 In Solution Explorer, right-click References and click Add a reference. 添加对 System.Configuration 程序集的引用。Add a reference to the System.Configuration assembly.

Program.cs 中添加以下 using 语句:Add the following using statements to Program.cs:

using StackExchange.Redis;
using System.Configuration;

与 Azure Redis 缓存的连接由 ConnectionMultiplexer 类管理。The connection to the Azure Cache for Redis is managed by the ConnectionMultiplexer class. 应当在整个客户端应用程序中共享并重复使用此类。This class should be shared and reused throughout your client application. 不要为每个操作都创建新连接。Do not create a new connection for each operation.

切勿将凭据存储在源代码中。Never store credentials in source code. 为了保持简单,此示例仅使用一个外部机密配置文件。To keep this sample simple, I’m only using an external secrets config file. 更好的方法是使用包含证书的 Azure Key VaultA better approach would be to use Azure Key Vault with certificates.

Program.cs 中,将以下成员添加到控制台应用程序的 Program 类:In Program.cs, add the following members to the Program class of your console application:

private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
    string cacheConnection = ConfigurationManager.AppSettings["CacheConnection"].ToString();
    return ConnectionMultiplexer.Connect(cacheConnection);

public static ConnectionMultiplexer Connection
        return lazyConnection.Value;

此方式在应用程序中共享 ConnectionMultiplexer 实例,它使用返回所连接的实例的静态属性。This approach to sharing a ConnectionMultiplexer instance in your application uses a static property that returns a connected instance. 该代码提供了一种线程安全方式,它仅初始化单个已连接的 ConnectionMultiplexer 实例。The code provides a thread-safe way to initialize only a single connected ConnectionMultiplexer instance. abortConnect 设置为 false,这意味着即使未建立与 Azure Redis 缓存的连接,调用也会成功。abortConnect is set to false, which means that the call succeeds even if a connection to the Azure Cache for Redis is not established. ConnectionMultiplexer 的一个关键功能是,一旦解决网络问题和其他原因,它便会自动还原缓存连接。One key feature of ConnectionMultiplexer is that it automatically restores connectivity to the cache once the network issue or other causes are resolved.

CacheConnection appSetting 的值用来将 Azure 门户中的缓存连接字符串引用为 password 参数。The value of the CacheConnection appSetting is used to reference the cache connection string from the Azure portal as the password parameter.

执行缓存命令Executing cache commands

为控制台应用程序的 Program 类的 Main 过程添加以下代码:Add the following code for the Main procedure of the Program class for your console application:

static void Main(string[] args)
    // Connection refers to a property that returns a ConnectionMultiplexer
    // as shown in the previous example.
    IDatabase cache = lazyConnection.Value.GetDatabase();

    // Perform cache operations using the cache object...

    // Simple PING command
    string cacheCommand = "PING";
    Console.WriteLine("\nCache command  : " + cacheCommand);
    Console.WriteLine("Cache response : " + cache.Execute(cacheCommand).ToString());

    // Simple get and put of integral data types into the cache
    cacheCommand = "GET Message";
    Console.WriteLine("\nCache command  : " + cacheCommand + " or StringGet()");
    Console.WriteLine("Cache response : " + cache.StringGet("Message").ToString());

    cacheCommand = "SET Message \"Hello! The cache is working from a .NET console app!\"";
    Console.WriteLine("\nCache command  : " + cacheCommand + " or StringSet()");
    Console.WriteLine("Cache response : " + cache.StringSet("Message", "Hello! The cache is working from a .NET console app!").ToString());

    // Demonstrate "SET Message" executed as expected...
    cacheCommand = "GET Message";
    Console.WriteLine("\nCache command  : " + cacheCommand + " or StringGet()");
    Console.WriteLine("Cache response : " + cache.StringGet("Message").ToString());

    // Get the client list, useful to see if connection list is growing...
    cacheCommand = "CLIENT LIST";
    Console.WriteLine("\nCache command  : " + cacheCommand);
    Console.WriteLine("Cache response : \n" + cache.Execute("CLIENT", "LIST").ToString().Replace("id=", "id="));


Azure Redis 缓存具有可配置的数据库数量(默认为 16 个),因此可以通过逻辑方式隔离 Azure Redis 缓存中的数据。 该代码将连接到默认数据库 DB 0。 有关详细信息,请参阅什么是 Redis 数据库?默认 Redis 服务器配置For more information, see What are Redis databases? and Default Redis server configuration.

可以使用 StringSetStringGet 方法来存储和检索缓存项。Cache items can be stored and retrieved by using the StringSet and StringGet methods.

Redis 将大多数数据存储为 Redis 字符串,但这些字符串可能包含许多类型的数据,包括序列化的二进制数据,可在缓存中存储 .NET 对象时使用。Redis stores most data as Redis strings, but these strings can contain many types of data, including serialized binary data, which can be used when storing .NET objects in the cache.

Ctrl+F5 生成并运行控制台应用。Press Ctrl+F5 to build and run the console app.

在以下示例中可以看到,Message 键事先已包含一个缓存值,该值是使用 Azure 门户中的 Redis 控制台设置的。In the example below, you can see the Message key previously had a cached value, which was set using the Redis Console in the Azure portal. 应用更新了该缓存值。The app updated that cached value. 应用还执行了 PINGCLIENT LIST 命令。The app also executed the PING and CLIENT LIST commands.


处理缓存中的 .NET 对象Work with .NET objects in the cache

Azure Redis 缓存可以缓存 .NET 对象以及基元数据类型,但在缓存 .NET 对象之前,必须将其序列化。Azure Cache for Redis can cache both .NET objects and primitive data types, but before a .NET object can be cached it must be serialized. 此 .NET 对象序列化是应用程序开发人员的责任,同时赋与开发人员选择序列化程序的弹性。This .NET object serialization is the responsibility of the application developer, and gives the developer flexibility in the choice of the serializer.

将对象序列化的一种简单方式是使用 Newtonsoft.Json 中的 JsonConvert 序列化方法,并以 JSON 为源和目标进行序列化。One simple way to serialize objects is to use the JsonConvert serialization methods in Newtonsoft.Json and serialize to and from JSON. 在本部分中,将向缓存添加一个 .NET 对象。In this section, you will add a .NET object to the cache.

在 Visual Studio 中,单击“工具” > “NuGet 包管理器” > “包管理器控制台”,然后从“包管理器控制台”窗口运行以下命令。 In Visual Studio, click Tools > NuGet Package Manager > Package Manager Console, and run the following command from the Package Manager Console window.

Install-Package Newtonsoft.Json

将下面的 using 语句添加到 Program.cs 的开头:Add the following using statement to the top of Program.cs:

using Newtonsoft.Json;

将下面的 Employee 类定义添加到 Program.cs 中:Add the following Employee class definition to Program.cs:

class Employee
    public string Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }

    public Employee(string EmployeeId, string Name, int Age)
        this.Id = EmployeeId;
        this.Name = Name;
        this.Age = Age;

Program.csMain() 过程的底部并且在 Dispose() 调用之前,添加以下代码行来缓存和检索序列化的 .NET 对象:At the bottom of Main() procedure in Program.cs, and before the call to Dispose(), add the following lines of code to cache and retrieve a serialized .NET object:

    // Store .NET object to cache
    Employee e007 = new Employee("007", "Davide Columbo", 100);
    Console.WriteLine("Cache response from storing Employee .NET object : " + 
        cache.StringSet("e007", JsonConvert.SerializeObject(e007)));

    // Retrieve .NET object from cache
    Employee e007FromCache = JsonConvert.DeserializeObject<Employee>(cache.StringGet("e007"));
    Console.WriteLine("Deserialized Employee .NET object :\n");
    Console.WriteLine("\tEmployee.Name : " + e007FromCache.Name);
    Console.WriteLine("\tEmployee.Id   : " + e007FromCache.Id);
    Console.WriteLine("\tEmployee.Age  : " + e007FromCache.Age + "\n");

Ctrl+F5 来生成并运行控制台应用以测试 .NET 对象的序列化。Press Ctrl+F5 to build and run the console app to test serialization of .NET objects.


清理资源Clean up resources

如果想要继续学习下一篇教程,可以保留本快速入门中创建的资源,以便重复使用。If you will be continuing to the next tutorial, you can keep the resources created in this quickstart and reuse them.

如果已完成快速入门示例应用程序,可以删除本快速入门中创建的 Azure 资源,以免产生费用。Otherwise, if you are finished with the quickstart sample application, you can delete the Azure resources created in this quickstart to avoid charges.


删除资源组的操作不可逆,资源组以及其中的所有资源将被永久删除。Deleting a resource group is irreversible and that the resource group and all the resources in it are permanently deleted. 请确保不会意外删除错误的资源组或资源。Make sure that you do not accidentally delete the wrong resource group or resources. 如果在现有资源组(其中包含要保留的资源)中为托管此示例而创建了相关资源,可从各自的边栏选项卡逐个删除这些资源,而不要删除资源组。If you created the resources for hosting this sample inside an existing resource group that contains resources you want to keep, you can delete each resource individually from their respective blades instead of deleting the resource group.

登录到 Azure 门户,并单击“资源组”。 Sign in to the Azure portal and click Resource groups.

在“按名称筛选...”文本框中键入资源组的名称 。In the Filter by name... textbox, type the name of your resource group. 本文的说明使用了名为 TestResources 的资源组。The instructions for this article used a resource group named TestResources. 在结果列表中的资源组上,单击“...”,然后单击“删除资源组” 。On your resource group in the result list, click ... then Delete resource group.


系统会要求确认是否删除资源组。You will be asked to confirm the deletion of the resource group. 键入资源组的名称进行确认,然后单击“删除” 。Type the name of your resource group to confirm, and click Delete.

片刻之后,将会删除该资源组及其包含的所有资源。After a few moments, the resource group and all of its contained resources are deleted.

后续步骤Next steps

本快速入门介绍了如何通过 .NET 应用程序使用 Azure Redis 缓存。In this quickstart, you learned how to use Azure Cache for Redis from a .NET application. 请继续学习下一个快速入门,将 Azure Redis 缓存与 ASP.NET Web 应用配合使用。Continue to the next quickstart to use Azure Cache for Redis with an ASP.NET web app.