1.首先引入maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
2.yml文件参数设置
spring
data:
mongodb:
primary:
uri: mongodb://sjj:sjj@127.0.0.1:27017/admin
database: data-center
max-wait-time: 120000
connect-timeout: 20000
socket-timeout: 20000
heartbeat-socket-timeout: 20000
heartbeat-connect-timeout: 20000
secondary:
uri: mongodb://sjj:sjj@127.0.0.1:27017/admin
database: ems
max-wait-time: 120000
connect-timeout: 20000
socket-timeout: 20000
heartbeat-socket-timeout: 20000
heartbeat-connect-timeout: 20000
此处设置多余参数的原因
:有时候在查询mongodb数据的时候 会出现socketOpenTime超时的情况或者socketTImeOut情况,因为MongoTemplate的默认设置是 socketTimOut=0,为了避免类似的情况出现,我们可以自定义加大时间,避免这种情况的出现。
3.设置配置类
先将yml的数据封装成一个类读取进来
package com.irootech.data.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
@Component
@Validated
@Data
@ConfigurationProperties(prefix = "spring.data.mongodb.primary")
public class MongoPropertie {
@NotEmpty
private String uri;
@NotBlank
private String database;
private Integer maxWaitTime;
private Integer connectTimeout;
private Integer socketTimeout;
private Integer heartbeatConnectTimeout;
private Integer heartbeatSocketTimeout;
}
在设置配置类 自定义mongoTemplate
package com.irootech.data.config;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoClientURI;
import org.springframework.beans.factory.annotation.Qualifier;
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;
@SuppressWarnings("ALL")
@Configuration
public class PrimaryMongoConfig {
@Primary
@Bean(name = "primaryMongoProperties")
public MongoPropertie primaryMongoProperties() {
return new MongoPropertie();
}
@Primary
@Bean(name = "primaryMongoTemplate")
public MongoTemplate primaryMongoTemplate(@Qualifier("primaryMongoProperties") MongoPropertie mongoProperties) throws Exception {
return new MongoTemplate(mongoDatabaseFactory(mongoProperties), mongoProperties.getDatabase());
}
@Bean(name = "mongoClient")
public MongoClient mongoDatabaseFactory(@Qualifier("primaryMongoProperties") MongoPropertie mongoProperties) {
MongoClientOptions.Builder builder = MongoClientOptions.builder().connectTimeout(mongoProperties.getConnectTimeout())
.maxWaitTime(mongoProperties.getMaxWaitTime())
.heartbeatSocketTimeout(mongoProperties.getHeartbeatSocketTimeout())
.socketTimeout(mongoProperties.getSocketTimeout())
.heartbeatConnectTimeout(mongoProperties.getHeartbeatConnectTimeout());
MongoClient mongoClient = new MongoClient(new MongoClientURI(mongoProperties.getUri(),builder));
return mongoClient;
}
}
知识点:
@Primary
在spring 中使用注解,常使用@Autowired, 默认是根据类型Type来自动注入的。但有些特殊情况,对同一个接口,可能会有几种不同的实现类,而默认只会采取其中一种的情况下 @Primary 的作用就出来了。或者说 如果在配置类中有多个相同的,加此注解的就会默认先使用这个
@Qualifier
有多个实现,注入时用来标明用哪个
自定义的MongoTemplate 需要先mongoclient来构建,Mongclient又需要uri等多种方式来构建。具体可以看源码,里边提供了很多的构建方式。比如说 自定义的参数主要是通过builer来进行构建的。
3.使用
package com.irootech.data.repository.impl;
import com.irootech.data.entity.MetricMinuteValue;
import com.irootech.data.entity.param.RequestTimeParam;
import com.irootech.data.entity.param.RequestTimesDataParam;
import com.irootech.data.repository.IMetricMinuteValueRepository;
import com.irootech.data.util.IdUtil;
import com.mongodb.MongoClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
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.Repository;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @author kongweiteng
*/
@Repository
public class MetricMinuteValueRepositoryImpl implements IMetricMinuteValueRepository {
@Autowired
private MongoTemplate mongoTemplate;
@Override
public Map<String, List<MetricMinuteValue>> segment(RequestTimeParam requestTimeParam) {
List<MetricMinuteValue> metricMinuteValues = mongoTemplate.find(
Query.query(Criteria.where(MetricMinuteValue.Fields.deviceUuid)
.in(requestTimeParam.getDeviceUuid())
.and(MetricMinuteValue.Fields.tenantUuid)
.is(requestTimeParam.getTenantUuid())
.and(MetricMinuteValue.Fields.time)
.lte(requestTimeParam.getEnd())
.gte(requestTimeParam.getStart())
).with(Sort.by(
Sort.Order.desc(MetricMinuteValue.Fields.time)
)),
MetricMinuteValue.class
);
Map<String, List<MetricMinuteValue>> collect = metricMinuteValues.stream().collect(Collectors.groupingBy(MetricMinuteValue::getDeviceUuid));
return collect;
}
@Override
public List<MetricMinuteValue> condition(RequestTimesDataParam requestTimesDataParam) {
List<String> ids = new ArrayList<>();
requestTimesDataParam.getDeviceUuid().forEach(e -> {
requestTimesDataParam.getTime().forEach(t -> {
ids.add(IdUtil.id(requestTimesDataParam.getTenantUuid(), e, t));
});
});
List<MetricMinuteValue> metricMinuteValues = mongoTemplate.find(
Query.query(Criteria.where(MetricMinuteValue.Fields.id)
.in(ids)
).with(Sort.by(
Sort.Order.desc(MetricMinuteValue.Fields.time)
)),
MetricMinuteValue.class
);
// Map<String, List<MetricMinuteValue>> collect = metricMinuteValues.stream().collect(Collectors.groupingBy(MetricMinuteValue::getDeviceUuid));
return metricMinuteValues;
}
}
版权声明:本文为weixin_43928997原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。