我正在“不与主人交谈并重试已用完”语句DBCursor.hasNext()的异常。
当我搜索时,根据设置偏好获得解决方案。我仍然遇到了这个问题。
我的代码如下:
public void sampleTest() throws Exception
{
MongoClient client = new MongoClient("192.168.20.117", 27017);
DB database = client.getDB("CLME2ECORE");
boolean auth = database.authenticate("tecnotree", ("tecnotree").toCharArray());
DBCollection collection = database.getCollection("RegistrationRequest");
collection.setReadPreference(ReadPreference.primary());
BasicDBObject andQuery = new BasicDBObject("serviceRequest.serviceRequestSubtype.masterCode","RETPOSTREG");
andQuery.append("serviceRequest.serviceRequestStatus.masterCode", "PYMTPEND");
BasicDBObject andFields = new BasicDBObject("serviceRequest.customer.profileDetails.basicDetails.customerCode",1);
andFields.append("_id", 0);
DBCursor dbCursor = collection.find(andQuery);
DBObject dbObject;
dbCursor.setReadPreference(ReadPreference.primary());
if(dbCursor.hasNext())
{
dbObject = dbCursor.next();
String value = dbObject.get("serviceRequest.customer.profileDetails.basicDetails.customerCode").toString();
}
client.close();
}
我正在使用maven依赖项
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.13.0</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>bson</artifactId>
<version>2.13.0</version>
</dependency>
请帮助解决此问题。
答案 0 :(得分:3)
进行这些更改,然后就可以了。
连接到mongodb时传递完整的副本集字符串,不要传递单个服务器IP。
将readPreferance更改为PrimaryPrefferred,而不是仅限Primary。
答案 1 :(得分:0)
我遇到了和你完全一样的问题。我正在使用java spring连接到从属mongo数据库。以下代码应该会有所帮助。
@Configuration
@PropertySource("classpath:param.properties")
public class MongoConfig {
public @Bean MongoClientFactoryBean mongo() {
MongoClientFactoryBean mongo = new MongoClientFactoryBean();
mongo.setHost(mongoAddress);
mongo.setPort(mongoPort);
MongoClientOptions mco = new MongoClientOptions.Builder().readPreference(ReadPreference.secondaryPreferred()).build();
mongo.setMongoClientOptions(mco);
return mongo;
}
@Value("${mongo.address}")
private String mongoAddress;
@Value("${mongo.port}")
private Integer mongoPort;
}
关键行如下:
MongoClientOptions mco = new MongoClientOptions.Builder().readPreference(ReadPreference.secondaryPreferred()).build();
这表明mongo客户是次要的。