1、引入:
最近项目中遇到一个很头疼的问题,由于多接口并发请求刷新token失败,导致app老是掉线要重新登录。
当token过期处理首先想到的是在请求回调中获取到token过期的信息,然后进行刷新操作,但是由于项目中使用到的网络请求接口众多,而且大多数接口都有可能会出现token过期的情况,如果多个接口同时去刷新token就会导致token失效,进而导致用户需要重新登录,对用户的体验非常不好。
2、实现思想:
由于项目中的token 是放在 http 请求的 header 中,所以这里使用okhttp 的拦截器来实现。当多个请求都出现了因 token过期而需要重新刷新 token的情况,那么需要判断当前是否有另一个请求正在刷新 token,如果有,那么就不要发起刷新token的请求和其他请求,而是等待刷新 token的请求返回后,直接进行重试。
3、实现如下:
拦截数据判断是否Token过期,并实现并发处理:
private Interceptor mTokenInterceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response originalResponse = chain.proceed(request);
ResponseBody responseBody = originalResponse.body();
BufferedSource source = responseBody.source();
source.request(Long.MAX_VALUE);
Buffer buffer = source.buffer();
Charset charset = UTF8;
MediaType contentType = responseBody.contentType();
if (contentType != null) {
charset = contentType.charset(UTF8);
}
String bodyStr = buffer.clone().readString(charset);
Gson gson = new Gson();
HttpResult httpResult = gson.fromJson(bodyStr, HttpResult.class);
String requestUrl=request.url().encodedPath();
Log.e("Api","------------>request start> request_url="+requestUrl);
synchronized (getInstance()){//同步代码块,当在刷新token的时候暂停其他的request,锁为当前类的单例对象
//比较请求的token与本地存储的token 如果不一致还是直接重试
String request_token=request.header("token");
String access_token=TokenManager.getTokenInfo().getAccess_token();
if(request_token!=null&&access_token!=null&&!request_token.equals(access_token)){
Log.e("Api","------------>request retry request_url="+requestUrl);
Request newRequest=request.newBuilder().header("token", TokenManager.getTokenInfo().getAccess_token()).build();//等待的request重新拼装请求头
return chain.proceed(newRequest);//重试request
}
if (httpResult.getCode()==10003){//10003是服务器与客户端约定token过期的标识,在这里就执行刷新token的操作
Log.e("Api","------------>token longger");
RequestToken requestToken = new RequestToken();
requestToken.setRefresh_token("123456789");
Call<HttpResult<TokenInfo>> call= Api.getInstance().service.refreshTokenSync(requestToken);
Log.e("Api","------------>refreshToken start");
retrofit2.Response<HttpResult<TokenInfo>> response = call.clone().execute();//刷新token必须使用同步请求
TokenInfo tokenInfo = response.body().getData();
Log.e("Api","------------>refreshToken end access_token="+tokenInfo.getAccess_token());
TokenManager.saveTokenInfo(tokenInfo);//保存token
isAlreadyRefreshToken=true;//当前请求已经刷新完token了
Request newRequest=request.newBuilder().header("token", TokenManager.getTokenInfo().getAccess_token()).build();//重新拼装请求头
return chain.proceed(newRequest);//重试request
}
}
Log.e("Api","------------>request end> request_url="+requestUrl);
return originalResponse;
}
};
添加拦截器:
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(mTokenInterceptor)
.build();
API
@PATCH("oauth/token")
Call<HttpResult<TokenInfo>> refreshTokenSync(@Body RequestToken requestToken);
并发请求的输出日志
09-03 18:00:48.410 4702-6432/com.test E/Api: ------------>request start> request_url=/interface/app_active
09-03 18:00:48.410 4702-6432/com.test E/Api: ------------>request end> request_url=/interface/app_active
09-03 18:00:48.410 4702-6432/com.test E/Api: ------------>token longger
09-03 18:00:48.410 4702-6432/com.test E/Api: ------------>refreshToken start
09-03 18:00:48.414 4702-6430/com.test E/Api: ------------>request start> request_url=/interface/app_version
09-03 18:00:48.421 4702-6456/com.test E/Api: ------------>request start> request_url=/interface/hello
09-03 18:00:48.711 4702-6432/com.test E/Api: ------------>request start> request_url=/interface/oauth/token
09-03 18:00:48.711 4702-6432/com.test E/Api: ------------>request end> request_url=/interface/oauth/token
09-03 18:00:48.718 4702-6432/com.test E/Api: ------------>refreshToken end access_token=i m a new token
09-03 18:00:49.516 4702-6430/com.test E/Api: ------------>request retry> request_url=/interface/app_version
09-03 18:00:51.530 4702-6456/com.test E/Api: ------------>request retry> request_url=/interface/hello
09-03 18:01:07.295 4702-6432/com.test E/Api: ------------>request start> request_url=/interface/bat
09-03 18:01:07.295 4702-6432/com.test E/Api: ------------>request end> request_url=/interface/bat
09-03 18:01:07.777 4702-6456/com.test E/Api: ------------>request start> request_url=/interface/app_active
09-03 18:01:07.777 4702-6456/com.test E/Api: ------------>request end> request_url=/interface/app_active
End
经过大量并发请求测试刷新token之后都不再出现token失效的问题,到这里就大功告成了。