1. 程式人生 > >多資料來源MongoDB的使用(法一:直接通過配置檔案來建立不同的MongoDbFactory).md

多資料來源MongoDB的使用(法一:直接通過配置檔案來建立不同的MongoDbFactory).md


  1. 通過來個不同資料來源中指定資料庫中的collections中資料個數
  2. 技術要點
  • 1.配置檔案:
spring.application.name=spirngboot-integ-mongo-mdsource

spring.data.mongodb.primary.database=logs
spring.data.mongodb.primary.host=172.16.3.68
spring.data.mongodb.primary.password=user1
spring.data.mongodb.primary.port=27017
spring.data.mongodb.primary.username=user1

spring.data.mongodb.secondary.database=t_user
spring.data.mongodb.secondary.host=172.16.3.68
spring.data.mongodb.secondary.password=user1
spring.data.mongodb.secondary.port=27017
spring.data.mongodb.secondary.username=user1

配置了兩個資料來源primary和secondary。
本mongodb環境是設定了許可權認證的。
  • 2.建立SimpleMongoDbFactory:
/**
 * 根據配置檔案建立MongoDbFactory
 * @date   2017年10月14日
 *
 */
public abstract class AbstractMongoConfig {
	// Mongo DB Properties
	private String host, database, username, password;
	private int port;
	// Setter methods go here..

	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;
	}

	/*
	 * Method that creates MongoDbFactory Common to both of the MongoDb
	 * connections
	 */
	public MongoDbFactory mongoDbFactory() throws Exception {
		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;
}
	
自定義MongoDbFactory實現方法,不同資料來源繼承該方法建立對應的MongoDbFactory。
主要本例項mongodb環境是設定了許可權認證的,如未認證,可以簡單的通過newSimpleMongoDbFactory(newMongoClient(host, port), database)
實現。
  • 3.不同資料來源實現MongoDbFactory:

主資料來源載入

@Configuration  //Configuration class
@ConfigurationProperties(prefix = "spring.data.mongodb.primary") //Defines my custom prefix and points to the primary db properties
public class PrimaryMongoConfig extends AbstractMongoConfig {
    /**
     * Implementation of the MongoTemplate factory method      
     * @Bean gives a name (primaryMongoTemplate) to the created MongoTemplate instance      
     * @Primary declares that if MongoTemplate is autowired without providing a specific name, 
     * this is the instance which will be mapped by         default      
     */
    @Primary
    @Override
    public @Bean(name = "primaryMongoTemplate") MongoTemplate getMongoTemplate() throws Exception {
        return new MongoTemplate(mongoDbFactory());
    }
}

第二資料來源載入

@Configuration  //Configuration 
@ConfigurationProperties(prefix = "spring.data.mongodb.secondary")  //Defines my custom prefix and points to the secondary db properties
public class SecondaryMongoConfig extends  AbstractMongoConfig{     
    /**      
      * Implementation of the MongoTemplate factory method      
      * @Bean gives a name (primaryMongoTemplate) to the created MongoTemplate instance      
      * Note that this method doesn't have @Primary       
      */    
    @Override public @Bean(name = "secondaryMongoTemplate") 
    MongoTemplate getMongoTemplate() throws Exception {        
        return new MongoTemplate(mongoDbFactory());    
    }
}
其中:

> @Configuration  //Configuration class
> @ConfigurationProperties(prefix = "spring.data.mongodb.primary") //Defines my custom prefix and points to the primary db properties
載入了配置檔案屬性分隔符。

> public @Bean(name = "primaryMongoTemplate")
設定MongoTemplate通過name實現注入。
  • 4.在service層實現不同資料來源呼叫MongoTemplate
/**
 * 業務實現
 * @date   2017年10月14日
 *
 */
@Service
public class MongoObjectDaoImpl implements MongoObjectDao {

	// Using MongoTemplate for primary database
	@Autowired
	@Qualifier(value = "primaryMongoTemplate")
	protected MongoTemplate primaryMongoTemplate;

	// Using mongoTemplate for secondary database
	@Autowired
	@Qualifier(value = "secondaryMongoTemplate")
	protected MongoTemplate secondaryMongoTemplate;

	@Override
	public void savePrimary(PrimaryMongoObject primaryMongoObject) {
		primaryMongoTemplate.save(primaryMongoObject);
	}

	@Override
	public void saveSecondary(SecondaryMongoObject secondaryMongoObject) {
		secondaryMongoTemplate.save(secondaryMongoObject);
	}

	@Override
	public long getCount(String value) {
		Query query = new Query(Criteria.where("value").is(value));
		long primary = primaryMongoTemplate.count(query, PrimaryMongoObject.class);
		long secondary = secondaryMongoTemplate.count(query, SecondaryMongoObject.class);
		return (primary + secondary);
	}

}
	
根據Autowired+Qualifier註解例項化。