问题:
我目前正在使用socket.io (服务器端)来处理来自客户端的异步请求。这些请求正被传递到上游服务-这是相当昂贵/缓慢和速度有限的服务。我想解复用/缓存对上游业务的调用。,例如 10x调用getUserProfile(123) => 1x对上游业务的调用(在一段时间内)
getUserProfile(123)和getUserProfile(456) =>,期待profile_123和profile_456,但是返回profile_456 (两次)。最好我举个例子..。
server.js
// on request from client...
socket.on('getUserProfileRequest', userId => {
getUserProfile(userId).then(profile => socket.emit('getUserProfileResponse', profile))
})
...
function getUserProfile(userId) {
// ... call upstream server, do async work, return a Promise...
}发布于 2018-09-13 06:15:23
最后,我将lru-cache与maxAge和Promises结合使用,以获得所需的结果--我还向get(key, initialiseFn)函数添加了一个initialiseFn参数,以方便这一点。
PR: https://github.com/isaacs/node-lru-cache/pull/132
// setup an LRU cache (with eviction policy)...
const PROFILE_CACHE = LRU({ max: 50, maxAge: 1000 * 60 })
// receives "lots" of async requests from a client...
socket.on('getUserProfileRequest', userId => {
PROFILE_CACHE.get(userId, () => getUserProfile(userId))
.then(profile => socket.emit('getUserProfileResponse', profile))
})
// calls upstream server, does async/expensive/long running work, returns a Promise...
function getUserProfile(userId) { /* ... */ }https://stackoverflow.com/questions/52290043
复制相似问题