1. 程式人生 > >springboot配置多資料來源(MongoDB主從)

springboot配置多資料來源(MongoDB主從)

相信看過上一篇文章的小夥伴已經知道了, 這章要講的就是MongoDB主從配置。

在這邊文章中,你將要學到的是在專案中配置主從資料庫,並且相容其他資料庫喲。。這些都是博主專案中需要並且比較重要的知識哦~

好了,廢話不多說,直接進主題。

1.pom依賴

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-mongodb</artifactId>
		</dependency>
2.配置檔案的編寫

## master mongo
master:
  mongodb:
    host: localhost
    port: 27017
    database: db_ops
## slave1 mongo
slave1:
  mongodb:
    host: localhost
    port: 27017
    database: db_note
## zookeeper註冊中心
3.配置檔案的編寫

在mongodb主從配置中,配置有所不同
1.配置父類AbstractMongoConfigure

public abstract class AbstractMongoConfigure {
    private String host, database;
    private int port;
    public MongoDbFactory mongoDbFactory() throws Exception {

        return new SimpleMongoDbFactory(new MongoClient(host, port), database);
    }

    /*
     * Factory method to create the MongoTemplate
     */
    abstract public MongoTemplate getMongoTemplate() throws Exception;

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public String getDatabase() {
        return database;
    }

    public void setDatabase(String database) {
        this.database = database;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }
}
2.主資料庫配置

@Configuration
@EnableAutoConfiguration(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
@EnableMongoRepositories(basePackages = {"com.jx.ops.mapper.mongodb.ops"},mongoTemplateRef = "opsMongoTemplate")
@ComponentScan
@ConfigurationProperties(prefix = "ops.mongodb")
public class MongoMasterConfig extends AbstractMongoConfigure {

    @Override
    @Bean(name = "opsMongoTemplate")
    @Primary  //重點哦
public MongoTemplate getMongoTemplate() throws Exception { return new MongoTemplate(mongoDbFactory()); } }
3.從資料庫配置

@Configuration
@EnableAutoConfiguration(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
@EnableMongoRepositories(basePackages = {"com.jx.ops.mapper.mongodb.post"},mongoTemplateRef = "postMongoTemplate")
@ComponentScan
@ConfigurationProperties(prefix = "post.mongodb")
public class MongoPostConfig extends AbstractMongoConfigure {
    @Override
    @Bean(name = "postMongoTemplate")
    public MongoTemplate getMongoTemplate() throws Exception {
        return new MongoTemplate(mongoDbFactory());
    }
}


到此,主從資料庫也講解完畢,如果有不懂或出bug的小夥伴可以留言我喲。。