NoWarnDataJob.java 12.4 KB
package com.skua.modules.alarm.quartz;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.skua.core.util.chuanglan.HttpSenderMsg;
import com.skua.core.util.push.IPushService;
import com.skua.core.util.push.MessageEntity;
import com.skua.core.util.push.PushMessageFactory;
import com.skua.modules.alarm.entity.AlarmMessageHistory;
import com.skua.modules.alarm.entity.AlarmRecordHistory;
import com.skua.modules.alarm.service.AlarmMessageHistoryService;
import com.skua.modules.alarm.service.AlarmRecordHistoryService;
import com.skua.modules.alarm.service.AlarmRuleConfigService;
import com.skua.modules.alarm.vo.AlarmRuleAndAlarmRuleLevelVO;
import com.skua.modules.quartz.util.TimeUtils;
import com.skua.modules.system.entity.SysUser;
import com.skua.modules.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 采集数据报警
 */
@Slf4j
public class NoWarnDataJob implements Job {

    @Autowired
    private AlarmRuleConfigService alarmRuleConfigService;
    @Autowired
    private AlarmRecordHistoryService alarmRecordHistoryService;
    @Autowired
    private AlarmMessageHistoryService alarmMessageHistoryService;
    @Autowired
    private ISysUserService sysUserService;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
    	System.out.println("********30天异常数据监测服务开启********");
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateNowStr = sdf.format(d);
    	String nowDateTime = dateNowStr + " 23:59:59";

        Calendar now = Calendar.getInstance();
        String month = "01";
        if((now.get(Calendar.MONTH) + 1)>9){
            month = "" + (now.get(Calendar.MONTH) + 1);
        }else{
            month = "0" + (now.get(Calendar.MONTH) + 1);
        }
        String lastDateTime = now.get(Calendar.YEAR) +"-"+ month +"-"+ now.get(Calendar.DAY_OF_MONTH) + " 00:00:00";

        //30天无报警预警指标告警
        //查询需要实时数据报警厂的信息和报警规则字段的集合
        List<AlarmRuleAndAlarmRuleLevelVO> list = alarmRuleConfigService.getAlarmList(nowDateTime,lastDateTime);
        //查询mysql数据超标警报
        sendMessage(list);
        System.out.println("********30天异常数据监测服务结束********");
    }

    private void sendMessage(List<AlarmRuleAndAlarmRuleLevelVO> list) {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");

        List<AlarmRecordHistory> alarmRecordHistoryList = new ArrayList<>();
        List<AlarmMessageHistory> alarmMessageHistoryList = new ArrayList<>();

        List<String> userList = new ArrayList<>();
        //获取需要发送短信的手机号
        list.forEach(alarmRuleAndAlarmRuleLevelVO -> {
            if(alarmRuleAndAlarmRuleLevelVO.getIsSendSms() == 1) {
                String[] userArr = alarmRuleAndAlarmRuleLevelVO.getAlarmSmsRecipient().split(",");

                for (int i=0; i < userArr.length;i++){
                    userList.add(userArr[i]);
                }
            }

        });

        QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
        if(userList.size() >0){
            sysUserQueryWrapper.in("id",userList);
        }
        List<SysUser> sysUserList = sysUserService.list(sysUserQueryWrapper);

        //用map存放用户信息和手机号信息
        Map<String,String> userPhoneMap = new HashMap<>();

        Map<String,String> userCidMap = new HashMap<>();

        sysUserList.forEach(sysUser -> {
            userPhoneMap.put(sysUser.getId(),sysUser.getPhone());
            userCidMap.put(sysUser.getId(), sysUser.getCid());
        });

        list.forEach((alarmRuleAndAlarmRuleLevelVO)->{
            //查询上一条报警是否处理,未处理就不新增报警记录
            //TODO 先从数据库中获取,后期优化放redis中
            QueryWrapper<AlarmRecordHistory> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("alarm_rule_level_id",alarmRuleAndAlarmRuleLevelVO.getAlarmRuleLevelId());
            queryWrapper.orderByDesc("record_time").last("limit 1");
            AlarmRecordHistory alarmRecordHistoryOne = alarmRecordHistoryService.getOne(queryWrapper);

            //获取上次信息发送的时间,如果满足则发送
            //TODO 先从数据库中获取,后期优化方redis中
            QueryWrapper<AlarmMessageHistory> alarmMessageHistoryQueryWrapper = new QueryWrapper<>();
            alarmMessageHistoryQueryWrapper.eq("alarm_rule_level_id",alarmRuleAndAlarmRuleLevelVO.getAlarmRuleLevelId());
            alarmMessageHistoryQueryWrapper.eq("alarm_send_type","1");
            alarmMessageHistoryQueryWrapper.orderByDesc("alarm_send_time").last("limit 1");
            AlarmMessageHistory messageHistoryOne = alarmMessageHistoryService.getOne(alarmMessageHistoryQueryWrapper);

            String msgContent = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+","+alarmRuleAndAlarmRuleLevelVO.getFactoryName()+
                    "采集数据:"+alarmRuleAndAlarmRuleLevelVO.getAlarmParamName()+" 距当前时间30天无预警记录,请提高警惕!";
            Date lastTime = null;
            //如果数据库没有上次时间,则设置一个默认时间
            if(messageHistoryOne != null){
                lastTime = messageHistoryOne.getAlarmSendTime();
            }else{
                try {
                    lastTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2020-01-01 00:00:00");
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            //如果没有上条记录或者处理状态(0:未处理,1:已处理)为已处理
            if(alarmRecordHistoryOne == null || alarmRecordHistoryOne.getHandleStatus() == 1){

                AlarmRecordHistory alarmRecordHistory = new AlarmRecordHistory();
                //手动创建UUID,用于报警自动送审
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");

                alarmRecordHistory.setId(uuid);
                alarmRecordHistory.setAlarmParamName(alarmRuleAndAlarmRuleLevelVO.getAlarmParamName());
                alarmRecordHistory.setAlarmRuleLevelId(alarmRuleAndAlarmRuleLevelVO.getAlarmRuleLevelId());

                alarmRecordHistory.setAlarmRuleType(alarmRuleAndAlarmRuleLevelVO.getAlarmRuleType());
                alarmRecordHistory.setAlarmParamType(alarmRuleAndAlarmRuleLevelVO.getAlarmParamType());

                alarmRecordHistory.setRecordTime(new Date());
                alarmRecordHistory.setAlarmParamUnit(alarmRuleAndAlarmRuleLevelVO.getAlarmParamUnit());
                alarmRecordHistory.setFactoryId(alarmRuleAndAlarmRuleLevelVO.getFactoryId());
                alarmRecordHistory.setHandleStatus(0);

                alarmRecordHistory.setAlarmContent(msgContent);
                alarmRecordHistoryList.add(alarmRecordHistory);

            }

            //判断是否需要发送短信,1表示发送
            if(alarmRuleAndAlarmRuleLevelVO.getIsSendSms() == 1){
                //判读是否在发送时间内
                Date allowStartDate = null;
                Date allowEndDate = null;
                Date nowDate = null;
                try {
                    allowEndDate = simpleDateFormat.parse(alarmRuleAndAlarmRuleLevelVO.getSmsAllowSendTime().split("-")[1]);
                    allowStartDate = simpleDateFormat.parse(alarmRuleAndAlarmRuleLevelVO.getSmsAllowSendTime().split("-")[0]);
                    nowDate = simpleDateFormat.parse(simpleDateFormat.format(new Date()));
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                //如果在发送时间内,则发送
                if(isEffectiveDate(nowDate,allowStartDate,allowEndDate )){

                    //判断是否满足短信发送频率,将两个时间转为毫秒
                    Long lastTimeLong = lastTime.getTime();

                    Long nowDateLong = new Date().getTime();

                    if(nowDateLong - lastTimeLong > Double.parseDouble(alarmRuleAndAlarmRuleLevelVO.getSmsSendFrequency())*60*60*1000){

                        //获取报警接收人的手机号

                        StringBuilder phoneStringBuilder = new StringBuilder();

                        String[] userArr = alarmRuleAndAlarmRuleLevelVO.getAlarmSmsRecipient().split(",");

                        for (int i=0; i < userArr.length;i++){

//                                phoneStringBuilder.append(",");
//                                phoneStringBuilder.append(userPhoneMap.get(userArr[i]));
                            //发送短信
//                                HttpSenderMsg.sendMsg(msgContent, userPhoneMap.get(userArr[i]));
                            //移动端消息推送
                            MessageEntity messageEntity = new MessageEntity();
                            messageEntity.setMessageTitle("实时数据异常提示");
                            messageEntity.setMessageBody(msgContent);
                            List<String> cidList = new ArrayList<String>();
                            String cid = userCidMap.get(userArr[i]);
                            if(!StringUtils.isEmpty(cid)) {
                                cidList.add(cid);
                                messageEntity.setReceiveUserCid(cidList);
                                IPushService appPushService = PushMessageFactory.getPushService("MOB");
                                appPushService.pushMessage(messageEntity);
                            }
                        }

//                            String phone = phoneStringBuilder.toString().replaceFirst(",","");

                        //将发送的短信保存到数据库
                        AlarmMessageHistory alarmMessageHistory = new AlarmMessageHistory();

                        alarmMessageHistory.setAlarmRuleLevelId(alarmRuleAndAlarmRuleLevelVO.getAlarmRuleLevelId());
                        alarmMessageHistory.setAlarmSendUser(alarmRuleAndAlarmRuleLevelVO.getAlarmSmsRecipient());
//                            alarmMessageHistory.setAlarmSendPhone(phone);
                        alarmMessageHistory.setAlarmSendTime(new Date());
                        alarmMessageHistory.setAlarmSendContent(msgContent);
                        alarmMessageHistory.setAlarmParamName(alarmRuleAndAlarmRuleLevelVO.getAlarmParamName());
                        alarmMessageHistory.setAlarmRuleLevelId(alarmRuleAndAlarmRuleLevelVO.getAlarmRuleLevelId());
                        alarmMessageHistory.setAlarmSendType(1);
                        alarmMessageHistory.setAlarmRuleType(alarmRuleAndAlarmRuleLevelVO.getAlarmRuleType());
                        alarmMessageHistory.setAlarmParamType(alarmRuleAndAlarmRuleLevelVO.getAlarmParamType());
                        alarmMessageHistory.setAlarmParamUnit(alarmRuleAndAlarmRuleLevelVO.getAlarmParamUnit());
                        alarmMessageHistory.setFactoryId(alarmRuleAndAlarmRuleLevelVO.getFactoryId());

                        alarmMessageHistoryList.add(alarmMessageHistory);
                    }
                }
            }
        });
        alarmMessageHistoryService.saveBatch(alarmMessageHistoryList);
        alarmRecordHistoryService.saveBatch(alarmRecordHistoryList);


    }

    /**
     * 判断当前时间是否在[startTime, endTime]区间,注意时间格式要一致
     *
     * @param nowTime 当前时间
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return
     * @author xiechao
     */
    public static boolean isEffectiveDate(Date nowTime, Date startTime, Date endTime) {
        if (nowTime.getTime() == startTime.getTime()
                || nowTime.getTime() == endTime.getTime()) {
            return true;
        }

        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(startTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }


    }


}