KafkaBatteryConsumer.java 1.9 KB
package cn.com.glsx.kafka.queue.consumer;

import cn.com.glsx.kafka.model.BatteryDTO;
import cn.com.glsx.kafka.queue.base.MessageReceiver;
import cn.com.glsx.stdinterface.api.BatteryClient;
import cn.com.glsx.stdinterface.dto.DevicePowerDTO;
import com.alibaba.fastjson.JSONObject;
import com.glsx.plat.common.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.nio.charset.Charset;
import java.util.Optional;

/**
 * 消费电量数据
 *
 * @author xiangyanlin
 * @date 2022/4/12
 */
@Slf4j
public class KafkaBatteryConsumer extends MessageReceiver {

    @Autowired
    private BatteryClient batteryClient;

    @Override
    public void processMessage(String topic, byte[] message) throws Exception {
        String devicePowerJson = new String(message, Charset.defaultCharset());
        log.info("{}", "电量消息:" + devicePowerJson);
        if(StringUtils.isEmpty(devicePowerJson)) {
            return;
        }
        BatteryDTO devicePower = JSONObject.parseObject(devicePowerJson, BatteryDTO.class);
        //电量信息保存入库
        DevicePowerDTO devicePowerDTO = convert(devicePower);
        batteryClient.saveBatteryInfo(devicePowerDTO);
    }

    public DevicePowerDTO convert(BatteryDTO batteryDTO) {
        DevicePowerDTO devicePowerDTO = new DevicePowerDTO();
        Optional.ofNullable(batteryDTO.getId())
                .map(Integer::longValue)
                .ifPresent(devicePowerDTO::setId);
        devicePowerDTO.setSn(batteryDTO.getSn());
        devicePowerDTO.setAlarmTime(DateUtils.parse(batteryDTO.getAlarmTime()));
        devicePowerDTO.setSoc(batteryDTO.getSOC());
        devicePowerDTO.setCreatedDate(DateUtils.parse(batteryDTO.getCreateTime()));
        devicePowerDTO.setUpdatedDate(DateUtils.parse(batteryDTO.getUpdateTime()));
        return devicePowerDTO;
    }
}