| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- using System;
- using SHJX.Service.Common.Logging;
- using Microsoft.Extensions.Options;
- using Microsoft.Extensions.Logging;
- using Microsoft.Extensions.Caching.Memory;
- namespace SHJX.Service.Common.Utils
- {
- /// <summary>
- /// 数据缓存工具类
- /// </summary>
- public class DataCache
- {
- private static DataCache _cache;
- private static readonly object obj_lock = new();
- private static readonly ILogger Logger = LogFactory.BuildLogger(typeof(DataCache));
- private static readonly MemoryCache cache = new(Options.Create(new MemoryCacheOptions()));
- private DataCache() { }
- public static DataCache Instance
- {
- get
- {
- if (_cache is null)
- {
- lock (obj_lock)
- {
- _cache = new DataCache();
- }
- }
- return _cache;
- }
- }
- /// <summary>
- /// 新增
- /// </summary>
- /// <typeparam name="T">缓存类型</typeparam>
- /// <param name="key">键</param>
- /// <param name="value">值</param>
- /// <param name="cacheTime">缓存时间(秒)</param>
- public void Set<T>(object key, T value, int cacheTime = 5)
- {
- cache.GetOrCreate(key, entry =>
- {
- entry.SetAbsoluteExpiration(TimeSpan.FromSeconds(cacheTime));
- entry.RegisterPostEvictionCallback((key, value, reason, state) =>
- {
- Logger.LogInformation($"{value}已过期");
- });
- return value;
- });
- }
- /// <summary>
- /// 获取缓存中数据
- /// </summary>
- /// <param name="key"></param>
- /// <returns></returns>
- public T Get<T>(object key)
- {
- try
- {
- if (cache.TryGetValue(key, out var value))
- {
- return (T)value;
- }
- return default;
- }
- catch (Exception)
- {
- return default;
- }
- }
- /// <summary>
- /// 移除缓存中的数据
- /// </summary>
- /// <param name="key"></param>
- public void Remove(object key)
- {
- if (cache.TryGetValue(key, out _))
- {
- cache.Remove(key);
- }
- }
- public int Count => cache.Count;
- }
- }
|