【问题标题】:Mongo embedded server: the single instance is not primary in replica setMongo嵌入式服务器:单个实例不是副本集中的主实例
【发布时间】:2020-10-22 03:27:07
【问题描述】:

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

EmbeddedMongoConfig

@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)

进一步的研究表明,当它尝试启动会话时,它会检查我的服务器是主服务器还是次服务器,但得到 null 并失败(链是 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'

为什么它是空的?如何使它成为主要的,因为它是单个实例?

更新

embedded replicaSet status 来自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}}}}
    }
} 

【问题讨论】:

  • 我猜你没有正确配置副本集。
  • “embedded replicaSet status :”的日志条目显示了什么?
  • @Joe 添加了日志消息
  • 根据该副本集状态,该节点尚未成为主节点,因此无法写入会话集合,因此无法支持会话。您可以创建一个循环来检查 replSetGetStatus 直到成员拥有 state=1stateStr=PRIMARY
  • @Joe 谢谢,您帮助我了解了问题的根本原因

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


【解决方案1】:

正如@Joe 所提到的,问题是这样的,副本集中的那个节点在进入测试中用@Transactional 注释的方法之前没有足够的时间来正确配置。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-31
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    • 2017-02-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多