public class MongoConn {
/**
* 需要密码认证方式连接
*/
public static MongoClient getConnect(String ip, String port, String userName, String password, String dataBaseName) {
List adds = new ArrayList<>();
//ServerAddress()两个参数分别为 服务器地址 和 端口
ServerAddress serverAddress = new ServerAddress(ip, Integer.parseInt(port));
adds.add(serverAddress);
//List credentials = new ArrayList<>();
//MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
MongoCredential mongoCredential = MongoCredential.createScramSha1Credential(userName, dataBaseName, password.toCharArray());
//credentials.add(mongoCredential);
MongoClientOptions mongoClientOptions = new MongoClientOptions.Builder()
.maxConnectionLifeTime(60000)
.maxWaitTime(10000)
.maxConnectionIdleTime(10000)
.heartbeatConnectTimeout(1000)
.serverSelectionTimeout(30000).build();
//通过连接认证获取MongoDB连接
MongoClient mongoClient = new MongoClient(adds, mongoCredential, mongoClientOptions);
//返回连接数据库对象
return mongoClient;
}
}
引用:
/**
* 缓存所有项目包数
*/
@Scheduled(cron = "0 0 * * * *")
public void updateMongoDbPackageData() {
//获取所有项目
Map map = SynServerInfoTask.projectInfos;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if (map.size() > 0) {
log.info("定时任务开始更新所有项目数据包缓存,更新时间:{}", simpleDateFormat.format(new Date()));
Set> entries = map.entrySet();
long systemTime = System.currentTimeMillis();
double sub = DataUtils.sub(systemTime, 1000 * 60 * 60);
String startTime = simpleDateFormat.format(new Date((long) sub));
String endTime = simpleDateFormat.format(new Date((systemTime)));
for (Map.Entry sr : entries) {
String key = sr.getKey();
String value = sr.getValue();
MongoClient mongoClient = null;
MongoCursor periodData = null;
try {
List list = new LinkedList<>();
JSONObject mongoServerInfo = serverInfoBaseService.getServerInfo(key, BaseConstants.mongodbType);
if (StringUtils.isBlank(mongoServerInfo.getString(BaseConstants.databaseName))) {
continue;
}
mongoClient = MongoConn.getConnect(mongoServerInfo.getString(BaseConstants.ip), mongoServerInfo.getString(BaseConstants.port), mongoServerInfo.getString(BaseConstants.username), mongoServerInfo.getString(BaseConstants.password), mongoServerInfo.getString(BaseConstants.databaseName));
MongoDatabase database = mongoClient.getDatabase(mongoServerInfo.getString(BaseConstants.databaseName));
periodData = MongodbUtil.getPeriodData(database, mongoServerInfo.getString(BaseConstants.tableName), startTime, endTime, "systime", "0", "systime");
while (periodData.hasNext()) {
Document next = periodData.next();
list.add(next.getString("systime"));
}
String projectKey = key.concat(BaseConstants.DATAPACKAGE);
String str = (String) redisTemplate.opsForValue().get(projectKey);
if (null != str) {
List timeList = Arrays.asList(str.split(",")).stream().map(s -> (s.trim())).collect(Collectors.toList());
list.addAll(timeList);
}
String jsonStr = StringUtils.join(list.toArray(), ",");
redisTemplate.opsForValue().set(projectKey, jsonStr);
log.info("定时任务更新时间包数据缓存成功,项目名:{},时间:{}", value, simpleDateFormat.format(new Date()));
} catch (CommonException e) {
e.printStackTrace();
} finally {
if (null != periodData) {
periodData.close();
}
if (null != mongoClient) {
mongoClient.close();
}
}
}
log.info("定时任务更新时间包数据缓存结束");
}
}
工具类:
public class MongodbUtil {
/**
* 获取多时间点mongo数据
* @param mongoDatabase
* @param collectionName
* @param timeList
* @param dataType
* @return
*/
public static MongoCursor getMulTimeData(MongoDatabase mongoDatabase, String collectionName, List timeList, String dataType){
Bson systimes = Filters.in("systime", timeList);
Bson dateType = Filters.eq("datatype", dataType);
Bson queryBson = Filters.and(systimes, dateType);
FindIterable documentIterable = mongoDatabase.getCollection(collectionName).find(queryBson);
MongoCursor cursor = documentIterable.iterator();
return cursor;
}
/**
* 获取指定时间段mongo数据
* @param mongoDatabase
* @param collectionName
* @param startTime
* @param endTime
* @param orderColumn
* @param dataType
* @param fieldName
* @return
*/
public static MongoCursor getPeriodData(MongoDatabase mongoDatabase, String collectionName, String startTime, String endTime, String orderColumn, String dataType,String fieldName ) {
Bson stimeBson = Filters.gte("systime", startTime);
Bson etimeBson = Filters.lte("systime", endTime);
Bson dateType = Filters.eq("datatype", dataType);
BasicDBObject field = new BasicDBObject();
field.put(fieldName,1);
Bson sort = Sorts.ascending(orderColumn);
Bson queryBson = Filters.and(stimeBson, etimeBson, dateType);
FindIterable documentIterable = mongoDatabase.getCollection(collectionName).find(queryBson).projection(field).sort(sort);
MongoCursor cursor = documentIterable.iterator();
return cursor;
}