绍兴建设企业网站,太原建站的模板,申请了域名 网站怎么建设呢,东莞网站平台后缀在开发过程中#xff0c;我们经常需要使用缓存来提高应用程序的性能。本文将介绍如何使用C#实现一个简单的内存缓存系统#xff0c;它模仿了Redis的部分基本功能
功能#xff1a;
基本的键值存储支持过期时间支持泛型类型Hash 类型操作线程安全清理过期项
优点#xff1…在开发过程中我们经常需要使用缓存来提高应用程序的性能。本文将介绍如何使用C#实现一个简单的内存缓存系统它模仿了Redis的部分基本功能
功能
基本的键值存储支持过期时间支持泛型类型Hash 类型操作线程安全清理过期项
优点
不依赖第三方库实现简单内存操作速度快支持基本的 Redis 功能
限制
数据存储在内存中程序重启后数据会丢失不支持分布式功能相对简单
代码实现
using System.Collections.Concurrent;namespace SimpleRedisApp
{public interface ISimpleRedis{bool SetT(string key, T value, TimeSpan? expiry null);T GetT(string key);bool Delete(string key);bool Exists(string key);Liststring GetAllKeys();bool HashSet(string key, string field, object value);T HashGetT(string key, string field);void RemoveExpiredItems();}/// summary/// 简单的内存缓存实现/// /summarypublic class SimpleRedis : ISimpleRedis{// 使用ConcurrentDictionary保证线程安全private static readonly ConcurrentDictionarystring, CacheItem Cache new ConcurrentDictionarystring, CacheItem();// 缓存项类包含值和过期时间private class CacheItem{public object Value { get; set; }public DateTime? ExpireTime { get; set; }}/// summary/// 设置缓存/// /summarypublic bool SetT(string key, T value, TimeSpan? expiry null){var item new CacheItem{Value value,ExpireTime expiry.HasValue ? DateTime.Now.Add(expiry.Value) : null};Cache.AddOrUpdate(key, item, (k, old) item);return true;}/// summary/// 获取缓存/// /summarypublic T GetT(string key){if (Cache.TryGetValue(key, out CacheItem item)){if (item.ExpireTime.HasValue item.ExpireTime.Value DateTime.Now){// 已过期删除并返回默认值Cache.TryRemove(key, out _);return default(T);}return (T)item.Value;}return default(T);}/// summary/// 删除缓存/// /summarypublic bool Delete(string key){return Cache.TryRemove(key, out _);}/// summary/// 判断键是否存在/// /summarypublic bool Exists(string key){return Cache.ContainsKey(key) (!Cache[key].ExpireTime.HasValue || Cache[key].ExpireTime.Value DateTime.Now);}/// summary/// 清空所有缓存/// /summarypublic void Clear(){Cache.Clear();}/// summary/// 获取所有键/// /summarypublic Liststring GetAllKeys(){return Cache.Keys.ToList();}/// summary/// 设置Hash/// /summarypublic bool HashSet(string key, string field, object value){var hash GetDictionarystring, object(key) ?? new Dictionarystring, object();hash[field] value;return Set(key, hash);}/// summary/// 获取Hash/// /summarypublic T HashGetT(string key, string field){var hash GetDictionarystring, object(key);if (hash ! null hash.ContainsKey(field)){return (T)hash[field];}return default(T);}/// summary/// 删除过期的缓存项/// /summarypublic void RemoveExpiredItems(){var now DateTime.Now;var expiredKeys Cache.Where(kvp kvp.Value.ExpireTime.HasValue kvp.Value.ExpireTime.Value now).Select(kvp kvp.Key).ToList();foreach (var key in expiredKeys){Cache.TryRemove(key, out _);}}}public class User{public string Name { get; set; }public int Age { get; set; }}internal class Program{static void Main(string[] args){var redis new SimpleRedis();// 字符串操作redis.Set(name, 张三, TimeSpan.FromMinutes(1));var name redis.Getstring(name);Console.WriteLine($Name: {name});// 对象操作var user new User { Name 李四, Age 25 };redis.Set(user:1, user);var savedUser redis.GetUser(user:1);Console.WriteLine($User: {savedUser.Name}, {savedUser.Age});// Hash操作redis.HashSet(user:2, name, 王五);redis.HashSet(user:2, age, 30);var userName redis.HashGetstring(user:2, name);var userAge redis.HashGetint(user:2, age);Console.WriteLine($Hash User: {userName}, {userAge});// 删除操作redis.Delete(name);// 检查键是否存在var exists redis.Exists(user:1);Console.WriteLine($user:1 exists: {exists});// 获取所有键var allKeys redis.GetAllKeys();Console.WriteLine($All keys: {string.Join(, , allKeys)});// 存入缓存设置过期时间为30分钟redis.Set($user:3, user, TimeSpan.FromMinutes(30));// 清理过期项redis.RemoveExpiredItems();Console.ReadKey();}}
}可以写个定时器定期清理过期项