应用程序性能的主要问题之一是从外部数据源(主要是数据库)响应所需的时间。当数据库驻留在远程计算机中或遇到重负载时,挑战是很困难的。内存中缓存可以作为更好的实现,以避免性能瓶颈。
通常,开发人员直接从数据库中获取信息或数据。这是一种非常直接和简单的方法,但是当数据库处于重负载下时,可能会导致性能问题,从而影响应用程序性能并阻碍UI体验
public Product GetProductById(int id)
{
// Fetching product data from the database every time
var product = _dbContext.Products.FirstOrDefault(p => p.Id == id);
return product;
}
内存中缓存涉及将经常访问的数据临时存储在应用程序服务器的内存中,从而大大减少了从数据库中检索每个请求的数据的需要。
private static MemoryCache _cache = new MemoryCache(new MemoryCacheOptions());
public Product GetProductById(int id)
{
// Fetching product data from the cache if available
if (!_cache.TryGetValue(id, out Product product))
{
product = _dbContext.Products.FirstOrDefault(p => p.Id == id);
_cache.Set(id, product, TimeSpan.FromMinutes(30));
}
return product;
}
要使用 ,您需要将包添加到您的项目中。MemoryCacheMicrosoft.Extensions.Caching.Memory
dotnet add package Microsoft.Extensions.Caching.Memory
创建一个具有名为函数的类,该函数返回以下类型的类对象InMemoryCacheGetProductByIdProduct
public static class InMemoryCache
{
private static MemoryCache _cache = new MemoryCache(new MemoryCacheOptions());
private static ProductRepository _productRepository = new ProductRepository();
public static Product GetProductById(int id)
{
if (!_cache.TryGetValue(id, out Product product))
{
Console.WriteLine("Fetching from database...");
product = _productRepository.GetProductById(id);
_cache.Set(id, product, TimeSpan.FromMinutes(30)); // Cache for 30 minutes
}
else
{
Console.WriteLine("Fetching from cache...");
}
return product;
}
}
模拟相关类ProductRepository Product
// Simulating a product repository
public class ProductRepository
{
public Product GetProductById(int id)
{
// Simulate database access
return new Product { Id = id, Name = $"Product {id}" };
}
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
}
从 main 方法调用,如下所示,并显示从内存中获取的数据的相关控制台输出。
#region Day 16: In-Memory Cache
Console.WriteLine("Fetching product with ID 1 for the first time:");
var product = InMemoryCache.GetProductById(1);
Console.WriteLine($"Product Name: {product.Name}\n");
Console.WriteLine("Fetching product with ID 1 again:");
product = InMemoryCache.GetProductById(1); // This time, it should come from the cache
Console.WriteLine($"Product Name: {product.Name}\n");
#endregion
源代码获取:公众号回复消息【code:64046
】