sringboot中使用mondodb连接池,用户名和密码都对就是认证不过,客户端可以成功连接,为什么
解决方法:
错误信息:
Caused by: com.mongodb.MongoCommandException: Command failed with error 18 (AuthenticationFailed): 'Authentication failed.' on server localhost:27017. The full response is {"ok": 0.0, "errmsg": "Authentication failed.", "code": 18, "codeName": "AuthenticationFailed"}
看错误知道是登陆失败,用户认证不通过,但我使用客户端连接是可以的,到了java代码连接就不行,后来调试了一下,发现MongoProperties 注入的password是空字符串,因为在yml文件中我配置了password是123456,由于太过简单的原因springboot识别不了,后来改mongodb用户的密码为wlg123456就可以了
@Bean
public MongoDbFactory mongoDbFactory(MongoProperties mongo) throws Exception {
MongoCredential credential = MongoCredential
.createScramSha1Credential(mongo.getUsername(), mongo.getDatabase(), mongo.getPassword());
MongoClientOptions options = MongoClientOptions
.builder()
.minConnectionsPerHost(minConnectionsPerHost)//最小连接数
.connectionsPerHost(connectionsPerHost) //最大连接数
.connectTimeout(10000)//超时时间
.threadsAllowedToBlockForConnectionMultiplier(5)//当连接超过connectionsPerHost时,最多(connectionsPerHost*这个值)500个线程等待一个链接,推荐配置为5
.maxConnectionIdleTime(1000*10)// 最大空闲连接时长,不用的连接超过这个时间时回收
.socketTimeout((int) TimeUnit.MINUTES.toMillis(1)) // socket 超时时间
.build();
// MongoDB地址列表
List<ServerAddress> list = new ArrayList<ServerAddress>();
for (String address : mongo.getUri().split(",")) {
String[] hostAndPort = address.split(":");
String host = hostAndPort[0];
Integer port = Integer.parseInt(hostAndPort[1]);
ServerAddress serverAddress = new ServerAddress(host, port);
list.add(serverAddress);
}
MongoClient mongoClient = new MongoClient(list, credential, options);
return new SimpleMongoDbFactory(mongoClient,mongo.getDatabase());
}