Springboot2.0.X + mongodb多数据源(账号密码)(77)

原创
09/17 13:39
阅读数 282

        之前在崛起于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<Document>=========");
        }
        MongoTemplate template = (MongoTemplate) getApplicationContext().getBean(source);
        return (DBCollection) template.getCollection(name);
    }

    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

 

展开阅读全文
打赏
1
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
1
分享
返回顶部
顶部