跳過到頁腳內容
.NET幫助

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

為了建立響應迅速且高效的應用程序, .NET應用程式經常需要最佳化方法。 快取是一種有效的方法,它將經常請求的內容暫時儲存在分散式快取中,以便更快地檢索。 透過這種策略,可以減少處理時間和伺服器負載,從而顯著提高應用程式效能。 此外,還可以實施效能計數器來監控和增強快取系統。

在這種情況下,[快取](https://en.wikipedia.org/wiki/Cache_(computing)是一種有效的最佳化策略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 範例(附 PDF)C#:圖 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
$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、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
$vbLabelText   $csharpLabel

透過將 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;
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 範例(附 PDF)在 C# 中的應用:圖 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 任務時。

Jacob Mellor, Team Iron 首席技術官
首席技術官

Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我