1.自定义配置:这里是加入监听器,也可以修改mogodb其他配置
@Configuration
public class MongoConfig extends MongoAutoConfiguration {
private MongoClientOptions options;
private final MongoClientFactory factory;
private MongoClient mongo;
public MongoConfig(MongoProperties properties, ObjectProvider<MongoClientOptions> options, Environment environment) {
super(properties, options, environment);
this.options = options.getIfAvailable();
this.factory = new MongoClientFactory(properties, environment);
}
@Bean
@ConditionalOnMissingBean
public MongoClient mongo() {
this.options = MongoClientOptions.builder().addClusterListener(new LoggingClusterListener()).addServerListener(new CustomServerListener()).build();
this.mongo = this.factory.createMongoClient(this.options);
return this.mongo;
}
}
2.增加集群监听器
@Component
public class LoggingClusterListener implements ClusterListener {
@Override
public void clusterOpening(ClusterOpeningEvent event) {
System.out.println("clusterOpening");
}
@Override
public void clusterClosed(ClusterClosedEvent event) {
System.out.println("clusterClosed");
}
@Override
public void clusterDescriptionChanged(ClusterDescriptionChangedEvent event) {
System.out.println("clusterDescriptionChanged");
}
}
3.增加server监听器:
@Component
public class LoggingClusterListener implements ClusterListener {
@Override
public void clusterOpening(ClusterOpeningEvent event) {
System.out.println("clusterOpening");
}
@Override
public void clusterClosed(ClusterClosedEvent event) {
System.out.println("clusterClosed");
}
@Override
public void clusterDescriptionChanged(ClusterDescriptionChangedEvent event) {
/* event.getPreviousDescription().getClusterSettings();
System.out.println("clusterDescriptionChanged");*/
}
}