- MongoTemplate
- CRUD
- 实体
@Document @Id @Field @Transient
@Transient
指定此成员变量不参与文档的序列化
Query
Criteria
Sort
new BasicQuery(json)
- 聚合操作
MongoTemplate#aggregate
Aggregation
TypedAggregation
GroupOperation
MatchOperation
SortOperation
ProjectionOperation
- 事务操作
- 编程式事务:
TransactionOptions -> ClientSession
- 声明式事务(配置事务管理器):
MongoDatabaseFactory -> MongoTransactionManager
- change stream:
MessageListenerContainer
var txo = TransactionOptions.builder()
.readPreference(ReadPreference.primary())
.readConcern(ReadConcern.MAJORITY)
.writeConcern(WriteConcern.MAJORITY).build();
try (ClientSession clientSession = client.startSession()) {
clientSession.startTransaction(txo);
clientSession.commitTransaction();
clientSession.abortTransaction();
}
@Bean
MongoTransactionManager transactionManager(MongoDatabaseFactory factory){
TransactionOptions txnOptions = TransactionOptions.builder()
.readPreference(ReadPreference.primary())
.readConcern(ReadConcern.MAJORITY)
.writeConcern(WriteConcern.MAJORITY).build();
return new MongoTransactionManager(factory);
}
@Bean
MessageListenerContainer messageListenerContainer(MongoTemplate template,
DocumentMessageListener documentMessageListener) {
Executor executor = Executors.newFixedThreadPool(5);
MessageListenerContainer messageListenerContainer =
new DefaultMessageListenerContainer(template, executor) {
@Override
public boolean isAutoStartup() { return true; }
};
ChangeStreamRequest<Document> request = ChangeStreamRequest
.builder(documentMessageListener)
.collection("user")
.filter(Aggregation.newAggregation(
Aggregation.match(
Criteria
.where("operationType")
.in("insert", "update", "delete"))))
.fullDocumentLookup(FullDocument.UPDATE_LOOKUP)
.build();
messageListenerContainer.register(request, Document.class);
return messageListenerContainer;
}
@Component
public class DocumentMessageListener<S, T> implements MessageListener<S, T> {
@Override
public void onMessage(Message<S, T> message) {
System.out.println(String.format(
"Received Message in collection %s.\n\trawsource: %s\n\tconverted: %s",
message.getProperties().getCollectionName(),
message.getRaw(),
message.getBody()));
}
}