适当的Vertx数据库礼仪

时间:2017-01-12 09:09:01

标签: java vert.x

我对Vertx很新,并试图找到一些现实的数据库使用示例。

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

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

是否有人拥有任何具有数据库实际实现的Java Vertx示例?

提前谢谢。

2 个答案:

答案 0 :(得分:3)

使用依赖注入。我用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

答案 1 :(得分:1)

只需specify a pool name

  

如果使用相同的Vert.x实例创建不同的客户端   指定相同的池名称,它们将共享相同的数据源。

所以更新你的例子:

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

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

相关问题