/// <summary> /// 解锁实例 /// </summary> /// <param name="key">key</param> /// <param name="value">值</param> private void UnlockInstance(string key, byte[] value) { RedisKey[] keys = { CacheKeyConverter.GetKeyWithRegion(key) }; RedisValue[] values = { value }; GetDatebase().ScriptEvaluate( UnlockScript, keys, values ); }
public T GetOrAdd <T>(string key, Func <T> getData, TimeSpan?expiry = null) { var value = GetDatebase().StringGet(CacheKeyConverter.GetKeyWithRegion(key)); if (value.HasValue) { return(GetValue <T>(value)); } var mutexKey = string.Format(MutexKeyFormat, key); // 防击穿(热点key并发) var uniqueValue = CreateUniqueLockId(); try { if (SetNotExists(mutexKey, uniqueValue, TimeSpan.FromMinutes(1))) { var result = getData(); _loggerLazy.Value.LogInformation($"GetOrAdd, [key:{key}], call getData func"); //防穿透 if (result == null) { Set(key, default(T), TimeSpan.FromSeconds(1)); } else { Set(key, result, expiry); } return(result); } } finally { UnlockInstance(mutexKey, uniqueValue); } Thread.Sleep(50); return(GetOrAdd(key, getData, expiry)); }
/// <summary> /// 设置不存在的值 /// </summary> /// <param name="key">缓存键</param> /// <param name="value">值</param> /// <param name="expiry">过期时间</param> /// <returns></returns> private bool SetNotExists(string key, byte[] value, TimeSpan?expiry = null) { return(GetDatabase().StringSet(CacheKeyConverter.GetKeyWithRegion(key), value, expiry, When.NotExists)); }
/// <summary> /// 删除指定key /// </summary> /// <param name="key">缓存键</param> /// <returns></returns> public bool Delete(string key) { return(GetDatabase().KeyDelete(CacheKeyConverter.GetKeyWithRegion(key))); }
/// <summary> /// 设置数据 /// </summary> /// <typeparam name="T">数据类型</typeparam> /// <param name="key">缓存键</param> /// <param name="value">值</param> /// <param name="expiry">过期时间</param> /// <returns></returns> public bool Set <T>(string key, T value, TimeSpan?expiry = null) { return(GetDatabase().StringSet(CacheKeyConverter.GetKeyWithRegion(key), JsonUtil.ToJson(value), expiry)); }
/// <summary> /// 获取key的数据 /// </summary> /// <typeparam name="T">数据类型</typeparam> /// <param name="key">缓存键</param> /// <returns></returns> public T Get <T>(string key) { return(GetValue <T>(GetDatabase().StringGet(CacheKeyConverter.GetKeyWithRegion(key)))); }
public bool Set <T>(string key, T value, TimeSpan?expiry = null) { return(GetDatebase().StringSet(CacheKeyConverter.GetKeyWithRegion(key), JsonHelper.SerializeObject(value), expiry)); }