koatty_cacheable 1.6.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/README.md CHANGED
@@ -1,57 +1,235 @@
1
- # koatty_cacheable
2
- Cacheable for koatty.
3
-
4
- Koatty框架的 CacheAble, Cacheable, CacheEvict 支持库
5
-
6
-
7
- # Usage
8
-
9
- db.ts in koatty project:
10
-
11
- ```js
12
- export default {
13
- ...
14
-
15
- "CacheStore": {
16
- type: "memory", // redis or memory, memory is default
17
- // key_prefix: "koatty",
18
- // host: '127.0.0.1',
19
- // port: 6379,
20
- // name: "",
21
- // username: "",
22
- // password: "",
23
- // db: 0,
24
- // timeout: 30,
25
- // pool_size: 10,
26
- // conn_timeout: 30
27
- },
28
-
29
- ...
30
- };
31
-
32
- ```
33
-
34
- used in service:
35
-
36
- ```js
37
- import { CacheAble, CacheEvict, GetCacheStore } from "koatty_cacheable";
38
-
39
- export class TestService {
40
-
41
- @CacheAble("testCache") // auto cached
42
- getTest(){
43
- //todo
44
- }
45
-
46
- @CacheEvict("testCache") // auto clear cache
47
- setTest(){
48
- //todo
49
- }
50
-
51
- test(){
52
- const store = GetCacheStore(this.app);
53
- store.set(key, value);
54
- }
55
- }
56
-
57
- ```
1
+ # koatty_cacheable
2
+
3
+ Cacheable plugin for Koatty.
4
+
5
+ Koatty框架的 CacheAble, CacheEvict 缓存装饰器插件,提供方法级别的缓存功能。
6
+
7
+ ## 特性
8
+
9
+ - 🚀 **简单易用**: 通过装饰器轻松添加缓存功能
10
+ - 🔄 **自动缓存**: `@CacheAble` 装饰器自动缓存方法返回值
11
+ - 🗑️ **智能清除**: `@CacheEvict` 装饰器智能清除相关缓存
12
+ - **延迟双删**: 支持延迟双删策略,解决缓存一致性问题
13
+ - 🔧 **多后端支持**: 支持 Memory 和 Redis 缓存后端
14
+ - 🎯 **参数化缓存**: 支持基于方法参数的缓存键生成
15
+ - 🛡️ **类型安全**: 完整的 TypeScript 支持
16
+ - 📦 **插件化设计**: 遵循 Koatty 插件标准,统一管理
17
+
18
+ ## 安装
19
+
20
+ ```bash
21
+ npm install koatty_cacheable
22
+ ```
23
+
24
+ ## 配置
25
+
26
+ ### 1. Generate Plugin Template
27
+
28
+ Use Koatty CLI to generate the plugin template:
29
+
30
+ ```bash
31
+ kt plugin Cacheable
32
+ ```
33
+
34
+ Create `src/plugin/Cacheable.ts`:
35
+
36
+ ```typescript
37
+ import { Plugin, IPlugin, App } from "koatty";
38
+ import { KoattyCache } from "koatty_cacheable";
39
+
40
+ @Plugin()
41
+ export class Cacheable implements IPlugin {
42
+ run(options: any, app: App) {
43
+ return KoattyCache(options, app);
44
+ }
45
+ }
46
+ ```
47
+
48
+ ### 2. Configure Plugin
49
+
50
+ Update `src/config/plugin.ts`:
51
+
52
+ ```typescript
53
+ export default {
54
+ list: ["Cacheable"], // Plugin loading order
55
+ config: {
56
+ Cacheable: {
57
+ cacheTimeout: 300, // 默认缓存过期时间(秒)
58
+ delayedDoubleDeletion: true, // 默认启用延迟双删策略
59
+ redisConfig: {
60
+ host: "127.0.0.1",
61
+ port: 6379,
62
+ password: "",
63
+ db: 0,
64
+ keyPrefix: "koatty:cache:"
65
+ }
66
+ }
67
+ }
68
+ };
69
+ ```
70
+
71
+ ## 使用方法
72
+
73
+ ### 基本用法
74
+
75
+ ```typescript
76
+ import { CacheAble, CacheEvict, GetCacheStore } from "koatty_cacheable";
77
+ import { Component } from "koatty_container";
78
+
79
+ @Component()
80
+ export class UserService {
81
+
82
+ // 自动缓存方法返回值
83
+ @CacheAble("userCache", {
84
+ params: ["id"], // 使用 id 参数作为缓存键的一部分
85
+ timeout: 300 // 缓存过期时间(秒),默认使用插件配置的 cacheTimeout
86
+ })
87
+ async getUserById(id: string): Promise<User> {
88
+ // 数据库查询逻辑
89
+ return await this.userRepository.findById(id);
90
+ }
91
+
92
+ // 自动清除相关缓存
93
+ @CacheEvict("userCache", {
94
+ params: ["id"], // 使用 id 参数定位要清除的缓存
95
+ delayedDoubleDeletion: true // 启用延迟双删策略,默认使用插件配置的 delayedDoubleDeletion
96
+ })
97
+ async updateUser(id: string, userData: Partial<User>): Promise<User> {
98
+ // 更新用户数据
99
+ const updatedUser = await this.userRepository.update(id, userData);
100
+ return updatedUser;
101
+ }
102
+
103
+ // 手动操作缓存
104
+ async customCacheOperation() {
105
+ const store = await GetCacheStore(this.app);
106
+
107
+ // 设置缓存
108
+ await store.set("custom:key", "value", 60);
109
+
110
+ // 获取缓存
111
+ const value = await store.get("custom:key");
112
+
113
+ // 删除缓存
114
+ await store.del("custom:key");
115
+ }
116
+ }
117
+ ```
118
+
119
+ ### 高级用法
120
+
121
+ ```typescript
122
+ import { Component } from "koatty_container";
123
+
124
+ @Component()
125
+ export class ProductService {
126
+
127
+ // 无参数缓存
128
+ @CacheAble("productStats")
129
+ async getProductStats(): Promise<ProductStats> {
130
+ return await this.calculateStats();
131
+ }
132
+
133
+ // 多参数缓存
134
+ @CacheAble("productSearch", {
135
+ params: ["category", "keyword"],
136
+ timeout: 600 // 覆盖插件配置的默认时间
137
+ })
138
+ async searchProducts(category: string, keyword: string, page: number = 1): Promise<Product[]> {
139
+ return await this.productRepository.search(category, keyword, page);
140
+ }
141
+
142
+ // 立即清除缓存(不使用延迟双删)
143
+ @CacheEvict("productSearch", {
144
+ params: ["category"],
145
+ delayedDoubleDeletion: false // 覆盖插件配置的默认策略
146
+ })
147
+ async updateProductCategory(category: string, updates: any): Promise<void> {
148
+ await this.productRepository.updateCategory(category, updates);
149
+ }
150
+ }
151
+ ```
152
+
153
+ ## API 文档
154
+
155
+ ### @CacheAble(cacheName, options?)
156
+
157
+ 自动缓存装饰器,缓存方法的返回值。
158
+
159
+ **参数:**
160
+ - `cacheName: string` - 缓存名称
161
+ - `options?: CacheAbleOpt` - 缓存选项
162
+ - `params?: string[]` - 用作缓存键的参数名数组
163
+ - `timeout?: number` - 缓存过期时间(秒),默认 300
164
+
165
+ ### @CacheEvict(cacheName, options?)
166
+
167
+ 自动清除缓存装饰器,在方法执行后清除相关缓存。
168
+
169
+ **参数:**
170
+ - `cacheName: string` - 要清除的缓存名称
171
+ - `options?: CacheEvictOpt` - 清除选项
172
+ - `params?: string[]` - 用于定位缓存的参数名数组
173
+ - `delayedDoubleDeletion?: boolean` - 是否启用延迟双删策略,默认 true
174
+
175
+ ### GetCacheStore(app?)
176
+
177
+ 获取缓存存储实例。
178
+
179
+ **参数:**
180
+ - `app?: Application` - Koatty 应用实例
181
+
182
+ **返回:** `Promise<CacheStore>`
183
+
184
+ ## 缓存键生成规则
185
+
186
+ 缓存键按以下格式生成:
187
+ ```
188
+ {cacheName}:{paramName1}:{paramValue1}:{paramName2}:{paramValue2}...
189
+ ```
190
+
191
+ 例如:
192
+ - `@CacheAble("user", {params: ["id"]})` + `getUserById("123")` → `user:id:123`
193
+ - 当缓存键长度超过 128 字符时,会自动使用 murmur hash 进行压缩
194
+
195
+ ## 延迟双删策略
196
+
197
+ 延迟双删是一种解决缓存一致性问题的策略:
198
+
199
+ 1. 立即删除缓存
200
+ 2. 执行数据更新操作
201
+ 3. 延迟 5 秒后再次删除缓存
202
+
203
+ 这样可以避免在并发场景下出现脏数据。
204
+
205
+ ## 配置优先级
206
+
207
+ 配置项的优先级从高到低:
208
+
209
+ 1. **装饰器配置**: 直接在 `@CacheAble` 或 `@CacheEvict` 中指定的选项
210
+ 2. **插件配置**: 在 `src/config/plugin.ts` 中配置的 `Cacheable` 插件选项
211
+ 3. **默认值**: 系统内置的默认配置
212
+
213
+ 例如:
214
+ ```typescript
215
+ // 插件配置
216
+ Cacheable: {
217
+ cacheTimeout: 300,
218
+ delayedDoubleDeletion: true
219
+ }
220
+
221
+ // 装饰器配置会覆盖插件配置
222
+ @CacheAble("user", {
223
+ timeout: 600 // 使用 600 秒而不是插件配置的 300 秒
224
+ })
225
+ ```
226
+
227
+ ## 注意事项
228
+
229
+ 1. 缓存的数据会自动进行 JSON 序列化/反序列化
230
+ 2. 如果缓存服务不可用,方法会正常执行,不会抛出错误
231
+ 3. 插件会在应用启动时自动注入缓存功能到所有使用装饰器的方法
232
+
233
+ ## 许可证
234
+
235
+ BSD-3-Clause
package/dist/index.d.ts CHANGED
@@ -1,12 +1,13 @@
1
1
  /*!
2
2
  * @Author: richen
3
- * @Date: 2024-11-07 16:07:00
3
+ * @Date: 2025-06-23 01:59:58
4
4
  * @License: BSD (3-Clause)
5
5
  * @Copyright (c) - <richenlin(at)gmail.com>
6
6
  * @HomePage: https://koatty.org/
7
7
  */
8
- import { Application } from 'koatty_container';
9
- import { CacheStore } from 'koatty_store';
8
+ import { Koatty } from 'koatty_core';
9
+
10
+ export declare const CACHE_METADATA_KEY = "CACHE_METADATA_KEY";
10
11
 
11
12
  /**
12
13
  * Decorate this method to support caching.
@@ -26,15 +27,15 @@ import { CacheStore } from 'koatty_store';
26
27
  * Use the 'id' parameters of the method as cache subkeys, the cache expiration time 30s
27
28
  * @returns {MethodDecorator}
28
29
  */
29
- export declare function CacheAble(cacheName: string, opt?: CacheAbleOpt): MethodDecorator;
30
+ export declare function CacheAble(cacheNameOrOpt?: string | CacheAbleOpt, opt?: CacheAbleOpt): MethodDecorator;
30
31
 
31
32
  /**
32
- * @description:
33
- * @return {*}
33
+ * @description: CacheAble decorator options
34
34
  */
35
35
  export declare interface CacheAbleOpt {
36
36
  params?: string[];
37
37
  timeout?: number;
38
+ cacheName?: string;
38
39
  }
39
40
 
40
41
  /**
@@ -53,24 +54,40 @@ export declare interface CacheAbleOpt {
53
54
  * and clear the cache after the method executed
54
55
  * @returns
55
56
  */
56
- export declare function CacheEvict(cacheName: string, opt?: CacheEvictOpt): (target: any, methodName: string, descriptor: PropertyDescriptor) => PropertyDescriptor;
57
+ export declare function CacheEvict(cacheNameOrOpt?: string | CacheEvictOpt, opt?: CacheEvictOpt): MethodDecorator;
57
58
 
58
59
  /**
59
- * @description:
60
- * @return {*}
60
+ * @description: CacheEvict decorator options
61
61
  */
62
62
  export declare interface CacheEvictOpt {
63
63
  params?: string[];
64
64
  delayedDoubleDeletion?: boolean;
65
+ cacheName?: string;
66
+ }
67
+
68
+ declare interface CacheOptions {
69
+ cacheTimeout?: number;
70
+ delayedDoubleDeletion?: boolean;
71
+ redisConfig?: RedisConfig;
72
+ }
73
+
74
+ export declare enum DecoratorType {
75
+ CACHE_EVICT = "CACHE_EVICT",
76
+ CACHE_ABLE = "CACHE_ABLE"
65
77
  }
66
78
 
67
79
  /**
68
- * get instances of storeCache
69
- *
70
- * @export
71
- * @param {Application} app
72
- * @returns {*} {CacheStore}
80
+ * @param options - The options for the scheduled job
81
+ * @param app - The Koatty application instance
73
82
  */
74
- export declare function GetCacheStore(app?: Application): Promise<CacheStore>;
83
+ export declare function KoattyCache(options: CacheOptions, app: Koatty): Promise<void>;
84
+
85
+ declare interface RedisConfig {
86
+ host?: string;
87
+ port?: number;
88
+ password?: string;
89
+ db?: number;
90
+ keyPrefix?: string;
91
+ }
75
92
 
76
93
  export { }