1 public class ProductService 2 { 3 // Ctor 4 public ProductService(IProductRepository productRepository, ICacheStorage cacheStorage) 5 { 6 this.productRepository = productRepository; 7 this.cacheStorage = cacheStorage; 8 } 9 10 // Fields 11 private IProductRepository productRepository; 12 private ICacheStorage cacheStorage; 13 14 // Methods 15 public IList<Product> GetAllProductsIn(int categoryId) 16 { 17 IList<Product> products; 18 19 string storageKey = string.Format("products_in_category_id_{0}", categoryId); 20 21 products = cacheStorage.Retrieve<List<Product>>(storageKey); 22 23 if (products == null) 24 { 25 products = this.productRepository.GetAllProductsIn(categoryId); 26 cacheStorage.Store(storageKey, products); 27 } 28 29 return products; 30 } 31 }
诸位高手:
我想测试缓存是否发挥作用,要如何测试呢?
环境,ASP.NET MVC 4
其它 代码:
1 public interface ICacheStorage 2 { 3 void Remove(string key); 4 void Store(string key, object data); 5 T Retrieve<T>(string key); 6 }
1 public interface IProductRepository 2 { 3 IList<Product> GetAllProductsIn(int categoryId); 4 }
1 public class HttpContextCacheAdapter : ICacheStorage 2 { 3 public void Remove(string key) 4 { 5 HttpContext.Current.Cache.Remove(key); 6 } 7 8 public void Store(string key, object data) 9 { 10 HttpContext.Current.Cache.Insert(key, data); 11 } 12 13 public T Retrieve<T>(string key) 14 { 15 T itemStored = (T)HttpContext.Current.Cache.Get(key); 16 17 if(itemStored == null) 18 { 19 itemStored = default(T); 20 } 21 22 return itemStored; 23 } 24 }
在24行里面,加个LOG输出就知道了
谢谢 :)
1、通过浏览器 开发工具 查看 Cache-Control:是不是private,如果是,真没有cache,还有Expires过期时间等
2、if(Cache[key]==null) 将数据放到cache中
谢谢