import org.apache.kafka.common.MetricName; import org.apache.kafka.common.metrics.KafkaMetric; import org.apache.kafka.common.metrics.Metrics; import javax.management.AttributeNotFoundException; import javax.management.InstanceNotFoundException; import javax.management.MBeanException; import javax.management.MBeanServerConnection; import javax.management.MalformedObjectNameException; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.management.ReflectionException; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; import java.io.IOException; import java.net.MalformedURLException; import java.util.Iterator; import java.util.Map; import java.util.Set; public class KafkaCoreMetrics { public static void main(String[] args) { String jmxServiceURL = "service:jmx:rmi:///jndi/rmi://192.168.x.xx:9999/jmxrmi"; JMXServiceURL jmxURL = null; JMXConnector jmxConnector = null; MBeanServerConnection jmxs = null; ObjectName objectName = null; Iterator sampleIter = null; Set sampleSet = null; try { jmxURL = new JMXServiceURL(jmxServiceURL); jmxConnector = JMXConnectorFactory.connect(jmxURL); jmxs = jmxConnector.getMBeanServerConnection(); objectName = new ObjectName("kafka.server:type=BrokerTopicMetrics,name=TotalProduceRequestsPerSec,topic=*"); sampleSet = jmxs.queryMBeans(null, objectName); sampleIter = sampleSet.iterator(); while (sampleIter.hasNext()) { ObjectInstance sampleObj = (ObjectInstance) sampleIter.next(); ObjectName sampleMbeanName = sampleObj.getObjectName(); String value = jmxs.getAttribute(sampleMbeanName, "Count").toString(); System.out.println(sampleMbeanName.getCanonicalName() + "," + sampleMbeanName.getDomain() + "," + sampleMbeanName + "-----------va:" + value); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (MalformedObjectNameException e) { e.printStackTrace(); } catch (ReflectionException e) { e.printStackTrace(); } catch (InstanceNotFoundException e) { e.printStackTrace(); } catch (AttributeNotFoundException e) { e.printStackTrace(); } catch (MBeanException e) { e.printStackTrace(); } try { jmxConnector.close(); } catch (IOException e) { e.printStackTrace(); } } }