当值不在缓存中时,将值添加到缓存中

时间:2011-11-20 09:51:19

标签: caching appfabric

我想编写缓存的基本CRUD操作(创建新对象,删除它,更新...)我首先创建对象并显示其名称这是我的代码: (我的缓存名称="默认")

的web.config:

..........

<configuration>
<configSections>
<section name="dataCacheClient"
   type="Microsoft.ApplicationServer.Caching.DataCacheClientSection,
    Microsoft.ApplicationServer.Caching.Core,
    Version=1.0.0.0,  Culture=neutral,PublicKeyToken=31bf3856ad364e35" />
     </configSections>
     <dataCacheClient>
      <hosts>
        <host name="Amira-PC" cachePort="22233" />

        </hosts>
       </dataCacheClient>

         ......

Global.asax.cs:

     using Microsoft.ApplicationServer.Caching;

      namespace AppFabricCachingTest{
        public class Global : System.Web.HttpApplication
         {
         public static string CacheFactoryName = "CacheFactory";
          void Application_Start(object sender, EventArgs e)
          {
        // Code qui s'exécute au démarrage de l'application


        var dcf = new DataCacheFactory();
        Application[CacheFactoryName] = dcf;
        DataCache myCache = dcf.GetCache("default");// cache name=mycache

        object myCachedItem = new Object();
        string myCachedItemKey = "MyCacheKey";
        myCache.Add(myCachedItemKey, myCachedItem);



     }
    .....

     `  

Site.Master.cs

       `  
        using Microsoft.ApplicationServer.Caching;

         namespace AppFabricCachingTest
       {
           public partial class SiteMaster : System.Web.UI.MasterPage
               {
           protected void Page_Load(object sender, EventArgs e)
              {

                }

    public string GetCachedName()
     {
       string name = null;
       string key ="MyCacheKey";

        var dcf = Application[Global.CacheFactoryName] as DataCacheFactory;

          if (dcf != null)
            {
    var cache = dcf.GetCache("default");
    name = cache.Get(key) as string;
    if (name == null)
    {
        name = "Windows Server App Fabric Cache ";
        cache.Put(key, name);

    }
    else
    {
        name += " From Cache!";

            }
             }
        else name = "dcf is NULL";
           return name;
       }

         }
     }

Site.Master:

 <body>
        <form runat="server">
             <div class="page">
                <div class="header">
                   <div class="title">
            <h1>
               <%= GetCachedName() %>
            </h1>
        </div>
            ...............

跑完后我总是&#34; dcf是NULL&#34;而不是对象的名称 请问,

提前谢谢

1 个答案:

答案 0 :(得分:1)

我认为你缺少其他对象的声明作为DataCacheFactory初始化的一部分。 DataCacheFactory不知道它应该从哪里收集集群缓存。 请尝试以下代码

DataCacheServerEndpoint [] servers = new DataCacheServerEndpoint [1]; servers [0] = new DataCacheServerEndpoint(“localhost”,22233);

//设置DataCacheFactory配置。

DataCacheFactoryConfiguration factoryConfig = new DataCacheFactoryConfiguration(); factoryConfig.Servers = servers;

//创建一个已配置的DataCacheFactory对象。

DataCacheFactory cacheFactory = new DataCacheFactory(factoryConfig);