首页 | 新闻 | 新品 | 文库 | 方案 | 视频 | 下载 | 商城 | 开发板 | 数据中心 | 座谈新版 | 培训 | 工具 | 博客 | 论坛 | 百科 | GEC | 活动 | 主题月 | 电子展
返回列表 回复 发帖

Spring Boot配置MongoDB多数据源(1)

Spring Boot配置MongoDB多数据源(1)

新建一个基础的抽象类

AbstractMongoConfigure.java
内容如下:

package com.biologic.util;

import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;

import com.mongodb.MongoClient;

public abstract class AbstractMongoConfig {

    // 变量名跟配置的参数对应
    private String host, database, username, password;
    private int port;

    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 String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }


    public MongoDbFactory mongoDbFactory() throws Exception {
        // 无认证的初始化方法
        return new SimpleMongoDbFactory(new MongoClient(host, port), database);

        // 有认证的初始化方法
        // ServerAddress serverAddress = new ServerAddress(host, port);
        // List<MongoCredential> mongoCredentialList = new ArrayList<>();
        // mongoCredentialList.add(MongoCredential.createCredential(username, database,
        // password.toCharArray()));
        // return new SimpleMongoDbFactory(new MongoClient(serverAddress,
        // mongoCredentialList), database);
    }


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

}
或者


public abstract class AbstractMongoConfig {

private String uri;
/*
     * Method that creates MongoDbFactory Common to both of the MongoDb
     * connections
     */
    public MongoDbFactory mongoDbFactory() throws Exception {

        return new SimpleMongoDbFactory(new MongoClientURI(uri);
    }

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