gpt4 book ai didi

tomcat - 如何确定特定用户实际使用我的应用程序的时间?

转载 作者:行者123 更新时间:2023-11-28 23:25:05 24 4
gpt4 key购买 nike

我在 Tomcat 8 上部署了一个 Web 应用程序。我想跟踪特定用户使用我的应用程序的时间——定义为该用户执行每个请求所花费的时间。即系统有效工作的时间。

Tomcat 中是否已经存在这样的功能?

在 Tomcat 中,我已经可以看到 Used TimeInactive Time 可用于 Tomcat Manager application , 但 used time 不是我要找的:它只是减去 Creation TimeLast Accessed Time 给出“total session effective age ".

如何确定用户的实际使用时间?

最佳答案

您想使用一个过滤器 来记录每个请求的时间,然后将该时间添加到用户的总使用时间中。您可以将其存储在用户的 HttpSession 中,假设已经有可用的 session 。

请注意,如果您仅将其存储在 session 中,则一旦 session 过期,用户的累计使用时间将会丢失。如果您希望信息在 session 过期后继续存在,则需要将使用时间写入其他地方,例如磁盘上的文件或关系数据库。

@angryip 在上面的评论中给出的引用是 Filter 的一个很好的例子,但不是一个如何实际为请求计时的好例子。 FilterdoFilter 方法可以非常简单。像这样:

public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws IOException, ServletException
{
HttpSession session = null;

if(request instanceof HttpServletRequest)
session = ((HttpServletRequest)request).getSession(false);

// Start the clock
long elapsed = System.currentTimeMillis();

// Use try/finally because the request can throw an exception;
// We still want to capture the usage-time even if an error
// occurs.
try {
chain.doFilter(request, response);
} finally {
// Stop the clock
elapsed = System.currentTimeMillis() - elapsed;

// Store the cumulative usage time in the session
if(null != session) {
Long usage = (Long)session.getAttribute("usage");
if(null != usage)
elapsed = elapsed + usage.getLong();
session.setAttribute("usage", Long.valueOf(elapsed));
}
}
}

从 session 中获取信息取决于您。您可以使用 JMX 观察它通过标识符请求 session ,然后使用参数“usage”调用“getAttribute”。

关于tomcat - 如何确定特定用户实际使用我的应用程序的时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38358790/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com