Mongodb+SpringBoot,如果在 Java中,使用 @Transactional 注解,那么必须把服务器配置为 replication 模式或者分片集,否则会报错:
✘
Query failed with error code 20 with name 'IllegalOperation' and error message 'Transaction numbers are only allowed on a replica set member or mongos' on server xxx:27017
默认情况下Mongodb安装后为单机模式,启用副本集模式:
- 修改配置 mongod.cfg,启用 replication:
replication:
replSetName: "rs0"
- 配置keyFile。如果启用鉴权模式,即必须用用户名和密码登录,则必须配置好证书。否则会报错:
✘
BadValue: security.keyFile is required when authorization is enabled with replica sets
首先用以下指令生成证书文件。
openssl rand -base64 756 > cert.key
然后修改 mongod.cfg,配置 keyFile,记得把证书文件路径更改为你的cert.key对应的文件路径:
security:
authorization: enabled
keyFile: C:\Program Files\MongoDB\Server\6.0\bin\cert.key
- 重启 mongodb 服务,然后用 mongo shell程序连接mongo db 服务器,并运行指令: rs.initiate() 初始化副本集。如果不初始化副本集,在Java中查询会报错:
✘
"Query failed with error code 13436 with name 'NotPrimaryOrSecondary' and error message 'node is not in primary or recovering state' on server xxx:27017"
✘
rs.initiate() 报错:
shell got exception during repl set operation: MongoServerError: no such cmd: replSetInitiate in some circumstances, the primary steps down and closes connections on a reconfig
这是因为服务器未被配置为副本集模式,请修改配置为副本集模式,并重启服务器。