原因
之前使用Navicat看到時間存在時區(qū)問題恬偷,所以在后臺代碼都增加了8小時,但后來使用metabse時發(fā)現(xiàn)類似工具都支持修改時區(qū)废膘,例如Robo 3T等椒振。所以產(chǎn)生了此需求
步驟
- 修改原來的代碼效诅,把所有的增加/減少8小時碰酝,時區(qū)差的相關(guān)代碼都移除
- 重啟服務(wù)
- 重啟時使用接口調(diào)用修改時間的方法霎匈,確保新數(shù)據(jù)不受影響的同時,老數(shù)據(jù)全部處理
- 關(guān)鍵代碼
@Override
public void init() {
// 構(gòu)建聚合查詢的結(jié)果總數(shù)
Criteria criteria = new Criteria();
Aggregation countAggregation = newAggregation(
match(criteria),
group().count().as("total_count")
);
AggregationResults<Document> results = mongoTemplate.aggregate(countAggregation, "flow_tracking", Document.class);
if (results.getMappedResults().size() <= 0){
return;
}
Integer resultsSize = (Integer) results.getMappedResults().get(0).get("total_count");
/**
* 如果不存在空的數(shù)據(jù)砰粹,則結(jié)束方法
*/
if (resultsSize > 0) {
/**
* 根據(jù)結(jié)果總數(shù)分頁處理
*/
Integer cycleNum = (resultsSize / 10000) + 1;
for (Integer i = 0; i < cycleNum; i++) {
Integer skipNum = i==0?0:i*10000;
BulkOperations operations = mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED, "flow_tracking");
Aggregation aggregation = newAggregation(
match(criteria),
project("add_time","start_time","end_time"),
skip(skipNum),
limit(10000)
);
AggregationResults<Document> documents = mongoTemplate.aggregate(aggregation, "flow_tracking", Document.class);
List<Pair<Query, Update>> updateList = new LinkedList<>();
documents.getMappedResults().forEach(data -> {
Query query = new Query(new Criteria("_id").is(data.get("_id")));
Update update = new Update();
update.set("add_time", new Timestamp(data.getDate("add_time").getTime()).toLocalDateTime().minusHours(8));
update.set("start_time", new Timestamp(data.getDate("start_time").getTime()).toLocalDateTime().minusHours(8));
update.set("end_time", new Timestamp(data.getDate("end_time").getTime()).toLocalDateTime().minusHours(8));
Pair<Query, Update> updatePair = Pair.of(query, update);
updateList.add(updatePair);
});
operations.updateMulti(updateList);
operations.execute();
}
}
}
后續(xù)
查詢時使用Robo3T設(shè)置時區(qū)唧躲,Navicat查看是仍會顯示比正常時間少8小時