.NET C#基础教程第16天:Memory Caching

作者:微信公众号:【架构师老卢】
6-10 9:34
45

概述:介绍应用程序性能的主要问题之一是从外部数据源(主要是数据库)响应所需的时间。当数据库驻留在远程计算机中或遇到重负载时,挑战是很困难的。内存中缓存可以作为更好的实现,以避免性能瓶颈。学习目标如何使用内存中缓存主要优势开发人员的先决条件基本了解 C# 编程语言。开始通常,开发人员直接从数据库中获取信息或数据。这是一种非常直接和简单的方法,但是当数据库处于重负载下时,可能会导致性能问题,从而影响应用程序性能并阻碍UI体验public Product GetProductById(int id){ // Fetching product data from the database every

介绍

应用程序性能的主要问题之一是从外部数据源(主要是数据库)响应所需的时间。当数据库驻留在远程计算机中或遇到重负载时,挑战是很困难的。内存中缓存可以作为更好的实现,以避免性能瓶颈。

学习目标

  • 如何使用内存中缓存
  • 主要优势

开发人员的先决条件

  • 基本了解 C# 编程语言。

开始

通常,开发人员直接从数据库中获取信息或数据。这是一种非常直接和简单的方法,但是当数据库处于重负载下时,可能会导致性能问题,从而影响应用程序性能并阻碍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

相关代码下载地址
重要提示!:取消关注公众号后将无法再启用回复功能,不支持解封!
第一步:微信扫码关键公众号“架构师老卢”
第二步:在公众号聊天框发送code:64046,如:code:64046 获取下载地址
第三步:恭喜你,快去下载你想要的资源吧
阅读排行