今天就跟大家聊聊有关Springboot2.0.X+mongodb多数据源的账号密码该怎么设定,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
之前在崛起于Springboot2.X + Mongodb多数据源,结果发现没有用户名和密码,替换之后不管用,然后重新写一个带用户名和密码的多数据源,方便企业级使用,目前适用于2.0.X版本,高版本的话,里面的配置Factory会过期,所以等有时间在整一个高版本的配置博客。
<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>
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
@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(); } /** * 如果不写这个转换工具类你在通过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)); } }
@Componentpublic 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<Document>========="); } MongoTemplate template = (MongoTemplate) getApplicationContext().getBean(source); return (DBCollection) template.getCollection(name); }public static MappingMongoConverter mongoConverter() {return (MappingMongoConverter) getApplicationContext().getBean("mongoConverter");}}
@Getter@AllArgsConstructor@NoArgsConstructorpublic enum MongoDbEnum { /** * 数据源 */ LIVE("liveMongo"), MONITOR("monitorMongo"); private String databaseName;}
first库表
public interface UserRepository extends MongoRepository<User, String> {}
second库表
public interface ChatBanRepository extends MongoRepository<ChatBan, String> {}
@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"; } }
测试成功1
看完上述内容,你们对Springboot2.0.X+mongodb多数据源的账号密码该怎么设定有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。