Micronaut:在过滤器中获取响应的内容长度

时间:2019-05-24 04:29:31

标签: filter content-length micronaut

我们有一个Micronaut应用程序,我想在其中添加一些其他指标。我们添加了一个过滤器

@Filter("/**")
class MetricsHttpRequestFilter(private val meterRegistry: MeterRegistry) :
        OncePerRequestHttpServerFilter(), HttpServerFilter {
//...
}

实现这一目标。在该过滤器中,我想读取响应的Content-Length,以便能够在响应大小上创建直方图。我的工作代码可以正确读取响应的大小,但是我怀疑这是保存内容的正确方法。

更深层的代码:

    private fun success(httpResponse: HttpResponse<*>, httpMethod: String, requestPath: String) {
        val tags = getTags(httpResponse, httpMethod, requestPath)
        // TODO use content length header instead
        val size = if (httpResponse.getBody(ByteArray::class.java).isPresent()) {
            httpResponse.getBody(ByteArray::class.java).get().size
        } else {
            0
        }

        DistributionSummary.builder(metricName)
                .description("the response sizes of http requests")
                .tags(tags)
                .baseUnit("bytes")
                .maximumExpectedValue(1000000)
                .register(meterRegistry)
                .record(size.toDouble())
    }

我们想直接使用httpResponse.contentLength,但是该响应总是返回-1,尽管响应的末尾有一个Content-Length标头,并且给出了正确的大小(在休息界面)。 我怀疑将主体设置为字节数组是个好主意,因为我们有一些与发布者一起工作的端点,并且据我所知,框架通常是反应性的,这可能意味着响应实际上不完全被处理。标头正在发送。在这种情况下,我们没有收到响应大小就可以了。

更改过滤器的顺序无助于获得内容长度。有任何想法吗?在Micronaut中如何构造Content-Length标头的提示也将有所帮助!

0 个答案:

没有答案
相关问题