/// <summary> /// 向列表尾添加元素,若 key 对应无列表缓存,则自动创建并添加一个元素。 /// </summary> /// <param name="key">主键。</param> /// <param name="value">要缓存的值。</param> /// <param name="options">缓存时间设置,为 NULL 表示永久。</param> public async Task RightPushListCacheAsync(string key, string value, KolibreCacheOptions options) { ConditionalValue <CacheWrapper> state = await StateManager.TryGetStateAsync <CacheWrapper>(key); CacheWrapper cacheWrapper = new CacheWrapper(CacheType.List); if (state.HasValue) { if (cacheWrapper.CacheType != CacheType.List) { throw new InvalidOperationException($"Operation against a key holding the wrong type '{cacheWrapper.CacheType}'."); } if (!state.Value.IsExpired()) { cacheWrapper = state.Value; } } List <string> caches; try { caches = cacheWrapper.Cache.FromJson <List <string> >() ?? new List <string>(); } catch { throw new InvalidOperationException($"Operation against a key holding the wrong type '{cacheWrapper.CacheType}'."); } caches.Insert(caches.Count, value); CacheWrapper result = cacheWrapper.SetCache(caches.ToJson(), CacheType.List, options); await StateManager.SetStateAsync(key, result); }
/// <summary> /// 设置 Hash 缓存。 /// </summary> /// <param name="firstKey">主键。</param> /// <param name="secondKey">次键。</param> /// <param name="value">要缓存的值。</param> /// <param name="options">缓存时间设置,为 NULL 表示永久。</param> public async Task SetHashCacheAsync(string firstKey, string secondKey, string value, KolibreCacheOptions options) { ConditionalValue <CacheWrapper> state = await StateManager.TryGetStateAsync <CacheWrapper>(firstKey); CacheWrapper cacheWrapper = state.HasValue ? state.Value : new CacheWrapper(CacheType.Hash); if (cacheWrapper.CacheType != CacheType.Hash) { throw new InvalidOperationException($"Operation against a key holding the wrong type '{cacheWrapper.CacheType}'."); } // 若设置 Hash Cache 时,值不是 Dictionary<string,string> 类型,抛出异常 Dictionary <string, string> hashCacheWrappers; try { hashCacheWrappers = cacheWrapper.Cache.FromJson <Dictionary <string, string> >() ?? new Dictionary <string, string>(); } catch { throw new InvalidOperationException($"Operation against a key holding the wrong type '{cacheWrapper.CacheType}'."); } hashCacheWrappers[secondKey] = value; CacheWrapper result = cacheWrapper.SetCache(hashCacheWrappers.ToJson(), CacheType.Hash, options); await StateManager.SetStateAsync(firstKey, result); }