.NET 帮助

Microsoft.Extensions.Caching.Memory 示例(包含 PDF)在 C#

发布 2024年六月6日
分享:

为了快速有效地构建应用程序,.NET 应用程序经常需要使用优化方法。缓存是一种有效的方法,包括在分布式缓存中临时存储经常请求的材料,以加快检索速度。采用这种策略可以减少处理时间和服务器负载,从而显著提高应用程序的性能。此外,还可以使用性能计数器来监控和增强缓存系统。

缓存 在这种情况下,"Microsoft.Extensions.Caching.Memory "是一种有效的优化策略。Microsoft.Extensions.Caching.Memory "为.NET应用程序提供了高效的内存对象缓存解决方案。如果您有计划地将 MemoryCache 缓存与 IronPDF 一起使用,那么以 PDF 为中心的应用程序的运行和响应速度将大大加快。

我们将探讨如何将 "Microsoft.Extensions.Caching.Memory "c#示例与 IronPDF 高效集成。在本文中,我们将讨论缓存在以下方面的优势 PDF 生成 您还将了解到如何在您的 IronPDF 程序中配置缓存,如何在您的 IronPDF 程序中配置缓存,以及如何在您的 IronPDF 程序中配置缓存。所有内容完成后,您将掌握开发高效、直观的 PDF 应用程序所需的技能和资源。

Microsoft.Extensions.Caching.Memory:.NET中缓存的基础

缓存是许多高性能 .NET 应用程序中使用的一种方法,它将经常访问的数据存储在内存中,以便快速检索。Microsoft.Extensions "是许多可访问的缓存选项之一。Caching.Memory "是一个特别强大且适应性强的选项。该库是更大的 Microsoft.Extensions.Caching命名空间的一个组件,提供了一种直接但有效的内存缓存方法。

Microsoft.Extensions.Caching.Memory "中的键类型

IMemoryCache

  • 该接口代表了利用内存缓存的基本功能。它提供了管理缓存项、添加、检索和删除缓存项的方法。
  • 请将其视为缓存进程的主要入口。

MemoryCache

  • 该类是 IMemoryCache 的实际实现。它为缓存项提供管理和真正的内存存储。
  • ASP.NET Core 应用程序中通常使用依赖注入来检索MemoryCache的实例。

MemoryCacheEntryOptions

您可以使用该类为特定缓存项指定配置设置。这些设置可对以下事项进行管理

  • 过期:您可以配置滑动到期窗口 (如果条目在一定时间间隔内未被访问,则过期失效) 或绝对过期时间 (条目自动失效).
  • 优先级:当缓存填满时,这将影响是否删除条目。优先级较高的条目被删除的几率较低。

  • 驱逐后回调:这可以让你在数据过期时对处理数据的逻辑进行微调。它在需要刷新关键数据、资源管理和日志记录的情况下尤其有用。

CacheEntry

  • 在缓存中,该类型表示单个条目。它提供的方法和属性可用于检索大小详情、过期设置和缓存值。
  • 从本质上讲,它包含了缓存中保存的特定数据的所有信息。

ICacheEntry

  • 该接口概述了可在缓存项上执行的基本活动,尽管基本缓存操作并不需要它。它包含如何检索值和过期详情的说明。这在需要检索字符串密钥的情况下更为常见。
  • 该接口由 CacheEntry 类实现,它提供了这些功能的实际实现。

安装并配置 "Microsoft.Extensions.Caching.Memory"。

Microsoft.Extensions.Caching "配置。在应用程序启动期间,内存将用于在 ASP.NET Core 应用程序的服务集合中配置缓存服务。配置了 "Microsoft.Extensions.Caching.Memory "的 ASP.NET Core 应用程序如下所示:

安装所需的 NuGet 软件包

首先,确保为项目安装了 Microsoft.Extensions.Caching.Memory。使用 NuGet 软件包管理器控制台,可以用以下命令安装:

Install-Package Microsoft.Extensions.Caching.Memory

或者,我们可以使用 NuGet 软件包管理器来安装软件包:

C#中的Microsoft.Extensions.Caching.Memory示例(含PDF):图 1 - 在 NuGet 包管理器中搜索 Microsoft.Extensions.Caching.Memory 并安装

在 Startup.cs 中配置服务

打开 ASP.NET Core 应用程序中的 Startup.cs 文件,导航到 ConfigureServices 方法。要设置内存缓存服务,请添加以下代码:

using Microsoft.Extensions.Caching.Memory;
public void ConfigureServices(IServiceCollection services)
{
    // Add memory cache service
    services.AddMemoryCache();
    // Other service configurations...
}
using Microsoft.Extensions.Caching.Memory;
public void ConfigureServices(IServiceCollection services)
{
    // Add memory cache service
    services.AddMemoryCache();
    // Other service configurations...
}
Imports Microsoft.Extensions.Caching.Memory
Public Sub ConfigureServices(ByVal services As IServiceCollection)
	' Add memory cache service
	services.AddMemoryCache()
	' Other service configurations...
End Sub
VB   C#

内存缓存服务对象被添加到应用程序的服务集合中,并由该代码进行配置。内存缓存系统服务通过 "AddMemoryCache "函数使用默认配置注册。

注入IMemoryCache

缓存存储设置完成后,任何需要缓存的类或组件都可以注入 IMemoryCache 接口。例如,在控制器或服务类中:

public class MyService
{
    private readonly IMemoryCache _cache;
    public MyService(IMemoryCache cache)
    {
        _cache = cache;
    }
    // Use _cache to perform caching operations...
}
public class MyService
{
    private readonly IMemoryCache _cache;
    public MyService(IMemoryCache cache)
    {
        _cache = cache;
    }
    // Use _cache to perform caching operations...
}
Public Class MyService
	Private ReadOnly _cache As IMemoryCache
	Public Sub New(ByVal cache As IMemoryCache)
		_cache = cache
	End Sub
	' Use _cache to perform caching operations...
End Class
VB   C#

从内存中缓存和检索数据的方法由 IMemoryCache 接口提供。

配置缓存选项

通过设置缓存参数,可以改变内存缓存的行为方式。这需要配置一组参数,包括大小限制、缓存条目驱逐策略和缓存值过期规定。下面是如何设置缓存选项的示例:

public void ConfigureServices(IServiceCollection services)
{
    // Configure cache options
    services.AddMemoryCache(options =>
    {
        options.SizeLimit = 1024; // Set the maximum size limit for the cache
        options.CompactionPercentage = 0.75; // Set the percentage of memory to free up when the cache size exceeds the limit
        options.ExpirationScanFrequency = TimeSpan.FromMinutes(5); // Set how often the cache should scan for expired items
    });
    // Other service configurations...
}
public void ConfigureServices(IServiceCollection services)
{
    // Configure cache options
    services.AddMemoryCache(options =>
    {
        options.SizeLimit = 1024; // Set the maximum size limit for the cache
        options.CompactionPercentage = 0.75; // Set the percentage of memory to free up when the cache size exceeds the limit
        options.ExpirationScanFrequency = TimeSpan.FromMinutes(5); // Set how often the cache should scan for expired items
    });
    // Other service configurations...
}
Public Sub ConfigureServices(ByVal services As IServiceCollection)
	' Configure cache options
	services.AddMemoryCache(Sub(options)
		options.SizeLimit = 1024 ' Set the maximum size limit for the cache
		options.CompactionPercentage = 0.75 ' Set the percentage of memory to free up when the cache size exceeds the limit
		options.ExpirationScanFrequency = TimeSpan.FromMinutes(5) ' Set how often the cache should scan for expired items
	End Sub)
	' Other service configurations...
End Sub
VB   C#

根据应用程序的规格修改设置。

这些说明将帮助您配置 Microsoft.Extensions。在 ASP.NET Core 应用程序中使用 Caching.Memory。通过在内存缓存中存储和检索经常访问的数据,应用程序可以更快、更高效地运行。

入门

什么是 IronPDF?

借助著名的 .NET 库 IronPDF,程序员可以在 .NET 应用程序中生成、编辑和显示 PDF 文档。从 HTML 内容、照片或原始数据创建 PDF 只是它为处理 PDF 提供的众多功能之一。其他功能还包括在已有的 PDF 文档中添加文本、图像和形状,将 HTML 页面转换为 PDF,以及从 PDF 中提取文本和图像。

以下是 IronPDF 的部分功能:

  • 从 HTML、PNG 和未经处理的数据创建 PDF。
  • 从 PDF 中提取图像和文本。
  • 添加 PDF 页眉、页脚和水印。
  • 对 PDF 文档进行密码保护和加密。

  • 填写表格和数字签名功能。

安装 NuGet 软件包

在您的项目中,确保已安装 IronPDF 软件包。可使用 NuGet 软件包管理器控制台进行安装:

Install-Package IronPdf

要访问 "ConfigureServices "函数,请打开 ASP.NET Core 应用程序中的 Startup.cs 文件。要配置 IronPDF,请添加以下代码。

using IronPdf;
public void ConfigureServices(IServiceCollection services)
{
    // Configure IronPDF
    services.AddSingleton<HtmlToPdf>();
    // Other service configurations...
}
using IronPdf;
public void ConfigureServices(IServiceCollection services)
{
    // Configure IronPDF
    services.AddSingleton<HtmlToPdf>();
    // Other service configurations...
}
Imports IronPdf
Public Sub ConfigureServices(ByVal services As IServiceCollection)
	' Configure IronPDF
	services.AddSingleton(Of HtmlToPdf)()
	' Other service configurations...
End Sub
VB   C#

通过将 IronPDF 的 "HtmlToPdf "服务配置为单例,该代码可确保应用程序只创建和使用一个 "HtmlToPdf "实例。

使用 IronPDF 的 `Microsoft.Extensions.Caching.Memory

在 .NET 应用程序中,"Microsoft.Extensions.Caching.Memory "提供了一种实用的方法来存储经常请求的数据,以便更快地检索。

本源代码和代码段说明了如何从根本上使用它:

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using System.Net;
using System.Net.Http.Headers;
namespace DemoWebApplication.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class DemoController : ControllerBase
    {
        private readonly IMemoryCache _cache;
        private readonly HtmlToPdf _htmlToPdf;
        private readonly ILogger<DemoController > _logger;
        public DemoController(ILogger<DemoController > logger, IMemoryCache cache, HtmlToPdf htmlToPdf)
        {
            _logger = logger;
            _cache = cache;
            _htmlToPdf = htmlToPdf;
        }
        [HttpGet]
        public FileContentResult Generate()
        {
            string fileName = "Sample.pdf";
            var stream = GeneratePdf("Hello IronPDF");
            return new FileContentResult(stream, "application/octet-stream")
            {
                FileDownloadName = fileName
            };
        }
        private byte[] GeneratePdf(string htmlContent)
        {
        // object key
            string cacheKey = "GeneratedPdf";
            if (!_cache.TryGetValue(cacheKey, out byte[] pdfBytes))
            {
                // PDF not found in cache, generate it
                var pdfDocument = _htmlToPdf.RenderHtmlAsPdf(htmlContent);
                pdfBytes = pdfDocument.BinaryData;
                // Cache the generated PDF with a sliding expiration of 1 hour
                _cache.Set(cacheKey, pdfBytes, TimeSpan.FromHours(1));
            }
            return pdfBytes;
        }
    }
}
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using System.Net;
using System.Net.Http.Headers;
namespace DemoWebApplication.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class DemoController : ControllerBase
    {
        private readonly IMemoryCache _cache;
        private readonly HtmlToPdf _htmlToPdf;
        private readonly ILogger<DemoController > _logger;
        public DemoController(ILogger<DemoController > logger, IMemoryCache cache, HtmlToPdf htmlToPdf)
        {
            _logger = logger;
            _cache = cache;
            _htmlToPdf = htmlToPdf;
        }
        [HttpGet]
        public FileContentResult Generate()
        {
            string fileName = "Sample.pdf";
            var stream = GeneratePdf("Hello IronPDF");
            return new FileContentResult(stream, "application/octet-stream")
            {
                FileDownloadName = fileName
            };
        }
        private byte[] GeneratePdf(string htmlContent)
        {
        // object key
            string cacheKey = "GeneratedPdf";
            if (!_cache.TryGetValue(cacheKey, out byte[] pdfBytes))
            {
                // PDF not found in cache, generate it
                var pdfDocument = _htmlToPdf.RenderHtmlAsPdf(htmlContent);
                pdfBytes = pdfDocument.BinaryData;
                // Cache the generated PDF with a sliding expiration of 1 hour
                _cache.Set(cacheKey, pdfBytes, TimeSpan.FromHours(1));
            }
            return pdfBytes;
        }
    }
}
Imports Microsoft.AspNetCore.Mvc
Imports Microsoft.Extensions.Caching.Memory
Imports System.Net
Imports System.Net.Http.Headers
Namespace DemoWebApplication.Controllers
	<ApiController>
	<Route("[controller]")>
	Public Class DemoController
		Inherits ControllerBase

		Private ReadOnly _cache As IMemoryCache
		Private ReadOnly _htmlToPdf As HtmlToPdf
		Private ReadOnly _logger As ILogger(Of DemoController )
		Public Sub New(ByVal logger As ILogger(Of DemoController ), ByVal cache As IMemoryCache, ByVal htmlToPdf As HtmlToPdf)
			_logger = logger
			_cache = cache
			_htmlToPdf = htmlToPdf
		End Sub
		<HttpGet>
		Public Function Generate() As FileContentResult
			Dim fileName As String = "Sample.pdf"
			Dim stream = GeneratePdf("Hello IronPDF")
			Return New FileContentResult(stream, "application/octet-stream") With {.FileDownloadName = fileName}
		End Function
		Private Function GeneratePdf(ByVal htmlContent As String) As Byte()
		' object key
			Dim cacheKey As String = "GeneratedPdf"
			Dim pdfBytes() As Byte
			If Not _cache.TryGetValue(cacheKey, pdfBytes) Then
				' PDF not found in cache, generate it
				Dim pdfDocument = _htmlToPdf.RenderHtmlAsPdf(htmlContent)
				pdfBytes = pdfDocument.BinaryData
				' Cache the generated PDF with a sliding expiration of 1 hour
				_cache.Set(cacheKey, pdfBytes, TimeSpan.FromHours(1))
			End If
			Return pdfBytes
		End Function
	End Class
End Namespace
VB   C#

我们导入与 Microsoft 和 ASP.NET Microsoft.Extensions.Caching.Memory协同工作所需的命名空间。我们创建从 ControllerBase 派生的 DemoController 控制器。该控制器将响应通过 HTTP 发送的查询。我们在控制器的构造函数中注入了一个 IMemoryCache 实例。

为了控制服务(包括内存缓存)的生命周期,ASP.NET Core 提供了依赖注入功能。使用 [HttpGet] 属性,生成方法被标记为处理从指定路由向存储空间发出的 HTTP GET 请求 (/演示).我们尝试使用给定的缓存密钥从生成函数内的缓存中获取天气预报数据。如果缓存中的 ASP 数据无法使用,我们将使用生成函数创建新的天气数据。

在有多个应用程序服务器的情况下,请确保配置分布式缓存,以便在所有服务器上进行一致的缓存处理。

要使用 "Microsoft.Extensions",请参阅提供的文档和示例代码。在 ASP.NET Core 应用程序中,"Caching.Memory "用于缓存数据和提高性能。在实践中,您可以调整过期策略、缓存键和缓存行为,以满足应用程序的需要。对生成成本较高或经常被多个线程访问的数据进行缓存,可以改善整体用户体验并显著缩短响应时间。

C#中的Microsoft.Extensions.Caching.Memory示例(带PDF):图 2 - 上述代码的输出示例

结论

综上所述,"Microsoft.Extensions.Caching.Memory "可用于提高.NET 应用程序的可扩展性和性能,尤其是那些基于 ASP.NET Core 框架的应用程序。开发人员可以利用内存缓存改善用户体验、最大限度地减少延迟并优化数据访问。无论是缓存引用数据、查询结果还是计算值,该库都提供了灵活、用户友好的 API,用于开发针对特定应用需求的缓存策略。通过采用缓存最佳实践并将 "Microsoft.Extensions.Caching.Memory "添加到您的 .NET 应用程序中,您可以显著提高速度并增强应用程序的响应能力。

通过使用 "Microsoft.Extensions "功能。在用于动态 PDF 创建的 IronPDF 和用于有效数据缓存的 "Caching.Memory "的帮助下,.NET 开发人员可以大大提高应用程序的速度。这一强大的组合使开发人员能够通过减少服务器负载、改善用户体验和消除处理开销,轻松设计出高性能、可扩展和反应灵敏的应用程序。

IronPDF 的购买价格合理,而且购买套餐还可获得终身许可证。该软件包价值不菲,起价为"$liteLicense",只需支付一次费用即可使用多个系统。对于持有许可证的用户,它提供全天候在线工程帮助。有关收费的更多详情,请访问 网站.访问此处 网站 了解有关 Iron Software 产品的更多信息。

< 前一页
OpenAPI .NET(开发者如何使用)
下一步 >
Ocelot .NET(开发人员如何使用)

准备开始了吗? 版本: 2024.9 刚刚发布

免费NuGet下载 总下载量: 10,731,156 查看许可证 >