我使用的是 Micrometer Cloudwatch 1.1.3,通过 Gradle 引入,compile 'io.micrometer:micrometer-registry-cloudwatch:1.1.3'
在 Java 中,我可以通过执行以下操作来创建 CloudWatchConfig
:
CloudWatchConfig cloudWatchConfig = new CloudWatchConfig() {
@Override
public String get(String s) {
return "my-service-metrics";
}
@Override
public boolean enabled() {
return true;
}
@Override
public Duration step() {
return Duration.ofSeconds(30);
}
@Override
public int batchSize() {
return CloudWatchConfig.MAX_BATCH_SIZE;
}
};
Kotlin 中的等价物,我认为应该是:
val cloudWatchConfig = CloudWatchConfig {
fun get(s:String) = "my-service-metrics"
fun enabled() = true
fun step() = Duration.ofSeconds(30)
fun batchSize() = CloudWatchConfig.MAX_BATCH_SIZE
}
Koltin 编译器失败,指出 block 中的最后一行:fun batchSize() = CloudWatchConfig.MAX_BATCH_SIZE
表示它需要 String 类型的值?
经过多次调试,我能够通过返回步骤函数的 toString 来解决这个问题。您不能只传递任何字符串,因为它将被解析,就好像它是由 Duration 生成的一样。我的 Kotlin 代码现在可以运行,如下所示:
val cloudWatchConfig = CloudWatchConfig {
fun get(s:String) = "my-service-metrics"
fun enabled() = true
fun step() = Duration.ofSeconds(30)
fun batchSize() = CloudWatchConfig.MAX_BATCH_SIZE
step().toString()
}
在查看了 CloudWatchConfig、StepRegisteryConfig 和 MeterRegistryConfig 接口(interface)后,我无法弄清楚为什么会出现这种情况。为什么 Koltin 这样做,为什么它需要 Duration 的 toString?
最佳答案
要在 Java 中创建匿名类的等效项,语法有点不同。您需要使用 object
关键字,并且还需要为接口(interface)方法包含 override
关键字。例如
val cloudWatchConfig = object : CloudWatchConfig {
override fun get(key: String) = "my-service-metrics"
override fun enabled() = true
override fun step() = Duration.ofSeconds(30)
override fun batchSize() = CloudWatchConfig.MAX_BATCH_SIZE
}
关于java - 为什么 CloudWatchConfig 接口(interface)需要一个步骤持续时间的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55245237/