将java-List <T>转换为可与iomicrometer的MultiGauge

时间:2019-07-06 09:59:23

标签: java stream grafana prometheus micrometer

从我的springboot应用程序中,我收到结果列表List<T>,其中包含使用

从数据库表中读取的100个元素

T包含字段

  • 唯一标识符
  • 经度
  • 纬度

我想把它变成多个千分尺

object{id=<unique identifier>,longitude=<longitude>,latitude=<latitude>} <value>
object{id=<unique identifier>,longitude=<longitude>,latitude=<latitude>} <value>
object{id=<unique identifier>,longitude=<longitude>,latitude=<latitude>} <value>
...

度量应被普罗米修斯刮掉,然后使用grafana/worldmap 进行可视化 我正在使用建立多规格 MultiGauge l100 = MultiGauge.builder("metric-last100").register(registry);

严重失败,无法将List<T>转换为流以馈送l100.register(...),如here所示:

// SELECT count(*) from job group by status WHERE job = 'dirty'     
MultiGauge statuses = MultiGauge.builder("statuses")
        .tag("job", "dirty")
        .description("The number of widgets in various statuses")
        .baseUnit("widgets")
        .register(registry);

...

// run this periodically whenever you re-run your query     
statuses.register(
  resultSet.stream().map(result -> 
    Row.of(Tags.of("status", result.getAsString("status")),     
    result.getAsInt("count")))
)

这是我的实际代码:

private MultiGauge l100;
...
l100 = MultiGauge.builder("ids-metric-last100").register(registry);
...   
public void updateMetricLast100Deliveries() {
  List<C3MpGeodataDOM> last100 = c3MpGeodataDAO.getlast100();

  l100.register(
    last100.stream().map(
        res -> Row.of(
            Tags.of(
                "sdgnr", res.getMpPK().getSdgnr(),
                "latitude", "" + res.getGeo_latitude(),
                "longitude", "" + res.getGeo_longitude()),
            1)));
}

请原谅我的愚蠢,有人可以帮忙吗?

谢谢

/ M

1 个答案:

答案 0 :(得分:2)

您可以尝试执行以下操作:

1-创建一个类来存储结果并将数据转换为MultiGauge.Row

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class UserData {

  private String gender;
  private Long counter;

  public MultiGauge.Row<UserData> toRow() {
    return MultiGauge.Row.of(Tags.of("gender", gender), this, c -> this.counter);
  }

}

2-创建一个自定义查询以将结果分组

@Query(value = "select new multigauge.multigauge.UserData(usr.gender, count(usr.id)) " +
    "from users usr " +
    "group by usr.gender")
   List<UserData> retrieveUsersGroupedByGender();

3-使用toRow方法转换列表并注册您的MultiGauge

@Scheduled(fixedDelay = 1000)
  public void updateGauges() {
    multiGauge.register(userRepository.retrieveUsersGroupedByGender()
      .stream()
      .map(UserData::toRow)
      .collect(toList()), true);
  }

4-初始化MultiGauge

@PostConstruct
  public void init() {
    multiGauge = MultiGauge.builder("users_grouped_by_gender_metric").register(prometheusMeterRegistry);
  }

我建议查看GitHub官方仓库中的单元测试:

https://github.com/micrometer-metrics/micrometer/blob/master/micrometer-core/src/test/java/io/micrometer/core/instrument/MultiGaugeTest.java