JMXClient

以读取kafka metrics为例。

实际使用中可将读取的metrics存入时序数据库中,然后从页面展示。kafka-manager等不支持历史的指标展示。

JMXClient.scala

import javax.management.remote.{JMXConnector, JMXConnectorFactory, JMXServiceURL}
import javax.management._
import kafka.server.BrokerTopicMetrics
import kafka.utils.Logging
import kafka.metrics.KafkaMetricsGroup

object JMXClient {

    def useage() {
        println("Useage: java JMXClient <RMI url>")
    }

    def main(args: Array[String]) {
        if (args.length != 1) {
            useage
            System.exit(-1)
        }

        val url: JMXServiceURL = new JMXServiceURL(args(0))
        val connector: JMXConnector = JMXConnectorFactory.connect(url)
        val mbsc: MBeanServerConnection = connector.getMBeanServerConnection

        val beanSet: java.util.Set[ObjectInstance] = mbsc.queryMBeans(new ObjectName("*kafka*:type=*,name=*"), null)
        val beans: Array[ObjectInstance] = beanSet.toArray(
            new Array[ObjectInstance](0)).sortWith((o1, o2) => o1.getClassName.compare(o2.getClassName) < 0)
        for (bean <- beans) {
            val objectName: ObjectName = bean.getObjectName
            println(objectName)
            mbsc.getMBeanInfo(objectName).getAttributes.foreach(attr =>
                println("\t%s\t\t\t%s".format(attr.getName, mbsc.getAttribute(objectName, attr.getName))))
        }
    }
}

构建脚本build.sh,需设置好SCALA_HOME和KAFKA_HOME

#!/usr/bin/env bash

SCALA_HOME=~/opt/scala-2.9.2
KAFKA_HOME=~/opt/kafka_2.9.2-0.8.1.1
SCALAC=$SCALA_HOME/bin/scalac
LIBS=.
for i in $KAFKA_HOME/libs/*.jar; do
  LIBS="$LIBS:$i"
done

cmd="$SCALAC -classpath $LIBS JMXClient.scala"
echo "$cmd"
$cmd


你可能感兴趣的:(scala,kafka,jmx)