{"id":24688361,"url":"https://github.com/koatty/koatty_cacheable","last_synced_at":"2026-04-24T17:02:46.359Z","repository":{"id":42256701,"uuid":"277527873","full_name":"Koatty/koatty_cacheable","owner":"Koatty","description":"Cacheable for koatty.","archived":false,"fork":false,"pushed_at":"2026-02-10T09:20:34.000Z","size":843,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2026-02-10T15:00:23.181Z","etag":null,"topics":["cache","components","koa","koatty","memorycache","redis-cache"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsd-3-clause","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Koatty.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2020-07-06T11:50:17.000Z","updated_at":"2026-02-10T09:20:38.000Z","dependencies_parsed_at":"2026-02-10T12:02:37.920Z","dependency_job_id":null,"html_url":"https://github.com/Koatty/koatty_cacheable","commit_stats":{"total_commits":52,"total_committers":3,"mean_commits":"17.333333333333332","dds":"0.23076923076923073","last_synced_commit":"7e9b1abe6acdbdf1b6ad34efa053cbaca1e7b6d7"},"previous_names":["thinkkoa/koatty_cacheable","thinkkoa/think_cacheable"],"tags_count":20,"template":false,"template_full_name":null,"purl":"pkg:github/Koatty/koatty_cacheable","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Koatty%2Fkoatty_cacheable","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Koatty%2Fkoatty_cacheable/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Koatty%2Fkoatty_cacheable/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Koatty%2Fkoatty_cacheable/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Koatty","download_url":"https://codeload.github.com/Koatty/koatty_cacheable/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Koatty%2Fkoatty_cacheable/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32232628,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-24T13:21:15.438Z","status":"ssl_error","status_checked_at":"2026-04-24T13:21:15.005Z","response_time":64,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cache","components","koa","koatty","memorycache","redis-cache"],"created_at":"2025-01-26T17:16:52.156Z","updated_at":"2026-04-24T17:02:46.338Z","avatar_url":"https://github.com/Koatty.png","language":"TypeScript","readme":"# koatty_cacheable\n\nCacheable for koatty.\n\nKoatty框架的 CacheAble, CacheEvict 缓存装饰器支持库，提供方法级别的缓存功能。\n\n## 特性\n\n- 🚀 **简单易用**: 通过装饰器轻松添加缓存功能\n- 🔄 **自动缓存**: `@CacheAble` 装饰器自动缓存方法返回值\n- 🗑️ **智能清除**: `@CacheEvict` 装饰器智能清除相关缓存\n- ⚡ **延迟双删**: 支持延迟双删策略，解决缓存一致性问题\n- 🔧 **多后端支持**: 支持 Memory 和 Redis 缓存后端\n- 🎯 **参数化缓存**: 支持基于方法参数的缓存键生成\n- 🛡️ **类型安全**: 完整的 TypeScript 支持\n\n## 安装\n\n```bash\nnpm install koatty_cacheable\n```\n\n## 快速开始\n\n### 1. 生成插件模板\n\n使用 Koatty CLI 生成插件模板：\n\n```bash\nkt plugin Cacheable\n```\n\n创建 `src/plugin/Cacheable.ts`：\n\n```typescript\nimport { Plugin, IPlugin, App } from \"koatty\";\nimport { KoattyCached } from \"koatty_cacheable\";\n\n@Plugin()\nexport class Cacheable implements IPlugin {\n  run(options: any, app: App) {\n    return KoattyCached(options, app);\n  }\n}\n```\n\n### 2. 配置插件\n\n更新 `src/config/plugin.ts`：\n\n```typescript\nexport default {\n  list: [\"Cacheable\"], // 插件加载顺序\n  config: {\n    Cacheable: {\n      type: \"memory\", // 缓存类型: \"redis\" 或 \"memory\"，默认为 \"memory\"\n      db: 0,\n      timeout: 30,\n      // Redis 配置 (当 type 为 \"redis\" 时)\n      // key_prefix: \"koatty\",\n      // host: '127.0.0.1',\n      // port: 6379,\n      // name: \"\",\n      // username: \"\",\n      // password: \"\",\n      // pool_size: 10,\n      // conn_timeout: 30\n    }\n  }\n};\n```\n\n**注意事项**:\n- 插件会在应用启动时自动初始化缓存\n- 必须在插件配置中提供正确的缓存配置\n- 如果缓存未正确初始化，装饰器方法会直接执行而不进行缓存（优雅降级）\n\n## 使用方法\n\n### 基本用法\n\n```typescript\nimport { CacheAble, CacheEvict, GetCacheStore } from \"koatty_cacheable\";\n\nexport class UserService {\n\n    // 自动缓存方法返回值\n    @CacheAble(\"userCache\", {\n        params: [\"id\"],    // 使用 id 参数作为缓存键的一部分\n        timeout: 300       // 缓存过期时间（秒），默认 300 秒\n    })\n    async getUserById(id: string): Promise\u003cUser\u003e {\n        // 数据库查询逻辑\n        return await this.userRepository.findById(id);\n    }\n\n    // 自动清除相关缓存\n    @CacheEvict(\"userCache\", {\n        params: [\"id\"],                    // 使用 id 参数定位要清除的缓存\n        delayedDoubleDeletion: true        // 启用延迟双删策略，默认 true\n    })\n    async updateUser(id: string, userData: Partial\u003cUser\u003e): Promise\u003cUser\u003e {\n        // 更新用户数据\n        const updatedUser = await this.userRepository.update(id, userData);\n        return updatedUser;\n    }\n\n    // 手动操作缓存\n    async customCacheOperation() {\n        const store = await GetCacheStore(this.app);\n        \n        // 设置缓存\n        await store.set(\"custom:key\", \"value\", 60);\n        \n        // 获取缓存\n        const value = await store.get(\"custom:key\");\n        \n        // 删除缓存\n        await store.del(\"custom:key\");\n    }\n}\n```\n\n### 高级用法\n\n```typescript\nexport class ProductService {\n\n    // 无参数缓存\n    @CacheAble(\"productStats\")\n    async getProductStats(): Promise\u003cProductStats\u003e {\n        return await this.calculateStats();\n    }\n\n    // 多参数缓存\n    @CacheAble(\"productSearch\", {\n        params: [\"category\", \"keyword\"],\n        timeout: 600\n    })\n    async searchProducts(category: string, keyword: string, page: number = 1): Promise\u003cProduct[]\u003e {\n        return await this.productRepository.search(category, keyword, page);\n    }\n\n    // 立即清除缓存（不使用延迟双删）\n    @CacheEvict(\"productSearch\", {\n        params: [\"category\"],\n        delayedDoubleDeletion: false\n    })\n    async updateProductCategory(category: string, updates: any): Promise\u003cvoid\u003e {\n        await this.productRepository.updateCategory(category, updates);\n    }\n}\n```\n\n## API 文档\n\n### @CacheAble(cacheName, options?)\n\n自动缓存装饰器，缓存方法的返回值。\n\n**参数:**\n- `cacheName: string` - 缓存名称\n- `options?: CacheAbleOpt` - 缓存选项\n  - `params?: string[]` - 用作缓存键的参数名数组\n  - `timeout?: number` - 缓存过期时间（秒），默认 300\n\n### @CacheEvict(cacheName, options?)\n\n自动清除缓存装饰器，在方法执行后清除相关缓存。\n\n**参数:**\n- `cacheName: string` - 要清除的缓存名称\n- `options?: CacheEvictOpt` - 清除选项\n  - `params?: string[]` - 用于定位缓存的参数名数组\n  - `delayedDoubleDeletion?: boolean` - 是否启用延迟双删策略，默认 true\n\n### GetCacheStore(app?)\n\n获取缓存存储实例。\n\n**参数:**\n- `app?: Application` - Koatty 应用实例\n\n**返回:** `Promise\u003cCacheStore\u003e`\n\n## 缓存键生成规则\n\n缓存键按以下格式生成：\n```\n{cacheName}:{paramName1}:{paramValue1}:{paramName2}:{paramValue2}...\n```\n\n例如：\n- `@CacheAble(\"user\", {params: [\"id\"]})` + `getUserById(\"123\")` → `user:id:123`\n- 当缓存键长度超过 128 字符时，会自动使用 murmur hash 进行压缩\n\n## 延迟双删策略\n\n延迟双删是一种解决缓存一致性问题的策略：\n\n1. 立即删除缓存\n2. 执行数据更新操作\n3. 延迟 5 秒后再次删除缓存\n\n这样可以避免在并发场景下出现脏数据。\n\n## 注意事项\n\n1. **初始化顺序**: 必须先调用 `KoattyCached()` 初始化缓存，然后再使用装饰器。建议在应用启动时（如 `init()` 方法中）进行初始化\n2. 装饰器只能用于 `SERVICE` 和 `COMPONENT` 类型的类\n3. 被装饰的方法必须是异步方法（返回 Promise）\n4. 缓存的数据会自动进行 JSON 序列化/反序列化\n5. 如果缓存服务不可用，方法会正常执行，不会抛出错误（优雅降级）\n6. 缓存键长度超过 128 字符时会自动使用 murmur hash 进行压缩\n\n## 许可证\n\nBSD-3-Clause","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkoatty%2Fkoatty_cacheable","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkoatty%2Fkoatty_cacheable","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkoatty%2Fkoatty_cacheable/lists"}