OkHttp内存溢出
最近刚接触OkHttp,使用它调用其他的接口,我测试的时候单个调用或者少量多个调用也没问题,因为是钉钉提醒,我没办法做大规模测试,所以使用检查几遍逻辑和代码没问题就上线了,上线第一天job跑的时候就报了
2023-05-15 09:14:45.986 WARN 45019 --- [ ConnectionPool] okhttp3.OkHttpClient :
A connection to xxxxxx was leaked.
Did you forget to close a response body?
To see where this was allocated, set the OkHttpClient logger level to FINE:Logger.getLogger(OkHttpClient.class.getName()).setLevel(Level.FINE);
在百度找了很久,解决方式都不对,有的人说是因为reponse未手动关闭,需要手动关闭,但是我的是循环调用,手动关闭后只会执行第一个循环,后面发现是因为在reponse 中,实例化了reponse.body().string,是string的方法没有自动关闭reponse 的功能,由于我不需要接受返回值,于是我直接返回reponse ,解决问题.
我的程序逻辑:
public Response sendMessageDingTalk(String id,String token) throws Exception {
OkHttpClient client = new OkHttpClient().newBuilder()
.connectTimeout(5, TimeUnit.SECONDS)
.build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{"xxxxxxxx"
Request request = new Request.Builder()
.url(sendUrl)
.method("POST", body)
.addHeader("Authorization", "Bearer "+token)
.addHeader("Content-Type", "application/json")
.build();
Response response = client.newCall(request).execute();
return response;
}