七.SpringBoot集成实例系列-多数据源mongodb(一)

版权声明:本文为博主原创文章,转载请注明原地址 https://blog.csdn.net/a123demi/article/details/78234023
文章列表

本系列将通过实例分别实现Springboot集成mybatis(mysql),mail,mongodb,cassandra,scheduler,redis,kafka,shiro,websocket。
具体文章系列如下:
八.SpringBoot集成实例系列-缓存redis
九.SpringBoot集成实例系列-数据库cassandra
十.SpringBoot集成实例系列-定时任务scheduler
十一.SpringBoot集成实例系列-消息队列kafka
十二.SpringBoot集成实例系列-消息推送websocket

上一章,我们介绍了springboot集成单数据源的mongodb,但实际环境中单个mongodb一般是很少的,正常都是使用主从或集群mongodb环境。本来总结了两种方式实现springboot集成多数据源mongodb.第一种直接通过配置文件来创建不同的MongoDbFactory;第二种通过lombok+MongoDbFactory+MongoProperties+注解的方式。
下面让我们开始第一种集成方式:
1.需求
通过来个不同数据源中指定数据库中的collections中数据个数?
2.技术要点
2.1 配置文件

两个数据源primary和secondary
2.2 创建SimpleMongoDbFactory

自定义MongoDbFactory实现方法,不同数据源继承该方法创建对应的MongoDbFactory。
主要本实例mongodb环境是设置了权限认证的,如未认证,可以简单的通过
newSimpleMongoDbFactory(newMongoClient(host, port), database)
实现。
2.3 不同数据源实现

第一个框:加载配置文件属性分隔符
第二个框:设置MongoTemplate通过name实现注入
2.4 不同数据源调用

根据Autowired+Qualifier注解实例化
3.代码实现
3.1 项目结构

3.2 数据源配置文件
spring.application.name=spirngboot-integ-mongo-mdsource

spring.data.mongodb.primary.database=logs
spring.data.mongodb.primary.host=127.0.0.1
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=127.0.0.1
spring.data.mongodb.secondary.password=user1
spring.data.mongodb.secondary.port=27017
spring.data.mongodb.secondary.username=user1
3.3 通用SimpleMongoDbFactory生成类
package com.lm.first.config;

import java.util.ArrayList;
import java.util.List;

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

import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;

/**
 * 根据配置文件创建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;
}
3.4 主数据源加载
package com.lm.first.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.core.MongoTemplate;

@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());    
     }
}
3.5 第二数据源加载
package com.lm.first.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;

@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());    
    }
}
3.6 业务方法
package com.lm.first.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import com.lm.first.entry.PrimaryMongoObject;
import com.lm.first.entry.SecondaryMongoObject;

/**
 * 业务实现
 * @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);
	}

}
3.7 测试实例
package com.lm.first;

import java.util.Date;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import com.lm.first.dao.MongoObjectDao;
import com.lm.first.entry.PrimaryMongoObject;
import com.lm.first.entry.SecondaryMongoObject;

public class MongoDaoTest extends AppTest {

	@Autowired
	private MongoObjectDao mongoObjectDao;

	@Test
	public void testSavePrimary() throws Exception {
		PrimaryMongoObject primaryMongoObject = new PrimaryMongoObject();
		primaryMongoObject.setId("p1" + new Date().getTime());
		primaryMongoObject.setValue("xiaoming");
		mongoObjectDao.savePrimary(primaryMongoObject);
	}

	@Test
	public void testSaveSecondary() {
		SecondaryMongoObject secondaryMongoObject = new SecondaryMongoObject();
		secondaryMongoObject.setId("s1" + new Date().getTime());
		secondaryMongoObject.setValue("xiaoming");
		mongoObjectDao.saveSecondary(secondaryMongoObject);
	}

	@Test
	public void testGetCount() {

		long count = mongoObjectDao.getCount("xiaoming");
		System.out.println("===============================count:" + count);
	}

}
3.8 演示效果

4.代码地址
代码管理地址:
展开阅读全文

没有更多推荐了,返回首页