我想将spring mongodb中的WriteConcern设置为已确认。另外,我想知道这是否是默认值?我在我的application.properties中使用spring.data.mongodb.uri,所以我没有任何mongo配置类。
答案 0 :(得分:3)
来自SpringData here
的文档9.4.3。 WriteConcern 如果尚未通过较高级别的驱动程序(例如com.mongodb.Mongo)指定MongoTemplate将用于写入操作,则可以设置com.mongodb.WriteConcern属性。如果没有设置MongoTemplate的WriteConcern属性,它将默认为MongoDB驱动程序的DB或Collection设置中设置的属性。
9.4.4。 WriteConcernResolver 对于要在每个操作基础上设置不同WriteConcern值的更高级情况(用于删除,更新,插入和保存操作),可以在MongoTemplate上配置名为WriteConcernResolver的策略接口。由于MongoTemplate用于持久保存POJO,因此WriteConcernResolver允许您创建可将特定POJO类映射到WriteConcern值的策略。 WriteConcernResolver接口如下所示。
public interface WriteConcernResolver {
WriteConcern resolve(MongoAction action);
}
找到直接实施here
答案 1 :(得分:3)
你可以在Spring bean上做到这一点
@Configuration
public class MongoConfiguration {
@Bean
public WriteConcernResolver writeConcernResolver() {
return action -> {
System.out.println("Using Write Concern of Acknowledged");
return WriteConcern.ACKNOWLEDGED;
};
}
}
答案 2 :(得分:1)
您可以在xml配置中设置写问题(如果适用)
<mongo:db-factory ... write-concern="SAFE"/>
答案 3 :(得分:0)
仅在 Bean 配置上提供 WriteConcernResolver
是不够的。
MongoTemplate
不会使用它。
要实现这一点,您必须创建一个这样的类,其中包含两个选项来设置 WriteConcern
:
import com.mongodb.WriteConcern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.WriteResultChecking;
import org.springframework.data.mongodb.core.convert.MongoConverter;
@Configuration
public class MongoConfiguration {
Logger logger = LoggerFactory.getLogger(MongoConfiguration.class);
public MongoConfiguration() {
logger.info("MongoConfiguration applied ...");
}
@Bean
MongoTemplate mongoTemplate(MongoDatabaseFactory mongoDbFactory, MongoConverter converter) {
MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory, converter);+
// Version 1: set statically
logger.debug("Setting WriteConcern statically to ACKNOWLEDGED");
mongoTemplate.setWriteConcern(WriteConcern.ACKNOWLEDGED);
// Version 2: provide a WriteConcernResolver, which is called for _every_ MongoAction
// which might degrade performance slightly (not tested)
// and is very flexible to determine the value
mongoTemplate.setWriteConcernResolver(action -> {
logger.debug("Action {} called on collection {} for document {} with WriteConcern.MAJORITY. Default WriteConcern was {}", action.getMongoActionOperation(), action.getCollectionName(), action.getDocument(), action.getDefaultWriteConcern());
return WriteConcern.ACKNOWLEDGED;
});
mongoTemplate.setWriteResultChecking(WriteResultChecking.EXCEPTION);
return mongoTemplate;
}
}