Token导航 LogoToken导航TokenDH.com
研究检索external-servicegithub未标认证来源可访问clear审计未展示

cachingcaching 开发

Agent Skill

caching 用于查找、检索和筛选相关信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要根据关键词、任务场景或来源线索快速定位候选结果时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

324

周安装

13

GitHub Stars

公开资料未说明

下载量

105
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

MIT

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:caching(caching 开发)
来源仓库:https://github.com/yosrbennagra/3sc
仓库路径:skills/caching
安装命令:
npx skills add yosrbennagra/3sc --skill "caching"
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

AgentSkills.tonpx skills
npx skills add yosrbennagra/3sc --skill "caching"

简介

缓存技术技能发现模块,集成于 yosrbennagra/3sc 技能体系。

  • 适用于 Codex、Claude 等平台的多技能协同开发。
  • 支持按关键词检索并安装缓存相关功能组件。
  • 安装前请确认宿主对 GitHub 技能格式的兼容性。
  • 部分技能可能需要网络连接以拉取依赖项。caching 属于研究检索类 Skill,可作为该场景下的辅助能力补充。

SKILL.md

name
caching
description
In-memory caching patterns for the 3SC widget host. Covers cache strategies, invalidation, TTL policies, and when to cache vs when to fetch.

Caching

Overview

Caching improves performance by reducing database and network calls. This skill covers in-memory caching patterns suitable for desktop applications.

Definition of Done (DoD)

  • [ ] Frequently accessed data is cached appropriately
  • [ ] Cache has defined TTL (time-to-live) for each entry type
  • [ ] Cache invalidation is implemented for write operations
  • [ ] Memory usage is bounded (max entries or max memory)
  • [ ] Cache misses are logged for monitoring
  • [ ] Thread-safety is ensured for concurrent access

When to Cache

ScenarioCache?TTLNotes
Widget catalog (read-heavy)✅ Yes5 minInvalidate on install/uninstall
Installed widgets list✅ Yes10 minInvalidate on changes
Layout configurations✅ Yes5 minInvalidate on save
User preferences✅ YesSessionLoad once, cache for session
Active widget instances❌ No-Already in memory
Real-time data (sync queue)❌ No-Needs fresh data

Cache Service Implementation

Interface

public interface ICacheService
{
    /// <summary>Gets cached value or default if not found/expired.</summary>
    T? Get<T>(string key) where T : class;
    
    /// <summary>Gets cached value or executes factory to populate.</summary>
    Task<T> GetOrCreateAsync<T>(
        string key, 
        Func<CancellationToken, Task<T>> factory,
        TimeSpan? expiration = null,
        CancellationToken cancellationToken = default) where T : class;
    
    /// <summary>Sets value with optional expiration.</summary>
    void Set<T>(string key, T value, TimeSpan? expiration = null) where T : class;
    
    /// <summary>Removes specific key.</summary>
    void Remove(string key);
    
    /// <summary>Removes all keys matching prefix.</summary>
    void RemoveByPrefix(string prefix);
    
    /// <summary>Clears entire cache.</summary>
    void Clear();
    
    /// <summary>Gets cache statistics.</summary>
    CacheStatistics GetStatistics();
}

public record CacheStatistics(int EntryCount, long Hits, long Misses, long Evictions);

Implementation

public class MemoryCacheService : ICacheService, IDisposable
{
    private readonly ConcurrentDictionary<string, CacheEntry> _cache = new();
    private readonly Timer _cleanupTimer;
    private readonly int _maxEntries;
    
    private long _hits;
    private long _misses;
    private long _evictions;
    
    public MemoryCacheService(int maxEntries = 1000, TimeSpan? cleanupInterval = null)
    {
        _maxEntries = maxEntries;
        _cleanupTimer = new Timer(
            CleanupExpired, 
            null, 
            cleanupInterval ?? TimeSpan.FromMinutes(1),
            cleanupInterval ?? TimeSpan.FromMinutes(1));
    }
    
    public T? Get<T>(string key) where T : class
    {
        if (_cache.TryGetValue(key, out var entry) && !entry.IsExpired)
        {
            Interlocked.Increment(ref _hits);
            entry.Touch();
            return (T)entry.Value;
        }
        
        Interlocked.Increment(ref _misses);
        
        if (entry?.IsExpired == true)
        {
            _cache.TryRemove(key, out _);
        }
        
        return null;
    }
    
    public async Task<T> GetOrCreateAsync<T>(
        string key,
        Func<CancellationToken, Task<T>> factory,
        TimeSpan? expiration = null,
        CancellationToken cancellationToken = default) where T : class
    {
        var existing = Get<T>(key);
        if (existing != null)
            return existing;
        
        // Use lock to prevent duplicate factory calls
        var value = await factory(cancellationToken).ConfigureAwait(false);
        Set(key, value, expiration);
        return value;
    }
    
    public void Set<T>(string key, T value, TimeSpan? expiration = null) where T : class
    {
        EnsureCapacity();
        
        var entry = new CacheEntry(value, expiration);
        _cache[key] = entry;
        
        Log.Debug("Cache set: {Key}, Expires: {Expiration}", 
            key, entry.ExpiresAt?.ToString("HH:mm:ss") ?? "never");
    }
    
    public void Remove(string key)
    {
        if (_cache.TryRemove(key, out _))
        {
            Log.Debug("Cache removed: {Key}", key);
        }
    }
    
    public void RemoveByPrefix(string prefix)
    {
        var keysToRemove = _cache.Keys
            .Where(k => k.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
            .ToList();
        
        foreach (var key in keysToRemove)
        {
            _cache.TryRemove(key, out _);
        }
        
        Log.Debug("Cache cleared {Count} entries with prefix: {Prefix}", 
            keysToRemove.Count, prefix);
    }
    
    public void Clear()
    {
        var count = _cache.Count;
        _cache.Clear();
        Log.Information("Cache cleared: {Count} entries removed", count);
    }
    
    public CacheStatistics GetStatistics() => 
        new(_cache.Count, _hits, _misses, _evictions);
    
    private void EnsureCapacity()
    {
        if (_cache.Count < _maxEntries)
            return;
        
        // Evict oldest entries (LRU)
        var toEvict = _cache
            .OrderBy(x => x.Value.LastAccessed)
            .Take(_cache.Count / 4)  // Evict 25%
            .Select(x => x.Key)
            .ToList();
        
        foreach (var key in toEvict)
        {
            if (_cache.TryRemove(key, out _))
            {
                Interlocked.Increment(ref _evictions);
            }
        }
        
        Log.Debug("Cache evicted {Count} entries", toEvict.Count);
    }
    
    private void CleanupExpired(object? state)
    {
        var expired = _cache
            .Where(x => x.Value.IsExpired)
            .Select(x => x.Key)
            .ToList();
        
        foreach (var key in expired)
        {
            _cache.TryRemove(key, out _);
        }
        
        if (expired.Count > 0)
        {
            Log.Debug("Cache cleanup: {Count} expired entries removed", expired.Count);
        }
    }
    
    public void Dispose()
    {
        _cleanupTimer.Dispose();
    }
    
    private class CacheEntry
    {
        public object Value { get; }
        public DateTimeOffset? ExpiresAt { get; }
        public DateTimeOffset LastAccessed { get; private set; }
        public bool IsExpired => ExpiresAt.HasValue && DateTimeOffset.UtcNow > ExpiresAt;
        
        public CacheEntry(object value, TimeSpan? expiration)
        {
            Value = value;
            LastAccessed = DateTimeOffset.UtcNow;
            ExpiresAt = expiration.HasValue 
                ? DateTimeOffset.UtcNow.Add(expiration.Value) 
                : null;
        }
        
        public void Touch() => LastAccessed = DateTimeOffset.UtcNow;
    }
}

Cache Keys Convention

Use hierarchical keys for easy invalidation:

public static class CacheKeys
{
    // Pattern: {entity}:{scope}:{identifier}
    
    public const string WidgetCatalog = "widgets:catalog:all";
    public const string InstalledWidgets = "widgets:installed:all";
    
    public static string Widget(string widgetKey) => $"widgets:detail:{widgetKey}";
    public static string Layout(Guid layoutId) => $"layouts:detail:{layoutId}";
    public static string UserSettings(string key) => $"settings:user:{key}";
    
    // Prefixes for bulk invalidation
    public const string WidgetsPrefix = "widgets:";
    public const string LayoutsPrefix = "layouts:";
}

Repository with Caching

public class CachedWidgetRepository : IWidgetRepository
{
    private readonly IWidgetRepository _inner;
    private readonly ICacheService _cache;
    
    private static readonly TimeSpan CacheDuration = TimeSpan.FromMinutes(5);
    
    public CachedWidgetRepository(IWidgetRepository inner, ICacheService cache)
    {
        _inner = inner;
        _cache = cache;
    }
    
    public async Task<IReadOnlyList<Widget>> GetAllAsync(CancellationToken ct = default)
    {
        return await _cache.GetOrCreateAsync(
            CacheKeys.WidgetCatalog,
            async token => (await _inner.GetAllAsync(token)).ToList(),
            CacheDuration,
            ct);
    }
    
    public async Task<Widget?> GetByKeyAsync(string widgetKey, CancellationToken ct = default)
    {
        return await _cache.GetOrCreateAsync(
            CacheKeys.Widget(widgetKey),
            token => _inner.GetByKeyAsync(widgetKey, token),
            CacheDuration,
            ct);
    }
    
    public async Task AddAsync(Widget widget, CancellationToken ct = default)
    {
        await _inner.AddAsync(widget, ct);
        
        // Invalidate related caches
        _cache.Remove(CacheKeys.WidgetCatalog);
        _cache.Remove(CacheKeys.Widget(widget.WidgetKey));
    }
    
    public async Task UpdateAsync(Widget widget, CancellationToken ct = default)
    {
        await _inner.UpdateAsync(widget, ct);
        
        _cache.Remove(CacheKeys.Widget(widget.WidgetKey));
        _cache.Remove(CacheKeys.WidgetCatalog);
    }
    
    public async Task DeleteAsync(string widgetKey, CancellationToken ct = default)
    {
        await _inner.DeleteAsync(widgetKey, ct);
        
        _cache.RemoveByPrefix(CacheKeys.WidgetsPrefix);
    }
}

Cache-Aside Pattern

For more control over cache population:

public async Task<Widget?> GetWidgetAsync(string widgetKey, CancellationToken ct)
{
    // 1. Check cache
    var cached = _cache.Get<Widget>(CacheKeys.Widget(widgetKey));
    if (cached != null)
        return cached;
    
    // 2. Load from database
    var widget = await _repository.GetByKeyAsync(widgetKey, ct);
    
    // 3. Populate cache (even if null, to prevent repeated lookups)
    if (widget != null)
    {
        _cache.Set(CacheKeys.Widget(widgetKey), widget, TimeSpan.FromMinutes(5));
    }
    
    return widget;
}

Cache Warming

Pre-populate cache at startup:

public class CacheWarmupService
{
    private readonly ICacheService _cache;
    private readonly IWidgetRepository _widgetRepo;
    private readonly ILayoutRepository _layoutRepo;
    
    public async Task WarmupAsync(CancellationToken ct)
    {
        Log.Information("Starting cache warmup");
        
        var tasks = new[]
        {
            WarmWidgetsAsync(ct),
            WarmLayoutsAsync(ct)
        };
        
        await Task.WhenAll(tasks);
        
        var stats = _cache.GetStatistics();
        Log.Information("Cache warmup complete: {Count} entries", stats.EntryCount);
    }
    
    private async Task WarmWidgetsAsync(CancellationToken ct)
    {
        var widgets = await _widgetRepo.GetAllAsync(ct);
        _cache.Set(CacheKeys.WidgetCatalog, widgets.ToList(), TimeSpan.FromMinutes(10));
        
        foreach (var widget in widgets)
        {
            _cache.Set(CacheKeys.Widget(widget.WidgetKey), widget, TimeSpan.FromMinutes(10));
        }
    }
    
    private async Task WarmLayoutsAsync(CancellationToken ct)
    {
        // Similar pattern...
    }
}

Best Practices

PracticeReason
Always set TTLPrevents stale data and memory leaks
Invalidate on writesEnsures cache consistency
Use hierarchical keysEnables prefix-based invalidation
Bound cache sizePrevents unbounded memory growth
Log cache metricsHelps tune cache effectiveness
Don't cache nulls (usually)Unless preventing repeated lookups

Anti-Patterns

Anti-PatternProblemSolution
Unbounded cacheMemory leakSet max entries
No TTLStale data foreverAlways set expiration
Cache complex graphsInconsistent updatesCache simple DTOs
Distributed cache for desktopOver-engineeringUse simple in-memory
Caching mutable objectsRace conditionsCache immutable/copies

Monitoring

// Log cache effectiveness periodically
public void LogCacheMetrics()
{
    var stats = _cache.GetStatistics();
    var hitRate = stats.Hits + stats.Misses > 0 
        ? (double)stats.Hits / (stats.Hits + stats.Misses) * 100 
        : 0;
    
    Log.Information(
        "Cache metrics - Entries: {Entries}, HitRate: {HitRate:F1}%, " +
        "Hits: {Hits}, Misses: {Misses}, Evictions: {Evictions}",
        stats.EntryCount, hitRate, stats.Hits, stats.Misses, stats.Evictions);
}

References

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

04

需要参考平台分布和安装热度时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

补充不同宿主或平台的使用分布数据

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Gemini CLI

28.03%
按下载量换算29

windsurf

22.41%
按下载量换算24

trae

19.38%
按下载量换算20

OpenCode

13.42%
按下载量换算14

Codex

8.06%
按下载量换算8

Claude Code

3.56%
按下载量换算4

安全审计

暂无安全审计结果可展示。

权限和风险

external-service

该 Skill 可能调用第三方服务、云服务或外部模型 API,使用前需要确认账号、额度、数据发送范围和服务条款。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills