使用 Java 获取 Tomcat 中的活动会话列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4069444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 11:14:30  来源:igfitidea点击:

Getting a list of active sessions in Tomcat using Java

javatomcat

提问by rampatel

I am developing a project in Java in which I want the count of all active sessions in Tomcat. Based on that I want to see how much of those users are active and actually using the application.

我正在用 Java 开发一个项目,其中我想要 Tomcat 中所有活动会话的计数。基于此,我想查看这些用户中有多少是活跃的并实际使用该应用程序。

回答by Amir Raminfar

There isn't any way to get the session count directly from tomcat. But you can create and register a session listener and up the count when its created. Here is an example:

没有任何方法可以直接从 tomcat 获取会话计数。但是您可以创建和注册会话侦听器并在创建时增加计数。下面是一个例子:

http://tomcat-configure.blogspot.com/2009/01/tomcat-session-listener-example.html

http://tomcat-configure.blogspot.com/2009/01/tomcat-session-listener-example.html

public class SessionCounter implements HttpSessionListener {

  private static int activeSessions = 0;

  public void sessionCreated(HttpSessionEvent se) {
    activeSessions++;
  }

  public void sessionDestroyed(HttpSessionEvent se) {
    if(activeSessions > 0)
      activeSessions--;
    }

  public static int getActiveSessions() {
     return activeSessions;
  }
}

回答by Janning

You should use JMX (Java Managemnet eXtension) and query the following

您应该使用 JMX (Java Managemnet eXtension) 并查询以下内容

jmxObjectName:    Catalina:host=localhost,path=/,type=Manager
jmxAttributeName: activeSessions

You can use jconsole to access this data. To get jmx running see http://tomcat.apache.org/tomcat-6.0-doc/monitoring.html

您可以使用 jconsole 访问此数据。要运行 jmx,请参阅http://tomcat.apache.org/tomcat-6.0-doc/monitoring.html

You have lot of advantages using JMX as you get lots of other data, too. You can put it in a munin plugin and let munin monitor it and draw nice graphs to look at.

使用 JMX 有很多优势,因为您也可以获得大量其他数据。你可以把它放在一个 munin 插件中,让 munin 监控它并绘制漂亮的图表来查看。

回答by FelixD

"PSI Probe" may do the trick for you: http://code.google.com/p/psi-probe/

“PSI 探针”可能会为您解决问题:http: //code.google.com/p/psi-probe/

回答by Brimstedt

If you dont need the values in the actual web application, a groovy script can help:

如果您在实际的 Web 应用程序中不需要这些值,一个 groovy 脚本可以提供帮助:

import javax.management.remote.*
import javax.management.*
import groovy.jmx.builder.*

// Setup JMX connection.
def connection = new JmxBuilder().client(port: 4934, host: '192.168.10.6')
connection.connect()

// Get the MBeanServer.
def mbeans = connection.MBeanServerConnection

def activeBean = new GroovyMBean(mbeans, 'Catalina:type=Manager,host=localhost,context=/')
println "Active sessions: " + activeBean['activeSessions']

If you want the actual sessions, you have methods to retrieve them, like:

如果你想要实际的会话,你有方法来检索它们,比如:

def sessions = activeBean.listSessionIds().tokenize(' ');

回答by Miklos Krivan

Here is the Java 7 style JMX code snippet (what basZero asked for and exactly does the job what Janning described):

这是 Java 7 风格的 JMX 代码片段(basZero 要求的内容,并且正是 Janning 所描述的):

JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:9999/jmxrmi");
try(JMXConnector jmxc = JMXConnectorFactory.connect(url)) {
  MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
  ObjectName mbeanName = new ObjectName("Catalina:type=Manager,context=/,host=localhost");
  Object value = mbsc.getAttribute(mbeanName, "activeSessions");
}

Of course you need to replace root context (/) in ObjectName with your app context string if it is not deployed in the root context. See my detailed explanation on the Catalina JMX issue here: Accessing built-in MBeans in Tomcat programatically

当然,如果您的应用程序上下文字符串未部署在根上下文中,则需要将 ObjectName 中的根上下文 (/) 替换为您的应用程序上下文字符串。请在此处查看我对 Catalina JMX 问题的详细说明:以编程方式访问 Tomcat 中的内置 MBean

回答by AdeelMufti

Here is how to get the session count locally, if you're getting the stats within an application running on the tomcat server you want the stats for. No need to enable jmx remote this way:

如果您要获取在 tomcat 服务器上运行的应用程序中的统计信息,那么这里是如何在本地获取会话计数的方法。无需以这种方式启用 jmx 远程:

public void init(final ServletConfig config) throws ServletException
{
    context = config.getServletContext().getContextPath();
}
//...
private void getSessionStats()
{
    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    ObjectName objectName = new ObjectName("Catalina:type=Manager,context="+context+",host=localhost");
    Object activeSessions = mBeanServer.getAttribute(objectName, "activeSessions");
    System.out.println(activeSessions);
}

回答by Yash P Shah

A simple tutorial to demonstrate how to determine active users / sessions in a Java Web Application.

一个简单的教程,用于演示如何确定 Java Web 应用程序中的活动用户/会话。

package com.hubberspot.javaee.listener;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

@WebListener
public class OnlineUsersCounter implements HttpSessionListener {

private static int numberOfUsersOnline;

 public OnlineUsersCounter() {
  numberOfUsersOnline = 0;
 }

 public static int getNumberOfUsersOnline() { 
  return numberOfUsersOnline;
 }

    public void sessionCreated(HttpSessionEvent event) {

     System.out.println("Session created by Id : " + event.getSession().getId());
     synchronized (this) {
   numberOfUsersOnline++;
  }

    }

    public void sessionDestroyed(HttpSessionEvent event) {

     System.out.println("Session destroyed by Id : " + event.getSession().getId());
     synchronized (this) {
   numberOfUsersOnline--;
  }

    }

}

Running the below servlet on three different browsers will provide output as : (see fig below)

在三个不同的浏览器上运行以下 servlet 将提供如下输出:(见下图)

package com.hubberspot.javaee;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.hubberspot.javaee.listener.OnlineUsersCounter;

// @WebServlet annotation has a initParams field which takes
// in initialization parameters for a servlet.
// @WebInitParam annotation takes in a name and value for the
// initialization parameters for the current Servlet.

@WebServlet(name = "HelloWorldServlet" , urlPatterns = { "/HelloWorldServlet" }
, initParams = { @WebInitParam(name = "user" , value = "Jonty") })
public class HelloWorldServlet extends HttpServlet {

 protected void doGet(
   HttpServletRequest request, 
   HttpServletResponse response
   ) throws ServletException, IOException {

  response.setContentType("text/html");

  PrintWriter out = response.getWriter();

  // sessionCreated method gets executed
  HttpSession session = request.getSession();

  session.setMaxInactiveInterval(60);

  try {
   out.println("<html>");
   out.println("<body>");
   out.println("<h2>Number of Users Online : "
      + OnlineUsersCounter.getNumberOfUsersOnline() 
      + "</h2>");
   out.println("</body>");
   out.println("</html>");
  } finally {
   out.close();
  }

 }

}

Output of the program :

程序的输出:

  1. Eclipse Browser ->
  1. Eclipse 浏览器 ->

Eclipse

蚀

  1. Firefox Browser ->
  1. 火狐浏览器 ->

Firefox

火狐

  1. Internet Explorer Browser ->
  1. Internet Explorer 浏览器 ->

IE

IE

  1. Console Output ->
  1. 控制台输出 ->

Console

安慰

For more: http://www.hubberspot.com/2013/09/how-to-determine-active-users-sessions.html

更多信息:http: //www.hubberspot.com/2013/09/how-to-determine-active-users-sessions.html

回答by visit1985

You can attach a jolokia jvm agentto the running tomcat and query the activeSessionsattribute from the relevant MBeans via curl.

您可以将jolokia jvm 代理附加到正在运行的 tomcat,并activeSessions通过 curl 从相关 MBean查询属性。

java -jar agent.jar start [TOMCAT-PID]
curl 'http://127.0.0.1:8778/jolokia/read/Catalina:context=*,host=*,type=Manager/activeSessions'
java -jar agent.jar stop [TOMCAT-PID]

This will give you something like

这会给你类似的东西

{  
   "request":{  
      "mbean":"Catalina:context=*,host=*,type=Manager",
      "attribute":"activeSessions",
      "type":"read"
   },
   "value":{  
      "Catalina:context=\/SampleApp,host=localhost,type=Manager":{  
         "activeSessions":1
      }
   },
   "timestamp":1553105659,
   "status":200
}

回答by Yuci

Two more approaches to add, both of which I've been using all the time.

再添加两种方法,我一直在使用这两种方法。

1. VisualVM

1. 可视化虚拟机

To find out the number of active sessions, you can use Tomcat's internal statistics that can be accessed using JMX (Java Management Extension).

要找出活动会话的数量,您可以使用 Tomcat 的内部统计信息,该统计信息可以使用 JMX(Java 管理扩展)进行访问。

Practically, a profiling tool such as VisualVMor Java VisualVMcan be used to access the JMX statistics, such as the number of active sessions, on the MBeans tab (See below the screenshot)

实际上,可以使用诸如VisualVMJava VisualVM 之类的分析工具来访问 JMX 统计信息,例如 MBeans 选项卡上的活动会话数(请参见下面的屏幕截图)

enter image description here

在此处输入图片说明

2. JavaMelody

2.JavaMelody

You can also use a JavaEE applications monitoring tool, such as JavaMelody, which helps you monitor Java or Java EE applications in QA and production environments.

您还可以使用 JavaEE 应用程序监控工具,例如JavaMelody,它可以帮助您在 QA 和生产环境中监控 Java 或 Java EE 应用程序。

enter image description here

在此处输入图片说明