多数据源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注解实例化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值