Exportar (0) Imprimir
Expandir Tudo

How to: Use an Azure In-Role Cache in Azure Cloud Service

Atualizado: agosto de 2014

Caching can improve the performance of the web applications in your Azure cloud service projects by reducing the need for repeatedly computing the same results. When you use caching, frequently requested content and other data can be computed once and stored for repeated use.

By following this topic, you can add caching support to your Azure cloud service projects. By using the Azure In-Role Cache, you can set up roles that are dedicated to caching, or you can use otherwise unused resources in a role for caching. For example, if your web role is using only half of the available resources in each instance, you could use these resources to cache output, session state, or frequently used data.

You configure caching in the .cscfg and .csdef files for your Azure cloud service application, and you can perform this configuration most easily by using the settings in the Caching property page for a role. To use a cache in a particular role, you add information to the XML configuration files for that role. In an ASP.NET web role, the appropriate configuration file is web.config. For other roles, the configuration file is app.config. You can add the information to the configuration file manually or by using a NuGet package. For more information about In-Role Cache, see Azure In-Role Cache.

You can configure caching in two ways. You can add caching to a cloud service by adding a cache worker role that is dedicated to caching, or you can configure caching to use memory, CPU, and bandwidth resources on a previously existing role. A dedicated cache runs as a separate role. This option is appropriate if you want the resources of your instances to be dedicated solely to running those instances. A co-located cache runs in the same instance as another role. This option is an appropriate choice if you have role instances that don't fully use the machine resources on which they run.

This topic contains the following sections.

You can either add caching to an existing role, or you can create a cache worker role that you can use from other roles.

  1. Open the shortcut menu for the Azure cloud service project, and then choose New Worker Role Project.

  2. In the list of project templates, choose the Cache Worker Role template, and then specify a name for the project, such as CacheWorkerRole1.

    A worker role project is created.

  3. Under the Azure cloud service project, expand the Roles node, open the shortcut menu for the cache worker role that you just created, and then choose Properties.

    The role designer for this project appears.

  4. On the Configuration tab, set the appropriate size of the virtual machine and the number of instances for this role.

  5. On the Caching tab, note that, under Cache Cluster Settings, Dedicated Role is selected.

  6. Configure the behavior that you want for the default cache, or create named caches with customized properties.

    Each named cache has its own set of configurable properties. Point to the table headers to display information about how you can configure each named cache. For more information, see How to: Configure an Azure In-Role Cache.

  1. In the Azure cloud service project, expand the Roles node, open the shortcut menu for the role to which you want to add caching, and then choose Properties.

  2. On the Caching tab, select the Enable Caching check box.

  3. Choose the Co-located option, and then choose a percentage of the memory resources of the virtual machine that hosts the role to dedicate to the cache. Generally this number should be in the range of 30 to 55 percent for a Small virtual machine and up to 80 percent for an Extra Large virtual machine. You can optimize this number by using Remote Desktop to log onto the virtual machine when your cloud service is running under a normal load and then using Task Manager to view the % Physical Memory. You can use the remaining memory for a co-located cache.

  4. Configure the behavior that you want for the default cache, or create named caches with customized properties.

You can manually add caching references to your cloud service project, as this section describes, or you can use NuGet, as Using NuGet to add caching to a role describes later in this topic. Adding the references manually enables you to see where the assemblies exist on disk, but it is more cumbersome.

  1. On the shortcut menu for the References node under the cloud service project that contains the role in which you want to use a cache, choose Add Reference.

  2. In the Add Reference dialog box, select the appropriate check boxes to add references to the following assemblies, and then choose the OK button:

    • Microsoft.ApplicationServer.Caching.AzureClientHelper

    • Microsoft.ApplicationServer.Caching.Client

    • Microsoft.ApplicationServer.Caching.Core

    • Microsoft.Web.DistributedCache

  3. In the project that contains the role to which you want to add caching, open the web.config file for a web role project, or open the app.config file for other project types.

  4. If the configSections section doesn’t exist, add it. In that section, add a declaration of the caching section as the following code shows.

    <configSections>
        <section name="dataCacheClients" type="Microsoft.ApplicationServer.Caching.DataCacheClientsSection, Microsoft.ApplicationServer.Caching.Core" allowLocation="true" allowDefinition="Everywhere"/>
      </configSections>
    
    
  5. Add XML that identifies the named cache to use.

    <dataCacheClients>
        <tracing sinkType="DiagnosticSink" traceLevel="Verbose"/>
        <dataCacheClient name="default">
          <autoDiscover isEnabled="true" identifier="WebRole1"/>
        </dataCacheClient>
      </dataCacheClients>
    
    

    If you’re declaring only one cache, the name can be default, as the previous example shows. If you’re declaring multiple caches, add a separate dataCacheClient section for each cache, and give each cache a unique name. The cache that’s named default will be returned when, in code, you call the GetDefaultCache method on the DataCacheFactory object. The identifier attribute specifies either the name of the web role project to which you added caching support or a cache worker role.

    Now that you've configured a distributed cache in this role, you can access it from code by creating a DataCacheFactory and a DataCache object.

  6. In a code-behind file, add declarations to your Page class, and add a random number generator so that you have some data to test the cache.

            static DataCacheFactory myFactory;
            static DataCache myCache;
            static Random randomizer = new Random();
    
    
  7. To create a web application that uses the cache, replace the code in the Default.aspx web page with the following code.

    <%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
        CodeBehind="Default.aspx.cs" Inherits="WebRole1._Default" %>
    
    <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
    </asp:Content>
    <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
     
         <p style="font-size:large; height: 283px;">
            <asp:Label ID="Label0" runat="server" Text="Text for the cache:   " />
            <asp:TextBox runat="server" ID="TextBox1" Width="125" /> <br /> <br />
    
            <asp:Button runat="server" onclick="OnPutInCache" Text="Put in Cache" id="AddCachedItemsButton" /> &nbsp;&nbsp;&nbsp;
            <asp:Button runat="server" onclick="OnGetFromCache" Text="Get from Cache" id="GetCachedItemsButton" /> &nbsp;&nbsp;&nbsp;
            <asp:Label ID="Label1" runat="server" Width="500" />
    
            <br /> <br />  <br /> 
        
            Cached Datestamp: <%= DateTime.Now.ToString() %><br />
            Fresh Datestamp: <asp:Substitution runat="server" methodname="GetFreshDateTime" id="UnCachedArea" /><br /><br />
        </p>
    
    </asp:Content>
    
    
    
  8. Add code to initialize the cache.

            protected void Page_Load(object sender, EventArgs e)
            {
                try
                {
                    //Get a named cache (or default cache)
                    if (myCache == null)
                    {
                        // You should initialize the data cache factory
                        // once and keep reusing the same object.
                        myFactory = new DataCacheFactory();
                        myCache = myFactory.GetDefaultCache();
                        // If you want to get a handle to a named cache
                        // that is not the default cache, supply the
                        // cache's name from the configuration file:
                        // myCache = myFactory.GetCache("anotherNamedCache");
                    }
                }
                catch (DataCacheException dce)
                {
                    Label1.Text = dce.ToString();
                }
            }
    
    

    This initialization code should be called before any attempt to use the cache, for example, you might add this code to the Page_Load event handler. Otherwise, a handle to the cache is created by using the cache factory method GetDefaultCache(). If no cache name is specified, the cache that’s named default is used. The exception DataCacheException may be thrown whenever you work with cache methods. The previous code catches that exception and displays it to the user on a Label control.

  9. Add code to use the cache.

            /// <summary>
            /// Adds the value of the TextBox to the cache
            /// </summary>
            protected void OnPutInCache(object sender, EventArgs e)
            {
                try
                {
                    myCache.Put("MyKey", TextBox1.Text);
                    Label1.Text = " \" " + TextBox1.Text + "\" has been added to the cache.";
                }
                catch (DataCacheException dce)
                {
                    Label1.Text = dce.ToString();
                }
            }
    
    

    The previous example assumes a simple web form with a text box and a button, but you can use the same code to cache any data. As the example shows, you use the Put method to add data to the cache. The cache operates as a dictionary. The first argument is the key; the second argument is the data that you want to cache.

  10. Retrieve data from the caching by calling the Get method and providing the key.

            /// <summary>
            /// Gets the cached item (that was added from the TextBox)
            /// </summary>
            protected void OnGetFromCache(object sender, EventArgs e)
            {
                try
                {
                    string outputFromCache = myCache.Get("MyKey") as string;
                    Label1.Text = "\"" + outputFromCache + "\" has been retrieved from the cache.";
                }
                catch (DataCacheException dce)
                {
                    Label1.Text = dce.ToString();
                }
            }
    
    

Output caching improves the performance of a website by reducing the need to regenerate data that has already been retrieved. By editing the configuration file for the web application, you can use the distributed cache to cache output for an ASP.NET application without changing your program code. See How to: Configure an Azure In-Role Cache for more information.

  1. Open the web.config file for the ASP.NET application for which you want to configure output caching.

  2. Add the following lines to configure output caching to use the distributed cache.

        <caching>
          <outputCache defaultProvider="defaultProvider" >
            <providers>
              <add cacheName="default"
                   name="defaultProvider"
                   dataCacheClientName="nameOfDataCacheClient"
                   applicationName="<unique-appId>"
                   type= "Microsoft.Web.DistributedCache.DistributedCacheOutputCacheProvider, Microsoft.Web.DistributedCache" />
            </providers>
          </outputCache>
        </caching>
    
    

    For the cacheName, specify the name of the appropriate named cache, which is hosted by the specified dataCacheClient. The dataCacheClient attribute specifies the role that hosts the cache.

  3. Add the OutputCache directive to the pages where you want to cache the output.

    <%@ OutputCache Duration="60" VaryByParam="*" %>
    

    Duration is the amount of time, in seconds, that you want data to remain in the cache. VaryByParam indicates that a different version of the page should be cached for each parameter combination. The asterisk (*) in this context means vary by all parameters. You could also specify parameters by name. For a complete description of the available options, see OutputCache Directive

    You’ve configured the output cache.

This section shows you how to cache session state information for an ASP.NET web application without modifying its code.

  1. Open the web.config file for the ASP.NET web application for which you want to configure session state caching.

  2. Add the following lines, and specify the name of the cache that you want to use (in this case, "default"), the name of the provider, the name of the dataCacheClient, and the application's appId.

        <!--Set up custom session state provider -->
        <sessionState mode="Custom" customProvider="defaultProvider">
          <providers>
            <add cacheName="default"
                 name="defaultProvider"
                 dataCacheClientName="nameOfDataCacheClient"
                 applicationName="<unique-appId>"
                 type= "Microsoft.Web.DistributedCache.DistributedCacheSessionStateStoreProvider, Microsoft.Web.DistributedCache"/>
          </providers>
        </sessionState>
    
    

You can create and configure multiple named caches for different purposes. For example, you can use one cache for output and one cache programmatically for data.

  1. Open the Caching tab of the role designer for a role.

  2. Under Named Caches, add a named cache for output and another for session state information.

  3. In the Named Caches table, set the properties for the named caches.

    For example, you can set the eviction policy to TTL for the output cache and to None for the session state cache.

  4. Open the web.config file, and then change the cacheName attributes in the outputCache and sessionState sections to the new values.

You can add caching to an existing role most easily by using NuGet, which is a package manager. When you have the Azure Tools installed, NuGet can add the appropriate references and make the required modifications to your configuration files.

  1. Ensure that you have the newest version of NuGet installed.

    For more information and installation instructions, see NuGet.

  2. In Solution Explorer, open the shortcut menu for the project node for the role to which you want to add caching, and then choose Manage NuGet packages.

    The Manage NuGet Packages dialog box appears.

  3. In the Online gallery, Choose Azure In-Role Cache, and then choose the Install button.

    The project is modified, references to caching assemblies are added, and configuration files are updated to configure a cache.

  4. In the configuration file for the project, search for the dataCacheClient element, which has an autoDiscover child element.

  5. In that child element, change the value of the identifier attribute to the name of the role that provides the cache.

        <dataCacheClient name="default">
          <autoDiscover isEnabled="true" identifier="CacheWorkerRole1"/>
        </dataCacheClient>
    
    
  6. To start using the cache, modify your code as described previously in this topic.

    To enable an output cache or session state cache, edit the configuration file for the appropriate role and make other changes as described previously in this topic. To use the cache programmatically, add the appropriate code to your code-behind files to create a cache and add and retrieve data.

  7. (optional) To manage NuGet packages for an entire solution and add caching support to multiple projects simultaneously, open the shortcut menu for the solution node, and then choose Manage NuGet Packages.

Consulte também

Mostrar:
© 2014 Microsoft