caching - 自动过期字典

标签 caching d

我想要一个提供内存数据结构的库,以便我可以编写,例如:

cache.insert(key,value,expiry)

我可以使用cache[key]之类的方法检索该值,除非它已经过了过期秒数。

可以做吗?我应该使用什么库?

如果可能的话,首选 D 库

最佳答案

我不知道有哪个库可以做到这一点。另一方面,让某些东西发挥作用并不需要做很多工作。这是我在十分钟内整理出来的东西:

struct Dict(K, V, E)
if (isExpiry!E)
{
    import std.typecons : Tuple;
private:
    Tuple!(V, "value", E, "expiry")[K] _payload;
public:
    V opIndex(K key)
    {
        return *(key in this);
    }

    V* opBinaryRight(string op : "in")(K key)
    {
        auto p = key in _payload;
        if (!p || p.expiry.expired) return null;
        return &p.value;
    }

    void insert(K key, V value, E expiry)
    {
        expiry.initialize();
        _payload[key] = typeof(_payload[key])(value, expiry);
    }

    void remove(K key)
    {
        _payload.remove(key);
    }
}

enum isExpiry(T) = is(typeof((T t){
        t.initialize();
        if (t.expired) {}
    }));
static assert(!isExpiry!int);

struct Timeout
{
    import core.time;
    Duration duration;
    MonoTime start;

    void initialize() {
        start = MonoTime.currTime;
    }

    @property
    bool expired()
    {
        auto elapsed = MonoTime.currTime - start;
        return elapsed > duration;
    }
}
static assert(isExpiry!Timeout);

unittest
{
    import core.time;
    import core.thread;
    Dict!(int, string, Timeout) a;
    assert(3 !in a);
    a.insert(3, "a", Timeout(100.dur!"msecs"));
    a.insert(4, "b", Timeout(10.dur!"days"));
    assert(3 in a);
    assert(4 in a);
    Thread.sleep(200.dur!"msecs");
    assert(3 !in a);
    assert(4 in a);
    a.remove(4);
    assert(4 !in a);
}

关于caching - 自动过期字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50059065/

相关文章:

android - 如何在android中同步本地数据库和Parse?

java - hibernate-redis 是否支持由不同的 hibernate 实例共享的二级缓存

javascript - 如何从不同域的脚本报告 JS 错误?

d - 当我调用 new 时会发生什么?

pointers - 结构构造函数的奇怪行为

caching - 为什么打开 @Cacheable 会导致我的事务失败?

database - 缓存不经意的前瞻数组

d - 在 D 中的关联数组中查找最大值元素

d - 我应该使用 Phobos 还是 Tango?

templates - D 中是否可以使用可变参数混合模板?