之前在崛起于Springboot2.X + Mongodb多数据源(35),结果发现没有用户名和密码,替换之后不管用,然后重新写一个带用户名和密码的多数据源,方便企业级使用,目前适用于2.0.X版本,高版本的话,里面的配置Factory会过期,所以等有时间在整一个高版本的配置博客。
1、pom依赖
_<_dependency_> _ _<_groupId_>org.springframework.boot</_groupId_> _ <_artifactId_>spring-boot-starter-data-mongodb</_artifactId_> </_dependency_> _<_dependency_> _ _<_groupId_>org.springframework.boot</_groupId_> _ <_artifactId_>spring-boot-starter-web</_artifactId_> </_dependency_> _<_dependency_> _ _<_groupId_>org.projectlombok</_groupId_> _ _<_artifactId_>lombok</_artifactId_> _ <_optional_>true</_optional_> </_dependency_>
2、application.properties
spring.data.mongodb.first.database=数据库名 spring.data.mongodb.first.uri=mongodb://账号:密码@地址host:3717/数据库名?maxIdleTimeMS=3000
spring.data.mongodb.second.database=数据库名 spring.data.mongodb.second.uri=mongodb://账号:密码@地址host:3717/数据库名?maxIdleTimeMS=3000
3、config配置
@Configuration @Slf4j public class MultiMongoDbConfig { @Bean(name="firstMongoProperties") @Primary @ConfigurationProperties(prefix="spring.data.mongodb.first") public MongoProperties firstMongoProperties() { log.info("-------------------- liveMongoProperties init ---------------------"); return new MongoProperties(); }
@Bean(name\="secondMongoProperties")
@ConfigurationProperties(prefix\="spring.data.mongodb.second")
public MongoProperties secondMongoProperties() {
log.info("-------------------- monitorMongoProperties init ---------------------");
return new MongoProperties(); }
/\*\*
\* 如果不写这个转换工具类你在通过mongoTempleate默认向表中插入数据的时候会在表中多一个\_class的字段,通过这个转换类转换后不会出现这个\_class字段。
\* @param factory mongodb工厂类
\* @param context 上下文
\* @param beanFactory bean工厂
\* @return MappingMongoConverter
\*/
@Bean(name \= "mongoConverter")
public MappingMongoConverter mappingMongoConverter(MongoDbFactory factory, MongoMappingContext context, BeanFactory beanFactory) {
DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory);
MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver, context); try { mappingConverter.setCustomConversions(beanFactory.getBean(CustomConversions.class)); } catch (NoSuchBeanDefinitionException ignore) {
}
// Don't save \_class to mongo
mappingConverter.setTypeMapper(new DefaultMongoTypeMapper(null)); return mappingConverter; } }
first库配置
@Configuration @EnableMongoRepositories(basePackages = "com.sports.statistics.repository.live", mongoTemplateRef = "liveMongo") public class LiveMongoTemplate {
@Autowired
@Qualifier("firstMongoProperties") private MongoProperties mongoProperties; @Primary @Bean(name = "liveMongo") public MongoTemplate firstMongoTemplate() { return new MongoTemplate(firstFactory(this.mongoProperties)); // return new MongoTemplate(firstFactory(this.mongoProperties), MongoTemplateHolder.mongoConverter()); }
@Bean
@Primary public MongoDbFactory firstFactory(MongoProperties mongoProperties) { MongoClientOptions.Builder options = new MongoClientOptions.Builder(); options.readPreference(ReadPreference.primary()); options.connectionsPerHost(10); return new SimpleMongoDbFactory(new MongoClientURI(mongoProperties.getUri(), options)); } }
second库配置
@Configuration @EnableMongoRepositories(basePackages = "com.sports.statistics.repository.monitor", mongoTemplateRef = "monitorMongo") public class MonitorMongoTemplate { @Autowired @Qualifier("secondMongoProperties") private MongoProperties mongoProperties; @Bean(name = "monitorMongo") public MongoTemplate secondTemplate() { return new MongoTemplate(secondFactory(this.mongoProperties)); //return new MongoTemplate(secondFactory(this.mongoProperties), MongoTemplateHolder.mongoConverter()); }
@Bean
public MongoDbFactory secondFactory(MongoProperties mongoProperties) { MongoClientOptions.Builder options = new MongoClientOptions.Builder(); options.readPreference(ReadPreference.primary()); options.connectionsPerHost(10); return new SimpleMongoDbFactory(new MongoClientURI(mongoProperties.getUri(), options)); } }
@Component public class MongoTemplateHolder implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { if (MongoTemplateHolder.applicationContext == null) { MongoTemplateHolder.applicationContext = applicationContext; } }
/\*\*
\* 获取容器
\* @return ApplicationContext
\*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/\*\*
\* 获取MongoTemplate模板
\* @param source 数据源(你想要获取的数据源)
\* @return MongoTemplate
\*/
public static MongoTemplate getBean(String source) throws Exception {
if (StringUtils.isEmpty(source)) {
throw new Exception("=========数据源名称不能为空\=========");
} return (MongoTemplate) getApplicationContext().getBean(source); }
/\*\*
\* 获取不同数据源对应的mongodbTemplate
\* @author chengjian
\* @date 2020/9/15 9:47 上午
\* @param mongoDbEnum 数据源信息
\*/
public static MongoTemplate getBean(MongoDbEnum mongoDbEnum) throws Exception {
if (mongoDbEnum == null){
throw new Exception("=========数据源名称不能为空\=========");
}
return (MongoTemplate) getApplicationContext().getBean(mongoDbEnum.getDatabaseName());
}
/\*\*
\* @param source 数据源
\* @param name 数据库名称
\* @return MongoCollection
\*/
public static DBCollection getCollection(String source, String name) throws Exception {
if (StringUtils.isEmpty(source)) {
throw new Exception("=========数据源名称不能为空\=========");
}
if (StringUtils.isEmpty(name)) {
throw new Exception("=========空的表名称不能获取MongoCollection
public static MappingMongoConverter mongoConverter() {
return (MappingMongoConverter) getApplicationContext().getBean("mongoConverter"); } }
4、枚举
@Getter @AllArgsConstructor @NoArgsConstructor public enum MongoDbEnum { _ /** _ * 数据源 _ */ _ LIVE("liveMongo"), MONITOR("monitorMongo"); private String databaseName; }
5、repository
first库表
public interface UserRepository extends MongoRepository_<User, String_> { }
second库表
public interface ChatBanRepository extends MongoRepository_<ChatBan, String_> { }
6、controller测试
@RestController @RequestMapping(value = "/user") public class UserController { @Resource UserRepository userRepository; @Resource ChatBanRepository chatBanRepository;
@GetMapping(value = "/test1") public String test1() throws Exception { System.out.println("first库:user数量=="+ userRepository.count()); Query query = new Query(); MongoTemplate mongoTemplate = MongoTemplateHolder.getBean(MongoDbEnum.LIVE.getDatabaseName()); System.out.println("first库:user数量=="+ mongoTemplate.count(query,"user"));
System.out.println("second库:chat数量=="+ chatBanRepository.count());
return "OK"; } }
7、结果
测试成功1