[英]REST with Java using Jersey
我正在調用servlet doGet()
方法。 在doGet()
方法內部,我正在進行方法調用,這需要花費大量時間進行處理,因為doGet()
方法超時並且無法將響應發送回進行調用的應用程序。
所以現在我想將一個響應發送回應用程序,該應用程序立即調用doGet()
方法調用doGet()
。
我可以使用線程,如一個線程將回復,另一個將繼續方法調用。 我是否需要使用任何webservice
框架的工作就像Jersey
?
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("in the Do Get");
String tableName = (String)request.getParameter("tableName");
tableName = tableName.replaceAll("[^A-Z0-9_]", "");
System.out.println("setup connections");
SampleService sampleService = new SampleService(new Properties());
Thread t = new Thread(new Runnable() {
public void run() {
// stuff here
sampleService.execute(tableName);
}
});
t.start();
我正在使類實現Runnable接口並在run方法中編寫方法調用的邏輯(需要花費大量時間來處理的方法)。 還有如何在這個響應運行時發送響應
您可以使用2個threads
因此一個將響應並終止,其他將執行后台作業。 這種方法可以在上面的代碼中實現,也可以像Jersey
這樣的用戶框架實現。 使用任何框架的主要好處是框架隱藏復雜性並提供易於使用和可定制的界面( abstractions
的概念)
使用Jersey
,您可以使用AsyncResponse
創建Asynchronous API
,也可以使用@ManagedAsync
注釋和AsyncResponse
一個例子如下 -
@GET
@ManagedAsync
public void getMessage(@Suspended final AsyncResponse asyncResponse) {
System.out.println("1. Registering callback");
asyncResponse.register(new CompletionCallback() {
@Override
public void onComplete(Throwable throwable) {
if (throwable == null) {
// no error
System.out.println(
"4. Request processing is successful");
} else {
System.out.println(
"4. Error occurred in request processing");
}
}
});
System.out.println("2. Executing expensive operation");
String result = expensiveOperation();
System.out.println("3. Notify callback and send response ");
asyncResponse.resume(result);
System.out.println("5. Thread exiting");
}
Sysout語句僅供參考,可以刪除。
如果你想直接使用Servlet
,那么創建一個thread
,啟動它並返回當前的response
-
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("in the Do Get");
String tableName = (String)request.getParameter("tableName");
tableName = tableName.replaceAll("[^A-Z0-9_]", "");
System.out.println("setup connections");
SampleService sampleService = new SampleService(new Properties());
// this tread will run in even after response is send
Thread t = new Thread(new Runnable() {
public void run() {
// stuff here
sampleService.execute(tableName);
}
});
t.start();
// send the response
response.setContentType("application/json");
resp.getWriter().write("response JSON here");
return;
}
您還可以使用Jackson將object mapping
到JSON
以作為response
返回。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.