using Microsoft.Extensions.Caching.Distributed;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace XYY.Common.Standard
{
    public static class DistributedCacheExtensions
    {
        /// <summary>
        /// 异步获取缓存数据
        /// </summary>
        /// <typeparam name="T">获取数据类型</typeparam>
        /// <param name="cache"></param>
        /// <param name="key">Key</param>
        /// <param name="getData">异步委托</param>
        /// <returns></returns>
        public static async Task<T> GetAsync<T>(this IDistributedCache cache, string key, Func<Task<T>> getData, DistributedCacheEntryOptions options = null)
        {
            var str = await cache.GetStringAsync(key);
            if (string.IsNullOrEmpty(str))
            {
                var data = await getData();
                string json = Newtonsoft.Json.JsonConvert.SerializeObject(data);
                str = json;
                await cache.SetStringAsync(key, json);
                return data;
            }
            else
            {
                return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(str);
            }
        }
        public static async Task<T> GetAsync<T>(this IDistributedCache cache, string key, Func<Task<T>> getData)
        {
          return   await GetAsync(cache,key,getData,null);
        }
    }
}
