目录
  1. 1. 配置文件
  2. 2. 配置类
    1. 2.1. MongoClientOptions配置
  3. 3. 注册MongoClientOptions
    1. 3.1. 主配置类
  4. 4. 从配置类
    1. 4.1. 使用MongoTemplate
springboot mongodb多数据源

配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
spring:
data:
mongodb:
primary:
uri: mongodb://localhost:27017/primary
slave:
uri: mongodb://localhost:27017/slave

# option:

logging:
level:
org.springframework.data.mongodb.core.MongoTemplate: DEBUG

配置类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/**
* Created by IntelliJ IDEA.
* Mongodb多数据源处理:
* https://juejin.im/entry/5ab304dd51882555825241b3
* https://my.oschina.net/mdxlcj/blog/1928794
* @author chensubao
*/
@Getter
@Setter
public abstract class BaseMongoConfig {

/**
* 定义相关连接数据库参数
*/
private String host, database, username, password, uri;

/**
* 定义连接相关参数
*/
private Integer port;

/**
* 创建MongoDbFactory,不同数据源继承该方法创建对应的MongoDbFactory。
* @return
* @throws Exception
*/
protected MongoDbFactory mongoDbFactory(MongoClientOptions.Builder builder) throws Exception {
ServerAddress serverAddress = null;
if (!StringUtils.isEmpty(host) &&
null != port
) {
serverAddress = new ServerAddress(host, port);
}
if (!StringUtils.isEmpty(username) &&
!StringUtils.isEmpty(database) &&
!StringUtils.isEmpty(password) &&
null != serverAddress
) {
MongoCredential mongoCredential = MongoCredential.createCredential(username, database, password.toCharArray());
return new SimpleMongoDbFactory(new MongoClient(serverAddress, mongoCredential, builder.build()), database);
} else if (null != serverAddress &&
!StringUtils.isEmpty(database)
) {
return new SimpleMongoDbFactory(new MongoClient(serverAddress), database);
} else if (!StringUtils.isEmpty(uri)) {
return new SimpleMongoDbFactory(new MongoClientURI(uri, builder));
}
throw new IllegalStateException("初始化mongodb数据源失败");
}

/**
* 抽象方法,用于返回MongoTemplate
* @param context
* @return
* @throws Exception
*/
abstract public MongoTemplate getMongoTemplate(MongoMappingContext context) throws Exception;
}

不同数据源都继承改类,创建对应的MongoDbFactory,都实现getMongoTemplate方法

MongoClientOptions配置

配置属性接收对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@Data
@Component
@ConfigurationProperties(prefix = "spring.data.mongodb.option")
public class MongoOptionProperties {

private Integer minConnectionsPerHost = 0;
private Integer maxConnectionsPerHost = 100;
private Integer threadsAllowedToBlockForConnectionMultiplier = 5;
private Integer serverSelectionTimeout = 30000;
private Integer maxWaitTime = 120000;
private Integer maxConnectionIdleTime = 0;
private Integer maxConnectionLifeTime = 0;
private Integer connectTimeout = 10000;
private Integer socketTimeout = 0;
@Deprecated
private Boolean socketKeepAlive = false;
private Boolean sslEnabled = false;
private Boolean sslInvalidHostNameAllowed = false;
private Boolean alwaysUseMBeans = false;
private Integer heartbeatConnectTimeout = 20000;
private Integer heartbeatSocketTimeout = 20000;
private Integer minHeartbeatFrequency = 500;
private Integer heartbeatFrequency = 10000;
private Integer localThreshold = 15;
}

注册MongoClientOptions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@Configuration
public class MongoConfig {

@Bean
public MongoClientOptions.Builder builder(MongoOptionProperties mongoOptionProperties) {
return new MongoClientOptions.Builder()
.minConnectionsPerHost(mongoOptionProperties.getMinConnectionsPerHost())
.connectionsPerHost(mongoOptionProperties.getMaxConnectionsPerHost())
.threadsAllowedToBlockForConnectionMultiplier(mongoOptionProperties.getThreadsAllowedToBlockForConnectionMultiplier())
.serverSelectionTimeout(mongoOptionProperties.getServerSelectionTimeout())
.maxWaitTime(mongoOptionProperties.getMaxWaitTime())
.maxConnectionIdleTime(mongoOptionProperties.getMaxConnectionIdleTime())
.maxConnectionLifeTime(mongoOptionProperties.getMaxConnectionLifeTime())
.connectTimeout(mongoOptionProperties.getConnectTimeout())
.socketTimeout(mongoOptionProperties.getSocketTimeout())
.sslEnabled(mongoOptionProperties.getSslEnabled())
.sslInvalidHostNameAllowed(mongoOptionProperties.getSslInvalidHostNameAllowed())
.alwaysUseMBeans(mongoOptionProperties.getAlwaysUseMBeans())
.heartbeatConnectTimeout(mongoOptionProperties.getHeartbeatConnectTimeout())
.heartbeatSocketTimeout(mongoOptionProperties.getSocketTimeout())
.heartbeatFrequency(mongoOptionProperties.getHeartbeatFrequency())
.localThreshold(mongoOptionProperties.getLocalThreshold());
}
}

主配置类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Configuration
@ConfigurationProperties(prefix="spring.data.mongodb.primary")
@EnableMongoRepositories(basePackages = "com.xx.repo.primary", mongoTemplateRef = "primaryMongo")
public class ApiPlatformMongoTemplate extends BaseMongoConfig {

@Autowired
private MongoClientOptions.Builder builder;

@Primary
@Override
@Bean("primaryMongo")
@SuppressWarnings("SpringJavaAutowiringInspection")
public MongoTemplate getMongoTemplate(MongoMappingContext context) throws Exception {
MongoDbFactory mongoDbFactory = mongoDbFactory(builder);
//去除保存实体时,spring data mongodb 自动添加的_class字段
MappingMongoConverter converter = new MappingMongoConverter(new DefaultDbRefResolver(mongoDbFactory), context);
converter.setTypeMapper(new DefaultMongoTypeMapper(null));
return new MongoTemplate(mongoDbFactory, converter);
}
}

从配置类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Configuration
@ConfigurationProperties(prefix="spring.data.mongodb.slave")
@EnableMongoRepositories(basePackages = "com.xx.repo.slave", mongoTemplateRef = "slaveMongo")
public class JdMongoTemplate extends BaseMongoConfig {

@Autowired
private MongoClientOptions.Builder builder;

@Override
@Bean("slaveMongo")
@SuppressWarnings("SpringJavaAutowiringInspection")
public MongoTemplate getMongoTemplate(MongoMappingContext context) throws Exception {
MongoDbFactory mongoDbFactory = mongoDbFactory(builder);
//去除保存实体时,spring data mongodb 自动添加的_class字段
MappingMongoConverter converter = new MappingMongoConverter(new DefaultDbRefResolver(mongoDbFactory), context);
converter.setTypeMapper(new DefaultMongoTypeMapper(null));
return new MongoTemplate(mongoDbFactory, converter);
}
}

使用MongoTemplate

MongoTemplate支持Repository方式操作数据的所有方法;数据存储遵循了MongoDB数据结构松散、存储方便的特点,支持泛型存储到指定DBCollection中;动态collectionName,数据索引,POJO字段不一,map集合等都能很好的支持;也拥有save方法,新数据会进行新增,有记录进行更新;查询支持方法查询,原生查询,执行命令行等多种方式。

  • 注入
1
2
3
@Autowired
@Qualifier("slaveMongo")
private MongoTemplate mongoTemplate;
  • 保存
1
2
mongoTemplate.save(objectToSave, collectionName);
mongoTemplate.insert(objectToSave, collectionName);
  • 查询
1
2
3
AggregationResults<O> results = mongoTemplate.aggregate(aggregation, collectionName, outputType);
List<T> list = mongoTemplate.find(query, entityClass);
Document document = mongoTemplate.executeCommand(jsonCommand);
  • 删除
1
DeleteResult result = mongoTemplate.remove(object, collectionName);
文章作者: 今晚早睡
文章链接: https://www.chensubao.com/article/48fa1066.html
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 洛 苏り

评论