我怎么知道 Mongodb 查询在哪个节点上运行?
How can I know Mongodb query runs on which node?
连接到 MongoDB 复制集群时,我想知道查询在哪个节点上运行。
我尝试在mongoshell中使用explain()
,但是Java驱动程序似乎不支持这个命令。
如何使用 MongoDB Java 驱动程序实现此目的?
您可以尝试利用 MongoDB Java 驱动程序中的 Command Monitoring
;
public class CustomCommandListener implements CommandListener {
@Override
public void commandStarted(final CommandStartedEvent event) {
System.out.println(String.format("Sent command '%s:%s' with id %s to database" +
" '%s' on connection '%s' to server '%s'",
event.getCommandName(),
event.getCommand().get(event.getCommandName()),
event.getRequestId(),
event.getDatabaseName(),
event.getConnectionDescription().getConnectionId(),
event.getConnectionDescription().getServerAddress()));
}
@Override
public void commandSucceeded(CommandSucceededEvent event) {
//ignore
}
@Override
public void commandFailed(CommandFailedEvent event) {
//ignore
}
}
还有CommandSucceededEvent
和CommandFailedEvent
,但不管结果如何,你可以通过上面的CommandStartedEvent
得到一些细节。
然后将此自定义侦听器传递到您的 MongoClient
设置中;
ClusterSettings clusterSettings = ClusterSettings.builder().hosts(hostList).build();
MongoClientSettings settings = MongoClientSettings.builder()
.addCommandListener(new CustomCommandListener())
.clusterSettings(clusterSettings)
// other settings
.build();
MongoClient client = MongoClients.create(settings);
连接到 MongoDB 复制集群时,我想知道查询在哪个节点上运行。
我尝试在mongoshell中使用explain()
,但是Java驱动程序似乎不支持这个命令。
如何使用 MongoDB Java 驱动程序实现此目的?
您可以尝试利用 MongoDB Java 驱动程序中的 Command Monitoring
;
public class CustomCommandListener implements CommandListener {
@Override
public void commandStarted(final CommandStartedEvent event) {
System.out.println(String.format("Sent command '%s:%s' with id %s to database" +
" '%s' on connection '%s' to server '%s'",
event.getCommandName(),
event.getCommand().get(event.getCommandName()),
event.getRequestId(),
event.getDatabaseName(),
event.getConnectionDescription().getConnectionId(),
event.getConnectionDescription().getServerAddress()));
}
@Override
public void commandSucceeded(CommandSucceededEvent event) {
//ignore
}
@Override
public void commandFailed(CommandFailedEvent event) {
//ignore
}
}
还有CommandSucceededEvent
和CommandFailedEvent
,但不管结果如何,你可以通过上面的CommandStartedEvent
得到一些细节。
然后将此自定义侦听器传递到您的 MongoClient
设置中;
ClusterSettings clusterSettings = ClusterSettings.builder().hosts(hostList).build();
MongoClientSettings settings = MongoClientSettings.builder()
.addCommandListener(new CustomCommandListener())
.clusterSettings(clusterSettings)
// other settings
.build();
MongoClient client = MongoClients.create(settings);