flush() and evictAll() not working for okhttp3 cache

380 views Asked by At

I am accessing TestRail's API which has a 180 Req/min rate limit,

  1. I am using okHttpClient for accessing it
  2. To keep a count of a count of requests I am using okhttp cache
  3. After every 180 Requests, I want to reset the cache but cache.flush() and cache.evictAll() both are not working
@Bean
@Named("testRail")
fun createClient(appConfig: AppConfig): OkHttpClient = OkHttpClient
  .Builder()
  .cache(Cache(File("http_cache"),100*1024*1024))
  .readTimeout(Duration.ofHours(1)).build()

I have tried these methods to clear the cache but nothing seems to be working,

println("Client Request original: ${httpClient.cache?.requestCount()}") //prints n
httpClient.cache?.evictAll()
println("Client Request after evict: ${httpClient.cache?.requestCount()}") //prints n
httpClient.cache?.flush()
println("Client Request after flush: ${httpClient.cache?.requestCount()}") //prints n
httpClient.cache?.delete()
httpClient.cache?.initialize()
println("Client Request after deleting and initializing: ${httpClient.cache?.requestCount()}") //prints n

I tried adding an interceptor too, but that didn't work too or I am doing something wrong here:

@Bean
@Named("testRail")
fun createClient(appConfig: AppConfig): OkHttpClient = OkHttpClient
  .Builder()
  .cache(Cache(File("http_cache"),100*1024*1024))
  .readTimeout(Duration.ofHours(1)).build()
  .addInterceptor(provideCacheInterceptor(1))

private fun provideCacheInterceptor(maxMinutes: Int): Interceptor {
    return Interceptor { chain ->
      val response: Response = chain.proceed(chain.request())
      val cacheControl: CacheControl = CacheControl.Builder()
        .maxAge(maxMinutes, TimeUnit.MINUTES)
        .build()
      response.newBuilder()
        .header(CACHE_CONTROL, cacheControl.toString())
        .build()
    }
  }

Please let me know if there is a way to clear this

1

There are 1 answers

0
Jesse Wilson On

OkHttp’s cache has no API to reset statistics.

Flush forces in-memory data to disk. Use this before your program exits.

EvictAll removes all elements from the cache.

If you want to reset statistics, create an object to remember the current state, then subtract.