触发器和函数示例
如何使用触发器和函数
Redis 堆栈 | Redis 社区版 | Redis 企业软件 | Redis 云 | Redis 社区版 | 适用于 Kubernetes 的 Redis Enterprise | 客户 |
---|
Redis Stack 的触发器和函数功能可以在数据发生更改时检测到这些更改,并保证在数据源中无缝执行业务逻辑。这确保了作数据的新选项是可能的,并且可以同时为所有客户端提供,同时简化了部署和维护。让我们探索一些特定于行业的使用案例,这些功能在这些用例中大放异彩:
- 零售:在零售领域,可以开发一个功能,在收到订单后立即更新库存。这使企业能够准确预测任何给定日期特定仓库的库存需求。
- 旅游:对于旅游行业,可以使用触发器来检测新的航班预订,并有效地将相关信息加载到不同消费者的队列中。然后,服务可以利用这些数据为酒店、餐馆、汽车租赁服务等提供建议。利用 Redis 几何图形,强大的推荐系统可以提供本地化和个性化的建议。
- 订阅服务:在订阅服务领域,使用密钥空间触发器可以自动识别订阅已续订的用户,从而无缝将其状态更改为活动状态。可以对这些用户执行进一步的作,例如将他们添加到队列中以发送通知或执行其他作。
这些示例突出了触发器和功能在不同行业中的实际应用,展示了它们在简化流程和提供高效解决方案方面的价值。
使用键空间和 Stream 触发器来捕获事件并执行所需的 JavaScript 函数需要几行代码来丰富应用程序,从而使用新行为来丰富应用程序。以下示例显示了如何使用 JavaScript 解决典型问题。
审计和日志记录
Redis 触发器可用于检测对特定数据结构的更改,并在 Redis 日志中记录审计跟踪。最新更改的时间戳可以在同一函数中更新。
function alertUserChanged(client, data) {
// detect the event and log an audit trail
if (data.event == 'hset'){
redis.log('User data changed: ' + data.key);
}
else if (data.event == 'del'){
redis.log('User deleted: ' + data.key);
}
var curr_time = client.call("time")[0];
// add the current timestamp to the Hash
client.call('hset', data.key, 'last', curr_time);
}
redis.registerKeySpaceTrigger('alert_user_changed', 'user:',
alertUserChanged, {description: 'Report user data change.'});
Enrich and transform data
Data can be extracted, enriched or transformed, and loaded again. As an example, upon insertion of a document in a Hash data structure, a Trigger can launch the execution of a Function that computes the number of words in the text (in the example, a simple tokenization is presented but the logic can be as complex as required). The counter is finally stored in the same Hash together with the original document.
function wordsCounter(client, data){
text = client.call('hget', data.key, 'content');
words = text.split(' ').length;
client.call('hset', data.key, 'cnt', words.toString());
redis.log('Number of words: ' + words.toString()); //This log is for demo purposes, be aware of spamming the log file in production
}
redis.registerKeySpaceTrigger('words_counter', 'doc:',
wordsCounter, {description: 'Count words in a document.'});
Batch operations
JavaScript functions can be executed when required, for example as part of scheduled or periodic maintenance routines. An example could be deleting data identified by the desired pattern.
#!js api_version=1.0 name=utils
redis.registerAsyncFunction('del_keys', async function(async_client, pattern){
var count = 0;
var cursor = '0';
do {
async_client.block((client)=>{
var res = client.call('scan', cursor, 'match', pattern);
cursor = res[0];
var keys = res[1];
keys.forEach((key) => {
client.call('del', key);
});
});
} while(cursor != '0');
return count;
});
The function del_keys
performs an asynchronous batch scan of all the keys in the database matching the desired pattern, and enters a blocking section where it gets partial results. The asynchronous design of this function permits non-blocking execution, so other clients will not starve while the iteration is performed on a keyspace of arbitrary size. The function can be invoked as follows.
TFCALLASYNC utils.del_keys 0 "user:*"
Automatic expiration
Sometimes it is useful to enforce expiration time for data that by nature is short-lived. An example could be session data, or authentication tokens. A trigger fits the use case and can execute a function that sets the desired TTL.
function automaticSessionExpiry(client, data){
client.call('expire', data.key, '3600');
redis.log('Session ' + data.key + ' has been automatically expired'); //This log is for demo purposes, be aware of spamming the log file in production
}
redis.registerKeySpaceTrigger('automaticSessionExpiry', 'session:',
automaticSessionExpiry, {description: 'Set the session TTL to one hour.'});
On this page