const cached = async (key, getFn, expire) => { let value = await redisClient.getAsync(key); value = value !== 'undefined' && JSON.parse(value) || null; if (!value) { value = await getFn(); await redisClient.setAsync(key, JSON.stringify(value), 'EX', expire || 3600); } return value; }
Promise.all( addedToFront.map( s => redisClient.setAsync(storyAddedEventRedisKey(s), JSON.stringify(s), 'EX', 60 * 60 * 24 * 10) ) )
async insert (link, random) { const id = await db.incrAsync(LASTID_KEY); await db.setAsync(id, random + link); return id; }
//Do I need to stream this? I dont think so. Small piece storePlanet(planet){ return client.setAsync('freqly_planet', planet.toString()) }
(async () => { await client.setAsync('0', 'Hello World!', 'EX', 5); const value = await client.getAsync('0'); console.log(value); await client.hsetAsync('1', 'Hello', 'World'); await client.hsetAsync('1', 'Hello!', 'World!'); const values = await client.hmgetAsync('1', 'Hello', 'Hello!'); console.log(values); await client.quitAsync(); })();
/* 为了保证同一时间只有一个 task 在执行,我们需要用这个函数,参数分别是锁的名字和要执行的函数(需要返回一个 Promise) */ function runTask(lock, task) { var taskId = [lock, os.hostname(), process.pid, _.uniqueId()].join(':'); // NX 表示仅当不存在这个键的情况下才创建(说明我们得到了这个锁),5 是锁的超时时间(秒) redisClient.setAsync(lock, taskId, 'EX', 5, 'NX').then(function(result) { if (result) { task(taskId).finally(function() { redisClient.delAsync(lock).catch(function(err) { console.error(err.stack); }); }); } else { console.log(taskId, 'fail to get lock'); } }).catch(function(err) { console.error(err.stack); }); }
/* 从缓存中读取一个 User, 如果没有找到则从云存储中查询 */ function fetchUserFromCache(userId) { return redisClient.getAsync(userId).then(function(cachedUser) { if (cachedUser) { // 反序列化为 AV.Object return new AV.User(JSON.parse(cachedUser), {parse: true}); } else { new AV.Query(AV.User).get(userId).then(function(user) { if (user) { // 将序列化后的 JSON 字符串存储到 LeanCache redisClient.setAsync(redisUserKey(userId), JSON.stringify(user)).catch(console.error); } return user; }); } }); }
async set(key, val) { if (!key || !val) { const whichOne = !key && !val ? 'Key and val' : !key ? 'key' : 'val' throw new Error(`❌ ${whichOne} required when set new cache item.`) } if (typeof key !== 'string') { throw new Error('❌ Expected key is a string.') } try { const result = this.redisClient.setAsync(key, val) this.redisClient.expire(key, 180) if (result.toString() === 'OK') { return val } } catch (error) { throw new Error(`❌ Set cache failed, key is ${key}`) } }
socketAuth(io, { authenticate: async (socket, data, cb) => { const {token} = data; try { const user = await verifyUser(toekn); const canConnect = await redis .setAsync(`users: ${user.id}`, socket.id, 'NX', 'EX', 30); socket.user = user; if(!canConnect){ return cb({message: 'already connected'}); } socket.user = user; return cb(null, true); }catch (err){ console.log(`client with id: ${socket.id} is unauthorized`); return cb({message: 'unauthorized'}); } }, postAuthenticate: (socket) => { // packet sending authenticating can be handeled with redis console.log(`client with socket id: ${socket.id} is authenticated`); },disconnect: async (socket) => { console.log(`client with id: ${socket.id} is diconnected`); // deleting user from redis } });
return } else { await REDIS.setAsync(name, true) REDIS.expire(name, PROXY_FREQUENCY)
await REDIS.setAsync('proxy', JSON.stringify(proxies)) REDIS.expire('proxy', interval) } catch (e) {
return } else { await REDIS.setAsync(name, true) REDIS.expire(name, PREVIEW_FREQUENCY)
//Do I need to stream this? I dont think so. Small piece storeActor(actor){ return client.setAsync('freqly_actor', actor.toString()) }
async set (key, val) { if (!key || !val) { const whichOne = (!key && !val) ? 'Key and val' : (!key ? 'key' : 'val') throw new Error(`❌ ${whichOne} required when set new cache item.`) } if (typeof key !== 'string') { throw new Error('❌ Expected key is a string.') } try{ const result = this.redisClient.setAsync(key, val) this.redisClient.expire(key, 180) if (result.toString() === 'OK') { return val } } catch (error) { throw new Error(`❌ Set cache failed, key is ${key}`) } }