【问题标题】:Why does CloudWatchConfig interface expect a String of step duration为什么 CloudWatchConfig 接口需要一个步骤持续时间字符串
【发布时间】:2019-03-19 16:00:09
【问题描述】:

我正在使用 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 编译器失败了,指出块中的最后一行:fun batchSize() = CloudWatchConfig.MAX_BATCH_SIZE 说它需要一个 String 类型的值?

经过多次调试,我能够通过返回 step 函数的 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 接口后,我无法弄清楚为什么会出现这种情况。为什么 Koltin 会这样做,为什么它需要一个 Duration 的 toString?

【问题讨论】:

    标签: java kotlin micrometer spring-micrometer


    【解决方案1】:

    要在 Java 中创建等效的匿名类,语法有点不同。您需要使用object 关键字,并且还包括接口方法的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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-30
      • 1970-01-01
      • 1970-01-01
      • 2021-12-01
      • 1970-01-01
      • 2012-01-03
      • 1970-01-01
      相关资源
      最近更新 更多