[英]Okio Throttler integration with OkHttp
My team is suffering from this issue with slack integration to upload files, so following the comments in that issue I would like to throttle the requests in our Kotlin implementation.我的团队在上传文件时遇到了松弛集成的问题,因此根据该问题中的评论,我想在我们的 Kotlin 实现中限制请求。
I am trying to integrate Okio Throttler within an OkHttp interceptor, so I have the setup:我正在尝试将 Okio Throttler集成到 OkHttp 拦截器中,所以我有以下设置:
val client = OkHttpClient.Builder()
.retryOnConnectionFailure(false)
.addInterceptor { chain ->
val request = chain.request()
val originalRequestBody = request.body
val newRequest = if (originalRequestBody != null) {
val wrappedRequestBody = ThrottledRequestBody(originalRequestBody)
request.newBuilder()
.method(request.method, wrappedRequestBody)
.build()
} else {
request
}
chain.proceed(newRequest)
}
.build()
class ThrottledRequestBody(private val delegate: RequestBody) : RequestBody() {
private val throttler = Throttler().apply {
bytesPerSecond(1024, 1024 * 4, 1024 * 8)
}
override fun contentType(): MediaType? {
return delegate.contentType()
}
override fun writeTo(sink: BufferedSink) {
delegate.writeTo(throttler.sink(sink).buffer())
}
}
It seems throttler.sink
returns a Sink
, but a BufferedSink
is required to the method delegate.writeTo
, so I called buffer()
to get that BufferedSink
.似乎throttler.sink
返回一个Sink
,但是方法delegate.writeTo
需要一个BufferedSink
,所以我调用了buffer()
来获取那个BufferedSink
。 Am I doing it wrong ?我做错了吗? Is the call for .buffer()
breaking the integration?对.buffer()
的调用是否会破坏集成?
It's almost perfect.这几乎是完美的。 You just need to flush the buffer when you're done otherwise it'll finish with a few bytes inside.您只需要在完成后刷新缓冲区,否则它将在内部完成几个字节。
override fun writeTo(sink: BufferedSink) {
throttler.sink(sink).buffer().use {
delegate.writeTo(it)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.