Java 開發筆記16

sensen~||^_^|||&發表於2024-07-04
@Override
public int saveBroadcastStatusInfo(String bureauCode, String stationCode, List<BroadcastInfoDTO> broadcastInfoDTOList) {
// 轉為 deviceId - this map集合
Map<String, BroadcastStatus> deviceIdThisMap = broadcastInfoDTOList.stream().map(o -> {
BroadcastStatus target = new BroadcastStatus();
// BeanUtils.copyProperties(o, target);
target.setDeviceId(o.getDeviceID());
target.setDeviceName(o.getDeviceName());
target.setDeviceClass(o.getDeviceClass());
target.setOnlineStatus(o.getStatus().getOnlineStatus());
target.setFaultState(o.getStatus().getFaultState());
target.setFaultDescribe(o.getStatus().getFaultDescribe());
target.setOcupyState(o.getStatus().getOcupyState());
target.setOcupyDescribe(o.getStatus().getOcupyDescribe());
target.setTemp(o.getStatus().getTemp());
target.setBureauCode(bureauCode);
target.setStationCode(stationCode);
target.setCreateTime(new Date());
target.setModifyTime(new Date());
return target;
}).collect(Collectors.toMap(BroadcastStatus::getDeviceId, BroadcastStatus -> BroadcastStatus));

// 獲取當前車站所有資料集合
LambdaQueryWrapper<BroadcastStatus> queryWrapper = new LambdaQueryWrapper<BroadcastStatus>().eq(BroadcastStatus::getBureauCode, bureauCode).eq(BroadcastStatus::getStationCode, stationCode);
List<BroadcastStatus> dbAllList = broadcastStatusMapper.selectList(queryWrapper);

// 資料庫當前裝置id集合
Set<String> dbDeviceIds = dbAllList.stream().map(BroadcastStatus::getDeviceId).collect(Collectors.toSet());

// 非同步更新
CompletableFuture<Integer> updateFuture = CompletableFuture.supplyAsync(() -> {
List<BroadcastStatus> upList = deviceIdThisMap.keySet().stream().filter(dbDeviceIds::contains).map(deviceIdThisMap::get).collect(Collectors.toList());
int size = 0;
if (!CollectionUtils.isEmpty(upList)) {
size = broadcastStatusMapper.batchUpdate(bureauCode, stationCode, upList);
}
return size;
}, executor);


// 非同步插入資料
CompletableFuture<Integer> insertFuture = CompletableFuture.supplyAsync(() -> {
List<BroadcastStatus> insertList = deviceIdThisMap.keySet().stream().filter(deviceId -> !dbDeviceIds.contains(deviceId)).map(deviceIdThisMap::get).collect(Collectors.toList());
int size = 0;
if (!CollectionUtils.isEmpty(insertList)) {
size = broadcastStatusMapper.batchInsert(insertList);
}
return size;
}, executor);

// //TODO 廣播狀態插入歷史記錄表
// List<BroadcastStatus> collect = deviceIdThisMap.keySet().stream().map(deviceIdThisMap::get).collect(Collectors.toList());
// if(!CollectionUtils.isEmpty(collect)) {
// broadcastStatusHistoryMapper.batchInsertHistory(collect);
// }

try {
Integer updateSize = updateFuture.get();
Integer insertSize = insertFuture.get();
return insertSize + updateSize;
} catch (InterruptedException | ExecutionException e) {
log.error("裝置狀態資訊-廣播狀態資訊儲存錯誤:", e);
}

return 0;
}

相關文章