.NET 幫助

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

發佈 2024年6月6日
分享:

為了響應性和有效地構建應用程式,NET 應用程式經常需要優化方法。快取是一個強大的方法,包括將經常請求的資料暫時存儲在分佈式快取中,以便於更快地檢索。使用這種策略減少處理時間和伺服器負載可以顯著提高應用程式的性能。此外,可以實施性能計數器來監控和增強快取系統。

快取 這是一種在此上下文中的強大優化策略。Microsoft.Extensions.Caching.Memory 為 .NET 應用程式提供了一個高效的記憶體內部物件快取解決方案。如果你策略性地使用 MemoryCache 快取結合 IronPDF,你的 PDF 相關應用程式將會運行和回應得更快。

我們將探討如何有效地將 Microsoft.Extensions.Caching.Memory 與 IronPDF 整合的 C# 示例。在本文中,我們將討論快取在這方面的優勢。 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 所需的命名空間。我們創建了 DemoController 控制器,它派生自 ControllerBase。此控制器將回應通過 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 開始,單一費用即可在多個系統上使用。對於擁有許可證的用戶,它提供全天的線上工程幫助。關於費用的更多詳情,請訪問 網站. 訪問這個 網站 了解更多有關Iron Software產品的信息。

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

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

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >