Spring Boot连AWS DocumentDB遇301错误:已设retryWrites=false仍报错
解决方案
1. 统一使用完整连接URI配置
当前采用零散的host/port等配置,导致URL中的retryWrites=false参数未生效。修改application.properties,改用完整URI配置:
spring.data.mongodb.uri=mongodb://${DATABASE_USERNAME}:${DATABASE_PASSWORD}@mongo-dev-cluster.cluster-xxxxx.eu-west-2.docdb.amazonaws.com:27017/cars-db?replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false
注释原有的host、port、username、password、database配置项,确保Spring使用指定的完整URI建立连接。
2. 替换save方法为精准更新操作
MongoRepository.save()在处理已存在文档时,内部会触发重试写入逻辑(即使URI禁用了重试),这是报错的核心原因。改用MongoTemplate执行精准更新,避免触发重试:
@Service public class CarService { @Autowired private MongoTemplate mongoTemplate; public void update(String id, Car car) { // 根据ID匹配目标文档 Query query = Query.query(Criteria.where("_id").is(id)); // 构建更新字段,仅修改需要更新的内容 Update update = new Update(); if (car.getColor() != null) { update.set("color", car.getColor()); } if (car.getCarName() != null) { update.set("carName", car.getCarName()); } // 执行更新,仅修改已存在的文档 mongoTemplate.updateFirst(query, update, Car.class); } }
该方式直接发送单条更新指令,无重试逻辑,同时能精准控制更新字段,避免索引键重复冲突。
3. 确保驱动版本兼容
使用与AWS DocumentDB兼容的MongoDB驱动版本,建议选择Spring Boot 2.7.x版本(对应MongoDB驱动4.5.x左右),避免过新版本引入DocumentDB不支持的特性:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> <version>2.7.12</version> </dependency>
内容的提问来源于stack exchange,提问作者smorenoq
相关产品推荐
相关产品推荐

