Мое приложение выполняет вызовы API для двух разных серверов для получения данных. Итак, я заменил Http Classes на CloseableHttp Classes. Пожалуйста, посоветуйте лучшую практику, чтобы избежать проблемы утечки памяти JVM.
@Service
@Transactional(rollbackFor={Exception.class},
propagation=Propagation.REQUIRED)
public class LoanService {
static Logger log = (Logger)
LoggerFactory.getLogger(LoanService.class);
// First API Call request starts here
public String getLanguagePreferenceFromFirstAPI(BigInteger loanNumber) throws Exception {
CloseableHttpResponse response = null;
try {
log.info("First API Call with Get Request starts here with LoanID :"+loanNumber );
response = getApiResponse(LSASConstants.FIRST_API, loanNumber, LSASConstants.HTTP_GET_METHOD);
if(response.getStatusLine() !=null && response.getStatusLine().getStatusCode() ==200){
log.info("Received LanguagePreferenceJSON Response from CustMart API ");
String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
return responseString;
}else{
String errorMsg = "ERRMSG: FirsttAPI Failed : HTTP error code : ";
if (response.getStatusLine()!=null) errorMsg +=response.getStatusLine();
log.error(errorMsg);
throw new LSASException(errorMsg);
}
} catch (LSASException ex) {
throw ex;
}
catch (Exception ex) {
ex.printStackTrace();
throw new LSASException(ex.getMessage());
}finally{
response.close();
}
}
// Second API Call request starts here
public LoanServicesResponse getLoanFromLoanServices(BigInteger loanNumber) throws LSASException, IOException {
CloseableHttpResponse response = null;
try{
response = getApiResponse(LSASConstants.SECOND_API, loanNumber, LSASConstants.HTTP_GET_METHOD);
if(response.getStatusLine() !=null && response.getStatusLine().getStatusCode() ==200){
log.info("Received LoanServicesResponse (Loan Summary) from "+LSASConstants.SECOND_API);
String responseJson = EntityUtils.toString(response.getEntity());
LoanServicesResponse loanServicesResponse = new Gson().fromJson(responseJson, LoanServicesResponse.class);
return loanServicesResponse;
}else{
String errorMsg = "ERRMSG: Second API API Failed : HTTP error code : ";
if (response.getStatusLine()!=null) errorMsg +=response.getStatusLine();
throw new LSASException(errorMsg);
}
} catch (LSASException ex) {
throw ex;
}
catch (Exception ex) {
ex.printStackTrace();
throw new LSASException(ex.getMessage());
}finally{
response.close();
}
}
// Actual API Call goes here
private CloseableHttpResponse getApiResponse(String apiName, BigInteger loanNumber, byte methodType) throws LSASException, ClientProtocolException, IOException, URISyntaxException {
String url="";
CloseableHttpResponse response = null;
URIBuilder uriBuilder=null;
if(apiName.equalsIgnoreCase(LSASConstants.FIRST_API)) {
String firstURL = LSASProperties.getProperty("firstService.url");
if(firstURL !=null && !firstURL .isEmpty())
url = String.format(LSASProperties.getProperty("firstService.url"), loanNumber.toString());
else{
log.error("ERRMSG : " + apiName + "API Failed : URL missing from properties file.");
throw new LSASException("ERRMSG: " + apiName + "API Failed : URL missing from properties file.");
}
}
else if(apiName.equalsIgnoreCase(LSASConstants.SECOND_API)) {
String secURL=LSASProperties.getProperty("sec.url");
if(secURL!=null && !secURL.isEmpty()){
uriBuilder = new URIBuilder(sec.URL);
uriBuilder.setParameter("id", String.valueOf(loanNumber));
url = uriBuilder.build().toString();
}
else{
log.error("ERRMSG : " + apiName + "API Failed : URL missing from properties file.");
throw new LSASException("ERRMSG: " + apiName + "API Failed : URL missing from properties file.");
}
}
String userName=LSASProperties.getProperty("principal");
String password=LSASProperties.getProperty("credentials");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY,
new NTCredentials(userName, password, null, null));
CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider).build();
if(methodType==LSASConstants.HTTP_GET_METHOD) {
HttpGet httpGetRequest = new HttpGet(url);
httpGetRequest.setHeader("Content-type", "application/json; charset=utf-8");
response = client.execute(httpGetRequest);
}
else if(methodType==LSASConstants.HTTP_POST_METHOD) {
HttpPost httpPostRequest = new HttpPost(url);
httpPostRequest.setHeader("Content-type", "application/json; charset=utf-8");
response = client.execute(httpPostRequest);
}
return response;
}
}
Мне нужны решения по нижеприведенным вопросам.
1. Как предотвратить утечку памяти в JVM?
2. Как закрыть ссылку CloseableHttpCleint с каждым запросом от обоих серверов?
пожалуйста, помогите.