java 如何在Spring MVC的contextConfigLocation中设置MongoDB ReadPreference

zynd9foi  于 2023-05-15  发布在  Java
关注(0)|答案(8)|浏览(97)

我在Spring MVC中通过mongodb java驱动程序连接到MongoDB分片服务器。我使用以下版本:

  • spring-webmvc-3.2.1.RELEASE
  • mongo-java-driver/2.10.0/mongo-java-driver-2.10.0
  • spring-data-mongodb-1.2.0.RELEASE

MyMongo选项在contextConfigLocation文件mvc-dispatcher-servlet.xml中设置

<mongo:mongo host="mongo.sample.com" port="30000">
     <mongo:options auto-connect-retry="true"
                    slave-ok="true"/>
</mongo:mongo>

它工作得很好,但是slave-ok被come.MongoDB.ReadPreference.js弃用。我只是想知道是否有任何方法可以在contextConfiLocation文件中设置SpringMVC的readPreference。

cigdeys3

cigdeys31#

声明以下bean

<bean id="readPreferenceSecondary" class="com.mongodb.TaggableReadPreference.SecondaryReadPreference">
</bean>


你把它注入到你的mongotemplate中

<bean id="mongoTemplateProdDb" class="org.springframework.data.mongodb.core.MongoTemplate" >
        <property name="readPreference" ref="readPreferenceSecondary"></property>
</bean>
zed5wv10

zed5wv102#

将@Trisha的回复扩展为一个答案:“在MongoTemplate中以编程方式完成”,方法是将ReadPreference设置为SECONDARY

MongoTemplate template = new MongoTemplate(...);
template.setReadPreference(com.mongodb.ReadPreference.SECONDARY);
k75qkfdt

k75qkfdt3#

如果您使用spring-data-mongodb,并且需要基于find query使用多个读取首选项,则可以创建多个Mongo模板和/或存储库,如

@EnableMongoRepositories(basePackages = {
            "com.you.repo.package" }, mongoTemplateRef = "mongoTemplateOne")    
    @Configuration
    public class MongoConfig {

    @Bean(name="mongoTemplateOne")
    public MongoTemplate getMongoTemplateOne() throws UnknownHostException {
        MongoTemplate templateOne = new MongoTemplate(new SimpleMongoDbFactory(new MongoClientURI("YOUR_MONGO_URL")));
        templateOne.setReadPreference(ReadPreference.secondaryPreferred());

        //setting WriteConcern but not relevant for this thread
        templateOne.setWriteConcernResolver(yourWriteConcernResolver());
        return templateOne;
    }

    @Bean(name = "mongoTemplateTwo")
    public MongoTemplate getMongoTemplateTwo() throws UnknownHostException {
        MongoTemplate templateTwo = new MongoTemplate(new SimpleMongoDbFactory(new MongoClientURI("YOUR_MONGO_URL")));
        templateTwo.setReadPreference(ReadPreference.secondaryPreferred());
        return templateTwo;
    }

    private WriteConcernResolver yourWriteConcernResolver() {
        return action -> {
            if (action.getCollectionName()
                    .equals("your_collecton")
                    && (action.getMongoActionOperation() == MongoActionOperation.SAVE
                            || action.getMongoActionOperation() == MongoActionOperation.UPDATE)) {
                return WriteConcern.MAJORITY;
            }
            return action.getDefaultWriteConcern();
        };
    }
xzv2uavs

xzv2uavs4#

如果你有一个以上的secondary(replica-set),你可以更具体地告诉mongo驱动程序你想从哪个secondary读取,使用tags
在mongo端运行以下命令:

db.getMongo().setReadPref('secondaryPreferred',
                          [{"tagName":"TagVal1"},
                            {"tagName":"TagVal2"},
                            {}])

在代码中,它看起来像这样:

MongoTemplate template = new MongoTemplate(...)
template.setReadPreference(ReadPreference.secondaryPreferred("your DBObject that reflect your mongo tag names");

希望能帮上忙。

ut6juiuv

ut6juiuv5#

这里是另一种使用Mongo存储库的方法

@Configuration
@EnableMongoRepositories
class ApplicationConfig extends AbstractMongoClientConfiguration {

    @Autowired
    private Environment env;

    @Value("${spring.data.mongodb.uri}")
    public String mongoUri;

    @Override
    protected String getDatabaseName() {
        return env.getProperty("spring.data.mongodb.database");
    }

    @Override
    protected void configureClientSettings(MongoClientSettings.Builder builder) {
        builder.applyConnectionString(new ConnectionString(mongoUri)).readPreference(ReadPreference.secondary());
    }

}

https://github.com/prashanthmadi/cosmosdb-mongodb-readpreference-springboot-java/blob/main/src/main/java/azure/cosmosdb/mongodb/spring/cosmosdbmongodb/ApplicationConfig.java提供示例应用程序

icnyk63a

icnyk63a6#

如果需要根据集合混合读取主数据和辅助数据,可以在DBCollection对象上设置ReadPreference。这有助于避免复杂的多个MongoTemplate配置。相反,在应用程序生存期内设置一次如下所示的集合级别首选项。该特定集合的所有读取都将转到辅助集合,而对于其他集合,则转到主集合。

DBCollection dbCollection = mongoTemplate.getCollection(mongoTemplate.getCollectionName(collection));
dbCollection.setReadPreference(ReadPreference.secondaryPreferred());

如果你想知道不同的选项来实现它,请检查Spring data mongodb secondary reads

y3bcpkx1

y3bcpkx17#

spring-mongo-2.0.xsd开始,slave-ok已被完全删除,但添加了对ReadPreference的XML配置的支持。下面是为当前XSD翻译的原始问题的XML:

<mongo:mongo-client host="mongo.sample.com" port="30000">
     <mongo:client-options read-preference="SECONDARY_PREFERRED" />
</mongo:mongo-client>
jc3wubiy

jc3wubiy8#

或者,您可以在查询级别使用存储库界面中的注解定义:

@Meta(flags = CursorOption.SECONDARY_READS)
Stream<MyClass> findBySomeField(String someField);

这在使用spring从方法名或注解(如**@Query@Aggregation**)生成的查询时非常有用

相关问题