ChouBox/Utile/HuanMeng.DotNetCore/CacheHelper/MemoryCacheHelper.cs
2025-04-23 19:20:23 +08:00

56 lines
1.7 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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();
}
}
}