巧用Dictionary實現日志數據批量插入


背景

最近再做一個需求,就是對站點的一些事件進行埋點,說白了就是記錄用戶的訪問行為。那么這些數據怎么保存呢,人家點一下保存一下?顯然不合適,肯定是需要批量保存,提高效率。

問題窺探

首先,我想到的是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操作安全。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM