成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

我們聊聊 C# 通用 Cache 緩沖類開發指南

數據庫 其他數據庫
本文介紹了如何開發一個通用的 CacheService,并展示了其在不同場景中的應用:數據庫查詢結果緩存、API 響應緩存、復雜計算結果緩存。

在現代應用程序中,緩存是一種有效的優化手段,能夠顯著提高系統的性能,減少延遲。緩存可以用于數據庫查詢結果的存儲、API 響應的緩存、復雜計算結果的保存等多個場景。本文將介紹如何開發一個通用的 CacheService 類,并展示其在不同場景中的應用。

引言

緩存是一種存儲機制,用于臨時性地保存數據,以減少數據獲取的時間和頻次。在高性能應用程序中,合理使用緩存,可以顯著提高系統的響應速度,減輕后臺服務的負擔。接下來我們講解如何開發一個通用的 CacheService 并展示其在具體場景中的應用。

開發通用的 CacheService

ICacheService 接口

首先,定義一個 ICacheService 接口,定義基本的緩存操作:

using System;
using System.Threading.Tasks;


public interface ICacheService
{
    void Set<T>(string key, T value, TimeSpan expiration);
    T Get<T>(string key);
    Task SetAsync<T>(string key, T value, TimeSpan expiration);
    Task<T> GetAsync<T>(string key);
    void Remove(string key);
    Task RemoveAsync(string key);
}

CacheService 實現

接下來,開發 CacheService 類,它實現了 ICacheService 接口。該類同時支持內存緩存和分布式緩存(例如 Redis),基于啟動時的配置選擇緩存方式:

using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Logging;


public class CacheService : ICacheService
{
    private readonly IMemoryCache _memoryCache;
    private readonly IDistributedCache _distributedCache;
    private readonly ILogger<CacheService> _logger;
    private readonly bool _useDistributedCache;


    public CacheService(IMemoryCache memoryCache, IDistributedCache distributedCache, ILogger<CacheService> logger, bool useDistributedCache = false)
    {
        _memoryCache = memoryCache;
        _distributedCache = distributedCache;
        _logger = logger;
        _useDistributedCache = useDistributedCache;
    }


    public void Set<T>(string key, T value, TimeSpan expiration)
    {
        if (_useDistributedCache)
        {
            var options = new DistributedCacheEntryOptions
            {
                AbsoluteExpirationRelativeToNow = expiration
            };
            var serializedValue = System.Text.Json.JsonSerializer.Serialize(value);
            _distributedCache.SetString(key, serializedValue, options);
        }
        else
        {
            var cacheEntryOptions = new MemoryCacheEntryOptions
            {
                AbsoluteExpirationRelativeToNow = expiration
            };
            _memoryCache.Set(key, value, cacheEntryOptions);
        }
    }


    public T Get<T>(string key)
    {
        if (_useDistributedCache)
        {
            var serializedValue = _distributedCache.GetString(key);
            if (serializedValue != null)
            {
                return System.Text.Json.JsonSerializer.Deserialize<T>(serializedValue);
            }
            return default;
        }
        _memoryCache.TryGetValue(key, out T value);
        return value;
    }


    public async Task SetAsync<T>(string key, T value, TimeSpan expiration)
    {
        if (_useDistributedCache)
        {
            var options = new DistributedCacheEntryOptions
            {
                AbsoluteExpirationRelativeToNow = expiration
            };
            var serializedValue = System.Text.Json.JsonSerializer.Serialize(value);
            await _distributedCache.SetStringAsync(key, serializedValue, options);
        }
        else
        {
            var cacheEntryOptions = new MemoryCacheEntryOptions
            {
                AbsoluteExpirationRelativeToNow = expiration
            };
            _memoryCache.Set(key, value, cacheEntryOptions);
        }
    }


    public async Task<T> GetAsync<T>(string key)
    {
        if (_useDistributedCache)
        {
            var serializedValue = await _distributedCache.GetStringAsync(key);
            if (serializedValue != null)
            {
                return System.Text.Json.JsonSerializer.Deserialize<T>(serializedValue);
            }
            return default;
        }
        _memoryCache.TryGetValue(key, out T value);
        return await Task.FromResult(value);
    }


    public void Remove(string key)
    {
        if (_useDistributedCache)
        {
            _distributedCache.Remove(key);
        }
        else
        {
            _memoryCache.Remove(key);
        }
    }


    public async Task RemoveAsync(string key)
    {
        if (_useDistributedCache)
        {
            await _distributedCache.RemoveAsync(key);
        }
        else
        {
            _memoryCache.Remove(key);
        }
    }
}

配置依賴注入

在項目的 Program.cs 中配置依賴注入:

using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Logging;


public class Program
{
    static void Main(string[] args)
    {
      var serviceProvider = new ServiceCollection()
     .AddMemoryCache()
     .AddStackExchangeRedisCache(options =>
     {
         options.Configuration = "localhost:6379";
     })
     .AddLogging()
     .AddSingleton<CacheService>()
     .BuildServiceProvider();
  
      // 使用緩存服務的示例
      var cacheService = serviceProvider.GetService<CacheService>();
  
      cacheService.Set("key1", "value1",new TimeSpan(0, 10, 0));
      var value = cacheService.Get<string>("key1");
  }


}

我們還可以啟用分布試的緩沖(Redis);

static void Main(string[] args)
{
    var serviceProvider = new ServiceCollection()
   .AddMemoryCache()
   .AddStackExchangeRedisCache(options =>
   {
       options.Configuration = "localhost:6379";
   })
   .AddLogging()
    .AddSingleton<CacheService>(sp =>
    {
        var memoryCache = sp.GetRequiredService<IMemoryCache>();
        var distributedCache = sp.GetRequiredService<IDistributedCache>();
        var logger = sp.GetRequiredService<ILogger<CacheService>>();
        return new CacheService(memoryCache, distributedCache, logger, useDistributedCache: true);
    })
   .BuildServiceProvider();


    // 使用緩存服務的示例
    var cacheService = serviceProvider.GetService<CacheService>();


    cacheService.Set("key1", "value1",new TimeSpan(0, 10, 0));
    var value = cacheService.Get<string>("key1");
}

圖片圖片

緩存應用場景示例

數據庫查詢結果緩存

DatabaseService.cs

using System;


public class DatabaseService
{
    private readonly ICacheService _cacheService;


    public DatabaseService(ICacheService cacheService)
    {
        _cacheService = cacheService;
    }


    public string GetDataFromDatabase(string query)
    {
        string cacheKey = $"DatabaseQuery-{query}";
        var cacheData = _cacheService.Get<string>(cacheKey);


        if (cacheData != null)
        {
            return cacheData;
        }


        // 模擬數據庫查詢操作
        string data = "返回數據";
        _cacheService.Set(cacheKey, data, TimeSpan.FromMinutes(5));
        return data;
    }
}

程序入口

internal class Program
{
    static void Main(string[] args)
    {
        var serviceProvider = new ServiceCollection()
        .AddMemoryCache()
        .AddStackExchangeRedisCache(options =>
        {
            options.Configuration = "localhost:6379";
        })
        .AddLogging()
        .AddSingleton<CacheService>()
        .AddSingleton<ICacheService, CacheService>()
        .AddSingleton<DatabaseService>()
        .BuildServiceProvider();


        var databaseService = serviceProvider.GetService<DatabaseService>();
        string query = "SELECT * FROM Users";
        Console.WriteLine("Query Result: " + databaseService.GetDataFromDatabase(query));


        // 再次調用以展示緩存效果
        Console.WriteLine("Query Result from Cache: " + databaseService.GetDataFromDatabase(query));
    }
}

圖片圖片

API 響應緩存

ApiService.cs

using System;
using System.Net.Http;
using System.Threading.Tasks;


public class ApiService
{
    private readonly ICacheService _cacheService;
    private readonly HttpClient _httpClient;


    public ApiService(ICacheService cacheService, HttpClient httpClient)
    {
        _cacheService = cacheService;
        _httpClient = httpClient;
    }


    public async Task<string> GetApiResponseAsync(string url)
    {
        string cacheKey = $"ApiUrl-{url}";
        var cacheData = await _cacheService.GetAsync<string>(cacheKey);


        if (cacheData != null)
        {
            return cacheData;
        }


        var response = await _httpClient.GetStringAsync(url);
        await _cacheService.SetAsync(cacheKey, response, TimeSpan.FromMinutes(10));
        return response;
    }
}

程序入口

using System.Net.Http;
using System.Threading.Tasks;


public class Program
{
    public static async Task Main(string[] args)
    {
        var serviceProvider = new ServiceCollection()
            .AddMemoryCache()
            .AddStackExchangeRedisCache(options =>
            {
                options.Configuration = "localhost:6379";
            })
            .AddLogging()
            .AddSingleton<HttpClient>()
            .AddSingleton<CacheService>()
            .AddSingleton<ICacheService, CacheService>()
            .AddSingleton<ApiService>()
            .BuildServiceProvider();


        var apiService = serviceProvider.GetService<ApiService>();
        string apiUrl = "https://jsonplaceholder.typicode.com/posts";
        
        var result = await apiService.GetApiResponseAsync(apiUrl);
        Console.WriteLine("API Response: " + result);


        // 再次調用以展示緩存效果
        var cachedResult = await apiService.GetApiResponseAsync(apiUrl);
        Console.WriteLine("Cached API Response: " + cachedResult);
    }
}

圖片圖片

復雜計算結果緩存

CalculationService.cs

using System;


public class CalculationService
{
    private readonly ICacheService _cacheService;


    public CalculationService(ICacheService cacheService)
    {
        _cacheService = cacheService;
    }


    public int HeavyComputation(int input)
    {
        string cacheKey = $"HeavyComputation-{input}";
        var cacheData = _cacheService.Get<int>(cacheKey);


        if (cacheData != 0)
        {
            return cacheData;
        }


        // 模擬復雜計算
        int result = input * input;
        _cacheService.Set(cacheKey, result, TimeSpan.FromMinutes(10));
        return result;
    }
}

程序入口

public class Program
{
    public static void Main(string[] args)
    {
        var serviceProvider = new ServiceCollection()
            .AddMemoryCache()
            .AddStackExchangeRedisCache(options =>
            {
                options.Configuration = "localhost:6379";
            })
            .AddLogging()
            .AddSingleton<CacheService>()
            .AddSingleton<ICacheService, CacheService>()
            .AddSingleton<CalculationService>()
            .BuildServiceProvider();


        var calculationService = serviceProvider.GetService<CalculationService>();
        int input = 42;
        Console.WriteLine("Computation Result: " + calculationService.HeavyComputation(input));


        // 再次調用以展示緩存效果
        Console.WriteLine("Cached Computation Result: " + calculationService.HeavyComputation(input));
    }
}

總結

本文介紹了如何開發一個通用的 CacheService,并展示了其在不同場景中的應用:數據庫查詢結果緩存、API 響應緩存、復雜計算結果緩存。這種通用的緩存服務設計,可以顯著提高應用的性能和響應速度,減少對外部資源(如數據庫、外部 API)的頻繁訪問,從而優化用戶體驗。

通過上述示例,開發者可以更輕松地在項目中集成和管理緩存,提高應用的整體性能和可靠性。希望本文對你有所幫助,能夠在實際項目中充分利用緩存技術。

責任編輯:武曉燕 來源: 技術老小子
相關推薦

2024-11-28 09:57:50

C#事件發布器

2025-02-13 09:32:12

C#重寫override

2023-10-10 08:00:07

2024-08-26 08:34:47

AES加密算法

2022-08-02 08:01:09

開發插件Chrome前端技術

2011-07-25 16:21:22

Sencha touc

2025-01-09 07:54:03

2009-09-16 10:56:22

C#開發ActiveX

2022-11-12 12:33:38

CSS預處理器Sass

2021-08-12 07:49:24

mysql

2009-06-24 16:30:21

JSF組件模型

2011-06-09 18:24:36

QT Wince

2012-03-26 09:27:40

谷歌安卓開發谷歌安卓

2023-05-15 18:44:07

前端開發

2024-12-23 10:20:50

2024-08-30 11:00:22

2024-10-15 09:34:57

2024-05-20 11:33:20

AI模型數據

2021-01-30 11:12:21

C#List數據

2024-05-29 13:18:12

線程Thread?方式
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 国产精品视频一区二区三区不卡 | 97伊人| 91日韩在线 | 精品三级在线观看 | 日日久 | 国产二区精品视频 | 一区二区视频在线观看 | 亚洲视频免费在线观看 | 国产精品永久在线观看 | 成人h视频在线 | 毛片的网址 | 日本免费一区二区三区 | 日批免费看 | 91在线精品秘密一区二区 | 天天夜夜人人 | 日韩av资源站 | 中文字幕不卡在线88 | 成人欧美一区二区三区在线播放 | 色999日韩 | 成人在线免费网站 | 在线观看国产网站 | 亚洲视频欧美视频 | 日韩精品一区二区三区中文在线 | 国产在线精品一区二区 | 91精品国产777在线观看 | 国产不卡一区在线观看 | 欧美一区二区三区一在线观看 | 国产在线视频网 | 国产精品3区 | 日韩在线视频一区 | 亚洲自拍偷拍视频 | 欧美日韩视频在线第一区 | 国产一区二区在线免费观看 | 国产亚洲日本精品 | 亚洲成人精品一区 | 欧美精品一区二区蜜桃 | 欧美一区在线视频 | 大香在线伊779 | 亚洲欧美日韩久久久 | 国产精品视频二区三区 | 久久精品一区二区三区四区 |