diff options
10 files changed, 251 insertions, 317 deletions
diff --git a/nz-admin/src/main/java/com/nis/common/thread/RedisCacheSubscribe.java b/nz-admin/src/main/java/com/nis/common/thread/RedisCacheSubscribe.java index 7bf5cb83..ed3b74a9 100644 --- a/nz-admin/src/main/java/com/nis/common/thread/RedisCacheSubscribe.java +++ b/nz-admin/src/main/java/com/nis/common/thread/RedisCacheSubscribe.java @@ -4,9 +4,13 @@ import java.util.Map; import javax.servlet.Filter; +import com.alibaba.fastjson.JSONPath; +import com.nis.common.utils.Tool; +import com.nis.modules.report.job.ReportJobManager; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.crazycake.shiro.RedisCacheManager; import org.crazycake.shiro.RedisSessionDAO; +import org.quartz.SchedulerException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.data.redis.connection.Message; @@ -48,6 +52,9 @@ public class RedisCacheSubscribe implements MessageListener{ @Autowired private SNMPTrapReceiver trapReceiver; + + @Autowired + private ReportJobManager reportJobManager; @Override public void onMessage(Message message, byte[] pattern) { @@ -78,6 +85,31 @@ public class RedisCacheSubscribe implements MessageListener{ redisSessionDao.setExpire(Integer.valueOf(sessionTimeOut) * 60); mySessionManager.setGlobalSessionTimeout(Integer.valueOf(sessionTimeOut) * 60 * 1000); } + + // dashboard report + if(StrUtil.equals(topic, Constant.REPORT_TOPIC_NAME)){ + log.info("Report consumer message, report begin ..."); + log.info("consumer message :{}", value); + String reportEnable = JSONPath.read(value, "report.enable").toString(); + String panelId = JSONPath.read(value, "panelId").toString(); + + if (Tool.StrUtil.equalsIgnoreCase("true", StrUtil.nullToDefault(reportEnable, "false"))) { + try { + reportJobManager.delJobByName(panelId); + reportJobManager.createReportJob(value, panelId); + log.info("createReportJob success."); + } catch (SchedulerException e) { + log.error("report job create or update error,panelId:{}", e, panelId); + } + } else { + try { + reportJobManager.delJobByName(panelId); + } catch (SchedulerException e) { + log.error("delete report job error, panelId:{}", panelId, e); + } + } + log.info("Report consumer message, report finished"); + } } @Bean @@ -87,6 +119,7 @@ public class RedisCacheSubscribe implements MessageListener{ container.setConnectionFactory(redisTemplate.getConnectionFactory()); container.addMessageListener(listenerAdapter, new PatternTopic(Constant.SYSCONFIG_SESSION_TIMEOUT_KEY)); container.addMessageListener(listenerAdapter, new PatternTopic(Constant.SYSCONFIG_SNMP_PORT_KEY)); + container.addMessageListener(listenerAdapter, new PatternTopic(Constant.REPORT_TOPIC_NAME)); return container; } diff --git a/nz-admin/src/main/java/com/nis/common/utils/Constant.java b/nz-admin/src/main/java/com/nis/common/utils/Constant.java index 02f5045c..21c51290 100644 --- a/nz-admin/src/main/java/com/nis/common/utils/Constant.java +++ b/nz-admin/src/main/java/com/nis/common/utils/Constant.java @@ -1104,6 +1104,13 @@ public class Constant { public static final String SYSCONFIG_SNMP_PORT_KEY = "snmp_trap_listen_port"; public static final String SYSCONFIG_SESSION_TIMEOUT_KEY = "session_timeout"; + public static final String REPORT_TOPIC_NAME = "report_topic"; + + public static final String REPORT_JOB_GROUP = "report_job_group"; + + // sys_config key + public static final String REPORT_EMAIL_TEMPLATE = "report_email_template"; + public static final String SETUP_FILE_NAME = "setup.json"; /** * aes 对称加密 密钥 diff --git a/nz-admin/src/main/java/com/nis/modules/panel/service/impl/VisualPanelServiceImpl.java b/nz-admin/src/main/java/com/nis/modules/panel/service/impl/VisualPanelServiceImpl.java index 23e3f915..a7d48dc6 100644 --- a/nz-admin/src/main/java/com/nis/modules/panel/service/impl/VisualPanelServiceImpl.java +++ b/nz-admin/src/main/java/com/nis/modules/panel/service/impl/VisualPanelServiceImpl.java @@ -24,7 +24,6 @@ import com.nis.modules.panel.service.VisualChartService; import com.nis.modules.panel.service.VisualPanelService; import com.nis.modules.promserver.service.LokiserverService; import com.nis.modules.promserver.service.PromserverService; -import com.nis.modules.report.config.ReportConstant; import com.nis.modules.report.job.ReportJobManager; import com.nis.modules.stat.service.impl.StatServiceImpl; import com.nis.modules.sys.dao.SysConfigDao; @@ -36,11 +35,11 @@ import com.nis.modules.sys.service.SysConfigService; import com.nis.modules.sys.service.SysDictService; import com.nis.modules.sys.service.SysUserStarredService; import com.nis.modules.sys.shiro.ShiroUtils; -import com.nis.modules.topic.service.TopicService; import org.apache.commons.collections.CollectionUtils; import org.quartz.SchedulerException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; +import org.springframework.data.redis.core.RedisTemplate; import org.springframework.http.ResponseEntity; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.mock.web.MockHttpServletRequest; @@ -118,7 +117,7 @@ public class VisualPanelServiceImpl extends ServiceImpl<VisualPanelDao, VisualPa private MonitorEndpointService monitorEndpointService; @Autowired - private TopicService topicService; + private RedisTemplate redisTemplate; @Autowired private ReportJobManager reportJobManager; @@ -236,7 +235,7 @@ public class VisualPanelServiceImpl extends ServiceImpl<VisualPanelDao, VisualPa try { // 删除 Report job for (Integer panelId : allPanelIds) { - reportJobManager.findJobAndDelByGroup(panelId.toString()); + reportJobManager.delJobByName(panelId.toString()); } } catch (SchedulerException e) { log.error("Delete dashboard report job error", e); @@ -471,7 +470,7 @@ public class VisualPanelServiceImpl extends ServiceImpl<VisualPanelDao, VisualPa publishMap.put("panelId", panel.getId()); publishMap.putAll(JSONObject.parseObject(panel.getParam().toString(), Map.class)); - topicService.publishMessage(ReportConstant.REPORT_TOPIC_NAME, publishMap); + redisTemplate.convertAndSend(Constant.REPORT_TOPIC_NAME, JSONObject.toJSONString(publishMap)); } } @@ -514,7 +513,7 @@ public class VisualPanelServiceImpl extends ServiceImpl<VisualPanelDao, VisualPa publishMap.put("panelId", panel.getId()); publishMap.putAll(newParamMap); - topicService.publishMessage(ReportConstant.REPORT_TOPIC_NAME, publishMap); + redisTemplate.convertAndSend(Constant.REPORT_TOPIC_NAME, JSONObject.toJSONString(publishMap)); } } @@ -652,7 +651,7 @@ public class VisualPanelServiceImpl extends ServiceImpl<VisualPanelDao, VisualPa publishMap.put("panelId", panel.getId()); publishMap.putAll(JSONObject.parseObject(panel.getParam().toString(), Map.class)); - topicService.publishMessage(ReportConstant.REPORT_TOPIC_NAME, publishMap); + redisTemplate.convertAndSend(Constant.REPORT_TOPIC_NAME, JSONObject.toJSONString(publishMap)); } // 复制panel 下的 charts diff --git a/nz-admin/src/main/java/com/nis/modules/report/config/ReportConstant.java b/nz-admin/src/main/java/com/nis/modules/report/config/ReportConstant.java deleted file mode 100644 index 94a71b53..00000000 --- a/nz-admin/src/main/java/com/nis/modules/report/config/ReportConstant.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.nis.modules.report.config; - -/** - * report 常量类 - */ -public class ReportConstant { - - public static final String REPORT_TOPIC_NAME = "report_topic"; - - public static final String REPORT_JOB_NAME = "report_job"; - - public static final String REPORT_JOB_DATAMAP = "report_job_datamap"; - - // sys_config key - public static final String REPORT_EMAIL_TEMPLATE = "report_email_template"; - -} diff --git a/nz-admin/src/main/java/com/nis/modules/report/config/ReportConsumerListener.java b/nz-admin/src/main/java/com/nis/modules/report/config/ReportConsumerListener.java deleted file mode 100644 index 4e40cf2c..00000000 --- a/nz-admin/src/main/java/com/nis/modules/report/config/ReportConsumerListener.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.nis.modules.report.config; - -import cn.hutool.core.util.StrUtil; -import cn.hutool.log.Log; -import com.alibaba.fastjson.JSONPath; -import com.nis.common.utils.Constant; -import com.nis.common.utils.Tool; -import com.nis.modules.report.job.ReportJobManager; -import org.quartz.SchedulerException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.redis.connection.Message; -import org.springframework.data.redis.connection.MessageListener; -import org.springframework.data.redis.core.RedisTemplate; - -/** - * Report Consumer - */ -public class ReportConsumerListener implements MessageListener { - - private static Log log = Log.get(); - - @Autowired - private RedisTemplate redisTemplate; - - @Autowired - private ReportJobManager reportJobManager; - - @Override - public void onMessage(Message message, byte[] pattern) { - doBusiness(message); - } - - /** - * Consumer message - * - * @param message - */ - public void doBusiness(Message message) { - // 检查 haMode - String serverId = (String) redisTemplate.opsForValue().get(Constant.SYS_HA_LOCK); - if (!StrUtil.equals(serverId, Constant.SERVER_ID)) return; - - log.info("Report consumer message, report begin ..."); - - Object consumerMsg = redisTemplate.getValueSerializer().deserialize(message.getBody()); - log.info("consumer message :{}", consumerMsg.toString()); - - String consumerMsgJsonStr = consumerMsg.toString(); - String reportEnable = JSONPath.read(consumerMsgJsonStr, "report.enable").toString(); - String panelId = JSONPath.read(consumerMsgJsonStr, "panelId").toString(); - - if (Tool.StrUtil.equalsIgnoreCase("true", StrUtil.nullToDefault(reportEnable, "false"))) { - try { - // 先删后增 - reportJobManager.findJobAndDelByGroup(panelId); - - // 创建任务 - reportJobManager.createReportJob(consumerMsgJsonStr, panelId); - log.info("createReportJob success."); - } catch (SchedulerException e) { - log.error("report job create or update error,panelId:{}", e, panelId); - } - } else { - try { - // 先删后增 - reportJobManager.findJobAndDelByGroup(panelId); - } catch (SchedulerException e) { - log.error("delete report job error, panelId:{}", panelId, e); - } - } - log.info("Report consumer message, report finished"); - } - -} diff --git a/nz-admin/src/main/java/com/nis/modules/report/config/ReportTopicConfig.java b/nz-admin/src/main/java/com/nis/modules/report/config/ReportTopicConfig.java deleted file mode 100644 index 81adce75..00000000 --- a/nz-admin/src/main/java/com/nis/modules/report/config/ReportTopicConfig.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.nis.modules.report.config; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; -import org.springframework.data.redis.listener.ChannelTopic; -import org.springframework.data.redis.listener.RedisMessageListenerContainer; - -@Configuration -public class ReportTopicConfig { - - @Autowired - private LettuceConnectionFactory connectionFactory; - - @Bean - public ReportConsumerListener reportConsumerListener() { - return new ReportConsumerListener(); - } - - @Bean - public ChannelTopic reportTopic() { - return new ChannelTopic(ReportConstant.REPORT_TOPIC_NAME); - } - - /** - * 注册消息监听容器,使监听器和 topic 进行绑定 - */ - @Bean - public RedisMessageListenerContainer redisMessageListenerContainer() { - RedisMessageListenerContainer container = new RedisMessageListenerContainer(); - container.setConnectionFactory(connectionFactory); - container.addMessageListener(reportConsumerListener(), reportTopic()); - return container; - } - -} diff --git a/nz-admin/src/main/java/com/nis/modules/report/job/ReportJob.java b/nz-admin/src/main/java/com/nis/modules/report/job/ReportJob.java index 89f565c0..84623a19 100644 --- a/nz-admin/src/main/java/com/nis/modules/report/job/ReportJob.java +++ b/nz-admin/src/main/java/com/nis/modules/report/job/ReportJob.java @@ -1,21 +1,26 @@ package com.nis.modules.report.job; -import cn.hutool.core.io.FileUtil; +import cn.hutool.core.date.DateUnit; import cn.hutool.core.util.StrUtil; import cn.hutool.log.Log; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONPath; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.nis.common.utils.*; +import com.nis.common.utils.Constant; +import com.nis.common.utils.MailUtil; +import com.nis.common.utils.TemplateUtil; +import com.nis.common.utils.Tool; import com.nis.modules.panel.entity.VisualPanel; import com.nis.modules.panel.service.VisualPanelService; -import com.nis.modules.report.config.ReportConstant; import com.nis.modules.sys.entity.SysUserEntity; import com.nis.modules.sys.service.SysConfService; import com.nis.modules.sys.service.SysUserService; import freemarker.template.Template; import freemarker.template.TemplateException; -import org.quartz.*; +import org.quartz.DisallowConcurrentExecution; +import org.quartz.JobExecutionContext; +import org.quartz.JobExecutionException; +import org.quartz.JobKey; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.scheduling.quartz.QuartzJobBean; @@ -25,8 +30,11 @@ import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; import javax.mail.MessagingException; import java.io.File; import java.io.IOException; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.temporal.TemporalAdjusters; import java.util.*; -import java.util.Calendar; +import java.util.stream.Collectors; @Component @DisallowConcurrentExecution @@ -57,83 +65,150 @@ public class ReportJob extends QuartzJobBean { String serverId = (String) redisTemplate.opsForValue().get(Constant.SYS_HA_LOCK); if (!StrUtil.equals(serverId, Constant.SERVER_ID)) return; - log.info("dashboard report notific begin ..."); - JobDetail jobDetail = context.getJobDetail(); - - JobKey key = jobDetail.getKey(); + JobKey key = context.getJobDetail().getKey(); log.info(String.format("Job name: %s, Job group: %s", key.getName(), key.getGroup())); - String configJsonStr = jobDetail.getJobDataMap().get(ReportConstant.REPORT_JOB_DATAMAP).toString(); - - String receiversStr = JSONPath.read(configJsonStr, "report.receivers").toString(); - String panelId = key.getGroup(); - - if (StrUtil.isEmpty(receiversStr)) { - log.error("dashboard report receiver user is empty, panelId:{}", panelId); + String panelId = key.getName(); + VisualPanel visualPanel = visualPanelService.getById(panelId); + if (visualPanel == null) { + log.error("dashboard report panel not found, panelId:{}", panelId); return; } - List<String> receiverIds = JSONObject.parseArray(receiversStr, String.class); - List<SysUserEntity> userList = sysUserService.list(new LambdaQueryWrapper<SysUserEntity>().in(SysUserEntity::getId, receiverIds)); - if (receiverIds.size() != userList.size()) { - log.error("dashboard report receiver user not found, panelId:{}", panelId); - return; - } + // JOB 每天都执行,根据匹配规则,检查本次是否执行 + String configJsonStr = visualPanel.getParam().toString(); + Boolean isRun = this.checkJobIsRun(configJsonStr); + if (isRun) { + log.info("dashboard report notific begin ..."); + String receiversStr = JSONPath.read(configJsonStr, "report.receivers").toString(); + if (StrUtil.isEmpty(receiversStr)) { + log.error("dashboard report receiver user is empty, panelId:{}", panelId); + return; + } - // 计算 query_range start&end - String timezone = sysConfService.getValue("timezone"); - timezone = StrUtil.emptyToDefault(timezone, TimeZone.getDefault().getID()); - Map<String, Long> queryRangeStartAndEndTime = getQueryRangeStartAndEndTime(configJsonStr, timezone.trim()); - log.info("dashboard report range data, panelId:{}, query_range start&end {}", panelId, JSONObject.toJSONString(queryRangeStartAndEndTime)); + List<String> receiverIds = JSONObject.parseArray(receiversStr, String.class); + List<SysUserEntity> userList = sysUserService.list(new LambdaQueryWrapper<SysUserEntity>().in(SysUserEntity::getId, receiverIds)); + if (receiverIds.size() != userList.size()) { + log.error("dashboard report receiver user not found, panelId:{}", panelId); + return; + } - VisualPanel visualPanel = visualPanelService.getById(panelId); - if(visualPanel == null){ - log.error("dashboard report panel not found,panelId:{}", panelId); - return; - } - try { - Template template = getEmailTemplate(); - String content = this.genMailContent(visualPanel, template); - - String format = "html"; - String fileName = String.format("%s.%s", visualPanel.getName(), format); - for (SysUserEntity user : userList) { - // 以用户默认语言生成 快照文件 - String lang = user.getLang(); - String snapshotStr = visualPanelService.snapshot(format, Integer.valueOf(panelId), queryRangeStartAndEndTime.get("start"), queryRangeStartAndEndTime.get("end"), StrUtil.emptyToDefault(lang, "zh")); - - if (StrUtil.isEmpty(snapshotStr)) { - log.error("dashboard snapshot generate error"); - continue; + // 计算 query_range start&end + String timezone = sysConfService.getValue("timezone"); + timezone = StrUtil.emptyToDefault(timezone, TimeZone.getDefault().getID()); + Map<String, Long> queryRangeStartAndEndTime = getQueryRangeStartAndEndTime(configJsonStr, timezone.trim()); + log.info("dashboard report range data, panelId:{}, query_range start&end {}", panelId, JSONObject.toJSONString(queryRangeStartAndEndTime)); + + try { + Template template = getEmailTemplate(); + String content = this.genMailContent(visualPanel, template); + + String format = "html"; + String fileName = String.format("%s.%s", visualPanel.getName(), format); + for (SysUserEntity user : userList) { + // 以用户默认语言生成 快照文件 + String lang = user.getLang(); + String snapshotStr = visualPanelService.snapshot(format, Integer.valueOf(panelId), queryRangeStartAndEndTime.get("start"), queryRangeStartAndEndTime.get("end"), StrUtil.emptyToDefault(lang, "zh")); + + if (StrUtil.isEmpty(snapshotStr)) { + log.error("dashboard snapshot generate error"); + continue; + } + + File file = null; + try { + // 写到临时目录下,通知用户之后,此文件删除 + file = Tool.FileUtil.newFile(Constant.TEMP_PATH + File.separator + fileName); + Tool.FileUtil.writeUtf8String(snapshotStr, file); + + // 发送邮件通知 + mailUtil.sendHTMLAndAppendFile(Tool.ListUtil.toList(user.getEmail()), "Dashboard report", content, file.getAbsolutePath()); + log.info("dashboard report notific success ,user {}", user.getUsername()); + } finally { + if (file != null && file.exists()) file.delete(); + } } + } catch (IOException | TemplateException | MessagingException e) { + log.error("dashboard report notific error.", e); + } + log.info("dashboard report notific finished."); + } else { + log.info("dashboard report is not executed, this time does't match the report schedule"); + } + } + - File file = null; - try { - // 写到临时目录下,通知用户之后,此文件删除 - file = FileUtil.newFile(Constant.TEMP_PATH + File.separator + fileName); - Tool.FileUtil.writeUtf8String(snapshotStr, file); - - // 发送邮件通知 - mailUtil.sendHTMLAndAppendFile(Tool.ListUtil.toList(user.getEmail()), "Dashboard report", content, file.getAbsolutePath()); - log.info("dashboard report notific success ,user {}", user.getUsername()); - } finally { - if (file != null && file.exists()) file.delete(); + /** + * 根据 startAt 和 report 规则 判断本次是否执行 + * @param reportScheduleJsonStr + * @return + */ + public Boolean checkJobIsRun(String reportScheduleJsonStr) { + String scheduleType = JSONPath.read(reportScheduleJsonStr, "report.schedule.type").toString(); + + String stime = JSONPath.read(reportScheduleJsonStr, "report.schedule.stime").toString(); + Date startAt = Tool.DateUtil.parse(stime, "yyyy-MM-dd HH:mm:ss"); + Date now = new Date(); + + String repeatStr = JSONPath.read(reportScheduleJsonStr, "report.schedule.repeat").toString(); + Integer repeat = Integer.valueOf(StrUtil.emptyToDefault(repeatStr, "1")); + + switch (scheduleType) { + // one time + case "1": return true; + case "2": {// daily + if (repeat == 1) return true; + // 判断间隔时间 + long betweenDay = Tool.DateUtil.between(startAt, now, DateUnit.DAY); + if (betweenDay % repeat == 0) return true; + break; + } + case "3": {// weekly + String nums = JSONPath.read(reportScheduleJsonStr, "report.schedule.nums").toString().replaceAll("\\[|\\]", ""); + List<Integer> execWeekArray = Arrays.asList(nums.split(",")).stream().mapToInt(Integer::parseInt).sorted().boxed().collect(Collectors.toList()); + + // 获取今天周几 + Calendar cal = Calendar.getInstance(); + cal.setTime(now); + int todayWeek = cal.get(Calendar.DAY_OF_WEEK) - 1; + if (todayWeek == 0) todayWeek = 7; + + // startAt 和当前时间在同一周, 符合 周几、周几 执行即可 + if (Tool.DateUtil.weekOfYear(startAt) == Tool.DateUtil.weekOfYear(now)) { + if (execWeekArray.contains(todayWeek)) return true; + } else { + // startAt 和当前时间 不在同一周,根据 repeat + weekly 判断是否执行 + if (repeat == 1) { + // 每周都执行 符合 周几、周几 执行即可 + if (execWeekArray.contains(todayWeek)) return true; + } else { + // 根据今天是周几,找到 startAt 所在周 周几的日期,差值取模 + Date date = this.getSpecifiedWeekByDate(startAt, todayWeek); + long betweenDay = Tool.DateUtil.between(date, now, DateUnit.DAY); + if (betweenDay % (repeat * 7) == 0 && execWeekArray.contains(todayWeek)) return true; + } } + break; } - } catch (IOException | TemplateException | MessagingException e) { - log.error("dashboard report notific error.", e); - } + case "4": {// monthly + Calendar cal = Calendar.getInstance(); + cal.setTime(now); + int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH); + String execDayArray = JSONPath.read(reportScheduleJsonStr, "report.schedule.nums").toString(); + List<String> execDayList = Arrays.asList(execDayArray.split(",")); + + if (StrUtil.contains(execDayArray, "-1")) { + LocalDateTime lastDayOfMonth = now.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime().with(TemporalAdjusters.lastDayOfMonth()); + if (dayOfMonth == lastDayOfMonth.getDayOfMonth()) return true; + } - // 下次执行时间 & 最后执行时间 UTC - Trigger trigger = context.getTrigger(); - Date endTime = trigger.getEndTime(); - Date nextFireTime = trigger.getNextFireTime(); - if (nextFireTime == null) { - log.info(String.format("Job name: %s, Job group: %s, Job endtime: %s ,Job is over", key.getName(), key.getGroup(), DateUtil.getTime(endTime))); - } else { - log.info(String.format("Job name: %s, Job group: %s, Job endtime: %s ,Job nextFireTime: %s", key.getName(), key.getGroup(), DateUtil.getTime(endTime), DateUtil.getTime(nextFireTime))); + if (execDayList.contains(dayOfMonth + "")) return true; + break; + } + default: + break; } - log.info("dashboard report notific finished."); + return false; } /** @@ -160,7 +235,7 @@ public class ReportJob extends QuartzJobBean { */ private Template getEmailTemplate() throws IOException { if (template == null) { - String templateString = sysConfService.getValue(ReportConstant.REPORT_EMAIL_TEMPLATE); + String templateString = sysConfService.getValue(Constant.REPORT_EMAIL_TEMPLATE); template = TemplateUtil.stringToTemplate(templateString, "reportEmailTemplate"); } return template; @@ -168,6 +243,30 @@ public class ReportJob extends QuartzJobBean { /** + * 根据传入日期,获取所在周指定周几的 时间 + * @param date + * @param week + * @return + */ + public Date getSpecifiedWeekByDate(Date date, Integer week) { + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + // 判断要计算的日期是否是周日,如果是则减一天计算周六的,否则会出问题,计算到下一周去了 + int dayWeek = cal.get(Calendar.DAY_OF_WEEK); + if (1 == dayWeek) { + cal.add(Calendar.DAY_OF_MONTH, -1); + } + // 设置一个星期的第一天 + cal.setFirstDayOfWeek(Calendar.MONDAY); + int day = cal.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天 + // 根据日历的规则,给当前日期减去星期几与一个星期第一天的差值 + cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day); + // 获取指定星期的日期 + cal.add(Calendar.DATE, week - 1); + return cal.getTime(); + } + + /** * 根据 report range param 得到 startTime & endTime * * @param rangeConfigJsonStr diff --git a/nz-admin/src/main/java/com/nis/modules/report/job/ReportJobManager.java b/nz-admin/src/main/java/com/nis/modules/report/job/ReportJobManager.java index f08e2bae..89abcb5c 100644 --- a/nz-admin/src/main/java/com/nis/modules/report/job/ReportJobManager.java +++ b/nz-admin/src/main/java/com/nis/modules/report/job/ReportJobManager.java @@ -4,20 +4,14 @@ import cn.hutool.core.date.DateTime; import cn.hutool.core.util.StrUtil; import cn.hutool.log.Log; import com.alibaba.fastjson.JSONPath; +import com.nis.common.utils.Constant; import com.nis.common.utils.Tool; -import com.nis.modules.report.config.ReportConstant; import org.quartz.*; -import org.quartz.impl.matchers.GroupMatcher; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component; -import java.time.DayOfWeek; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.time.temporal.TemporalAdjusters; -import java.util.Calendar; -import java.util.*; +import java.util.Date; @Component public class ReportJobManager { @@ -28,19 +22,12 @@ public class ReportJobManager { @Lazy private Scheduler scheduler; - public static final JobKey getJobKey(String jobName, String jobGroup) { + public JobKey getJobKey(String jobName, String jobGroup) { return JobKey.jobKey(jobName, jobGroup); } - /** - * 创建调度 - * - * @param reportScheduleJsonStr report schedule config json str - * @param jobGroup jobGroup panelId - * @throws SchedulerException - */ - public void createReportJob(String reportScheduleJsonStr, String jobGroup) throws SchedulerException { - log.info("ReportJobManager create job,job group: {}", jobGroup); + public void createReportJob(String reportScheduleJsonStr, String jobName) throws SchedulerException { + log.info("ReportJobManager create job,job name: {}", jobName); String scheduleType = JSONPath.read(reportScheduleJsonStr, "report.schedule.type").toString(); String stime = JSONPath.read(reportScheduleJsonStr, "report.schedule.stime").toString(); @@ -53,40 +40,33 @@ public class ReportJobManager { // job 已结束,不再创建 Date now = new Date(); if (endAt != null && !now.before(endAt)) { - log.info("Report endtime is before current time,job is over.panelId:{}", jobGroup); + log.info("Report endtime is before current time,job is over. panelId:{}", jobName); return; } - String repeatStr = JSONPath.read(reportScheduleJsonStr, "report.schedule.repeat").toString(); - Integer repeat = Integer.valueOf(StrUtil.emptyToDefault(repeatStr, "1")); - - JobDataMap jobDataMap = new JobDataMap(); - jobDataMap.put(ReportConstant.REPORT_JOB_DATAMAP, reportScheduleJsonStr); + JobKey jobKey = this.getJobKey(jobName, Constant.REPORT_JOB_GROUP); + JobDetail jobDetail = JobBuilder.newJob(ReportJob.class).withIdentity(jobKey).storeDurably().build(); switch (scheduleType) { case "1": {// one time - JobKey jobKey = getJobKey(ReportConstant.REPORT_JOB_NAME, jobGroup); SimpleTrigger simpleTrigger = TriggerBuilder.newTrigger().forJob(jobKey).withIdentity(jobKey.getName(), jobKey.getGroup()) .withSchedule(SimpleScheduleBuilder.simpleSchedule()) .startNow().startAt(startAt).endAt(endAt).build(); - JobDetail jobDetail = JobBuilder.newJob(ReportJob.class).withIdentity(jobKey).setJobData(jobDataMap).storeDurably().build(); scheduler.scheduleJob(jobDetail, simpleTrigger); break; } - case "2": {// daily - makeDailyJobAndStart(jobGroup, jobDataMap, startAt, endAt, repeat); - break; - } - case "3": {// weekly. - String nums = JSONPath.read(reportScheduleJsonStr, "report.schedule.nums").toString().replaceAll("\\[|\\]", ""); - int[] execWeekArray = Arrays.asList(nums.split(",")).stream().mapToInt(Integer::parseInt).sorted().toArray(); - - makeWeeklyJobAndStart(jobGroup, jobDataMap, startAt, endAt, execWeekArray, repeat); - break; - } + case "2": // daily + case "3": // weekly case "4": {// monthly - String execDayArray = JSONPath.read(reportScheduleJsonStr, "report.schedule.nums").toString(); - makeMonthlyJobAndStart(jobGroup, jobDataMap, startAt, endAt, execDayArray); + // 创建每天执行的定时任务,在定时任务中判定是否执行 + SimpleScheduleBuilder simpleScheduleBuilder = SimpleScheduleBuilder.simpleSchedule() + .withIntervalInHours(24) + .repeatForever(); + SimpleTrigger simpleTrigger = TriggerBuilder.newTrigger().forJob(jobKey).withIdentity(jobKey.getName(), jobKey.getGroup()) + .withSchedule(simpleScheduleBuilder) + .startNow().startAt(startAt).endAt(endAt).build(); + scheduler.scheduleJob(jobDetail, simpleTrigger); + break; } default: break; @@ -94,6 +74,17 @@ public class ReportJobManager { } /** + * 根据 jobkey 查询 JOB 是否存在,存在则删除 + * @param panelId + * @throws SchedulerException + */ + public void delJobByName(String panelId) throws SchedulerException { + JobKey jobKey = this.getJobKey(panelId, Constant.REPORT_JOB_GROUP); + boolean b = scheduler.checkExists(jobKey); + if (b) scheduler.deleteJob(jobKey); + } + + /** * 每隔几天执行一次 * * @param jobGroup @@ -103,7 +94,7 @@ public class ReportJobManager { * @param repeat * @throws SchedulerException */ - public void makeDailyJobAndStart(String jobGroup, JobDataMap jobDataMap, DateTime startAt, DateTime endAt, Integer repeat) throws SchedulerException { + /*public void makeDailyJobAndStart(String jobGroup, JobDataMap jobDataMap, DateTime startAt, DateTime endAt, Integer repeat) throws SchedulerException { JobKey jobKey = getJobKey(ReportConstant.REPORT_JOB_NAME, jobGroup); SimpleScheduleBuilder simpleScheduleBuilder = SimpleScheduleBuilder.simpleSchedule() @@ -115,8 +106,7 @@ public class ReportJobManager { JobDetail jobDetail = JobBuilder.newJob(ReportJob.class).withIdentity(jobKey).setJobData(jobDataMap).storeDurably().build(); scheduler.scheduleJob(jobDetail, simpleTrigger); - } - + }*/ /** * 每隔几周的 周一,周三、、、 执行 @@ -129,7 +119,7 @@ public class ReportJobManager { * @param repeat * @throws SchedulerException */ - public void makeWeeklyJobAndStart(String jobGroup, JobDataMap jobDataMap, DateTime startAt, DateTime endAt, int[] execWeekArray, Integer repeat) throws SchedulerException { + /* public void makeWeeklyJobAndStart(String jobGroup, JobDataMap jobDataMap, DateTime startAt, DateTime endAt, int[] execWeekArray, Integer repeat) throws SchedulerException { SimpleScheduleBuilder simpleScheduleBuilder = SimpleScheduleBuilder.simpleSchedule() .withIntervalInHours(24 * 7 * repeat)// 每搁几周执行一次 .repeatForever(); @@ -170,7 +160,7 @@ public class ReportJobManager { JobDetail jobDetail = JobBuilder.newJob(ReportJob.class).withIdentity(jobKey).setJobData(jobDataMap).storeDurably().build(); scheduler.scheduleJob(jobDetail, simpleTrigger); } - } + }*/ /** * 每月指定日期执行 -1 表示最后一天 'L' @@ -182,7 +172,7 @@ public class ReportJobManager { * @param execDayArray * @throws SchedulerException */ - public void makeMonthlyJobAndStart(String jobGroup, JobDataMap jobDataMap, DateTime startAt, DateTime endAt, String execDayArray) throws SchedulerException { + /*public void makeMonthlyJobAndStart(String jobGroup, JobDataMap jobDataMap, DateTime startAt, DateTime endAt, String execDayArray) throws SchedulerException { // 每月几号执行 List<String> cronExpreLiost = new ArrayList<>(); if (StrUtil.contains(execDayArray, "-1")) { @@ -206,22 +196,5 @@ public class ReportJobManager { JobDetail jobDetail = JobBuilder.newJob(ReportJob.class).withIdentity(jobKey).setJobData(jobDataMap).storeDurably().build(); scheduler.scheduleJob(jobDetail, cronTrigger); } - } - - - /** - * 根据 group 查找 Job,找到关闭 Job - * - * @param panelId - * @throws SchedulerException - */ - public void findJobAndDelByGroup(String panelId) throws SchedulerException { - // 新增|修改 JOB 先删后增 - Set<JobKey> jobKeys = scheduler.getJobKeys(GroupMatcher.groupEquals(panelId)); - if (Tool.CollectionUtil.isNotEmpty(jobKeys)) { - for (JobKey key : jobKeys) { - scheduler.deleteJob(key); - } - } - } + }*/ } diff --git a/nz-admin/src/main/java/com/nis/modules/topic/service/TopicService.java b/nz-admin/src/main/java/com/nis/modules/topic/service/TopicService.java deleted file mode 100644 index 33c728f0..00000000 --- a/nz-admin/src/main/java/com/nis/modules/topic/service/TopicService.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.nis.modules.topic.service; - -import java.util.Map; - -public interface TopicService { - - /** - * @param topicName 名称 - * @param contentMap 内容 - */ - void publishMessage(String topicName, Map<String, Object> contentMap); - -} diff --git a/nz-admin/src/main/java/com/nis/modules/topic/service/impl/TopicServiceImpl.java b/nz-admin/src/main/java/com/nis/modules/topic/service/impl/TopicServiceImpl.java deleted file mode 100644 index 813e65bf..00000000 --- a/nz-admin/src/main/java/com/nis/modules/topic/service/impl/TopicServiceImpl.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.nis.modules.topic.service.impl; - -import cn.hutool.log.Log; -import com.alibaba.fastjson.JSONObject; -import com.nis.common.utils.Tool; -import com.nis.modules.report.config.ReportConstant; -import com.nis.modules.topic.service.TopicService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.stereotype.Service; - -import java.util.Map; - -@Service -public class TopicServiceImpl implements TopicService { - - private Log log = Log.get(); - - @Autowired - private RedisTemplate redisTemplate; - - @Override - public void publishMessage(String topicName, Map<String, Object> contentMap) { - if (Tool.MapUtil.isEmpty(contentMap)) { - log.info("Send message is empty,Not publish,topic :{}", topicName); - return; - } - - try { - redisTemplate.convertAndSend(topicName, JSONObject.toJSONString(contentMap)); - log.info("message send success. topic :{} , msg:{}", topicName, JSONObject.toJSONString(contentMap)); - } catch (Exception e) { - log.error("message send error. topic :{} , msg:{}", topicName, JSONObject.toJSONString(contentMap), e); - } - } -} |
