gpt4 book ai didi

java - Play!Framework 中的批量 HTTP 请求

转载 作者:行者123 更新时间:2023-11-30 03:58:02 25 4
gpt4 key购买 nike

我已经实现了当前的一组路由(例如):

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"
}
]

为此,我想知道如何调用 play 框架路由器来传递这些请求?我计划使用与单元测试建议类似的东西:

@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);
}
}

所以我的问题是:有没有比复制上面的代码更“hacky”的方法来用 Play 来做到这一点(我不反对混合 Scala 和 Java 来实现它)?我还想提供并行或顺序执行批处理调用的选项...我想使用类加载器仅实例化一个 Routes 会有问题吗?

最佳答案

您可以使用以下方法调用来路由您的虚假请求:Play.current.global.onRouteRequest。请参阅这篇文章的完整示例:http://yefremov.net/blog/play-batch-api/

关于java - Play!Framework 中的批量 HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22625538/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com