-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathDB.cs
92 lines (79 loc) · 2.84 KB
/
DB.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using BinaryRage.Functions;
namespace BinaryRage
{
static public class DB
{
static BlockingCollection<SimpleObject> sendQueue = new BlockingCollection<SimpleObject>();
static readonly object LockObject = new object();
static public void Insert<T>(string key, T value, string filelocation)
{
Interlocked.Increment(ref Cache.counter);
SimpleObject simpleObject = new SimpleObject { Key = key, Value = value, FileLocation = filelocation };
sendQueue.Add(simpleObject);
var data = sendQueue.Take(); //this blocks if there are no items in the queue.
//Add to cache
lock (Cache.LockObject)
{
Cache.CacheDic[filelocation + key] = simpleObject;
}
ThreadPool.QueueUserWorkItem(state =>
{
lock (Cache.LockObject)
{
Storage.WritetoStorage(data.Key, Compress.CompressGZip(ConvertHelper.ObjectToByteArray(value)),
data.FileLocation);
}
});
}
static public void Remove(string key, string filelocation)
{
lock (Cache.LockObject)
{
Cache.CacheDic.Remove(filelocation + key);
}
lock (DB.LockObject)
{
File.Delete(Storage.GetExactFileLocation(key, filelocation));
}
}
static public T Get<T>(string key, string filelocation)
{
//Try getting the object from cache first
lock (Cache.LockObject)
{
SimpleObject simpleObjectFromCache;
if (Cache.CacheDic.TryGetValue(filelocation + key, out simpleObjectFromCache))
return (T)simpleObjectFromCache.Value;
}
//Get from disk
lock (DB.LockObject)
{
byte[] compressGZipData = Compress.DecompressGZip(Storage.GetFromStorage(key, filelocation));
T umcompressedObject = (T) ConvertHelper.ByteArrayToObject(compressGZipData);
return umcompressedObject;
}
}
static public string GetJSON<T>(string key, string filelocation)
{
return SimpleSerializer.Serrialize(Get<T>(key, filelocation));
}
static public bool Exists(string key, string filelocation)
{
return Storage.ExistingStorageCheck(key, filelocation);
}
static public void WaitForCompletion()
{
while (Cache.counter > 0)
{
Thread.Sleep(10);
}
}
}
}