2017-01-12 30 views
0

我是Vertx的新手,并试图找到一些实际的数据库使用示例。我有一个创建共享数据库对象的Verticle(和一些处理路由的类,但我想使用主类之外的共享数据库,显然我可以在其他类的构造函数中传递数据库对象,但我敢肯定,Vertx有一些更好的方式来做到这一点。正确的Vertx数据库礼仪

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

有没有人有一个数据库的现实实现任何Java Vertx例子吗?

预先感谢您。

回答

1

specify a pool name

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

所以更新例如:

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

注意,这样做时,在第一次调用提供的配置将被使用。随后的调用将简单地返回现有的客户端。

+0

那么从我需要的地方运行createShared? –

+0

@AlexHaslam(尽管使用同一个名字!) – tsegismont

+0

非常感谢!感觉有点奇怪......但它的作品! –

2

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

+0

谢谢你的回答。此外还有一个好方法,但是我会使用默认的Vertx方法,如@tsegismont所示。 我会记住这一点并注意。 –