(编辑:jimmy 日期: 2025/11/1 浏览:2)
前言
业务中碰到的需求(抽象描述一下):针对不同的用户能够实现不同时间的间隔循环任务。比如在用户注册成功24小时后给用户推送相关短信等类似需求。
使用crontab"external nofollow" target="_blank" href="https://redis.io/topics/notifications">官方文档。
技术栈
redis / nodeJs / koa
技术重难点
"talk is cheap, show me the code "
核心代码
核心代码
const { saveClient, subClient } = require('./db/redis') // 存储实例和订阅实例需要为两个不同的实例
const processor = require('./service/task')
const config = require('./config/index')
const innerDistributedLockKey = '&&__&&' // 内部使用的分布式锁的key的特征值
const innerDistributedLockKeyReg = new RegExp(`^${innerDistributedLockKey}`)
saveClient.on('ready', async () => {
saveClient.config('SET', 'notify-keyspace-events', 'Ex') // 存储实例设置为推送键过期事件
console.log('redis init success')
})
subClient.on('ready', () => { // 服务重启后依旧可以初始化所有processor
subClient.subscribe(`__keyevent@${config.redis.sub.db}__:expired`) // 订阅实例负责订阅消息
subClient.on('message', async (cahnnel, expiredKey) => {
// 分布式锁的key不做监听处理
if (expiredKey.match(innerDistributedLockKeyReg)) return
// 简易分布式锁,拿到锁的实例消费event
const cackeKey = `${innerDistributedLockKey}-${expiredKey}`
const lock = await saveClient.set(cackeKey, 2, 'ex', 5, 'nx') // 这里的用法可以实现简易的分布式锁
if (lock === 'OK') {
await saveClient.del(cackeKey)
for (let key in processor) {
processor[key](expiredKey) // processor对应的是接收到相关键过期通知后执行的业务逻辑,比如推送短信,然后在相关processor中再次set一个定时过期的key
}
}
})
console.log('subClient init success')
})
servide/task (processor)
exports.sendMessage = async function sendMessage(expiredKey, subClient) {
// 只处理相关业务的过期事件
if (expiredKey.match(/^send_message/)) {
const [prefix, userId, type] = expiredKey.split('-')
let user = getUser(userId)
if (user.phone) {
push(message) // 伪代码
resetRedisKey(expiredKey, ttl) // 重新把key设置为一段时间后过期,过期后会再次触发本逻辑
}
}
}
总结
因此需要权衡使用redis的过期机制实现的定时任务的使用场景。
好了,以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。