Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【Q363】如何获取当前系统中的在线用户数 (并发用户数) #368

Open
shfshanyue opened this issue Jul 13, 2020 · 1 comment
Labels

Comments

@shfshanyue
Copy link
Owner

一些 SaaS 系统基于 Pricing 的考虑,会限制团队人数及同时在线数,如何实现

@shfshanyue
Copy link
Owner Author

shfshanyue commented Jul 13, 2020

一些 SaaS 系统基于定价策略的考虑,会限制团队人数及同时在线数,如何实现?

通过 rediszset 可实现并发用户数。

当一个用户请求任何接口时,实现一个 middleware,处理以下逻辑

// 当一个用户访问任何接口时,对该用户Id,写入 zset
await redis.zadd(`Organization:${organizationId}:concurrent`, Date.now(), `User:${userId}`)

// 查询当前机构的并发数
// 通过查询一分钟内的活跃用户来确认并发数,如果超过则抛出特定异常
const activeUsers = await redis.zrangebyscore(`Organization:${organizationId}:concurrent`, Date.now() - 1000 * 60, Date.now())

// 查出并发数
const count = activeUsers.length

// 删掉过期的用户
await redis.zrembyscore(`Organization:${organizationId}:concurrent`, Date.now() - 1000 * 60, Date.now())

总结

  1. 每当用户访问服务时,把该用户的 ID 写入优先级队列,权重为当前时间
  2. 根据权重(即时间)计算一分钟内该机构的用户数
  3. 删掉一分钟以上过期的用户

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant