1
我已經創建了一個簡單的Jersey客戶端,它能夠成功地使用有效負載執行POST請求。但現在它等待來自HTTP端點的響應:Jersey客戶端異步POST請求不等待響應
public void callEndpoint(String endpoint, String payload) {
try {
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource webResource = client.resource(getBaseURI(endpoint));
log.debug("Sending payload [" + payload + "] to URL - [" + getBaseURI(endpoint) + "]");
// POST method - Is this blocking?
// Is it possible to not wait for response here
ClientResponse response = webResource.accept("application/json")
.type("application/json")
.post(ClientResponse.class, payload);
if (response.getStatus() != 200) {
log.error("The endpoint [" + getBaseURI(endpoint) + "] returned a non 200 status code [" + response.getStatus() + "] ");
}
} catch (Exception e) {
log.error("The endpoint for " + endpoint + " - " + getBaseURI(endpoint) + " is not reachable. This is the exception - " + e);
}
}
private URI getBaseURI(String endpoint) {
// Get this URI from config
String URL = "http://www.somewhere.com/v2/" + endpoint;
return UriBuilder.fromUri(URL).build();
}
QUES:是否有可能爲代碼不等待響應。
我正在嘗試閱讀Jersey client docs以查找其代碼是否可能不等待響應?我看到,只有當我們閱讀迴應時,我們才能關閉連接,但在我的情況下,它沒有用處。我希望在將有效負載發佈到端點後立即關閉連接。
我只需要開火併忘記POST請求,因爲我不關心響應。這是因爲處理在該端點花費了大量時間,我不希望線程等待處理。
也有可能等待一些請求的響應,但不是所有的請求?是否有一個參數可以在客戶端設置,使其等待/不等待?我仍然在閱讀Java文檔,所以這可能是一個非常簡單的設置,但我無法找到到現在這麼問這裏。謝謝!
[更新]
我把它用下面的代碼的工作,但是當我跑我的Java代碼示例它打印開始&立即進行但該程序保持運行一段時間,然後退出。我猜測它正在等待Future的迴應,所以有可能讓我的腳本不再等待呢?代碼是:
public static void callEndpoint(String endpoint, String payload) {
try {
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
AsyncWebResource webResource = client.asyncResource(getBaseURI(endpoint));
// POST method
System.out.println("start");
Future<ClientResponse> resp = webResource.accept("application/json")
.type("application/json")
.post(ClientResponse.class, payload);
// This line makes the code wait for output
//System.out.println(resp.get());
} catch (Exception e) {
System.out.println ("The endpoint for " + endpoint + " - " + getBaseURI(endpoint) + " is not reachable. This is the exception - " + e);
}
System.out.println("done");
}
您可以使用javax.ws.rs.client嗎?我相信Invocation.Builder.async()會做你想做的事情:http://docs.oracle.com/javaee/7/api/javax/ws/rs/client/Invocation.Builder.html#async%28%29 –
是的,我想我可以使用javax.ws.rs.client,但是因爲我已經有Jersey客戶端運行了,所以我認爲只是使用異步方法而不是改變整個類會更容易。 – Sumitk