设计问题:如何显示在线用户数?
计划开发 LAMP Web 应用程序。我可以使用哪些一般策略来显示当前登录到我的网站的用户数量?我希望能够准确地显示“当前有 1000 个用户在线”或“用户 John Doe 当前在线”之类的内容。
Planning to develop a LAMP web application. What general strategies can I use to display the number of users currently logged in to my site? I want to be able to accurately display something like, "There are currently 1000 users online" or "User John Doe is currently online".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
将涉及到数据库。因此,每次有人登录站点时,您都可以在用户表中添加一个用于 last_login 的字段。然后可以有一个脚本对该用户的表进行查询,以计算最近 x 时间内的 last_login 行数。最好缓存它并每隔 z 时间重新填充此缓存,然后从该缓存中提取数据,而不是每次请求都针对用户的表运行查询。所以数据库+某种缓存系统。
A database will be involved. So every time someone logs into the site, you can have a field in a user's table for last_login. And then there can be a script that does a query against this user's table to count the number of rows last_login within the last x amount of time. It may be good to cache this and repopulate this cache every z amount of time, and then pull from this cache as oppose to running a query against the user's table every request. So database + some kind of caching system.
我建议使用 CodeIgniter PHP 框架。
这将允许您非常轻松地将会话数据存储在数据库中(您只需在 config.php 文件中启用它)。然后你可以在你的数据库的session表中查询session id的数量。
以下是 CodeIgniter 会话类的信息,以便您了解如何使用它:
CodeIgniter 会话类
这里还有一个 CodeIgniter 论坛的链接,详细介绍了如何使用正是为了实现这个: CodeIgniter 论坛
I recommend using the CodeIgniter PHP framework.
This will allow you to store your session data in the database very easily (you just enable it in the config.php file). Then you can query the number of session ids in the session table of your database.
Here is the information for the CodeIgniter session class so you can see how to use it:
CodeIgniter Session Class
Here is also a link to the CodeIgniter forums going through more detail of how exactly to get this implemented: CodeIgniter Forum
这很容易做到,但不准确。 Html 是无状态的,无法知道用户是否仍在查看您的页面或已经离开。
如果您想记录匿名和已登录的用户,您可以使用具有较短超时(例如五分钟)的跟踪 cookie,并让此 cookie 链接到活动会话的数据库。
This is quite easy to do, but cannot be accurate. Html being stateless, there is no way of knowing if a user is still looking at your page or has left.
If you want to log anonymous and logged in users, you coud use a tracking cookie with a short timeout, say five minutes and have this cookie link to a database of active sessions.
如果您使用数据库来存储会话信息,则可以轻松查询会话表并获取存储了多少个唯一会话。
If you're using your database to store session information, you can easily query the session table and get how many unique sessions there are stored.
在数据库中有某种上次访问时间记录,并记录该人一直处于活动状态。然后在数据库中查询最近 5 分钟左右处于活动状态的用户。会给你一个接近的大约。
Have some sort of last accessed time record in the DB, and record that the person has been active. Then query the DB for those users who have been active in the last 5mins or so. Will give you a close approx.