using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Caching.Distributed; using Volo.Abp.Caching; namespace Win_in.Sfs.Shared.Application; /// /// /// public static class CachingExtensions { /// /// 获取或添加缓存 /// /// /// /// /// /// /// public static async Task GetOrAddItemAsync( this IDistributedCache cache, string key, Func> factory, int minutes) where TCacheItem : class { TCacheItem cacheItem; var result = await cache.GetAsync(key).ConfigureAwait(false); if (result == null) { cacheItem = await factory.Invoke().ConfigureAwait(false); await cache.SetItemAsync(key, cacheItem, minutes).ConfigureAwait(false); } else { cacheItem = result; } return cacheItem; } /// /// /// /// /// /// /// public static async Task> GetItemsAsync( this IDistributedCache cache, IEnumerable keys) where TCacheItem : class { var cacheItems = await cache.GetManyAsync(keys, null, true).ConfigureAwait(false); return cacheItems.Select(p => p.Value); } /// /// /// /// /// /// /// /// public static async Task SetItemAsync( this IDistributedCache cache, string key, TCacheItem cacheItem, int minutes) where TCacheItem : class { var options = CreateDistributedCacheEntryOptions(minutes); await cache.SetAsync(key, cacheItem, options, null, true).ConfigureAwait(false); } /// /// /// /// /// /// /// public static async Task SetItemsAsync( this IDistributedCache cache, IEnumerable> cacheItems, int minutes) where TCacheItem : class { var options = CreateDistributedCacheEntryOptions(minutes); await cache.SetManyAsync(cacheItems, options).ConfigureAwait(false); } /// /// /// /// /// /// public static async Task DeleteItemAsync( this IDistributedCache cache, string key) where TCacheItem : class { var result = await cache.GetAsync(key).ConfigureAwait(false); if (result != null) { await cache.RemoveAsync(key).ConfigureAwait(false); } } private static DistributedCacheEntryOptions CreateDistributedCacheEntryOptions(int minutes) { var options = new DistributedCacheEntryOptions(); if (minutes != SfsCacheConst.Never) { options.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(minutes); } return options; } }