Java 正确的Vertx数据库礼仪

Java 正确的Vertx数据库礼仪,java,vert.x,Java,Vert.x,我对Vertx还比较陌生,正在尝试寻找一些实际的数据库使用示例 我有一个创建共享数据库对象的Verticle(和许多处理路由的类),但我想在主类之外使用共享数据库,显然我可以在其他类构造函数中传递数据库对象,但我相信Vertx有更好的方法来做到这一点 public void start() { ... this.postgreSQLClient = PostgreSQLClient.createShared(vertx, sqlClientConfig); ... }

我对Vertx还比较陌生,正在尝试寻找一些实际的数据库使用示例

我有一个创建共享数据库对象的Verticle(和许多处理路由的类),但我想在主类之外使用共享数据库,显然我可以在其他类构造函数中传递数据库对象,但我相信Vertx有更好的方法来做到这一点

public void start() {
    ...
    this.postgreSQLClient = PostgreSQLClient.createShared(vertx, sqlClientConfig);
    ...
}
有没有人有任何Java Vertx示例,其中包含真实的数据库实现

提前谢谢你。

只要:

如果使用相同的Vert.x实例和 指定相同的池名称,它们将共享相同的数据源

因此,更新您的示例:

public void start() {
  this.postgreSQLClient = PostgreSQLClient.createShared(vertx, sqlClientConfig, "my-shared-client");
}
请注意,执行此操作时,将使用第一次调用中提供的配置。后续调用将只返回现有客户端。

只需:

如果使用相同的Vert.x实例和 指定相同的池名称,它们将共享相同的数据源

因此,更新您的示例:

public void start() {
  this.postgreSQLClient = PostgreSQLClient.createShared(vertx, sqlClientConfig, "my-shared-client");
}

请注意,执行此操作时,将使用第一次调用中提供的配置。后续调用将只返回现有客户端。

使用依赖项注入。我已使用 下面是一个例子:

Main.java

//within main function where you have object of vertx
Guice.createInjector(new AppInjector(vertx));
AppInjector.java

//Create an Injector file and bind your injections
PostgreSQLClient postgreSQLClient = PostgreSQLClient.createShared(vertx, sqlClientConfig, "my-shared-client");
bind(PostgreSQLClient.class).annotatedWith(Names.named("DBClient")).toInstance(postgreSQLClient);
UserService.java

public class UserService {

    @Inject
    @Named("DBClient")
    private PostgreSQLClient client;

}

您可以找到使用依赖注入的源代码 下面是一个例子:

Main.java

//within main function where you have object of vertx
Guice.createInjector(new AppInjector(vertx));
AppInjector.java

//Create an Injector file and bind your injections
PostgreSQLClient postgreSQLClient = PostgreSQLClient.createShared(vertx, sqlClientConfig, "my-shared-client");
bind(PostgreSQLClient.class).annotatedWith(Names.named("DBClient")).toInstance(postgreSQLClient);
UserService.java

public class UserService {

    @Inject
    @Named("DBClient")
    private PostgreSQLClient client;

}

你可以找到源代码

所以在我需要的地方运行createShared?@AlexHaslam(尽管使用相同的名称!)非常感谢!感觉有点奇怪…但是它工作了!所以在我需要的地方运行createShared?@AlexHaslam(尽管使用相同的名称!)非常感谢!感觉有点奇怪…但它很有效!谢谢你的回答。这也是一个好方法,但我会使用@tsegismont突出显示的默认Vertx方法。我会记住这一点并进行投票。谢谢你的回答。这也是一个好方法,但我会使用@tsegismont突出显示的默认Vertx方法。我会保留这一点用心去投票。