您的当前位置:首页 >系统运维 >我们聊聊 C# 通用 Cache 缓冲类开发指南 正文
时间:2025-11-05 01:58:03 来源:网络整理编辑:系统运维
在现代应用程序中,缓存是一种有效的优化手段,能够显著提高系统的性能,减少延迟。缓存可以用于数据库查询结果的存储、API 响应的缓存、复杂计算结果的保存等多个场景。本文将介绍如何开发一个通用的Cache
在现代应用程序中,通用缓存是冲类一种有效的优化手段,能够显著提高系统的指南性能,减少延迟。通用缓存可以用于数据库查询结果的冲类存储、API 响应的指南缓存、复杂计算结果的通用保存等多个场景。本文将介绍如何开发一个通用的冲类 CacheService 类,并展示其在不同场景中的指南应用。
缓存是通用一种存储机制,用于临时性地保存数据,冲类以减少数据获取的指南时间和频次。IT技术网在高性能应用程序中,通用合理使用缓存,冲类可以显著提高系统的指南响应速度,减轻后台服务的负担。接下来我们讲解如何开发一个通用的 CacheService 并展示其在具体场景中的应用。
首先,定义一个 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); }1.2.3.4.5.6.7.8.9.10.11.12.13.接下来,开发 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); } } }1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.31.32.33.34.35.36.37.38.39.40.41.42.43.44.45.46.47.48.49.50.51.52.53.54.55.56.57.58.59.60.61.62.63.64.65.66.67.68.69.70.71.72.73.74.75.76.77.78.79.80.81.82.83.84.85.86.87.88.89.90.91.92.93.94.95.96.97.98.99.100.101.102.103.104.105.106.107.108.109.110.111.112.113.114.115.116.117.118.119.120.121.122.123.124.125.在项目的 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"); } }1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.我们还可以启用分布试的源码下载缓冲(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"); }1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.
图片
图片
图片
本文介绍了如何开发一个通用的 CacheService,并展示了其在不同场景中的应用:数据库查询结果缓存、API 响应缓存、复杂计算结果缓存。这种通用的缓存服务设计,可以显著提高应用的性能和响应速度,减少对外部资源(如数据库、外部 API)的频繁访问,从而优化用户体验。
通过上述示例,开发者可以更轻松地在项目中集成和管理缓存,提高应用的整体性能和可靠性。希望本文对你有所帮助,能够在实际项目中充分利用缓存技术。站群服务器
三星GalaxyS4Zoom(将相机与手机完美结合,打造出色的拍摄体验)2025-11-05 01:57
小米时代二期2025-11-05 01:42
微软舒适蓝影4500的使用体验(打造舒适愉悦的工作环境)2025-11-05 01:35
解决iPhone关机键失灵开机问题的方法(快速恢复使用iPhone的关机功能,告别失灵的开机按钮)2025-11-05 01:32
联想电脑开机出现关键错误的解决方案(排除联想电脑开机关键错误的方法及注意事项)2025-11-05 01:20
小魅手机的性能和用户体验如何?(探索小魅手机的功能与特点,为你解答购买疑虑)2025-11-05 00:50
J2objc(实现跨平台开发的利器)2025-11-05 00:17
戴尔G3Win10激活教程(详细步骤教你如何激活戴尔G3笔记本电脑上的Windows10系统)2025-11-05 00:11
手机插U盘使用教程(快速实现手机和U盘的数据传输,让移动存储更便捷)2025-11-04 23:50
骁龙410处理器(骁龙410处理器的特点及适用领域)2025-11-04 23:12
使用U盘安装固态硬盘系统教程(一步步教你如何将系统安装到固态硬盘上)2025-11-05 01:42
限定的皮肤(探索游戏中的珍稀皮肤和特殊外观)2025-11-05 01:39
UEFI系统安装Win7系统教程(详细步骤让您轻松安装Win7系统)2025-11-05 01:15
解决电脑无系统声音的实用方法(轻松解决电脑无声问题,让您的系统重归音乐世界)2025-11-05 01:13
联想电脑进BIOS教程(简易教程帮您轻松进入BIOS设置界面)2025-11-05 01:12
增速海淘的新趋势与发展(探索中国消费者对增速海淘的热情与需求)2025-11-05 01:05
使用PE工具安装Windows7的完全指南(详细步骤教你在PE环境下安装Windows7)2025-11-05 01:05
MT15i拍照表现如何?(探索MT15i相机的性能与特点)2025-11-04 23:53
解决电脑Java平台错误的有效方法(探索如何应对和修复常见的电脑Java平台错误)2025-11-04 23:28
山寨苹果X的性能表现如何?(深入探讨山寨苹果X的关键特点和性能优劣)2025-11-04 23:22