当前位置:主页 > 查看内容

巧用Dictionary实现日志数据批量插入

发布时间:2021-06-17 00:00| 位朋友查看

简介:本文转载自微信公众号「UP技术控」,作者conan5566 。转载本文请联系UP技术控公众号。 背景 最近再做一个需求,就是对站点的一些事件进行埋点,说白了就是记录用户的访问行为。那么这些数据怎么保存呢,人家点一下保存一下?显然不合适,肯定是需要批量保存,……

本文转载自微信公众号「UP技术控」,作者conan5566 。转载本文请联系UP技术控公众号。 

背景

最近再做一个需求,就是对站点的一些事件进行埋点,说白了就是记录用户的访问行为。那么这些数据怎么保存呢,人家点一下保存一下?显然不合适,肯定是需要批量保存,提高效率。

问题窥探

首先,我想到的是Dictionary,对于C#中的Dictionary类相信大家都不陌生,这是一个Collection(集合)类型,可以通过Key/Value(键值对的形式来存放数据;该类最大的优点就是它查找元素的时间复杂度接近O(1),实际项目中常被用来做一些数据的本地缓存,提升整体效率。Dictionary是非线程安全的类型,可以实现先添加到内存当中,在批量保存进去数据库。

主要代码实现

1、定义一个Dictionary。

  1. private readonly Dictionary<string, Tuple<ObjectInfo, object>> _storage = new Dictionary<string, Tuple<ObjectInfo, object>>(StringComparer.OrdinalIgnoreCase); 

2、添加元素,操作的时候需要对其进行线程安全处理,最简单的方式就是加锁(lock)。

  1. public bool SaveObject<T>(string path, T value) where T : class { 
  2.             if (String.IsNullOrWhiteSpace(path)) 
  3.                 throw new ArgumentNullException("path"); 
  4.  
  5.             lock (_lock) { 
  6.                 _storage[path] = Tuple.Create(new ObjectInfo { 
  7.                     Created = DateTime.Now, 
  8.                     Modified = DateTime.Now, 
  9.                     Path = path 
  10.                 }, (object)value); 
  11.  
  12.                 if (_storage.Count > MaxObjects) 
  13.                     _storage.Remove(_storage.OrderByDescending(kvp => kvp.Value.Item1.Created).First().Key); 
  14.             } 
  15.  
  16.             return true
  17.         } 

3、定义一个队列,定时消费日志。

  1. public DefaultEventQueue(ExceptionlessConfiguration config, IExceptionlessLog log, ISubmissionClient client, IObjectStorage objectStorage, IJsonSerializer serializer, TimeSpan? processQueueInterval, TimeSpan? queueStartDelay) { 
  2.             _log = log; 
  3.             _config = config; 
  4.             _client = client; 
  5.             _storage = objectStorage; 
  6.             _serializer = serializer; 
  7.             if (processQueueInterval.HasValue) 
  8.                 _processQueueInterval = processQueueInterval.Value; 
  9.  
  10.             _queueTimer = new Timer(OnProcessQueue, null, queueStartDelay ?? TimeSpan.FromSeconds(2), _processQueueInterval); 
  11.         } 

这里删除的时候也需要lock 操作。

  1. public bool DeleteObject(string path) { 
  2.             if (String.IsNullOrWhiteSpace(path)) 
  3.                 throw new ArgumentNullException("path"); 
  4.  
  5.             lock (_lock) { 
  6.                 if (!_storage.ContainsKey(path)) 
  7.                     return false
  8.  
  9.                 _storage.Remove(path); 
  10.             } 
  11.  
  12.             return true
  13.         } 
  1. public IEnumerable<ObjectInfo> GetObjectList(string searchPattern = nullint? limit = null, DateTime? maxCreatedDate = null) { 
  2.             if (searchPattern == null
  3.                 searchPattern = "*"
  4.             if (!maxCreatedDate.HasValue) 
  5.                 maxCreatedDate = DateTime.MaxValue; 
  6.  
  7.             var regex = new Regex("^" + Regex.Escape(searchPattern).Replace("\\*"".*?") + "$"); 
  8.             lock (_lock) 
  9.                 return _storage.Keys.Where(k => regex.IsMatch(k)).Select(k => _storage[k].Item1).Where(f => f.Created <= maxCreatedDate).Take(limit ?? Int32.MaxValue).ToList(); 
  10.         } 

总结

1、利用Dictionary。多线程添加数据到内存;

2、达到一定量的时候,批量保存数据。

3、使用lock ,保证Dictionary操作安全。


本文转载自网络,原文链接:https://mp.weixin.qq.com/s/MH2mgk92Bl8a206ABOVuEw
本站部分内容转载于网络,版权归原作者所有,转载之目的在于传播更多优秀技术内容,如有侵权请联系QQ/微信:153890879删除,谢谢!

推荐图文

  • 周排行
  • 月排行
  • 总排行

随机推荐