正确的 Vertx 数据库礼仪

Proper Vertx database etiquette

我是 Vertx 的新手,正在尝试寻找一些实际的数据库使用示例。

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

public void start() {
    ...
    this.postgreSQLClient = PostgreSQLClient.createShared(vertx, sqlClientConfig);
    ...
}

有没有人有任何 Java Vertx 示例和数据库的实际实现?

提前致谢。

specify a pool name:

if different clients are created using the same Vert.x instance and specifying the same pool name, they will share the same data source.

所以更新你的例子:

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

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

使用依赖注入。我用过 Guice 这是它的例子:

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;

}

你可以找到源代码here