mirror of
https://github.com/Bubuni-Team/telegram-bot.git
synced 2026-07-31 00:29:24 +03:00
Initial work on cache
This commit is contained in:
@@ -0,0 +1,10 @@
|
||||
using System;
|
||||
|
||||
namespace Kruzya.TelegramBot.Core.Cache
|
||||
{
|
||||
public interface ICacheStorage<TKey, TValue>
|
||||
{
|
||||
public bool TryGetValue(TKey key, ref TValue value);
|
||||
public void SetValue(TKey key, TValue value, int timeToLive);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
|
||||
namespace Kruzya.TelegramBot.Core.Cache
|
||||
{
|
||||
public class MemoryCache<TKey, TValue> : ICacheStorage<TKey, TValue>
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a cache entry in internal dictionary.
|
||||
/// </summary>
|
||||
/// <typeparam name="TVal"></typeparam>
|
||||
internal struct CacheEntry<TVal>
|
||||
{
|
||||
public TVal Value;
|
||||
public DateTime Created;
|
||||
public int ExpiresAt;
|
||||
|
||||
public bool IsExpired()
|
||||
{
|
||||
if (ExpiresAt == Timeout.Infinite)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return (Created.AddSeconds(ExpiresAt)) < DateTime.Now;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
private Dictionary<TKey, CacheEntry<TValue>> dict = new Dictionary<TKey, CacheEntry<TValue>>();
|
||||
|
||||
/// <summary>
|
||||
/// The TTL for all entries if not set.
|
||||
/// </summary>
|
||||
private int _defaultTtl;
|
||||
|
||||
public MemoryCache() : this(Timeout.Infinite)
|
||||
{
|
||||
}
|
||||
|
||||
public MemoryCache(int defaultTtl)
|
||||
{
|
||||
_defaultTtl = defaultTtl;
|
||||
}
|
||||
|
||||
public bool TryGetValue(TKey key, ref TValue value)
|
||||
{
|
||||
if (dict.ContainsKey(key))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
CacheEntry<TValue> temp;
|
||||
if (!dict.TryGetValue(key, out temp))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (temp.IsExpired())
|
||||
{
|
||||
dict.Remove(key);
|
||||
return false;
|
||||
}
|
||||
|
||||
value = temp.Value;
|
||||
return true;
|
||||
}
|
||||
|
||||
public void SetValue(TKey key, TValue value)
|
||||
{
|
||||
SetValue(key, value, _defaultTtl);
|
||||
}
|
||||
|
||||
public void SetValue(TKey key, TValue value, int timeToLive)
|
||||
{
|
||||
if (dict.ContainsKey(key))
|
||||
{
|
||||
dict.Remove(key);
|
||||
}
|
||||
|
||||
dict.Add(key, new CacheEntry<TValue>()
|
||||
{
|
||||
Created = DateTime.Now,
|
||||
ExpiresAt = timeToLive,
|
||||
Value = value
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user