我正在使用RESTlet ClientResource从服务器资源调用google places端点。具体来说,REST请求调用RESTlet ServerResource,它调用ClientResource并返回Google Places结果。它在Tomcat中作为Web应用程序运行。
这可以正常工作大约一个小时,然后每个请求都会挂起。停止tomcat后,我看到所有请求都在日志中处理完毕。这非常不稳定,因为Tomcat需要每小时重启一次。
我已经找了一段时间的答案,并发现问题可能是连接未被释放。建议是在表示上使用耗尽并停止在客户端资源上。
我正在使用restlets 2.1.1的最新稳定版本。
以下是我执行上述过程的方法:
ClientResource storeRoot = new ClientResource(placeEndPoint);
Client c = (Client)storeRoot.getNext();
String jsonString = storeRoot.get().getText();
try {
c.stop();
} catch (Exception e) {
e.printStackTrace();
}
storeRoot.release();
在服务器资源返回表示的部分中,我称之为废气:
JSONArray ja = new JSONArray(placesList);
JsonRepresentation jr = new JsonRepresentation(ja);
jr.setCharacterSet(CharacterSet.UTF_8);
try {
jr.exhaust();
jr.release();
} catch (IOException e) {
e.printStackTrace();
} finally{
}
return jr;
有谁知道如何阻止客户端资源挂起?
答案 0 :(得分:0)
问题是ClientResource在关闭连接时遇到问题。对我有用的是使用apache httpclient。
我使用以下方法在RESTlet资源中执行http get:
public String httpGet(String url) throws IllegalStateException, IOException {
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response = httpclient.execute(httpget);
// Examine the response status
System.out.println(response.getStatusLine());
// Get hold of the response entity
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null) {
InputStream instream = entity.getContent();
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(instream));
// do something useful with the response
//System.out.println(reader.readLine());
StringBuilder builder = new StringBuilder();
String aux = "";
while ((aux = reader.readLine()) != null) {
builder.append(aux);
}
String text = builder.toString();
return text;
} catch (IOException ex) {
// In case of an IOException the connection will be released
// back to the connection manager automatically
throw ex;
} catch (RuntimeException ex) {
// In case of an unexpected exception you may want to abort
// the HTTP request in order to shut down the underlying
// connection and release it back to the connection manager.
httpget.abort();
throw ex;
} finally {
// Closing the input stream will trigger connection release
instream.close();
httpclient.getConnectionManager().shutdown();
}
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
}
return null;
}
答案 1 :(得分:0)
ClientConnectionHelper负责关闭ClientResource的连接。每当您完成请求时,您应该调用storeRoot.release()来告诉ClientConnectionHelper停止连接。