1 module appbase.utils.cache; 2 3 import std.conv; 4 import std.datetime; 5 import std.variant; 6 7 __gshared private CacheValue[string] _cacheContainer; 8 9 private class CacheValue 10 { 11 DateTime time; 12 int expireMinutes; 13 Variant value; 14 15 this(Variant value, int expireMinutes) 16 { 17 time = cast(DateTime)Clock.currTime(); 18 this.expireMinutes = expireMinutes; 19 this.value = value; 20 } 21 } 22 23 class Cache 24 { 25 static void set(T)(string key, T value, int expireMinutes = 30) 26 { 27 _cacheContainer[key] = new CacheValue(Variant(value), expireMinutes); 28 } 29 30 static T get(T)(string key, T defaultValue) 31 { 32 CacheValue item; 33 34 if (key !in _cacheContainer) 35 { 36 return defaultValue; 37 } 38 39 synchronized (Cache.classinfo) 40 { 41 if (key !in _cacheContainer) 42 { 43 return defaultValue; 44 } 45 46 item = _cacheContainer.get(key, null); 47 48 if (item is null) 49 { 50 return defaultValue; 51 } 52 53 DateTime now = cast(DateTime)Clock.currTime(); 54 if ((now - item.time).total!"minutes" > item.expireMinutes) 55 { 56 _cacheContainer.remove(key); 57 58 return defaultValue; 59 } 60 } 61 62 if (!item.value.convertsTo!T) 63 { 64 return defaultValue; 65 } 66 67 return item.value.get!T; 68 } 69 70 static void remove(string key) 71 { 72 if (key in _cacheContainer) 73 { 74 synchronized (Cache.classinfo) 75 { 76 if (key in _cacheContainer) 77 { 78 _cacheContainer.remove(key); 79 } 80 } 81 } 82 } 83 }