简介

多数据源有很多好处,根据重要性区别备份,也可以区别分配资源等
网上查了很多例子都是针对Repository用法的mongodb多数据源
奈何我就喜欢用MongoTemplate
参考了以下这篇博客,自己实现了一下mongodb 多数据源 搭配多个MongoTemplate

参考:https://blog.csdn.net/u011663149/article/details/88634598



代码


配置源

application.yml

  1. test1:
  2. mongodb:
  3. host:localhost
  4. port:27001
  5. database:test1
  6. test2:
  7. mongodb:
  8. host:localhost
  9. port:27001
  10. database:test2

springboot配置类

AbstractMongoConfig.java

  1. package com.zzzmh.api.config;
  2. import com.mongodb.MongoClient;
  3. import org.springframework.data.mongodb.MongoDbFactory;
  4. import org.springframework.data.mongodb.core.MongoTemplate;
  5. import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
  6. public abstract class AbstractMongoConfig {
  7. private String host;
  8. private String database;
  9. private int port;
  10. public String getHost() {
  11. return host;
  12. }
  13. public void setHost(String host) {
  14. this.host = host;
  15. }
  16. public String getDatabase() {
  17. return database;
  18. }
  19. public void setDatabase(String database) {
  20. this.database = database;
  21. }
  22. public int getPort() {
  23. return port;
  24. }
  25. public void setPort(int port) {
  26. this.port = port;
  27. }
  28. public MongoDbFactory mongoDbFactory() throws Exception {
  29. return new SimpleMongoDbFactory(new MongoClient(host, port), database);
  30. }
  31. abstract public MongoTemplate getMongoTemplate() throws Exception;
  32. }

Test1MongoConfig.java

  1. @Configuration
  2. @ConfigurationProperties(prefix = "test1.mongodb")
  3. public class Test1MongoConfig extends AbstractMongoConfig {
  4. /**
  5. * @Primary 设为默认
  6. * MongoTemplate实现
  7. */
  8. @Primary
  9. @Override
  10. public @Bean(name = "test1MongoTemplate")
  11. MongoTemplate getMongoTemplate() throws Exception {
  12. return new MongoTemplate(mongoDbFactory());
  13. }
  14. }

Test2MongoConfig.java

  1. @Configuration
  2. @ConfigurationProperties(prefix = "test2.mongodb")
  3. public class Test2MongoConfig extends AbstractMongoConfig {
  4. /**
  5. * MongoTemplate实现
  6. */
  7. @Override
  8. public @Bean(name = "test2MongoTemplate")
  9. MongoTemplate getMongoTemplate() throws Exception {
  10. return new MongoTemplate(mongoDbFactory());
  11. }
  12. }

用法

使用Qualifier配置MongoTemplate用哪个数据源
不配置则使用默认数据源

  1. @Autowired
  2. @Qualifier(value = "test1MongoTemplate")
  3. private MongoTemplate mongoTemplate;


END