本文转载自微信公众号「UP技术控」,作者conan5566 。转载本文请联系UP技术控公众号。
背景
最近再做一个需求,就是对站点的一些事件进行埋点,说白了就是记录用户的访问行为。那么这些数据怎么保存呢,人家点一下保存一下?显然不合适,肯定是需要批量保存,提高效率。
问题窥探
首先,我想到的是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))
- throw new ArgumentNullException("path");
- lock (_lock) {
- if (!_storage.ContainsKey(path))
- return false;
- _storage.Remove(path);
- }
- return true;
- }
- public IEnumerable<ObjectInfo> GetObjectList(string searchPattern = null, int? limit = null, DateTime? maxCreatedDate = null) {
- if (searchPattern == null)
- searchPattern = "*";
- if (!maxCreatedDate.HasValue)
- maxCreatedDate = DateTime.MaxValue;
- var regex = new Regex("^" + Regex.Escape(searchPattern).Replace("\\*", ".*?") + "$");
- lock (_lock)
- return _storage.Keys.Where(k => regex.IsMatch(k)).Select(k => _storage[k].Item1).Where(f => f.Created <= maxCreatedDate).Take(limit ?? Int32.MaxValue).ToList();
- }
总结
1、利用Dictionary。多线程添加数据到内存;
2、达到一定量的时候,批量保存数据。
3、使用lock ,保证Dictionary操作安全。
本文转载自公众号读芯术(ID:AI_Discovery)。 这一刻你正在应对什么挑战?这位前...
在Python开发过程中,我们难免会遇到多重条件判断的情况的情况,此时除了用很多...
背景 我们知道 如果在Kubernetes中支持GPU设备调度 需要做如下的工作 节点上安装...
本文转载自微信公众号「bugstack虫洞栈」,作者小傅哥 。转载本文请联系bugstack...
想了解更多内容,请访问: 51CTO和华为官方战略合作共建的鸿蒙技术社区 https://...
近几年,互联网行业蓬勃发展,在互联网浪潮的冲击下,互联网创业已成为一种比较...
前言 统计科学家使用交互式的统计工具(比如R)来回答数据中的问题,获得全景的认...
溢价 域名 的续费价格如何?通常来说,因为溢价域名的价值高于普通域名,所以溢...
TIOBE 公布了 2021 年 3 月的编程语言排行榜。 本月 TIOBE 指数没有什么有趣的变...
基本介绍 给定 n 个权值作为 n 个叶子节点,构造一颗二叉树,若该树的带权路径长...