美文网首页
MongoDB多数据源及多数据源下存储类库使用

MongoDB多数据源及多数据源下存储类库使用

作者: 蜀山_竹君子 | 来源:发表于2021-09-09 10:49 被阅读0次

我们知道Spring Data MongoDB默认仅支持一个DataBase,而实际情况往往一个应用需要同时使用多个数据源。而此时我们需要自定义 MongoDB数据库连接。

MongoDB多数据源实现

抽象mongoDB配置 AbstractMongoConfig

普通配置

import com.mongodb.client.MongoClients;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDbFactory;

@Getter
@Setter
public abstract class AbstractMongoConfig {

  //连接MongoDB地址
  private String uri;

  //数据库
  private String dataBaseName;

  /**
   * 获取mongoDBTemplate对象
   */
  public abstract MongoTemplate getMongoTemplate() throws Exception;
  /**
   * 创建mongoDb工厂
   */
  public MongoDbFactory mongoDbFactory() throws Exception {
    return new SimpleMongoClientDbFactory(MongoClients.create(uri), dataBaseName);
  }

}

反应式 MongoDB 支持

import com.mongodb.reactivestreams.client.MongoClients;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.mongodb.ReactiveMongoDatabaseFactory;
import org.springframework.data.mongodb.core.ReactiveMongoTemplate;
import org.springframework.data.mongodb.core.SimpleReactiveMongoDatabaseFactory;


@Setter
@Getter
public abstract class AbstractMongoConfigure {

  //数据库连接
  private String uri;

  //数据库
  private String dataBaseName;

  public ReactiveMongoDatabaseFactory mongoDbFactory() throws Exception {

    //使用uri创建数据库连接
    SimpleReactiveMongoDatabaseFactory simpleMongoDbFactory
        = new SimpleReactiveMongoDatabaseFactory(MongoClients.create(uri), dataBaseName);
    return simpleMongoDbFactory;
  }

  abstract public ReactiveMongoTemplate getMongoTemplate() throws Exception;
}

继承AbstractMongoConfig 根据自定义配置获取多数据源MongoTemplate

普通模式

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

@Configuration
@EnableMongoRepositories(basePackages = {"com.xxxx.saas.xxx.infrastructure.mongo.umcservice"}, mongoTemplateRef = "umcMongoTemplate")
@RefreshScope
@ConfigurationProperties(prefix = "umc.spring.data.mongodb")
public class UmcServiceMongoConfig extends AbstractMongoConfig {

  @Bean(name = "umcMongoTemplate")
  @Override
  public MongoTemplate getMongoTemplate() throws Exception {
    return new MongoTemplate(mongoDbFactory());
  }
}

反应式支持

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.ReactiveMongoTemplate;
import org.springframework.data.mongodb.repository.config.EnableReactiveMongoRepositories;

@Configuration
@EnableReactiveMongoRepositories
@RefreshScope
@ConfigurationProperties(prefix = "userevent.spring.data.mongodb")
public class UserEventMongoConfig extends AbstractMongoConfigure {

  @Bean(name = "usereventMongoTemplate")
  @Override
  public ReactiveMongoTemplate getMongoTemplate() throws Exception {
    return new ReactiveMongoTemplate(mongoDbFactory());
  }
}

自此应用便可根据不同业务使用对应的MongoTemplate Bean对MongoDB进行操作。

MongoDB多数据源场景下使用存储库

我们知道Spring Data repository 抽象了为各种持久性存储实现数据访问层所需的样板代码量,使用MongoDB存储库大大简化了对MongoDB的访问。但是根据spring-data官方文档中的技术指引,默认创建存储库实例的方法并未提供多数据源的支持,因此无法常规配置指定自定义的数据源。
通过源码片段我们也可以看出存储库实例创建后,其数据源也无法正常修改。

public class SimpleMongoRepository<T, ID> implements MongoRepository<T, ID> {
  private final MongoOperations mongoOperations;
  private final MongoEntityInformation<T, ID> entityInformation;

  public SimpleMongoRepository(MongoEntityInformation<T, ID> metadata, MongoOperations mongoOperations) {
    Assert.notNull(metadata, "MongoEntityInformation must not be null!");
    Assert.notNull(mongoOperations, "MongoOperations must not be null!");
    this.entityInformation = metadata;
    this.mongoOperations = mongoOperations;
  }
//省略

思路

基于AOP和反射机制,在存储库实例操作MongoDB之前动态修改存储库实例的mongoOperations以达到存储库支持多数据源的效果。

配置存储库

使用@EnableJpaRepositories("com.acme.repositories"),来触发存储库基础结构,并自定义数据源

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

@Configuration
@EnableMongoRepositories(basePackages = {"com.xxxx.saas.xxxxoperationserver.infrastructure.mongo.umcservice"}, mongoTemplateRef = "umcMongoTemplate")
@RefreshScope
@ConfigurationProperties(prefix = "umc.spring.data.mongodb")
public class UmcServiceMongoConfig extends AbstractMongoConfig {

  @Bean(name = "umcMongoTemplate")
  @Override
  public MongoTemplate getMongoTemplate() throws Exception {
    return new MongoTemplate(mongoDbFactory());
  }
}

编写AOP

通过AOP操作,动态更改更改mongo的repository层mongoTemplate,实现MongoDB存储库分库。

import java.lang.reflect.Field;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.aop.framework.AopProxyUtils;
import org.springframework.aop.framework.ReflectiveMethodInvocation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;

@Aspect
@Component
public class UmcRepositoryAop {

  @Autowired

  WebApplicationContext context;

  @Around("execution(* com.xxxx.saas.xxxxoperationserver.infrastructure.mongo.umcservice..*.*(..))")

  public Object setMongoOperations(ProceedingJoinPoint joinPoint) throws Throwable {
    setMongoTemplate4Repository(joinPoint,
        context.getBean("umcMongoTemplate", MongoTemplate.class));

    return joinPoint.proceed();

  }

  private void setMongoTemplate4Repository(ProceedingJoinPoint joinPoint, MongoTemplate template)
      throws NoSuchFieldException, IllegalAccessException {
    // 通过反射获取到target

    Field methodInvocationField = joinPoint.getClass().getDeclaredField("methodInvocation");

    methodInvocationField.setAccessible(true);

    ReflectiveMethodInvocation o = (ReflectiveMethodInvocation) methodInvocationField
        .get(joinPoint);

    Field targetField = o.getClass().getDeclaredField("target");

    targetField.setAccessible(true);

    Object target = targetField.get(o);

    // 获得SimpleMongoRepository,并往里面填入指定mongoTemplate

    Object singletonTarget = AopProxyUtils.getSingletonTarget(target);

    Field mongoOperationsField = singletonTarget.getClass().getDeclaredField("mongoOperations");

    mongoOperationsField.setAccessible(true);

    mongoOperationsField.set(singletonTarget, template);

  }

}

完成上述步骤,即完成存储库的分库操作。可以进行对应分库下的业务实现。

简单举例umc下的邮箱模板操作

定义邮箱模板Document

import lombok.Data;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;

@Data
@Document(collection="emailTemplate")
public class EmailTemplateDO {

  @Field("_id")//主键,使用mongo内置主键,效率更高
  private String id;

  @Indexed(unique = true) //唯一索引
  private String templateId;

  private String template;

  private String title;

  private String locale;

}

定义邮箱模板存储库实例

这里继承分页存储库PagingAndSortingRepository

import com.xxxx.saas.xxxxoperationserver.infrastructure.mongo.umcservice.model.EmailTemplateDO;
import org.springframework.data.repository.PagingAndSortingRepository;


public interface EmailTemplateCrudRepository extends PagingAndSortingRepository<EmailTemplateDO, String> {

}

使用存储库操作MongoDB

@Component
public class EmailTemplateRepositoryImpl implements EmailTemplateRepository {

  @Autowired
  private EmailTemplateCrudRepository emailTemplateCrudRepository;

  @Override
  public PageResult<EmailTemplate> findAll(PageBean pageBean) {

    Page<EmailTemplateDO> pageRet = emailTemplateCrudRepository.findAll(PageRequest.of(pageBean.getPage(), pageBean.getPagesize()));

    List<EmailTemplateDO> modelList = pageRet.get().collect(Collectors.toList());

    return PageResult.<EmailTemplate>builder()
        .data(EmailTemplateDOAssembler.INSTANCE.toEntitys(modelList))
        .code(200)
        .count(Long.valueOf(pageRet.getTotalPages()))
        .build();
  }
}

经过单元测试,上述代码实现ok。

相关文章

网友评论

      本文标题:MongoDB多数据源及多数据源下存储类库使用

      本文链接:https://www.haomeiwen.com/subject/pmqbwltx.html