缓存设置
cacheSet
组件:设置指定key的值到缓存中。缓存实例使用config.Cache 。
# 配置
字段 | 类型 | 说明 | 默认值 |
---|---|---|---|
items | []CacheItem | 缓存项列表,可以使用组件配置变量 | 无 |
# CacheItem
字段 | 类型 | 说明 | 默认值 |
---|---|---|---|
level | string | 缓存级别 | chain |
key | string | 键,可以使用组件配置变量 | 无 |
value | any | 值,可以使用组件配置变量 | 无 |
ttl | string | 过期时间,示例:1h(1小时) 1h30m(1小时30分钟) 10m(10分钟) 10s(10秒),如果为空或者0,则表示永不过期 | 无 |
- level: 缓存级别
- chain: 当前规则链级别缓存,在当前规则链命名空间下操作,用于规则链实例内不同执行上下文之间的数据共享。如果规则链实例被销毁,会自动删除该规则链命名空间下所有缓存。
- global: 全局级别缓存,在全局命名空间下操作,用于跨规则链间的数据共享
# 缓存实现配置
默认情况下,RuleGo 使用内置的本地内存缓存(utils/cache.MemoryCache
),并提供了一个全局默认实例 cache.DefaultCache
(默认GC清理周期为5分钟)。如果未通过 types.WithCache
选项指定自定义缓存实现,则系统将自动使用此默认内存缓存。
如需使用其他缓存类型(例如 Redis、Memcached 等),您需要自行实现 types.Cache
接口,并通过 types.WithCache
选项在创建 Config
时将其注入。
types.Cache
接口定义如下:
type Cache interface {
// Set 在缓存中存储一个键值对,可选设置过期时间
// 参数:
// - key:缓存键(字符串)
// - value:要存储的值(interface{})
// - ttl:存活时间字符串(例如“10m”,“1h”)
// 返回:
// - error:如果 ttl 格式无效,则返回错误
// 注意:如果 ttl 为 0 或空字符串,则该项永不过期
Set(key string, value interface{}, ttl string) error
// Get 通过键从缓存中检索值
// 参数:
// - key:要查找的缓存键(字符串)
// 返回:
// - interface{}:存储的值,如果不存在或已过期则返回 nil
Get(key string) interface{}
// Has 检查键是否存在于缓存中
// 参数:
// - key:要检查的缓存键(字符串)
// 返回:
// - bool:如果键存在且未过期,则返回 true,否则返回 false
Has(key string) bool
// Delete 通过键删除缓存项
// 参数:
// - key:要删除的缓存键(字符串)
// 返回:
// - error:当前实现始终返回 nil
Delete(key string) error
// DeleteByPrefix 删除所有具有指定前缀的缓存项
// 参数:
// - prefix:要匹配的键前缀(字符串)
// 返回:
// - error:当前实现始终返回 nil
DeleteByPrefix(prefix string) error
// GetByPrefix 检索所有键与指定前缀匹配的值
// 参数:
// - prefix:要匹配的键前缀(字符串)
// 返回:
// - map[string]interface{}:匹配的键值对映射
GetByPrefix(prefix string) map[string]interface{}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
配置示例:
// 使用自定义缓存实现
config := rulego.NewConfig(types.WithCache(&myCacheImpl{}))
// 如果使用默认内存的实现,则不需要显式配置,RuleGo会自动使用 cache.DefaultCache
// config := rulego.NewConfig()
1
2
3
4
5
2
3
4
5
# Relation Type
- Success: 设置成功,把消息发送到
Success
链 - Failure: 设置失败,把消息发送到
Failure
链
# 执行结果
不改变消息负荷
# 配置示例
{
"id": "s1",
"type": "cacheSet",
"name": "设置缓存",
"configuration": {
"items": [
{
"level": "chain",
"key": "testKey",
"value": "testValue",
"ttl": ""
}
]
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
在 GitHub 上编辑此页 (opens new window)
上次更新: 2025/05/18, 14:00:38