配置事务
事务管理器配置代码:
@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
标签:事务,transaction,spring,配置,索引,mongoDB,注解 From: https://www.cnblogs.com/lukelhi/p/17306272.html