Java, Spring, Spring Boot

Add your own Grafana metrics

Grafana is a great tool to visualize operational information regarding of a running service. Recently I implemented a function, that continuously sends information to the Influx database that backs our Grafana server.  It provides information about the number of clients, currently connected to our Spring Boot service, via WebSocket.

As in the simplest case you can use the Micrometer framework, to drive the process. You need only to create your own MeterBinder interface, and implement your own binding. Your bean will be automatically bound to the Micrometer framework, and determines the operation, will be used periodically to expose the needed information.

import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.binder.MeterBinder;

public class ActiveConnectionsMetrics implements MeterBinder {

private LifeSocketConnectionRepository lifeSocketConnectionRepository;

public void bindTo(MeterRegistry registry) {
	Gauge.builder("", 		lifeSocketConnectionRepository,
	.description("Number of connected sessions from Database")


In the bindTo() method you need to define the details of the binding, and register your metric to the MeterRygistry. The name “” is used to define the table name in InfluxDb, in which the data gets stored. As second and third parameter, you need to define a bean and a method, that returns a number. These will be called by Micrometer to get the actual value, to be stored in InfluxDb. In my case, while the service is running, my repository bean gets periodically asked for the number of connected sessions.

In order to be able to use the InfluxDb database, you need to import the following dependency to your project:


You also need to configure the InfluxDb connection, used by Micrometer. Therefore I added the following entries to the application.yml file:

				auto-create-db: false
				uri: https://my.server:8001
				db: my_schema
				user-name: user
				password: password
				enabled: true
				step: 1m

In Grafana GUI, you need to build your own chart, using “my_schema” as Data source, and use a query something like this:

SELECT sum("value") FROM "myservice_active_connections" WHERE "ActiveProfiles" = '[prod]') AND $timeFilter GROUP BY time(30s) fill(none)

Please note, that the table “myservice_active_connections” is used in the query, as you defined the name “” above, by the registration.

At the end, your diagram looks something like this: