Permalink
Cannot retrieve contributors at this time
Join GitHub today
GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together.
Sign up
Find file
Copy path
ScalaLearning/ScalaRecipe/src/main/scala/recipe/MetricsSample.scala
Find file
Copy path
Fetching contributors…

package recipe | |
import java.util.concurrent.TimeUnit | |
import com.codahale.metrics._ | |
import com.yammer.metrics.core.{HealthCheck, HealthCheckRegistry} | |
import scala.collection.mutable | |
object MetricsSample extends App { | |
def startReport(): Unit = { | |
val reporter = ConsoleReporter.forRegistry(metrics) | |
.convertRatesTo(TimeUnit.SECONDS) | |
.convertDurationsTo(TimeUnit.MILLISECONDS) | |
.build() | |
reporter.start(1, TimeUnit.SECONDS) | |
// ConsoleReporter.forRegistry(healthChecks) | |
} | |
val metrics = new MetricRegistry() | |
startReport() | |
// Gauge | |
val l = mutable.MutableList[Int]() | |
metrics.register( | |
MetricRegistry.name(l.getClass, "l", "size"), | |
new Gauge[Int]() { | |
override def getValue: Int = l.size | |
} | |
) | |
// Meter | |
val requests = metrics.meter("requests") | |
// Counter | |
val pendingJobs = metrics.counter( | |
MetricRegistry.name("myclass", "pending-jobs")) | |
// Histogram | |
val responseSizes = metrics.histogram( | |
MetricRegistry.name("myclass", "response-size") | |
) | |
// Timer | |
val responseTimer = metrics.timer( | |
MetricRegistry.name("myclass", "response-timer") | |
) | |
def foo(): Unit = { | |
Thread.sleep(500 + scala.util.Random.nextInt(500)) | |
} | |
// def using[T <: AutoCloseable, M](resource: T)(block: (M) => Unit)(args: M): Unit = { | |
def using[T <: AutoCloseable, M](resource: T)(block: () => Unit): Unit = { | |
// def using[T <: { def close() }, M](resource: T)(block: (M) => Unit)(args: M): Unit = { | |
try { | |
block() | |
} finally { | |
if (resource != null) resource.close() | |
} | |
} | |
var mockDataBaseStatus = 0 | |
class MockDataBaseHealthCheck(name: String) extends HealthCheck(name) { | |
override def check(): HealthCheck.Result = { | |
if (mockDataBaseStatus != 0) HealthCheck.Result.healthy("Good") | |
else HealthCheck.Result.unhealthy("NeedCheck") | |
} | |
} | |
val healthChecks = new HealthCheckRegistry | |
healthChecks.register(new MockDataBaseHealthCheck("mockDataBase")) | |
new Thread() { | |
for (i <- 1 to 9000) { | |
requests.mark() | |
l += i | |
val r = scala.util.Random.nextInt(5) | |
mockDataBaseStatus = r | |
if (r == 0) { | |
pendingJobs.dec() | |
} else { | |
pendingJobs.inc() | |
} | |
responseSizes.update(r) | |
using(responseTimer.time())(foo) | |
} | |
} | |
Thread.sleep(1200 * 1000) | |
} |