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

namespace HuanMeng.DotNetCore.CacheHelper
{
    /// <summary>
    /// 内存缓存帮助类
    /// </summary>
    public class MemoryCacheHelper
    {
        public static MemoryCache cache = new MemoryCache(new MemoryCacheOptions());

        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="cacheName"></param>
        /// <returns></returns>
        public static T? GetCache<T>(string cacheName) where T : class, new()
        {
            
            return cache.TryGetValue(cacheName, out var value) ? value as T : null;
        }

        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <param name="cacheName"></param>
        /// <param name="val"></param>
        /// <param name="cacheTime">单位秒，默认1小时</param>
        public static void SetCache(string cacheName, object val, int cacheTime = 21000)
        {
            //数据量渐渐大了，每次因为很多都是同时缓存 所以在这里分流一下
            if (cacheTime == 21000)
                cacheTime = new Random().Next(21000, 43200);
            cache.Set(cacheName, val, TimeSpan.FromSeconds(cacheTime));
        }

        /// <summary>
        /// 删除缓存
        /// </summary>
        /// <param name="cacheName"></param>
        public static void DelCache(string? cacheName = null)
        {
            if (!string.IsNullOrEmpty(cacheName))
                cache.Remove(cacheName);
            else
                cache.Dispose();
        }
    }
}
