You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求推荐D语言自动过期内存字典库:支持带过期时间的键值存取

在D语言中实现带过期时间的内存缓存

当然可以实现!在D语言的生态里,有现成的库能满足你的需求,甚至你也可以基于标准库快速封装出符合预期的缓存工具。下面给你详细说明:

优先推荐:使用dcache库

dcache是D语言生态中专门针对缓存场景设计的库,原生支持过期时间设置,用法完全匹配你想要的API风格。你可以通过DUB包管理器直接安装它。

使用示例

import dcache;
import std.stdio;

void main() {
    // 创建键为string、值为int的缓存实例
    auto cache = new Cache!(string, int);

    // 插入键值对,设置10秒后过期
    cache.insert("foo", 42, 10.seconds);

    // 通过索引器检索值,会自动校验是否过期
    if ("foo" in cache) {
        writeln(cache["foo"]); // 未过期时输出42
    }
}

这个库已经帮你处理了过期条目自动校验、内存管理等细节,完全不需要自己重复造轮子。

手动封装方案(基于D标准库)

如果你需要高度定制缓存的行为,或者不想依赖第三方库,基于D的标准库也能快速实现需求。我们可以用std.container.HashMap存储带过期时间的条目,结合std.datetime做时间校验。

实现示例

import std.container;
import std.datetime;
import std.stdio;
import core.thread;

struct CacheEntry(V) {
    V value;
    SysTime expiryTime;
}

class Cache(K, V) {
    private HashMap!(K, CacheEntry!V) _data;

    this() {
        _data = new HashMap!(K, CacheEntry!V);
    }

    // 插入带过期时间的键值对
    void insert(K key, V value, Duration expiry) {
        auto entry = CacheEntry!V(value, Clock.currTime() + expiry);
        _data[key] = entry;
    }

    // 通过索引器检索值,自动处理过期逻辑
    V opIndex(K key) {
        auto entryPtr = key in _data;
        if (!entryPtr || entryPtr.expiryTime < Clock.currTime()) {
            _data.remove(key); // 清理过期条目
            throw new Exception("Key not found or has expired");
        }
        return entryPtr.value;
    }

    // 实现in运算符,方便判断键是否有效
    bool opBinaryRight(string op)(K key) if (op == "in") {
        auto entryPtr = key in _data;
        if (!entryPtr || entryPtr.expiryTime < Clock.currTime()) {
            _data.remove(key);
            return false;
        }
        return true;
    }
}

void main() {
    auto cache = new Cache!(string, int);
    cache.insert("bar", 123, 5.seconds);

    if ("bar" in cache) {
        writeln(cache["bar"]); // 输出123
    }

    // 等待6秒后验证过期逻辑
    Thread.sleep(6.seconds);
    if ("bar" !in cache) {
        writeln("Key has expired"); // 输出此内容
    }
}

这个自定义实现完全可控,你可以根据需求扩展功能,比如添加后台定时清理过期条目、调整异常处理逻辑等。

内容的提问来源于stack exchange,提问作者Pasqui23

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:02:22