如何获取MBean绑定类实例

时间:2012-02-07 14:08:58

标签: java jmx jboss5.x mbeans

我正在尝试使用MBean来获取jboss-service.xml中绑定的服务类的实例。

JBoss-Service.xml定义了BasicThreadPool,我们希望在代码中使用它。 这就是JBOSS-Service.xml中的内容。

  <mbean 
        code="org.jboss.util.threadpool.BasicThreadPool"
        name="jboss.system:service=ThreadPool">

  <attribute name="Name">JBoss System Threads</attribute>
  <attribute name="ThreadGroupName">System Threads</attribute>
  <attribute name="KeepAliveTime">60000</attribute>
  <attribute name="MaximumPoolSize">10</attribute>

  <attribute name="MaximumQueueSize">1000</attribute>
  <!-- The behavior of the pool when a task is added and the queue is full.
  abort - a RuntimeException is thrown
  run - the calling thread executes the task
  wait - the calling thread blocks until the queue has room
  discard - the task is silently discarded without being run
  discardOldest - check to see if a task is about to complete and enque
     the new task if possible, else run the task in the calling thread
  -->
  <attribute name="BlockingMode">run</attribute>
   </mbean>

我正在尝试在我的代码中访问此内容,如下所示

MBeanServer server = MBeanServerLocator.locateJBoss();          
MBeanInfo mbeaninfo = server.getMBeanInfo(new ObjectName("jboss.system:service=ThreadPool"));

现在我有MBean信息。我想要在MBean中定义BasicThreadPool对象的实例。有可能吗?

我知道一种方法,我们可以从MBean Info获取类名,我们也可以获取构造实例的属性。有没有更好的方法呢?

2 个答案:

答案 0 :(得分:3)

正如skaffman指出的那样,你无法直接获取线程池的直接实例,但使用MBeanServerInvocationHandler会让你非常接近。

import org.jboss.util.threadpool.BasicThreadPoolMBean;
import javax.management.MBeanServerInvocationHandler;
import javax.management.ObjectName;
.....
BasicThreadPoolMBean threadPool = (BasicThreadPoolMBean)MBeanServerInvocationHandler.newProxyInstance(MBeanServerLocator.locateJBoss(); new ObjectName("jboss.system:service=ThreadPool"), BasicThreadPoolMBean.class, false);

该示例中的 threadPool 实例现在实现了底层线程池服务的所有方法。

请注意,如果您只需要它来提交执行任务,那么您只需要一件事就是 Instance 属性,这几乎是相同的界面,所以您也可以这样做这样:

import  org.jboss.util.threadpool.ThreadPool;
import javax.management.ObjectName;
.....
ThreadPool threadPool = (ThreadPool)MBeanServerLocator.locateJBoss().getAttribute(new ObjectName("jboss.system:service=ThreadPool"), "Instance");

....但不是远程,只能在同一个VM中。

答案 1 :(得分:2)

  

我想在MBean中定义一个BasicThreadPool对象的实例。有可能吗?

JMX无法正常工作。相反,它通过公开通用反射接口来工作,允许您在任何给定的MBean上调用操作和属性。这是通过MBeanServerConnection接口完成的(其中MBeanServer是子类型)。

对于您的示例,您将使用以下内容获取Name MBean上的jboss.system:service=ThreadPool属性:

MBeanServer server = MBeanServerLocator.locateJBoss();      
ObjectName objectName = new ObjectName("jboss.system:service=ThreadPool");    
String threadPoolName = (String) server.getAttribute(objectName , "Name");

这是一个丑陋的API,但可以胜任。

如果你感兴趣,Spring提供了一个围绕JMX的非常好的抽象re-exposes the target MBean using a Java interface that you specify。这使得一切感觉更像普通的Java,并且更容易使用。

相关问题