.NET 幫助

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

發佈 2024年6月6日
分享:

要以響應性和有效性構建應用程序,.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

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 套件管理器來安裝該套件:

使用記憶體快取的範例 (含 PDF) C#: 圖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
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 實例。

使用 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
VB   C#

我們導入需要用來處理 Microsoft 和 ASP.NET 的命名空間 Microsoft.Extensions.Caching.Memory。 我們創建了從 ControllerBase 派生的 DemoController 控制器。 此控制器將回應透過 HTTP 發送的查詢。在控制器的建構函式中注入一個 IMemoryCache 的實例。

為了控制服務的生命週期,包括記憶體快取,ASP.NET Core 提供了相依性注入。 隨著[HttpGet]屬性應用後,Generate 方法被標記為處理來自指定路徑的 HTTP GET 請求至商店。(/Demo). 我們嘗試通過使用給定的快取鍵從 Generate 函數內的快取中獲取天氣預報數據。 如果無法使用的數據在緩存中,我們使用Generate函數創建新的天氣數據。

在多個應用伺服器的場景中,請確保配置分散式快取以在所有伺服器中一致地處理快取。

若要使用 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 可以以合理的價格購買,並且購買套件包括終身許可。 該套件提供卓越的價值,因為它起價為 $749,這是一個針對多個系統的單一費用。 對於持有許可證的用戶,它提供全天候的在線工程幫助。 如需有關費用的更多詳細資訊,請造訪IronPDF 授權頁面. 訪問此頁面有關 Iron Software 的網頁了解更多有關 Iron Software 產品的信息。

< 上一頁
OpenAPI .NET(適用於開發人員的工作原理)
下一個 >
Ocelot .NET(對開發人員的運作方式)

準備開始了嗎? 版本: 2024.12 剛剛發布

免費 NuGet 下載 總下載次數: 11,622,374 查看許可證 >