Java 开发笔记16

异步新增和更新:
@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;
}
posted @ 2024-07-04 16:08  sensen~||^_^|||&  阅读(2)  评论(0编辑  收藏  举报