using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Newtonsoft.Json; using Sony.Filtr.DistributedCaching.ETW; using StackExchange.Redis; namespace Sony.Filtr.DistributedCaching { public class RedisGenericCacheProvider : IGenericCacheProvider { private readonly IDatabase _db; public RedisGenericCacheProvider(IDatabase db) { this._db = db; } public T Get(string cacheKey) { var value = this._db.StringGet(cacheKey); return value.IsNull ? default(T) : JsonConvert.DeserializeObject(value); } public T GetOrAdd(string cacheKey, Func loadData, [CallerMemberName]string caller = "") { //T data = this.Get(cacheKey); //if (data == null) //{ // data = this.LoadData(loadData, caller); // this.Set(cacheKey, data); //} //return data; return this.GetOrAddAsync(cacheKey, () => Task.Run(() => loadData()), caller).Result; } public async Task GetOrAddAsync(string cacheKey, Func> loadData, [CallerMemberName]string caller = "") { T data = this.Get(cacheKey); if (data == null) { data = await this.LoadDataAsync(loadData, caller); this.Set(cacheKey, data); } return data; } public void Set(string cacheKey, object value) { bool setResult = this._db.StringSet(cacheKey, JsonConvert.SerializeObject(value)); } public bool Remove(string cacheKey) { return this._db.KeyDelete(cacheKey); } public bool Clear() { return false; } private async Task LoadDataAsync(Func> loadData, string caller) { ApolloRedisCacheProviderEventSource.Log.LoadDataStart(caller); T data = await loadData(); ApolloRedisCacheProviderEventSource.Log.LoadDataStop(); return data; } } }