spring 中mongoDB事务配置
配置事务
事务管理器配置代码:
@Configuration
public class TransactionConfig {
@Bean
MongoTransactionManager transactionManager(MongoDatabaseFactory factory) {
return new MongoTransactionManager(factory);
}
}
在对应方法加上事务注解。
事务中只能读主库,从库不能读。
错误:Read preference in a transaction must be primary。
mongoDB配置:
mongodb://xxxxx?readPreference=secondaryPreferred&authMechanism=SCRAM-SHA-256&maxPoolSize=20&minPoolSize=5&connectTimeoutMS=10000&socketTimeoutMS=10000&serverSelectionTimeoutMS=5000
去掉配置:readPreference=secondaryPreferred
不能创建索引:
Command failed with error 263 (OperationNotSupportedInTransaction): 'Cannot run 'createIndexes' in a multi-document transaction。
由于代码中的PO代码加了创建索引的注解:
@Data
@Document(collection = "xxx")
@CompoundIndex(name = "xx", def = "{'xx' : 1}")
public class xxxPO {
}
类似错误:
How to prevent Spring from trying to create indexes during MongoDB transactions? - Stack Overflow
去掉创建索引的注解。
参考:https://blog.csdn.net/weixin_43931625/article/details/102236889
posted on 2023-04-11 19:34 passionConstant 阅读(479) 评论(0) 编辑 收藏 举报