您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關(guān)Springboot2.0.X+mongodb多數(shù)據(jù)源的賬號密碼該怎么設(shè)定,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
之前在崛起于Springboot2.X + Mongodb多數(shù)據(jù)源,結(jié)果發(fā)現(xiàn)沒有用戶名和密碼,替換之后不管用,然后重新寫一個帶用戶名和密碼的多數(shù)據(jù)源,方便企業(yè)級使用,目前適用于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=數(shù)據(jù)庫名spring.data.mongodb.first.uri=mongodb://賬號:密碼@地址host:3717/數(shù)據(jù)庫名?maxIdleTimeMS=3000spring.data.mongodb.second.database=數(shù)據(jù)庫名spring.data.mongodb.second.uri=mongodb://賬號:密碼@地址host:3717/數(shù)據(jù)庫名?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(); } /** * 如果不寫這個轉(zhuǎn)換工具類你在通過mongoTempleate默認(rèn)向表中插入數(shù)據(jù)的時候會在表中多一個_class的字段,通過這個轉(zhuǎn)換類轉(zhuǎn)換后不會出現(xiàn)這個_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 數(shù)據(jù)源(你想要獲取的數(shù)據(jù)源) * @return MongoTemplate */public static MongoTemplate getBean(String source) throws Exception {if (StringUtils.isEmpty(source)) {throw new Exception("=========數(shù)據(jù)源名稱不能為空========="); }return (MongoTemplate) getApplicationContext().getBean(source); } /** * 獲取不同數(shù)據(jù)源對應(yīng)的mongodbTemplate * @author chengjian * @date 2020/9/15 9:47 上午 * @param mongoDbEnum 數(shù)據(jù)源信息 */public static MongoTemplate getBean(MongoDbEnum mongoDbEnum) throws Exception {if (mongoDbEnum == null){throw new Exception("=========數(shù)據(jù)源名稱不能為空========="); }return (MongoTemplate) getApplicationContext().getBean(mongoDbEnum.getDatabaseName()); } /** * @param source 數(shù)據(jù)源 * @param name 數(shù)據(jù)庫名稱 * @return MongoCollection */public static DBCollection getCollection(String source, String name) throws Exception {if (StringUtils.isEmpty(source)) {throw new Exception("=========數(shù)據(jù)源名稱不能為空========="); }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 { /** * 數(shù)據(jù)源 */ 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數(shù)量=="+ userRepository.count()); Query query = new Query(); MongoTemplate mongoTemplate = MongoTemplateHolder.getBean(MongoDbEnum.LIVE.getDatabaseName()); System.out.println("first庫:user數(shù)量=="+ mongoTemplate.count(query,"user")); System.out.println("second庫:chat數(shù)量=="+ chatBanRepository.count()); return "OK"; } }
測試成功1
看完上述內(nèi)容,你們對Springboot2.0.X+mongodb多數(shù)據(jù)源的賬號密碼該怎么設(shè)定有進(jìn)一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。