加入收藏 | 设为首页 | 会员中心 | 我要投稿 拼字网 - 核心网 (https://www.hexinwang.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 编程要点 > 语言 > 正文

分析Dictionary实现日志数据批量插入

发布时间:2021-06-04 06:24:22 所属栏目:语言 来源:互联网
导读:最近再做一个需求,就是对站点的一些事件进行埋点,说白了就是记录用户的访问行为。那么这些数据怎么保存呢,人家点一下保存一下?显然不合适,肯定是需要批量保
副标题[/!--empirenews.page--]

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

问题窥探

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

主要代码实现

1、定义一个Dictionary。

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

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

public bool SaveObject<T>(string path, T value) where T : class { 

            if (String.IsNullOrWhiteSpace(path)) 

                throw new ArgumentNullException("path"); 

 

            lock (_lock) { 

                _storage[path] = Tuple.Create(new ObjectInfo { 

                    Created = DateTime.Now, 

                    Modified = DateTime.Now, 

                    Path = path 

                }, (object)value); 

 

                if (_storage.Count > MaxObjects) 

                    _storage.Remove(_storage.OrderByDescending(kvp => kvp.Value.Item1.Created).First().Key); 

            } 

 

            return true; 

        } 

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

public DefaultEventQueue(ExceptionlessConfiguration config, IExceptionlessLog log, ISubmissionClient client, IObjectStorage objectStorage, IJsonSerializer serializer, TimeSpan? processQueueInterval, TimeSpan? queueStartDelay) { 

            _log = log; 

            _config = config; 

            _client = client; 

            _storage = objectStorage; 

            _serializer = serializer; 

            if (processQueueInterval.HasValue) 

                _processQueueInterval = processQueueInterval.Value; 

 

            _queueTimer = new Timer(OnProcessQueue, null, queueStartDelay ?? TimeSpan.FromSeconds(2), _processQueueInterval); 

        } 

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

public bool DeleteObject(string path) { 

            if (String.IsNullOrWhiteSpace(path)) 

(编辑:拼字网 - 核心网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!