在Spring Data MongoDB中使用反应式编程模型时,可以执行如下事务:
Mono<DeleteResult> result = template.inTransaction()
.execute(action -> action.remove(query(where("id").is("step-1")), Step.class));
但是Spring Data MongoDB也支持“反应性存储库”,例如:
public interface PersonRepository extends ReactiveMongoRepository<Person, String>
Flux<Person> findByLocationNear(Point location, Distance distance);
}
和
public interface CarRepository extends ReactiveMongoRepository<Car, String>
Flux<Car> findByYear(int year);
}
我的问题是,假设您有ReactiveMongoRepository
,可以以某种方式利用MongoDB事务,例如在同一笔交易中同时插入Person
和Car
(在情况下使用PersonRepository
和CarRepository
)?如果是这样,您该怎么做?
答案 0 :(得分:1)
只是有关MongoDB副本集初始化的公认答案的补充。
final MongoDBContainer mongoDBContainer = new MongoDBContainer("mongo:4.2.8");
我们可以通过“ mongoDBContainer.start()”启动它,并通过try-with-resources或“ mongoDBContainer.stop()”停止它。 See more details on this module and Spring Data MongoDB here。
try (
//create a PSA mongoDbReplicaSet and auto-close it afterwards
final MongoDbReplicaSet mongoDbReplicaSet = MongoDbReplicaSet.builder()
//with 2 working nodes
.replicaSetNumber(2)
//with an arbiter node
.addArbiter(true)
//create a proxy for each node to simulate network partitioning
.addToxiproxy(true)
.build()
) {
//start it
mongoDbReplicaSet.start();
assertNotNull(mongoDbReplicaSet.getReplicaSetUrl());
//do some testing
}