java - Mongo 嵌入式服务器 : the single instance is not primary in replica set

标签 java mongodb spring-boot spring-data-mongodb

我们在项目中使用了 Mongo (spring-boot-starter-data-mongodb 2.3.0.RELEASE),我们需要将它与 @Transactional 一起使用。因此,为了进行测试,我们使用包含单个实例的副本集配置以下嵌入式 Mongo:

嵌入式MongoConfig

@Configuration
@Slf4j
public class EmbeddedMongoConfig extends AbstractMongoClientConfiguration {


    @Value("${spring.data.mongodb.host:localhost}")
    private String dbHost;

    @Value("${spring.data.mongodb.database:sp-audit}")
    private String dbName;

    @Value("${spring.data.mongodb.port:27017}")
    private int dbPort;

    @Bean
    @Primary
    public IMongodConfig mongoConfigTest() throws IOException {
        return new MongodConfigBuilder()
            .version(Version.Main.PRODUCTION)
            .withLaunchArgument("--replSet", "rs0")
            .net(new Net(dbHost, dbPort, Network.localhostIsIPv6()))
            .cmdOptions(new MongoCmdOptionsBuilder()
                .useNoJournal(false)
                .build())
            .build();
    }

    @Bean
    public MongodExecutable embeddedMongoServer() throws IOException {
        MongodExecutable server = MongodStarter.getDefaultInstance().prepare(mongoConfigTest());
        server.start();
        return server;
    }

    @Bean
    @Primary
    public MongoClient mongoClient() {
        MongoClient client = MongoClients.create();
        MongoDatabase adminDatabase = client.getDatabase("admin");
        adminDatabase.runCommand(new Document("replSetInitiate", new Document()));
        log.info("embedded replicaSet status : " + adminDatabase.runCommand(new Document("replSetGetStatus", 1)));
        return client;
    }

    @Override
    protected String getDatabaseName() {
        return dbName;
    }
}

数据库配置

@Bean
public MongoTransactionManager transactionManager(MongoDatabaseFactory dbFactory) {
        return new MongoTransactionManager(dbFactory);
}

一切看起来都很好,但测试失败并出现异常:

com.mongodb.MongoClientException: Sessions are not supported by the MongoDB cluster to which this client is connected
    at com.mongodb.client.internal.MongoClientImpl.startSession(MongoClientImpl.java:128)
    at org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory.getSession(SimpleMongoClientDatabaseFactory.java:84)
    at org.springframework.data.mongodb.MongoTransactionManager.newResourceHolder(MongoTransactionManager.java:350)
    at org.springframework.data.mongodb.MongoTransactionManager.doBegin(MongoTransactionManager.java:139)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.startTransaction(AbstractPlatformTransactionManager.java:400)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
    at org.springframework.test.context.transaction.TransactionContext.startTransaction(TransactionContext.java:103)
    at org.springframework.test.context.transaction.TransactionalTestExecutionListener.beforeTestMethod(TransactionalTestExecutionListener.java:206)
    at org.springframework.test.context.TestContextManager.beforeTestMethod(TestContextManager.java:289)
    at org.springframework.test.context.junit.jupiter.SpringExtension.beforeEach(SpringExtension.java:108)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeBeforeEachCallbacks$1(TestMethodTestDescriptor.java:161)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeBeforeMethodsOrCallbacksUntilExceptionOccurs$5(TestMethodTestDescriptor.java:197)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeBeforeMethodsOrCallbacksUntilExceptionOccurs(TestMethodTestDescriptor.java:197)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeBeforeEachCallbacks(TestMethodTestDescriptor.java:160)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:131)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:71)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:248)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$5(DefaultLauncher.java:211)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:226)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:199)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:132)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:69)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)

进一步的研究表明,当它尝试启动 session 时,它会检查我的服务器是主服务器还是次服务器,但结果为空并失败(链是 MongoClientImpl.java:128 -> MongoClientDelegate.java:74 -> ClusterDescription.java :128)

另外,我在日志中有这个:

[cluster-ClusterId{value='5efcaf70e882a14d213c6a8f', description='null'}-localhost:27017] INFO  o.m.d.cluster.info() - Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=REPLICA_SET_GHOST, state=CONNECTED, ok=true, minWireVersion=0, maxWireVersion=7, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=2794500, setName='null', canonicalAddress=null, hosts=[], passives=[], arbiters=[], primary='null', tagSet=TagSet{[]}, electionId=null, setVersion=null, lastWriteDate=null, lastUpdateTimeNanos=366578580256200}

在您可以看到的地方,primary='null'

为什么它是空的?怎么让它成为主实例,因为它是单实例?

更新

来自 mongoClient() 的嵌入式副本集状态 日志消息:

embedded replicaSet status : 
Document{{
    set=rs0, 
    date=Thu Jul 02 09:19:24 MSK 2020, 
    myState=2, 
    term=1, 
    syncingTo=, 
    syncSourceHost=, 
    syncSourceId=-1, 
    heartbeatIntervalMillis=2000, 
    optimes=Document{{lastCommittedOpTime=Document{{ts=Timestamp{value=0, seconds=0, inc=0}, t=-1}}, appliedOpTime=Document{{ts=Timestamp{value=6844763807676366849, seconds=1593670763, inc=1}, t=-1}}, durableOpTime=Document{{ts=Timestamp{value=6844763807676366849, seconds=1593670763, inc=1}, t=-1}}}}, 
    lastStableCheckpointTimestamp=Timestamp{value=0, seconds=0, inc=0}, 
    members=[
        Document{{_id=0, name=127.0.0.1:27017, health=1.0, state=2, stateStr=SECONDARY, uptime=1, optime=Document{{ts=Timestamp{value=6844763807676366849, seconds=1593670763, inc=1}, t=-1}}, optimeDate=Thu Jul 02 09:19:23 MSK 2020, syncingTo=, syncSourceHost=, syncSourceId=-1, infoMessage=could not find member to sync from, configVersion=1, self=true, lastHeartbeatMessage=}}
    ], 
    ok=1.0, 
    operationTime=Timestamp{value=6844763807676366849, seconds=1593670763, inc=1}, 
    $clusterTime=Document{{clusterTime=Timestamp{value=6844763807676366849, seconds=1593670763, inc=1}, signature=Document{{hash=org.bson.types.Binary@c98f581, keyId=0}}}}
    }
} 

最佳答案

正如@Joe 提到的那样,问题在于,复制集中的节点在进入测试中用 @Transactional 注释的方法之前没有足够的时间进行正确配置。

我将 Thread.sleep(3000) 添加到 mongoClient() 并且它对我有用。不是最好的解决方案,但目前有效

关于java - Mongo 嵌入式服务器 : the single instance is not primary in replica set,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62680945/

相关文章:

mongodb - 在MongoDB中存储数据url

spring - 找不到匹配的工厂方法 :factory bean;factory method 'configurer()' . 检查指定名称的方法是否存在并且它是非静态的

java - 使用不支持 HTML 格式的不同样式重写 JButton PaintComponent

java - Hibernate 数据源连接未关闭

java - 如何按添加顺序绘制 X、Y 坐标?

mongodb - 如何使用数组中的多键索引改进 mongo 查询

mongodb - 返回字段长度/大小的投影选项

java - 如何让 java applet 重复自身

java - Spring 工具套件 - NoClassDefFoundError MappingJackson2XmlHttpMessageConverter

spring - Spring Data REST 中具有多对多关系的 POST 请求