今天就跟大家聊聊有关Springboot2.0.X+mongodb多数据源的账号密码该怎么设定,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
之前在崛起于Springboot2.X + Mongodb多数据源,结果发现没有用户名和密码,替换之后不管用,然后重新写一个带用户名和密码的多数据源,方便企业级使用,目前适用于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=3000spring.data.mongodb.second.database=数据库名spring.data.mongodb.second.uri=mongodb://账号:密码@地址host:3717/数据库名?maxIdleTimeMS=3000
3、config配置
@Configuration@Slf4jpublic 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(); } @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)); }}
@Componentpublic class MongoTemplateHolder implements ApplicationContextAware {private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {if (MongoTemplateHolder.applicationContext == null) { MongoTemplateHolder.applicationContext = applicationContext; } } public static ApplicationContext getApplicationContext() {return applicationContext; } public static MongoTemplate getBean(String source) throws Exception {if (StringUtils.isEmpty(source)) {throw new Exception("=========数据源名称不能为空========="); }return (MongoTemplate) getApplicationContext().getBean(source); } public static MongoTemplate getBean(MongoDbEnum mongoDbEnum) throws Exception {if (mongoDbEnum == null){throw new Exception("=========数据源名称不能为空========="); }return (MongoTemplate) getApplicationContext().getBean(mongoDbEnum.getDatabaseName()); } 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<Document>========="); } MongoTemplate template = (MongoTemplate) getApplicationContext().getBean(source); return (DBCollection) template.getCollection(name); }public static MappingMongoConverter mongoConverter() {return (MappingMongoConverter) getApplicationContext().getBean("mongoConverter");}}
4、枚举
@Getter@AllArgsConstructor@NoArgsConstructorpublic 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
看完上述内容,你们对Springboot2.0.X+mongodb多数据源的账号密码该怎么设定有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注编程网行业资讯频道,感谢大家的支持。