面试题答案
一键面试1. 缓存策略
- 思路:在网络请求中,合理设置缓存可以减少不必要的网络请求,提升响应速度,节省流量。对于一些不经常变化的数据,例如配置信息、静态列表等,可以进行缓存。
- 代码示例:
首先,在
OkHttpClient
中配置缓存。
然后,在创建val cacheSize = (10 * 1024 * 1024).toLong() // 10MB val cache = Cache(context.cacheDir, cacheSize) val okHttpClient = OkHttpClient.Builder() .cache(cache) .build()
Retrofit
实例时使用这个OkHttpClient
。
为了控制缓存行为,可以在请求接口方法上设置val retrofit = Retrofit.Builder() .baseUrl(BASE_URL) .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create()) .build()
@Headers
注解。例如:interface ApiService { @Headers("Cache-Control: public, max-age=600") // 缓存10分钟 @GET("data") suspend fun getData(): Response<DataModel> }
2. 并发请求管理
- 思路:在大型项目中,可能会同时发起多个网络请求。如果不加以管理,可能会导致资源耗尽、网络拥塞等问题。可以使用
Coroutine
的Semaphore
来限制并发请求的数量。 - 代码示例:
定义一个
Semaphore
来限制并发数。
在发起请求的函数中使用private val semaphore = Semaphore(3) // 最多同时处理3个请求
semaphore
。suspend fun fetchData() { semaphore.acquire() try { val response = apiService.getData() if (response.isSuccessful) { // 处理响应数据 } } finally { semaphore.release() } }
3. 连接池复用
- 思路:通过复用已有的网络连接,可以减少连接建立的开销,从而提升性能。
OkHttpClient
内部有一个连接池,合理配置连接池参数可以优化连接复用。 - 代码示例:
上述代码设置了连接池中最大空闲连接数为5,连接保持存活时间为5分钟。这样在这5分钟内,空闲连接不会被关闭,当下次有请求时可以复用这些连接。val connectionPool = ConnectionPool( maxIdleConnections = 5, keepAliveDuration = 5, TimeUnit.MINUTES ) val okHttpClient = OkHttpClient.Builder() .connectionPool(connectionPool) .build()