| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- using System;
- using System.Runtime.Caching;
- namespace SHJX.Service.Common.CustomUtil
- {
- /// <summary>
- /// 数据缓存工具类
- /// </summary>
- public static class DataCache
- {
- private static readonly MemoryCache cache = new("ErrorFromEmsCache");
- /// <summary>
- /// 在缓存中新增数据
- /// </summary>
- /// <param name="detailInfo"></param>
- public static void Set<T>(string key, T value)
- {
- var policy = new CacheItemPolicy
- {
- AbsoluteExpiration = DateTime.Now.AddHours(15)
- };
- if (!Contains(key))
- {
- cache.Set(key, value, policy);
- }
- cache[key] = value;
- }
- /// <summary>
- /// 查询缓存中是否包含指定键
- /// </summary>
- /// <param name="key"></param>
- /// <returns></returns>
- public static bool Contains(string key)
- {
- return cache.Contains(key);
- }
- /// <summary>
- /// 获取缓存中数据
- /// </summary>
- /// <param name="key"></param>
- /// <returns></returns>
- public static T Get<T>(string key)
- {
- try
- {
- if (Contains(key))
- {
- return (T)cache[key];
- }
- return default;
- }
- catch (Exception)
- {
- return default;
- }
- }
- /// <summary>
- /// 移除缓存中的数据
- /// </summary>
- /// <param name="key"></param>
- public static void Remove(string key)
- {
- if (Contains(key))
- {
- cache.Remove(key);
- }
- }
- }
- }
|