2016-03-23 229 views
2

我想在我们的应用程序中使用Memcached实现缓存,我能够设置键和值到服务器,但是当我试图获取值时它总是返回一个null 。以下是我的示例代码片段。MEMCACHED get方法总是返回null

//memcached configuration in my web config 
<enyim.com> 
    <memcached protocol="Binary"> 
    <servers> 
     <add address="127.0.0.1" port="11211"/> 
    </servers> 
    <socketPool minPoolSize="10" maxPoolSize="100" 
        connectionTimeout="00:10:00" deadTimeout="00:05:00"/> 

    </memcached> 
</enyim.com> 
<configSections> 
    <sectionGroup name="enyim.com"> 
     <section name="memcached" 
      type="Enyim.Caching.Configuration.MemcachedClientSection, 
      Enyim.Caching"/> 
    </sectionGroup> 
</configSections> 





//Get method in my controller 
public object GetSalesOrder() 
{ 
     using (Enyim.Caching.MemcachedClient mc = new Enyim.Caching.MemcachedClient()) 
     { 
      mc.FlushAll(); 
      var salesOrders = salesOrderListService.GetSalesOrders(); 
      byte[] val; 
      val = S.Serializer.objectToByteArray(salesOrders); 
      mc.Store(Enyim.Caching.Memcached.StoreMode.Set, "salesOrderList", val); 
      byte[] data = mc.Get<byte[]>("salesOrderList"); 
      var returnObj = S.Serializer.ByteArrayToObject<List<Model.SalesOrderList>>((byte[])val); 

      return returnObj; 
     }    
    } 


//Model 

[Serializable] 
[ResourceType("SalesOrderList")] 
public class SalesOrderList 
{ 
    public int Id { get; set; } 
    public string Code{ get; set; } 
    public string CustomerName{ get; set; } 
    public DateTime OrderDate { get; set; } 
    public DateTime ShipDate { get; set; } 
} 

//Serializer class 
public class Serializer 
    { 
     public static byte[] objectToByteArray<T>(T obj) 
     { 
      System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); 

      using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) 
      { 
       formatter.Serialize(ms, obj); 
       return ms.ToArray(); 
      } 
     } 

     public static Object ByteArrayToObject<T>(byte[] arrBytes) 
     { 
      using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) 
      { 
       System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); 
       ms.Write(arrBytes, 0, arrBytes.Length); 
       ms.Seek(0, System.IO.SeekOrigin.Begin); 

       object obj = (Object)formatter.Deserialize(ms); 

       return obj; 
      } 
     } 
    } 

我错过了什么吗?

回答

0

我在代码中看到错误的一件事是您没有缓存键来存储或检索您的数据。我在代码中的做法如下:

// create cachekey for storing and retrieving 
var cacheKey = Guid.NewGuid().ToString(); 
// store for an hour 
// memcachedClient.Store(StoreMode.Set, SanitizeCacheKey(cacheKey), value, validFor) 
mc.Store(StoreMode.Set, cacheKey , val, new TimeSpan(0, 1, 0, 0)); 

AccessCache.Get<byte[]>(cacheKey)