JNPF 缓存管理

📅 2026/7/23 14:51:48
JNPF 缓存管理
缓存管理一、核心功能缓存管理是 JNPF 框架提供的统一缓存系统支持内存缓存和 Redis 缓存两种实现方式。1.1 核心价值双缓存支持同时支持内存缓存和 Redis 缓存统一接口提供统一的缓存接口切换缓存实现无需修改业务代码缓存键管理支持缓存键的统一管理和构建过期策略支持绝对过期和滑动过期缓存穿透防护支持空值缓存防止缓存穿透二、缓存接口2.1 ICache 接口publicinterfaceICache{longDel(paramsstring[]key);TasklongDelAsync(paramsstring[]key);TasklongDelByPatternAsync(stringpattern);TasklongDelByNoPatternAsync(ListstringKey);boolExists(stringkey);TaskboolExistsAsync(stringkey);longIncrby(stringkey,longincrBy);TasklongIncrbyAsync(stringkey,longincrBy);stringGet(stringkey);TGetT(stringkey);TaskstringGetAsync(stringkey);TaskTGetAsyncT(stringkey);boolSet(stringkey,objectvalue);boolSet(stringkey,objectvalue,TimeSpanexpire);TaskboolSetAsync(stringkey,objectvalue);TaskboolSetAsync(stringkey,objectvalue,TimeSpanexpire);boolSetNx(stringkey,objectvalue,TimeSpanexpire);boolSetNx(stringkey,objectvalue);ListstringGetAllKeys();DateTimeGetCacheOutTime(stringkey);}2.2 ICacheManager 接口CacheManager是缓存管理的核心类提供了带作用域的缓存操作publicclassCacheManager:ICacheManager,IScoped{publicboolSet(CacheScopescope,stringcategory,stringkey,objectvalue,stringtenantIdnull,stringuserIdnull,stringappIdnull);publicboolSet(CacheScopescope,stringcategory,stringkey,objectvalue,TimeSpantimeSpan,stringtenantIdnull,stringuserIdnull,stringappIdnull);publicTGetT(CacheScopescope,stringcategory,stringkey,stringtenantIdnull,stringuserIdnull,stringappIdnull);publicboolDel(CacheScopescope,stringcategory,stringkey,stringtenantIdnull,stringuserIdnull,stringappIdnull);publicboolExists(CacheScopescope,stringcategory,stringkey,stringtenantIdnull,stringuserIdnull,stringappIdnull);}三、实现方式3.1 内存缓存使用MemoryCache实现内存缓存基于IMemoryCachepublicclassMemoryCache:ICache,ISingleton{privatereadonlyIMemoryCache_memoryCache;publicMemoryCache(IMemoryCachememoryCache){_memoryCachememoryCache;}publicstringGet(stringkey){return_memoryCache.GetOrCreate(key,entry{returnentry.Value;})?.ToString();}publicboolSet(stringkey,objectvalue){varentry_memoryCache.CreateEntry(key);entry.Valuevalue;_memoryCache.Set(key,entry);returntrue;}publicboolSet(stringkey,objectvalue,TimeSpanexpire){varentry_memoryCache.CreateEntry(key);entry.Valuevalue;_memoryCache.Set(key,entry,expire);returntrue;}publiclongDel(paramsstring[]key){foreach(string?kinkey){_memoryCache.Remove(k);}returnkey.Length;}}3.2 Redis 缓存使用RedisCache实现 Redis 缓存基于 CSRedispublicclassRedisCache:ICache,ISingleton{publicRedisCache(IOptionsCacheOptionscacheOptions){CSRedis.CSRedisClientcsredisnewCSRedis.CSRedisClient(string.Format(cacheOptions.Value.RedisConnectionString,cacheOptions.Value.ip,cacheOptions.Value.port,cacheOptions.Value.password));RedisHelper.Initialization(csredis);}publicstringGet(stringkey){returnRedisHelper.Get(key);}publicTGetT(stringkey){returnRedisHelper.GetT(key);}publicboolSet(stringkey,objectvalue){returnRedisHelper.Set(key,value);}publicboolSet(stringkey,objectvalue,TimeSpanexpire){returnRedisHelper.Set(key,value,expire);}publiclongDel(paramsstring[]key){returnRedisHelper.Del(key);}publiclongIncrby(stringkey,longincrBy){returnRedisHelper.IncrBy(key,incrBy);}}四、使用示例4.1 基础使用publicclassUserService{privatereadonlyCacheManager_cacheManager;publicUserService(CacheManagercacheManager){_cacheManagercacheManager;}publicUserInfoGetUserInfo(stringuserId){varcacheKeyUserInfo_userId;varcachedUser_cacheManager.GetUserInfo(CacheScope.User,User,cacheKey);if(cachedUser!null){returncachedUser;}varuser_db.QueryableUserInfo().Where(uu.IduserId).First();_cacheManager.Set(CacheScope.User,User,cacheKey,user,TimeSpan.FromHours(1));returnuser;}}4.2 缓存键管理CacheManager内部使用CacheKeyBuilder统一管理缓存键// 缓存键格式{Scope}_{Category}_{Key}_{TenantId}_{UserId}_{AppId}// 示例User_User_UserInfo_1_tenant001_user001_app0014.3 设置过期时间// 绝对过期1 小时后过期_cacheManager.Set(CacheScope.User,User,UserInfo_1,userInfo,TimeSpan.FromHours(1));// 无过期时间_cacheManager.Set(CacheScope.User,User,UserInfo_1,userInfo);4.4 删除缓存_cacheManager.Del(CacheScope.User,User,UserInfo_1);4.5 批量删除_cacheManager.DelByPatternAsync(User_User_*);4.6 判断缓存是否存在if(_cacheManager.Exists(CacheScope.User,User,UserInfo_1)){// 缓存存在}4.7 原子递增// Redis 缓存支持原子递增_cacheManager.Set(CacheScope.User,User,Counter,0);longcount_cacheManager.Incrby(User_Counter,1);五、配置选项5.1 缓存配置在appsettings.json中配置{Cache:{CacheType:Redis,RedisConnectionString:{0}:{1},password{2},ip:localhost,port:6379,password:}}5.2 配置项说明配置项默认值说明CacheTypeRedis缓存类型Memory/RedisRedisConnectionString{0}:{1},password{2}Redis 连接字符串模板iplocalhostRedis 服务器地址port6379Redis 端口passwordRedis 密码六、高级特性6.1 缓存作用域CacheScope枚举定义了不同的缓存作用域作用域说明User用户级缓存Tenant租户级缓存App应用级缓存TenantApp租户应用级缓存Global全局缓存6.2 缓存刷新CacheManager提供了多种缓存刷新方法// 刷新用户相关缓存await_cacheManager.RefushUser(userId);// 刷新租户相关缓存await_cacheManager.RefushTenant(tenantId);// 刷新应用相关缓存await_cacheManager.RefushApp(appId);// 刷新租户应用相关缓存await_cacheManager.RefushTenantApp(tenantId);// 刷新全局缓存await_cacheManager.RefushGlobal();6.3 缓存穿透防护使用SetNx方法实现分布式锁防止缓存穿透publicUserInfoGetUserInfo(stringuserId){varcacheKey$User_User_UserInfo_{userId};varcachedUser_cacheManager.GetUserInfo(CacheScope.User,User,cacheKey);if(cachedUser!null){returncachedUser;}// 使用分布式锁防止缓存击穿varlockKey$Lock_UserInfo_{userId};if(_cacheManager.SetNx(lockKey,1,TimeSpan.FromSeconds(30))){try{varuser_db.QueryableUserInfo().Where(uu.IduserId).First();_cacheManager.Set(CacheScope.User,User,cacheKey,user??newUserInfo(),TimeSpan.FromHours(1));returnuser;}finally{_cacheManager.Del(CacheScope.User,User,lockKey);}}// 等待其他线程完成缓存加载Thread.Sleep(100);returnGetUserInfo(userId);}6.4 缓存雪崩防护通过随机过期时间防止缓存雪崩publicUserInfoGetUserInfo(stringuserId){varcacheKey$User_User_UserInfo_{userId};varcachedUser_cacheManager.GetUserInfo(CacheScope.User,User,cacheKey);if(cachedUser!null){returncachedUser;}varuser_db.QueryableUserInfo().Where(uu.IduserId).First();varrandomExpireTimeSpan.FromHours(1)TimeSpan.FromMinutes(newRandom().Next(0,60));_cacheManager.Set(CacheScope.User,User,cacheKey,user,randomExpire);returnuser;}6.5 缓存预热在应用启动时预热缓存publicclassCacheWarmupService:IHostedService{privatereadonlyCacheManager_cacheManager;publicCacheWarmupService(CacheManagercacheManager){_cacheManagercacheManager;}publicasyncTaskStartAsync(CancellationTokencancellationToken){varhotUsersawait_db.QueryableUserInfo().Take(100).ToListAsync();foreach(varuserinhotUsers){_cacheManager.Set(CacheScope.User,User,$UserInfo_{user.Id},user,TimeSpan.FromHours(1));}}publicTaskStopAsync(CancellationTokencancellationToken)Task.CompletedTask;}6.6 缓存统计统计缓存使用情况publicCacheStatisticsGetCacheStatistics(){varallKeys_cacheManager.GetAllCacheKeys();returnnewCacheStatistics{TotalCountallKeys.Count,UserCountallKeys.Count(kk.StartsWith(User_)),TenantCountallKeys.Count(kk.StartsWith(Tenant_)),GlobalCountallKeys.Count(kk.StartsWith(Global_))};}七、核心文件文件说明ICache.cs缓存接口ICacheManager.cs缓存管理器接口CacheManager.cs缓存管理器实现MemoryCache.cs内存缓存实现RedisCache.csRedis 缓存实现CacheKeyBuilder.cs缓存键构建器CacheOptions.cs缓存配置选项八、总结缓存管理通过统一的缓存接口和双缓存支持实现了灵活的缓存管理。核心设计思想统一接口提供统一的缓存接口切换缓存实现无需修改业务代码双缓存支持同时支持内存缓存和 Redis 缓存满足不同场景需求缓存键管理支持缓存键的统一管理和构建避免硬编码过期策略支持绝对过期和滑动过期灵活控制缓存生命周期缓存作用域支持用户、租户、应用等不同级别的缓存作用域这种设计使得缓存管理更加灵活和便捷提高了应用的性能和可维护性。