项目场景:
使用springboot连接本地mongodb
问题描述
先安装mongodb依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
由于springboot本身就对依赖做了管理,所以直接启动就可以加载相关依赖并应用
进行mongodb连接配置
spring.data.mongodb.uri=mongodb://admin:admin@123@localhost:20017/test?authSource=admin
启动出现错误信息
The connection string contains invalid user information. If the username or password contains a colon (:) or an at-sign (@) then it must be urlencoded
原因分析:
错误 原因连接mongoDB 的url 中 用户名 或密码出现了 @ 或 : 符号
url 中原本就带有 @ 和 : 用户名 或密码 再出现 这两个字符时就无法区分哪个是真正的分隔符
解决办法:
对@使用16进制进行URL编码:%40
对:使用16进制进行URL编码:%3A
用上面16进制的URL编码代替原本的字符就行了。
看错误信息时囫囵吞枣,所以将uri里所有@和:都改了编码
spring.data.mongodb.uri=mongodb%3a//admin%3aadmin%40123%40localhost%3a20017/test?authSource=admin
结果出现新的错误关于双斜线等错误
查看客户端使用账号密码登录正常,应该没有问题,这个时候在百度查看,有的说需要将账号和密码添加引号,测试使用,还是没有成功
应该不是引号的问题这个时候然后将properties文件替换为yaml文件试试,格式也修改一下
spring:
data:
mongodb:
authentication-database: admin
host: 192.168.0.101
port: 27017
database: test
username: admin
password: 'admin%40123'
启动没问题,但是请求mongodb报错
Command failed with error 18 (AuthenticationFailed): 'Authentication failed.' on server localhost:20017. The full response is {"ok": 0.0, "errmsg": "Authentication failed.", "code": 18, "codeName": "AuthenticationFailed"}
权限校验错误?突然发现这时其实是可以正常连接,只是密码被我修改了将@改为了%40这时突然发现一些端倪,返回去还是用最开始的配置文件使用,仔细查看报错
果然,是账号密码里存在@或者:需要进行编译,而不是所有的,其他的@和:需要用来做分割,我把分割符都改了能不报错吗
解决方案:
只修改密码中的@为%40
spring.data.mongodb.uri=mongodb://admin:admin%40123@localhost:20017/test?authSource=admin
总结:
阅读错误时需要仔细,bug解决方案,其实就隐藏在错误信息中