alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Akka/Scala example source code file (GraphiteClient.scala)

This example Akka source code file (GraphiteClient.scala) is included in my "Source Code Warehouse" project. The intent of this project is to help you more easily find Akka and Scala source code examples by using tags.

All credit for the original source code belongs to akka.io; I'm just trying to make examples easier to find. (For my Scala work, see my Scala examples and tutorials.)

Akka tags/keywords

akka, bufferedwriter, charset, closeable, graphiteclient, inetsocketaddress, long, metrics, string, stringbuilder, test, testing, testkit, utf-8, whitespace

The GraphiteClient.scala Akka example source code

/**
 * Copyright (C) 2014 Typesafe Inc. <http://www.typesafe.com>
 */
package akka.testkit.metrics.reporter

import java.util.regex.Pattern
import java.nio.charset.Charset
import java.io._
import javax.net.SocketFactory
import java.net.InetSocketAddress

/**
 * Carbon (graphite) client, which can be used to send metrics.
 *
 * The data is sent over a plain Socket, even though it would fit AkkaIO nicely, but this way it has no dependencies.
 */
class GraphiteClient(address: InetSocketAddress) extends Closeable {

  private final val WHITESPACE = Pattern.compile("[\\s]+")
  private final val charset: Charset = Charset.forName("UTF-8")

  private lazy val socket = {
    val s = SocketFactory.getDefault.createSocket(address.getAddress, address.getPort)
    s.setKeepAlive(true)
    s
  }

  private lazy val writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream, charset))

  /** Send measurement carbon server. Thread-safe. */
  def send(name: String, value: String, timestamp: Long) {
    val sb = new StringBuilder()
      .append(sanitize(name)).append(' ')
      .append(sanitize(value)).append(' ')
      .append(timestamp.toString).append('\n')

    // The write calls below handle the string in-one-go (locking);
    // Whereas the metrics' implementation of the graphite client uses multiple `write` calls,
    // which could become interwoven, thus producing a wrong metric-line, when called by multiple threads.
    writer.write(sb.toString())
    writer.flush()
  }

  /** Closes underlying connection. */
  def close() {
    try socket.close() finally writer.close()
  }

  protected def sanitize(s: String): String = {
    WHITESPACE.matcher(s).replaceAll("-")
  }
}

Other Akka source code examples

Here is a short list of links related to this Akka GraphiteClient.scala source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2024 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.