123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- using System;
- using Newtonsoft.Json;
- using System.Globalization;
- using WingInterfaceLibrary.Enum;
- using System.Collections.Concurrent;
- namespace WingDeviceService.Common
- {
- public class CacheManager<TObject> : IDisposable where TObject : class
- {
- private ConcurrentDictionary<string, TObject> _source = new();
- /// <summary>
- /// 添加/更新缓存
- /// </summary>
- /// <param name="key"></param>
- /// <param name="obj"></param>
- public TObject AddOrUpdate(string key, TObject obj)
- {
- return _source.AddOrUpdate(key, obj, (k, v) => obj);
- }
- /// <summary>
- /// 删除缓存
- /// </summary>
- /// <param name="key"></param>
- /// <returns></returns>
- public bool Remove(string key)
- {
- return _source.TryRemove(key, out _);
- }
- /// <summary>
- /// 获取缓存信息
- /// </summary>
- /// <param name="key"></param>
- /// <returns></returns>
- public TObject Get(string key)
- {
- if (_source.TryGetValue(key, out TObject obj))
- {
- return obj;
- }
- return default;
- }
- /// <summary>
- /// 清空缓存
- /// </summary>
- public void Dispose()
- {
- _source.Clear();
- }
- }
- public class CacheManagerSingle<TObject> where TObject : class
- {
- private CacheManagerSingle() { }
- private readonly static object _locker = new();
- private static CacheManager<TObject> _instance;
- /// <summary>
- /// 单例对象
- /// </summary>
- /// <value></value>
- public static CacheManager<TObject> Instance
- {
- get
- {
- if (_instance == null)
- {
- lock (_locker)
- {
- if (_instance == null)
- {
- _instance = new CacheManager<TObject>();
- }
- }
- }
- return _instance;
- }
- }
- }
- }
|