public class ProductService : IProductService
{
private readonly object _locker = new object();
private readonly IMemoryCache _memoryCache;
public ProductService(IMemoryCache memoryCache)
{
_memoryCache = memoryCache;
}
public IEnumerable<Product> GetProducts()
{
List<Product> products;
if (!_memoryCache.TryGetValue("Products", out products))
{
if (!_memoryCache.TryGetValue("Products", out products))
{//当内存中不存在是,则从数据库中获取数据
lock (_locker)
{//当创建缓存时,需要加锁,防止多个线程同时创建缓存
products = new List<Product>
{
new Product { Id = 1, Name = "Product 1" },
new Product { Id = 2, Name = "Product 2" },
new Product { Id = 3, Name = "Product 3" }
};
_memoryCache.Set("Products", products, new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10)
});
}
}
}
return products;
}
}
public interface IProductService
{
IEnumerable<Product> GetProducts();
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
}