在生产环境中测试,无水印。
随时随地满足您的需求。
获得30天的全功能产品。
几分钟内就能启动并运行。
在您的产品试用期间,全面访问我们的支持工程团队。
为了快速有效地构建应用程序,.NET 应用程序经常需要优化方法。 缓存是一种有效的方法,包括将经常请求的材料暂时存储在分布式缓存中,以方便快速检索。 采用这种策略可以减少处理时间和服务器负载,从而显著提高应用程序性能。 此外,还可以使用性能计数器来监控和增强缓存系统。
缓存 是在这种情况下一个强大的优化策略。 Microsoft.Extensions.Caching.Memory
为 .NET 应用程序提供了高效的内存对象缓存解决方案。 如果您战略性地使用MemoryCache
缓存与IronPDF一起,您的以PDF为中心的应用程序将运行和响应更快。
我们探讨如何高效地将Microsoft.Extensions.Caching.Memory
C# 示例与 IronPDF 集成。 在本文中,我们将讨论缓存对IronPDF HTML 转换为 PDF过程的优势,提供一些有用的实现技巧,并提供配置缓存的详细指南,以在您的 IronPDF 程序中应用。 完成所有工作后,您将掌握开发有效、直观的 PDF 应用程序所需的技能和资源。
Microsoft.Extensions.Caching.Memory
:.NET 缓存的基础缓存是许多高性能 .NET 应用程序中使用的一种方法,可将经常访问的数据存储在内存中以便快速检索。 Microsoft.Extensions
是众多可用的缓存选项之一。 Caching.Memory
是一个特别强大且适应性强的选项。 这个库是更大的Microsoft.Extensions.Caching
命名空间的组成部分,提供了一种简单但有效的内存缓存方法。
Microsoft.Extensions.Caching.Memory
" 中的关键类型IMemoryCache
MemoryCache
IMemoryCache
的实际实现。 它为缓存项目提供管理和真正的内存存储。MemoryCache
的实例。MemoryCacheEntryOptions
您可以使用该类指定特定缓存项的配置设置。 这些设置规范如下
CacheEntry
ICacheEntry
CacheEntry
类实现,该类提供了这些功能的实用实现。Microsoft.Extensions.Caching.Memory
Microsoft.Extensions.Caching
配置。 在应用程序启动期间,内存用于在 ASP.NET Core 应用程序的服务集合内配置缓存服务。 下面显示了配置了Microsoft.Extensions.Caching.Memory
的ASP.NET Core应用程序:
首先,确保为您的项目安装了Microsoft.Extensions.Caching.Memory
。 使用 NuGet 软件包管理器控制台,您可以通过以下命令进行安装:
Install-Package Microsoft.Extensions.Caching.Memory
Install-Package Microsoft.Extensions.Caching.Memory
或者我们可以使用 NuGet 软件包管理器来安装软件包:
通过打开Startup.cs
文件,导航到ASP.NET Core应用程序中的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
内存缓存服务对象被添加到应用程序的服务集合中,并通过该代码进行配置。 内存缓存系统服务通过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
用于缓存和从内存中检索数据的方法由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
根据您应用程序的规格修改设置。
这些说明将帮助您配置Microsoft.Extensions
。 在您的 ASP.NET Core 应用程序中,使用Caching.Memory
。 通过在内存缓存中存储和检索经常访问的数据,应用程序可以更快、更高效地运行。
借助著名的 .NET 库 IronPDF,程序员可以在 .NET 应用程序中生成、编辑和显示 PDF 文档。 从 HTML 内容、照片或原始数据创建 PDF 只是它提供的处理 PDF 的众多功能之一。 其他功能包括在已有的 PDF 文档中添加文本、图像和形状,将 HTML 页面转换为 PDF,以及从 PDF 中提取文本和图像。
以下是 IronPDF 的一些功能:
在您的项目中,确保已安装 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
通过将 IronPDF 的 HtmlToPdf
服务配置为单例,这段代码确保应用程序仅创建和使用一个 HtmlToPdf
实例。
Microsoft.Extensions.Caching.Memory
与 IronPDF在 .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
我们导入了与 Microsoft 和 ASP.NET 一起使用所需的命名空间 Microsoft.Extensions.Caching.Memory
。 我们创建了DemoController
控制器,它派生自ControllerBase
。 该控制器将响应通过 HTTP 发送的查询。一个 IMemoryCache
实例被注入到控制器的构造函数中。
为了控制服务(包括内存缓存)的生命周期,ASP.NET Core 提供了依赖注入功能。 通过应用 [HttpGet
] 属性,Generate 方法被标记为处理来自指定路由 (/Demo) 的 HTTP GET 请求到商店。 我们尝试使用给定的缓存密钥从生成函数内部的缓存中获取天气预报数据。 如果缓存中的 ASP 数据无法使用,我们将使用生成功能创建新的天气数据。
在有多个应用程序服务器的情况下,请确保配置分布式缓存,以便在所有服务器上进行一致的缓存处理。
要使用Microsoft.Extensions.Caching.Memory
,请参考文档和示例代码,以便在ASP.NET Core应用程序中缓存数据并提高性能。 在实践中,您可以调整过期策略、缓存密钥和缓存行为,以满足您的应用程序需求。 对生成成本较高或经常被多个线程访问的数据进行缓存,可以改善整体用户体验并显著缩短响应时间。
总的来说,Microsoft.Extensions.Caching.Memory
可以用于提高 .NET 应用程序的可扩展性和性能,特别是那些基于 ASP.NET Core 框架的应用程序。 开发人员可以通过使用内存缓存来改善用户体验、减少延迟并优化数据访问。 无论是缓存参考数据、查询结果还是计算值,该库都提供了一个灵活、用户友好的 API,用于针对特定应用需求开发缓存策略。 通过采用缓存最佳实践并在 .NET 应用程序中添加Microsoft.Extensions.Caching.Memory
,您可以显著提高速度并增强应用程序的响应性。
通过利用Microsoft.Extensions
的功能,借助IronPDF进行动态PDF创建和Caching.Memory
进行高效数据缓存,.NET开发人员可以大大提高他们应用程序的速度。这种强大的组合使开发人员能够通过减轻服务器负载、改善用户体验和消除处理开销,轻松设计出高性能、可扩展和响应迅速的应用程序。
IronPdf 可以合理的价格购买,获得该软件包包括终身许可。 该套餐提供了卓越的价值,因为它的起价为$749,这是多个系统的单一费用。 对于持有许可证的用户,它可以提供全天候的在线工程帮助。 有关费用的详细信息,请访问IronPDF许可页面。 访问此Iron Software 页面以了解更多关于由 Iron Software 制作的产品的信息。