快速入门:将 Azure Redis 缓存与 ASP.NET Web 应用配合使用Quickstart: Use Azure Cache for Redis with an ASP.NET web app

在本快速入门中,将使用 Visual Studio 2019 创建一个 ASP.NET Web 应用程序,该应用程序连接到 Azure Redis 缓存以存储和检索缓存中的数据。In this quickstart, you use Visual Studio 2019 to create an ASP.NET web application that connects to Azure Cache for Redis to store and retrieve data from the cache. 然后,将该应用部署到 Azure 应用服务。You then deploy the app to Azure App Service.

先决条件Prerequisites

创建 Visual Studio 项目Create the Visual Studio project

  1. 打开 Visual Studio,然后选择“文件” >“新建” > “项目” 。Open Visual Studio, and then and select File >New > Project.

  2. 在“新建项目”对话框中执行以下步骤: In the New Project dialog box, take the following steps:

    创建项目

    a.a. 在“模板”列表中展开“Visual C#”节点。 In the Templates list, expand the Visual C# node.

    b.b. 选择“云”。 Select Cloud.

    c.c. 选择“ASP.NET Web 应用程序” 。Select ASP.NET Web Application.

    d.d. 验证是否已选择“.NET Framework 4.5.2”或更高版本。 Verify that .NET Framework 4.5.2 or higher is selected.

    e.e. 在“名称”框中,为项目提供一个名称。 In the Name box, give the project a name. 在此示例中,我们使用了 ContosoTeamStatsFor this example, we used ContosoTeamStats.

    f.f. 选择“确定” 。Select OK.

  3. 选择“MVC”作为项目类型。 Select MVC as the project type.

  4. 对于“身份验证”设置,请确保指定“不进行身份验证”。 Make sure that No Authentication is specified for the Authentication settings. 默认的“身份验证”设置可能因 Visual Studio 版本而异。 Depending on your version of Visual Studio, the default Authentication setting might be something else. 若要对其进行更改,请选择“更改身份验证”,然后选择“不进行身份验证”。 To change it, select Change Authentication and then No Authentication.

  5. 选择“确定”创建该项目。 Select OK to create the project.

创建缓存Create a cache

接下来,为应用创建缓存。Next, you create the cache for the app.

  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.

    新建缓存

  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 TestResourcesTestResources 要在其中创建缓存的新资源组的名称。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.
    位置Location 中国北部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.

    创建缓存

  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 门户检索主机名、端口和访问密钥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 文件的步骤To edit the CacheSecrets.config file

  1. 在计算机上创建名为 CacheSecrets.config 的文件。将其放到不会连同示例应用程序的源代码一起签入的位置。Create a file on your computer named CacheSecrets.config. Put 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 at C:\AppSecrets\CacheSecrets.config.

  2. 编辑 CacheSecrets.config 文件。Edit the CacheSecrets.config file. 然后添加以下内容:Then add the following content:

    <appSettings>
        <add key="CacheConnection" value="<cache-name>.redis.cache.chinacloudapi.cn,abortConnect=false,ssl=true,password=<access-key>"/>
    </appSettings>
    
  3. <cache-name> 替换为缓存主机名。Replace <cache-name> with your cache host name.

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

    Tip

    在密钥轮换期间重新生成主访问密钥时,可以将辅助访问密钥用作备用密钥。You can use the secondary access key during key rotation as an alternate key while you regenerate the primary access key.

  5. 保存文件。Save the file.

更新 MVC 应用程序Update the MVC application

在本部分,请对应用程序进行更新,使之支持一个新视图,该视图显示针对 Azure Redis 缓存执行的一项简单测试。In this section, you update the application to support a new view that displays a simple test against Azure Cache for Redis.

使用缓存的应用设置更新 web.config 文件Update the web.config file with an app setting for the cache

在本地运行应用程序时,将使用 CacheSecrets.config 中的信息连接到 Azure Redis 缓存实例 。When you run the application locally, the information in CacheSecrets.config is used to connect to your Azure Cache for Redis instance. 稍后请将此应用程序部署到 Azure。Later you deploy this application to Azure. 到时,请在 Azure 中配置一项应用设置,供应用程序用来检索缓存连接信息而不是此文件。At that time, you configure an app setting in Azure that the application uses to retrieve the cache connection information instead of this file.

由于 CacheSecrets.config 文件未连同应用程序一起部署到 Azure,因此,只是在本地测试应用程序时才使用此文件。Because the file CacheSecrets.config isn't deployed to Azure with your application, you only use it while testing the application locally. 请尽量安全地保管此信息,防止有人恶意访问缓存数据。Keep this information as secure as possible to prevent malicious access to your cache data.

更新 web.config 文件的步骤To update the web.config file

  1. 在“解决方案资源管理器”中,双击“web.config”文件将其打开。 In Solution Explorer, double-click the web.config file to open it.

    Web.config

  2. web.config 文件中找到 <appSetting> 元素。In the web.config file, find the <appSetting> element. 然后添加以下 file 属性。Then add the following file attribute. 如果使用了其他文件名或位置,请使用这些值来替换示例中显示的值。If you used a different file name or location, substitute those values for the ones that are shown in the example.

  • 之前: <appSettings>Before: <appSettings>
  • 之后:<appSettings file="C:\AppSecrets\CacheSecrets.config">After: <appSettings file="C:\AppSecrets\CacheSecrets.config">

ASP.NET 运行时合并了外部文件的内容以及 <appSettings> 元素中的标记。The ASP.NET runtime merges the contents of the external file with the markup in the <appSettings> element. 如果找不到指定的文件,运行时会忽略文件属性。The runtime ignores the file attribute if the specified file can't be found. 应用程序的源代码中将不包括机密(连接到缓存的连接字符串)。Your secrets (the connection string to your cache) aren't included as part of the source code for the application. 将 Web 应用部署到 Azure 时,不会部署 CacheSecrets.config 文件。When you deploy your web app to Azure, the CacheSecrets.config file isn't deployed.

将应用程序配置为使用 StackExchange.Redis 的步骤To configure the application to use StackExchange.Redis

  1. 若要将应用配置为使用 Visual Studio 的 StackExchange.Redis NuGet 包,请选择“工具”>“NuGet 包管理器”>“包管理器控制台”。 To configure the app to use the StackExchange.Redis NuGet package for Visual Studio, select Tools > NuGet Package Manager > Package Manager Console.

  2. Package Manager Console 窗口运行以下命令:Run the following command from the Package Manager Console window:

    Install-Package StackExchange.Redis
    
  3. NuGet 程序包会为客户端应用程序下载并添加所需的程序集引用,以通过 StackExchange.Azure Redis 缓存客户端访问 Azure Redis 缓存。The NuGet package downloads and adds the required assembly references for your client application to access Azure Cache for Redis with the StackExchange.Azure Cache for Redis client. 如果更愿使用强命名版本的 StackExchange.Redis 客户端库,请安装 StackExchange.Redis.StrongName 包。If you prefer to use a strong-named version of the StackExchange.Redis client library, install the StackExchange.Redis.StrongName package.

更新 HomeController 和布局的步骤To update the HomeController and Layout

  1. 在“解决方案资源管理器”中展开“Controllers”文件夹,然后打开“HomeController.cs”文件。 In Solution Explorer, expand the Controllers folder, and then open the HomeController.cs file.

  2. 在文件的顶部添加以下两个 using 语句,以支持缓存客户端和应用设置。Add the following two using statements at the top of the file to support the cache client and app settings.

    using System.Configuration;
    using StackExchange.Redis;
    
  3. 将以下方法添加到 HomeController 类,使之支持针对新缓存运行某些命令的新 RedisCache 操作。Add the following method to the HomeController class to support a new RedisCache action that runs some commands against the new cache.

        public ActionResult RedisCache()
        {
            ViewBag.Message = "A simple example with Azure Cache for Redis on ASP.NET.";
    
            var lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
            {
                string cacheConnection = ConfigurationManager.AppSettings["CacheConnection"].ToString();
                return ConnectionMultiplexer.Connect(cacheConnection);
            });
    
            // 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
            ViewBag.command1 = "PING";
            ViewBag.command1Result = cache.Execute(ViewBag.command1).ToString();
    
            // Simple get and put of integral data types into the cache
            ViewBag.command2 = "GET Message";
            ViewBag.command2Result = cache.StringGet("Message").ToString();
    
            ViewBag.command3 = "SET Message \"Hello! The cache is working from ASP.NET!\"";
            ViewBag.command3Result = cache.StringSet("Message", "Hello! The cache is working from ASP.NET!").ToString();
    
            // Demonstrate "SET Message" executed as expected...
            ViewBag.command4 = "GET Message";
            ViewBag.command4Result = cache.StringGet("Message").ToString();
    
            // Get the client list, useful to see if connection list is growing...
            ViewBag.command5 = "CLIENT LIST";
            ViewBag.command5Result = cache.Execute("CLIENT", "LIST").ToString().Replace(" id=", "\rid=");
    
            lazyConnection.Value.Dispose();
    
            return View();
        }
    
  4. 解决方案资源管理器中,展开“视图” > “共享”文件夹。 然后打开 _Layout.cshtml 文件。Then open the _Layout.cshtml file.

    将:Replace:

    @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
    

    替换为:with:

    @Html.ActionLink("Azure Cache for Redis Test", "RedisCache", "Home", new { area = "" }, new { @class = "navbar-brand" })
    

添加新 RedisCache 视图的步骤To add a new RedisCache view

  1. 在“解决方案资源管理器”中,展开“Views”文件夹,并右键单击“Home”文件夹。 In Solution Explorer, expand the Views folder, and then right-click the Home folder. 选择“添加” > “视图...”。 Choose Add > View....

  2. 在“添加视图”对话框中,输入 RedisCache 作为视图名称。 In the Add View dialog box, enter RedisCache for the View Name. 然后选择“添加” 。Then select Add.

  3. RedisCache.cshtml 文件中的代码替换为以下代码:Replace the code in the RedisCache.cshtml file with the following code:

    @{
        ViewBag.Title = "Azure Cache for Redis Test";
    }
    
    <h2>@ViewBag.Title.</h2>
    <h3>@ViewBag.Message</h3>
    <br /><br />
    <table border="1" cellpadding="10">
        <tr>
            <th>Command</th>
            <th>Result</th>
        </tr>
        <tr>
            <td>@ViewBag.command1</td>
            <td><pre>@ViewBag.command1Result</pre></td>
        </tr>
        <tr>
            <td>@ViewBag.command2</td>
            <td><pre>@ViewBag.command2Result</pre></td>
        </tr>
        <tr>
            <td>@ViewBag.command3</td>
            <td><pre>@ViewBag.command3Result</pre></td>
        </tr>
        <tr>
            <td>@ViewBag.command4</td>
            <td><pre>@ViewBag.command4Result</pre></td>
        </tr>
        <tr>
            <td>@ViewBag.command5</td>
            <td><pre>@ViewBag.command5Result</pre></td>
        </tr>
    </table>
    

在本地运行应用Run the app locally

默认情况下,项目配置为在 IIS Express 本地托管应用,以进行测试和调试。By default, the project is configured to host the app locally in IIS Express for testing and debugging.

在本地运行应用的步骤To run the app locally

  1. 在 Visual Studio 中选择“调试” > “开始调试”,在本地生成并启动用于测试和调试的应用。 In Visual Studio, select Debug > Start Debugging to build and start the app locally for testing and debugging.

  2. 在浏览器中,选择导航栏上的“Azure Redis 缓存测试”。 In the browser, select Azure Cache for Redis Test on the navigation bar.

  3. 在下面的示例中,Message 键以前有一个缓存值,该值是在门户中使用 Azure Redis 缓存控制台设置的。In the following example, the Message key previously had a cached value, which was set by using the Azure Cache for Redis console in the portal. 应用更新了该缓存值。The app updated that cached value. 应用还执行了 PINGCLIENT LIST 命令。The app also executed the PING and CLIENT LIST commands.

    对完成的本地项目进行简单测试

在 Azure 中发布和运行Publish and run in Azure

在本地成功测试应用后,即可将应用部署到 Azure 并在云中运行它。After you successfully test the app locally, you can deploy the app to Azure and run it in the cloud.

将应用发布到 Azure 的步骤To publish the app to Azure

  1. 在 Visual Studio 中右键单击解决方案资源管理器中的项目节点,In Visual Studio, right-click the project node in Solution Explorer. 然后选择“发布”。 Then select Publish.

    发布

  2. 依次选择“Azure 应用服务”、“新建”、“发布”。 Select Azure App Service, select Create New, and then select Publish.

    发布到应用服务

  3. 在“创建应用服务”对话框中进行以下更改: In the Create App Service dialog box, make the following changes:

    设置Setting 建议的值Recommended value 说明Description
    应用名称App name 使用默认值。Use the default. 应用名称是应用部署到 Azure 时对应的主机名。The app name is the host name for the app when it's deployed to Azure. 如果需要让该名称保持唯一,可在其后添加一个时间戳后缀。The name might have a timestamp suffix added to it to make it unique if necessary.
    订阅Subscription 选择自己的 Azure 订阅。Choose your Azure subscription. 将对此订阅收取任何相关的托管费用。This subscription is charged for any related hosting costs. 如果有多个 Azure 订阅,请验证是否选择了所需的订阅。If you have multiple Azure subscriptions, verify that the subscription that you want is selected.
    资源组Resource group 使用在其中创建了此缓存的资源组(例如,TestResourceGroup)。Use the same resource group where you created the cache (for example, TestResourceGroup). 该资源组用于将所有资源作为一个组管理。The resource group helps you manage all resources as a group. 以后想要删除此应用时,可以直接删除该组。Later, when you want to delete the app, you can just delete the group.
    应用服务计划App Service plan 选择“新建”,然后创建名为 TestingPlan 的新应用服务计划。 Select New, and then create a new App Service plan named TestingPlan.
    使用创建缓存时所用的相同位置Use the same Location you used when creating your cache.
    选择“免费”作为大小。 Choose Free for the size.
    应用服务计划为要运行的 Web 应用定义一组计算资源。An App Service plan defines a set of compute resources for a web app to run with.

    “应用服务”对话框

  4. 配置应用服务托管设置以后,请选择“创建” 。After you configure the App Service hosting settings, select Create.

  5. 监视 Visual Studio 中的“输出”窗口,了解发布状态。 Monitor the Output window in Visual Studio to see the publishing status. 发布应用后,系统会记录应用的 URL:After the app has been published, the URL for the app is logged:

    发布输出

为缓存添加应用设置Add the app setting for the cache

发布新应用以后,请添加新应用设置。After the new app has been published, add a new app setting. 此设置用于存储缓存连接信息。This setting is used to store the cache connection information.

添加应用设置的步骤To add the app setting

  1. 在 Azure 门户顶部的搜索栏中键入应用名称,查找刚创建的新应用。Type the app name in the search bar at the top of the Azure portal to find the new app you created.

    查找应用

  2. 为应用添加名为 CacheConnection 的新应用设置,用于连接到缓存。Add a new app setting named CacheConnection for the app to use to connect to the cache. 使用在 CacheSecrets.config 文件中为 CacheConnection 配置的相同值。Use the same value you configured for CacheConnection in your CacheSecrets.config file. 该值包含缓存主机名和访问密钥。The value contains the cache host name and access key.

    添加应用设置

在 Azure 中运行应用Run the app in Azure

在浏览器中,转到应用的 URL。In your browser, go to the URL for the app. 该 URL 显示在 Visual Studio 输出窗口的发布操作结果中。The URL appears in the results of the publishing operation in the Visual Studio output window. 此外,在 Azure 门户中,所创建应用的概览页上也提供了该 URL。It's also provided in the Azure portal on the overview page of the app you created.

选择导航栏上的“Azure Redis 缓存测试”以测试缓存访问 。Select Azure Cache for Redis Test on the navigation bar to test cache access.

对完成的 Azure 项目进行简单测试

清理资源Clean up resources

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

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

Important

删除资源组的操作不可逆。Deleting a resource group is irreversible. 删除资源组时,包含在其中的所有资源会被永久删除。When you delete a resource group, 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.

删除资源组的步骤To delete a resource group

  1. 登录到 Azure 门户,然后选择“资源组”。 Sign in to the Azure portal, and then select Resource groups.

  2. 在“按名称筛选...”框中键入资源组的名称 。In the Filter by name... box, 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 results list, select ..., and then select Delete resource group.

    Delete

系统会要求确认是否删除资源组。You're asked to confirm the deletion of the resource group. 键入资源组的名称进行确认,然后选择“删除” 。Type the name of your resource group to confirm, and then select Delete.

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

后续步骤Next steps

下一个教程会在一个更真实的场景中使用 Azure Redis 缓存来改善应用的性能。In the next tutorial, you use Azure Cache for Redis in a more realistic scenario to improve performance of an app. 请更新此应用程序,以便使用 ASP.NET 和数据库的缓存端模式来缓存排行榜结果。You update this application to cache leaderboard results using the cache-aside pattern with ASP.NET and a database.