[英]Batch HTTP requests in Play!Framework
我已經實現了當前的一組路由(例如):
GET /api/:version/:entity my.controllers.~~~~~
GET /api/:version/:entity/:id my.controllers.~~~~~
POST /api/:version/:entity my.controllers.~~~~~
POST /api/:version/:entity/:id my.controllers.~~~~~
DELETE /api/:version/:entity my.controllers.~~~~~
POST /api/:version/search/:entity my.controllers.~~~~~
他們工作得很漂亮。 現在,假設我要為同一API實現“批處理終結點”。 它看起來應該像這樣:
POST /api/:version/batch my.controllers.~~~~~
身體應該像這樣:
[
{
"method": "POST",
"call": "/api/1/customer",
"body": {
"name": "antonio",
"email": "tonysmallhands@gmail.com"
}
},
{
"method": "POST",
"call": "/api/1/customer/2",
"body": {
"name": "mario"
}
},
{
"method": "GET",
"call": "/api/1/company"
},
{
"method": "DELETE",
"call": "/api/1/company/22"
}
]
為此,我想知道如何調用播放框架路由器來傳遞這些請求? 我打算使用與單元測試建議類似的方法:
@Test
public void badRoute() {
Result result = play.test.Helpers.routeAndCall(fakeRequest(GET, "/xx/Kiki"));
assertThat(result).isNull();
}
通過routeAndCall()
的源代碼,您會發現如下所示:
/**
* Use the Router to determine the Action to call for this request and executes it.
* @deprecated
* @see #route instead
*/
@SuppressWarnings(value = "unchecked")
public static Result routeAndCall(FakeRequest fakeRequest) {
try {
return routeAndCall((Class<? extends play.core.Router.Routes>)FakeRequest.class.getClassLoader().loadClass("Routes"), fakeRequest);
} catch(RuntimeException e) {
throw e;
} catch(Throwable t) {
throw new RuntimeException(t);
}
}
/**
* Use the Router to determine the Action to call for this request and executes it.
* @deprecated
* @see #route instead
*/
public static Result routeAndCall(Class<? extends play.core.Router.Routes> router, FakeRequest fakeRequest) {
try {
play.core.Router.Routes routes = (play.core.Router.Routes)router.getClassLoader().loadClass(router.getName() + "$").getDeclaredField("MODULE$").get(null);
if(routes.routes().isDefinedAt(fakeRequest.getWrappedRequest())) {
return invokeHandler(routes.routes().apply(fakeRequest.getWrappedRequest()), fakeRequest);
} else {
return null;
}
} catch(RuntimeException e) {
throw e;
} catch(Throwable t) {
throw new RuntimeException(t);
}
}
所以我的問題是:與復制上面的代碼相比,使用Play做到這一點的方式是否更簡單(我不反對將Scala和Java混合使用)? 我還希望提供並行或順序執行批處理調用的選項……我猜想使用類加載器僅實例化一個Routes
會成問題嗎?
您可以使用以下方法調用來路由假請求: Play.current.global.onRouteRequest
。 請參閱此帖子以獲取完整示例:http: //yefremov.net/blog/play-batch-api/
您可能可以為此使用WS API ,但就我個人而言,我只是創建一個私有方法來收集數據並從“單個”動作和“批處理”動作中使用它們,這肯定會更快。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.