Spring Data MongoDB联邦查询:如何让接口方法使用自定义MongoTemplate?
动态多MongoDB数据源与集合名配置问题
需求背景
我开发的应用需要支持连接任意数量的MongoDB主机及对应数据库,实现基础级别的查询联邦能力。所有连接信息均通过配置指定,部署前无法预知需要访问的集合数量。我的实现基于一篇Spring Data多MongoDB数据库的文章并做了适配修改。
配置示例
datasources: - name: source1 uri: mongodb://user1:pass1@127.0.0.1:27017 fq_collection: db1.coll1 - name: source2 uri: mongodb://user1:pass1@192.168.0.100:27017 fq_collection: db2.coll2
注:datasources的条目数量会根据部署情况变化,无固定值。
当前实现方案
在@Configuration类中遍历通过配置属性注入的数据源条目,为每个条目创建自定义配置的MongoTemplate(不依赖默认的MongoTemplate实例)。我通过以下方式生成Repository实例:
- 定义Repository接口和可接收
MongoTemplate的自定义实现类 - 使用代码为每个
MongoTemplate生成对应Repository:
public MongoRepository<String, Item> mongoCustomRepositories(MongoTemplate template) { MyCustomMongoRepository customImpl = new MyCustomMongoRepositoryImpl(template); MongoRepositoryFactory repositoryFactory = new MongoRepositoryFactory(template); return repositoryFactory.getRepository(MyMongoRepository.class, customImpl); }
- 在
@Bean方法中调用上述方法,返回所有生成的Repository实例列表,注入到业务服务类中使用。
问题排查与需求
将MongoDB的profiling设置为2后,确认查询已发送至MongoDB,但无法查询到文档。原因是模型类未指定集合名称,系统默认使用模型类名的小驼峰形式作为集合名,与配置中指定的集合名不匹配。我有默认集合名,但实际使用的集合名由配置指定,希望得到动态设置集合名的方案建议。
后续进展
目前功能已接近实现,但过程中发现Spring Data MongoDB存在一个bug,已提交Issue。
内容的提问来源于stack exchange,提问作者Steve Storck
相关产品推荐
相关产品推荐

