HOME 2 years ago
parent
commit
99a6f7cafa
2 changed files with 36 additions and 0 deletions
  1. 32 0
      VCommon.Caching/CacheManager.cs
  2. 4 0
      VCommon.Caching/FixedCacheManager.cs

+ 32 - 0
VCommon.Caching/CacheManager.cs

@@ -35,6 +35,38 @@ namespace VCommon.Caching
 
         public T KeyGetJson<T>(int db, string key) => VJsonSerializer.Deserialize<T>(_cacheAccess.CacheOp(db, p => p.StringGet(key)));
 
+        public CacheValue KeyFetch(int db, string key, Func<CacheValue> missingCacheValueProvider, CacheExpire expire = null)
+        {
+            if (KeyExist(db, key))
+            {
+                return _cacheAccess.CacheOp(db, p => p.StringGet(key));
+            }
+            else
+            {
+                var value = missingCacheValueProvider();
+                _cacheAccess.CacheOp(db, p => p.StringSet(key, value));
+                KeyExpire(db, key, expire);
+                return value;
+            }
+        }
+
+        public T KeyFetchJson<T>(int db, string key, Func<T> missingCacheValueProvider, CacheExpire expire = null)
+        {
+            if (KeyExist(db, key))
+            {
+                var json = (string)_cacheAccess.CacheOp(db, p => p.StringGet(key));
+                return VJsonSerializer.Deserialize<T>(json);
+            }
+            else
+            {
+                var value = missingCacheValueProvider();
+                var json = VJsonSerializer.Serialize(value);
+                _cacheAccess.CacheOp(db, p => p.StringSet(key, json));
+                KeyExpire(db, key, expire);
+                return value;
+            }
+        }
+
         public void KeySet(int db, string key, CacheValue value, CacheExpire expire = null)
         {
             _cacheAccess.CacheOp(db, p => p.StringSet(key, value));

+ 4 - 0
VCommon.Caching/FixedCacheManager.cs

@@ -24,6 +24,10 @@ namespace VCommon.Caching
 
         public T KeyGetJson<T>(string key) => _underlying.KeyGetJson<T>(_fixedDb, key);
 
+        public T KeyGetFetchJson<T>(string key, Func<T> missProvider, CacheExpire expire = null) => _underlying.KeyFetchJson<T>(_fixedDb, key, missProvider, expire);
+
+        public CacheValue KeyGetFetch(string key, Func<CacheValue> missProvider, CacheExpire expire = null) => _underlying.KeyFetch(_fixedDb, key, missProvider, expire);
+
         public void KeySet(string key, CacheValue value, CacheExpire expire = null) => _underlying.KeySet(_fixedDb, key, value, expire);
 
         public CacheValue KeyGet(string key) => _underlying.KeyGet(_fixedDb, key);