千家信息网

Springboot2.0.X+mongodb多数据源的账号密码该怎么设定

发表于:2025-01-24 作者:千家信息网编辑
千家信息网最后更新 2025年01月24日,今天就跟大家聊聊有关Springboot2.0.X+mongodb多数据源的账号密码该怎么设定,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。之
千家信息网最后更新 2025年01月24日Springboot2.0.X+mongodb多数据源的账号密码该怎么设定

今天就跟大家聊聊有关Springboot2.0.X+mongodb多数据源的账号密码该怎么设定,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

之前在崛起于Springboot2.X + Mongodb多数据源,结果发现没有用户名和密码,替换之后不管用,然后重新写一个带用户名和密码的多数据源,方便企业级使用,目前适用于2.0.X版本,高版本的话,里面的配置Factory会过期,所以等有时间在整一个高版本的配置博客。

1、pom依赖
    org.springframework.boot    spring-boot-starter-data-mongodb    org.springframework.boot    spring-boot-starter-web    org.projectlombok    lombok    true
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();    }    /**     * 如果不写这个转换工具类你在通过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=========");        }        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 {}

second库表

public interface ChatBanRepository extends MongoRepository {}
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多数据源的账号密码该怎么设定有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注行业资讯频道,感谢大家的支持。

0