跳過到頁腳內容
.NET幫助

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

為了有彈性且有效的構建應用程式,對 .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 的實際實施即在此類中。 它提供了快取項目的管理和實際的內存存儲。
  • 在 ASP.NET Core 應用程式中通常使用相依注入來檢索 MemoryCache 的實例。

MemoryCacheEntryOptions

您可以通過此類為特定的快取項目指定配置設定。 這些設定調節如下事項:

  • 到期:您可以配置滑動到期窗口(在某個時間間隔內未訪問則項目過期)或絕對到期時間(項目自動過期)。
  • 優先級:這影響快取填滿時是否移除元件。更高優先級的項目被移除的可能性較低。
  • 事後驅逐回調:這允許您微調數據過期後的處理邏輯。 這在需要刷新關鍵數據、資源管理和日誌記錄時特別有用。

CacheEntry

  • 在快取中,這種類型表示單個條目。 它提供方法和屬性來檢索大小詳情、過期設置和快取值。
  • 實質上,它包含了快取中儲存的特定數據片段的所有信息。

ICacheEntry

  • 此介面概述了基本的快取項目活動,儘管對於基本的快取操作不是必需的。 它包含如何檢索值和過期信息的指示。 這在您需要檢索字串鍵的情況下更為普遍。
  • 該介面由 CacheEntry 類實施,提供了這些功能的實用實施。

安裝和配置 Microsoft.Extensions.Caching.Memory

在應用程式啟動期間,內存在 ASP.NET Core 應用程式的服務集合內配置快取服務。 下面是一個配置了 Microsoft.Extensions.Caching.Memory 的 ASP.NET Core 應用程式示例:

安裝所需的 NuGet 套件

首先,確保在您的專案中安裝了 Microsoft.Extensions.Caching.Memory。 您可以使用 NuGet 套件管理器控制台中的命令來安裝它:

Install-Package Microsoft.Extensions.Caching.Memory

或者我們可以使用 NuGet 套件管理器來安裝該套件:

Microsoft.Extensions.Caching.Memory 在 C# 中的示例(附 PDF):圖 1 - 在 NuGet 套件管理器中搜索 Microsoft.Extensions.Caching.Memory 並安裝

在 Startup.cs 中配置服務

通過打開 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
$vbLabelText   $csharpLabel

此代碼將內存快取服務對象添加到應用程序的服務集合並進行配置。 通過 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
$vbLabelText   $csharpLabel

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
$vbLabelText   $csharpLabel

根據應用程式的規範修改設置。

這些指導方針將幫助您在 ASP.NET Core 應用程式中配置Microsoft.Extensions.Caching.Memory,使其能夠更快、更高效地操作,通過存儲和檢索經常訪問的數據來提升性能。

入門指南

什麼是 IronPDF?

借助這個知名的 .NET 庫 IronPDF,程序員可以在 .NET 應用程式中生成、編輯和顯示 PDF 文檔。 從 HTML 內容、圖像或原始數據創建PDF僅僅是其提供的處理PDF的許多功能之一。 其他特點包括向現有PDF文檔添加文本、圖像和圖形,將HTML頁面轉換為PDF,並從PDF中提取文本和圖像。

以下是一些 IronPDF 的功能:

  • 從 HTML、PNGs和未處理的數據創建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
$vbLabelText   $csharpLabel

配置 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;
using IronPdf;

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;
using IronPdf;

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
Imports IronPdf

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
$vbLabelText   $csharpLabel

我們導入了處理 Microsoft 和 ASP.NET 的Microsoft.Extensions.Caching.Memory所需的命名空間。 我們創建了DemoController控制器,它繼承自ControllerBase。 此控制器將響應通過HTTP發送的查詢。將IMemoryCache的一個實例注入到控制器的構造函數中。

ASP.NET Core 提供了相依注入來控制服務的生命周期,包括內存快取。 帶有[HttpGet]屬性的Generate方法被標記為用於處理從指定路徑(/Demo)發送到存儲的HTTP GET請求。 我們嘗試使用給定的快取鍵從快取中獲取 PDF 數據。 如果在快取中找不到數據,則我們使用GeneratePdf函數來創建一個新的PDF。

在多個應用伺服器的情景中,請確保配置分布式快取以在所有伺服器之間保持一致的快取處理。

要利用 Microsoft.Extensions.Caching.Memory,請參閱所提供的文檔和範例程式碼,以便在 ASP.NET Core 應用程式中進行快取數據和提升性能。 在實踐中,您可以調整到期政策、快取鍵和快取行為以適合您的應用程式需求。 快取生成開銷大或經常被多個線程訪問的數據可以改善整體用戶體驗並顯著降低回應時間。

Microsoft.Extensions.Caching.Memory 在 C# 中的示例(附 PDF):圖 2 - 上述代碼的示例輸出

結論

總而言之,Microsoft.Extensions.Caching.Memory 可以用於提高 .NET 應用程式的可擴展性和性能,特別是基於 ASP.NET Core 框架的應用程式。 開發人員可以通過使用內存快取改善用戶體驗、減少延遲和優化數據存取。 該庫提供了一個靈活且用戶友好的 API 用於開發符合特定應用程式需求的快取策略,無論是用於快取引用數據、查詢結果或計算值。 通過採用快取最佳實踐並將 Microsoft.Extensions.Caching.Memory 添加到您的 .NET 應用程式中,您可以實現明顯的速度增加和增強的應用程式響應性。

透過使用Microsoft.Extensions的功能,借助於IronPDF動態PDF創建和Caching.Memory的有效數據快取,.NET 開發者能夠極大地提高應用程式的速度。這種強大的組合使開發人員能夠輕鬆設計高性能、可擴展和響應迅速的應用程式,通過減少伺服器負載、改善用戶體驗和消除處理開支。

IronPDF 可以以合理的價格購買,購買套件包括終身許可。 套件提供了極佳的價值,起始於$799,這是多個系統的一次性費用。 對於持有許可的用戶,提供全天候在線工程支持。 有關費用的更多詳細信息,請訪問IronPDF許可頁面。 訪問此Iron Software 頁面以了解有關 Iron Software 製作的產品的更多信息。

常見問題解答

Microsoft.Extensions.Caching.Memory 在 .NET 應用程式中的作用是什麼?

Microsoft.Extensions.Caching.Memory 用於提升 .NET 應用程式效能,通過提供記憶體中的物件快取。它將經常訪問的資料存儲於記憶體中以便快速檢索,尤其在與 IronPDF 共同使用時對 PDF 操作特別有益。

快取如何改善 .NET 中 PDF 處理的效能?

快取可透過將頻繁請求的 PDF 資料存儲於記憶體中來減少處理時間和伺服器負載。當與像 IronPDF 這樣的庫整合時,可加快 PDF 創建和操作速度,提高整體應用程式的速度和響應性。

如何在 ASP.NET Core 應用程式中實施記憶體內快取?

在 ASP.NET Core 中,你可以在 Startup.csConfigureServices 方法中添加 services.AddMemoryCache() 來實施記憶體內快取。這與 IronPDF 無縫整合,以實現高效的 PDF 處理和資料檢索。

IMemoryCache 在快取中扮演什麼角色?

IMemoryCache 是一個介面,用於在 .NET 應用程式中高效管理快取項目。當與 IronPDF 配合使用時,它允許開發人員快速存儲和檢索 PDF 資料,提升應用程式的效能。

在 .NET 中,快取的常見配置選項是什麼?

常見的配置選項包括使用 MemoryCacheEntryOptions 設置過期策略、大小限制和驅逐策略。這些配置優化了快取過程,尤其是在使用 IronPDF 處理 PDF 時。

開發人員如何在 .NET 應用程式中創建動態 PDF?

開發人員可以使用 IronPDF 在 .NET 應用程式中創建動態 PDF。它支持 HTML 到 PDF 的轉換、添加頁眉和頁腳等,是一個多功能的 PDF 生成和操作工具。

在 .NET 中將快取與 PDF 生成整合的好處是什麼?

在 .NET 應用程式中使用 IronPDF 將快取與 PDF 生成整合,可以顯著提升速度並降低延遲。這為用戶提供更好的體驗,也使應用程式更具擴展性,因為能更快速地訪問經常使用的數據。

如何監控和增強 .NET 應用程式的快取系統?

可以實施性能計數器來監控 .NET 應用程式中快取系統的效率。這種監控允許進行調整和增強,以確保最佳性能,尤其是在使用 IronPDF 執行 PDF 任務時。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。