如何使用Vert.x Web获取当前的Web请求?

我正在写一个使用Hibernate(JPA)+ Vert.x Web(Kotlin)的项目,我需要将EntityManager绑定到Web Request,我的意思是我想要为每个Web请求创建EntityManager。 我需要使用静态方法(Kotlin中的对象)从VertX获得当前的Web请求。 有没有办法做到这一点? 或者我错了,因为VertX是反应?

你通常应该做的是在一个Verticle中初始化EntityManager,并在另一个Verticle中处理Web请求。 使用EventBus进行通信。 一些沿着这些线(代码不是确切的):

public class DBVerticle extends AbstractVerticle { public void start() throws Exception { EntityManager em = ...; //init your EM vertx.eventBus().<String>consumer("some_description_of_what_you_want").handler(h -> { ResultSet rs = em.doSomeQuery(); h.reply(rs); }); } } public class WebVerticle extends AbstractVerticle { public void start() throws Exception { HttpServer server = vertx.createHttpServer(); Router router = Router.router(vertx); router.get("/").handler(ctx -> { vertx.eventBus().<String>send("some_description_of_what_you_want", "maybe payload", result -> { if (result.succeeded()) { ctx.end(result); } }); }); server.handler(router::accept); } } 

你可以在这里看到一个例子: https : //github.com/vert-x3/vertx-examples/tree/master/spring-examples/spring-example/src/main/java/io/vertx/examples/spring/verticle

如果我理解正确,你想要为每个请求初始化你的实体管理器,并在稍后的任何处理器上使它可用。 在这种情况下,您可以执行如下操作:

 public class MainVerticle extends AbstractVerticle { public void start() throws Exception { HttpServer server = vertx.createHttpServer(); Router router = Router.router(vertx); router.route().handler(ctx -> { EntityManager em = ...; //init your EM ctx.put("em", em); ctx.next(); // as of this moment the entity manager is available for all // handlers in the current request by the key "em" } router.get("/").handler(ctx -> { EntityManager em = ctx.get("em"); // use it as you would... ctx.response().end(/* your response here... */); }); server.handler(router::accept); } } 

请注意,此代码永远不会关闭/处置您的实体管理器,您可能需要在某处添加一个结束处理程序/异常处理程序来关闭它。