Recursion VertX:检查数据库配置是否可用
我对微服务领域,尤其是vertX,还是个新手。即使没有可用的数据库连接(例如,配置中缺少数据库URL),我也希望垂直链接能够启动。我已经做到了,我的眩晕开始了 现在的问题是,我希望我的verticle注意到数据库连接何时再次可用并连接到它。我该怎么做? 我考虑创建另一个垂直链接“DatabaseVerticle.java”,它将在事件总线上发送当前的DB配置,我的初始垂直链接将使用此消息,并检查配置信息是否一致(回复成功)或仍然缺少一些数据(回复失败并再次进行DatabaseVerticle检查) 这可能有效(也可能无效),但似乎不是我的最佳解决方案Recursion VertX:检查数据库配置是否可用,recursion,environment-variables,vert.x,Recursion,Environment Variables,Vert.x,我对微服务领域,尤其是vertX,还是个新手。即使没有可用的数据库连接(例如,配置中缺少数据库URL),我也希望垂直链接能够启动。我已经做到了,我的眩晕开始了 现在的问题是,我希望我的verticle注意到数据库连接何时再次可用并连接到它。我该怎么做? 我考虑创建另一个垂直链接“DatabaseVerticle.java”,它将在事件总线上发送当前的DB配置,我的初始垂直链接将使用此消息,并检查配置信息是否一致(回复成功)或仍然缺少一些数据(回复失败并再次进行DatabaseVerticle检查
如果有人能提出更好的解决方案,我将非常高兴。谢谢大家! 理想的方法是使用其他服务告知您的服务数据库连接。无论是通过事件总线还是HTTP,您可以做的是,当有人试图在未建立连接的情况下访问您的数据库时,只需尝试进行一些DB调用并处理异常,将布尔值返回为false。现在,当您在事件总线上获得消息时,使用它并将其保存在某个配置pojo中。现在,当有人试图访问您的数据库时,请查找config,如果可用,请建立连接 您的消费者:
public void start(){
EventBus eb = vertx.eventBus();
eb.consumer("database", message -> {
config.setConfig(message.body());
});
}
您的db客户端(本示例中的Mongo):
不是Vertx中的所有问题都应该通过另一个垂直点来解决。
在这种情况下,可以使用
.periodic()
我假设您有一些函数第一次检查数据库。
让我们称之为
checkDB()
在这里,我将使用
timerId
,因为我们无法立即将其传递给cancelTimer()
。但除此之外,它非常简单。对于您的用例,我建议使用vertx配置。特别是,请查看Vert.x配置文档的一节
您可以创建配置检索器并为更改设置处理程序:
ConfigRetrieverOptions options = new ConfigRetrieverOptions()
.setScanPeriod(2000)
.addStore(myConfigStore);
ConfigRetriever retriever = ConfigRetriever.create(vertx, options);
retriever.getConfig(json -> {
// If DB config available, start the DB client
// Otherwise set a "dbStarted" variable to false
});
retriever.listen(change -> {
// If "dbStarted" is still set to false
// Check the config and start the DB client if possible
// Set "dbStarted" to true when done
});
在本例中,消费者通过地址“数据库”消费,但没有人通过该地址发送任何消息。怎么可能呢?此外,我们支持多个数据库,这就是为什么不能应用db客户机示例的原因。我只需要保存配置并在它可用时立即连接到它。但我喜欢在DB调用完成后立即进行验证的想法。如果没有人在事件总线上发送任何东西,那么如何获取DB连接字符串?这相当复杂。我们正在使用spring上下文。无论如何,谢谢你。
class PeriodicVerticle extends AbstractVerticle {
private Long timerId;
@Override
public void start() {
System.out.println("Started");
// Should be called each time DB goes offline
final Long timerId = this.vertx.setPeriodic(1000, (l) -> {
final boolean result = checkDB();
// Set some variable telling verticle that DB is back online
if (result) {
cancelTimer();
}
});
setTimerId(timerId);
}
private void cancelTimer() {
System.out.println("Cancelling");
getVertx().cancelTimer(this.timerId);
}
private void setTimerId(final Long timerId) {
this.timerId = timerId;
}
}
ConfigRetrieverOptions options = new ConfigRetrieverOptions()
.setScanPeriod(2000)
.addStore(myConfigStore);
ConfigRetriever retriever = ConfigRetriever.create(vertx, options);
retriever.getConfig(json -> {
// If DB config available, start the DB client
// Otherwise set a "dbStarted" variable to false
});
retriever.listen(change -> {
// If "dbStarted" is still set to false
// Check the config and start the DB client if possible
// Set "dbStarted" to true when done
});