Commit 7861b8df authored by wangjinjing's avatar wangjinjing

init

parent 60a42fe1
Pipeline #40 failed with stages
...@@ -174,7 +174,10 @@ ...@@ -174,7 +174,10 @@
<version>1.7.25</version> <version>1.7.25</version>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
</dependencies> </dependencies>
......
package com.cx.cn.cxquartz.bean;
public class PatrolCtrlAlarm {
private String cameraCode;
private String cameraName;
private String time;
private String type;
private String file;
public String getCameraCode() {
return cameraCode;
}
public void setCameraCode(String cameraCode) {
this.cameraCode = cameraCode;
}
public String getCameraName() {
return cameraName;
}
public void setCameraName(String cameraName) {
this.cameraName = cameraName;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getFile() {
return file;
}
public void setFile(String file) {
this.file = file;
}
}
package com.cx.cn.cxquartz.bean;
public class PatrolCtrlRecord {
private String cameraCode;
private String cameraName;
private String patrolTime;
private String recordSrc;
private String file;
private String deviceid;
public String getDeviceid() {
return deviceid;
}
public void setDeviceid(String deviceid) {
this.deviceid = deviceid;
}
public String getCameraCode() {
return cameraCode;
}
public void setCameraCode(String cameraCode) {
this.cameraCode = cameraCode;
}
public String getCameraName() {
return cameraName;
}
public void setCameraName(String cameraName) {
this.cameraName = cameraName;
}
public String getPatrolTime() {
return patrolTime;
}
public void setPatrolTime(String patrolTime) {
this.patrolTime = patrolTime;
}
public String getRecordSrc() {
return recordSrc;
}
public void setRecordSrc(String recordSrc) {
this.recordSrc = recordSrc;
}
public String getFile() {
return file;
}
public void setFile(String file) {
this.file = file;
}
}
package com.cx.cn.cxquartz.bean;
public class PictureTime {
String deviceid;
String lasttime;
public String getDeviceid() {
return deviceid;
}
public void setDeviceid(String deviceid) {
this.deviceid = deviceid;
}
public String getLasttime() {
return lasttime;
}
public void setLasttime(String lasttime) {
this.lasttime = lasttime;
}
}
package com.cx.cn.cxquartz.bean;
public class QuartzTaskErrors {
private Long id;
private String taskexecuterecordid;
private String errorkey;
private Long createtime;
private Long lastmodifytime;
private String errorvalue;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTaskexecuterecordid() {
return taskexecuterecordid;
}
public void setTaskexecuterecordid(String taskexecuterecordid) {
this.taskexecuterecordid = taskexecuterecordid == null ? null : taskexecuterecordid.trim();
}
public String getErrorkey() {
return errorkey;
}
public void setErrorkey(String errorkey) {
this.errorkey = errorkey == null ? null : errorkey.trim();
}
public Long getCreatetime() {
return createtime;
}
public void setCreatetime(Long createtime) {
this.createtime = createtime;
}
public Long getLastmodifytime() {
return lastmodifytime;
}
public void setLastmodifytime(Long lastmodifytime) {
this.lastmodifytime = lastmodifytime;
}
public String getErrorvalue() {
return errorvalue;
}
public void setErrorvalue(String errorvalue) {
this.errorvalue = errorvalue == null ? null : errorvalue.trim();
}
}
package com.cx.cn.cxquartz.bean; package com.cx.cn.cxquartz.bean;
public class QuartzTaskInformations { import java.io.Serializable;
public class QuartzTaskInformations implements Serializable {
private Long id; private Long id;
private Integer version; private Integer version;
...@@ -39,7 +41,7 @@ public class QuartzTaskInformations { ...@@ -39,7 +41,7 @@ public class QuartzTaskInformations {
private String metatype; private String metatype;
private String imgsrc; private String imgsrc;
private String rtsp; private String objectType;
private String videoid; private String videoid;
public String getVideoid() { public String getVideoid() {
...@@ -58,12 +60,12 @@ public class QuartzTaskInformations { ...@@ -58,12 +60,12 @@ public class QuartzTaskInformations {
this.imgsrc = imgsrc; this.imgsrc = imgsrc;
} }
public String getRtsp() { public String getObjectType() {
return rtsp; return objectType;
} }
public void setRtsp(String rtsp) { public void setObjectType(String objectType) {
this.rtsp = rtsp; this.objectType = objectType;
} }
public String getMetatype() { public String getMetatype() {
......
package com.cx.cn.cxquartz.bean;
public class QuartzTaskRecords {
private Long id;
private String taskno;
private String timekeyvalue;
private Long executetime;
private String taskstatus;
private Integer failcount;
private String failreason;
private Long createtime;
private Long lastmodifytime;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTaskno() {
return taskno;
}
public void setTaskno(String taskno) {
this.taskno = taskno == null ? null : taskno.trim();
}
public String getTimekeyvalue() {
return timekeyvalue;
}
public void setTimekeyvalue(String timekeyvalue) {
this.timekeyvalue = timekeyvalue == null ? null : timekeyvalue.trim();
}
public Long getExecutetime() {
return executetime;
}
public void setExecutetime(Long executetime) {
this.executetime = executetime;
}
public String getTaskstatus() {
return taskstatus;
}
public void setTaskstatus(String taskstatus) {
this.taskstatus = taskstatus == null ? null : taskstatus.trim();
}
public Integer getFailcount() {
return failcount;
}
public void setFailcount(Integer failcount) {
this.failcount = failcount;
}
public String getFailreason() {
return failreason;
}
public void setFailreason(String failreason) {
this.failreason = failreason == null ? null : failreason.trim();
}
public Long getCreatetime() {
return createtime;
}
public void setCreatetime(Long createtime) {
this.createtime = createtime;
}
public Long getLastmodifytime() {
return lastmodifytime;
}
public void setLastmodifytime(Long lastmodifytime) {
this.lastmodifytime = lastmodifytime;
}
}
package com.cx.cn.cxquartz.bean;
public class User {
String id;
String loginName;
String loginCode;
String area1;
String areaName;
String organCode;
String organName;
String types;
String tatus;
String addTime;
String token;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public String getLoginCode() {
return loginCode;
}
public void setLoginCode(String loginCode) {
this.loginCode = loginCode;
}
public String getArea1() {
return area1;
}
public void setArea1(String area1) {
this.area1 = area1;
}
public String getAreaName() {
return areaName;
}
public void setAreaName(String areaName) {
this.areaName = areaName;
}
public String getOrganCode() {
return organCode;
}
public void setOrganCode(String organCode) {
this.organCode = organCode;
}
public String getOrganName() {
return organName;
}
public void setOrganName(String organName) {
this.organName = organName;
}
public String getTypes() {
return types;
}
public void setTypes(String types) {
this.types = types;
}
public String getTatus() {
return tatus;
}
public void setTatus(String tatus) {
this.tatus = tatus;
}
public String getAddTime() {
return addTime;
}
public void setAddTime(String addTime) {
this.addTime = addTime;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
package com.cx.cn.cxquartz.config;
import com.cx.cn.cxquartz.helper.MessageHelper;
import com.cx.cn.cxquartz.rabbitmq.QueueConstants;
import com.cx.cn.cxquartz.service.quartz.SbtdspsrService;
import com.cx.cn.cxquartz.vo.Sbtdspsr;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.PeriodicTrigger;
import java.util.Date;
import java.util.List;
import java.util.UUID;
@Configuration
@EnableScheduling
public class PerformedTaskCornChange implements SchedulingConfigurer {
@Autowired
private SbtdspsrService sbtdspsrService;
@Autowired
private RabbitTemplate rabbitTemplate;
private Long timer=1000L;
public Long getTimer() {
return timer;
}
public void setTimer(Long timer) {
this.timer = timer;
}
@Override
public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
scheduledTaskRegistrar.addTriggerTask(new Runnable() {
@Override
public void run() {
//判断最小执行时间, // 如果小于2分钟,立即执行所有设备的获取rtsp与hls 的服务,下次执行时间为间隔2分钟
// 如果大于2分钟,下次执行时间为间隔1秒
Long time= sbtdspsrService.getPeriodicseconds();
if(time<1200){
setTimer(120000L);
List<Sbtdspsr> list= sbtdspsrService.getPerformedTasks();
if(null!=list && list.size()>0) {
for(Sbtdspsr sbtdspsr:list) {
//丢到rabbitMq中
String msgId = UUID.randomUUID().toString();
CorrelationData correlationData = new CorrelationData(msgId);
rabbitTemplate.convertAndSend(QueueConstants.QueueRTSPEnum.QUEUE_RTSP_ENUM.getExchange(),
QueueConstants.QueueRTSPEnum.QUEUE_RTSP_ENUM.getRouteKey(),
MessageHelper.objToMsg(sbtdspsr),
correlationData);
}
}
else{
//查询所有数据
}
}
else {
setTimer(1000L);
}
}
}, new Trigger() {
@Override
public Date nextExecutionTime(TriggerContext triggerContext) {
PeriodicTrigger trigger=new PeriodicTrigger(timer);
Date nextDate= trigger.nextExecutionTime(triggerContext);
return nextDate;
}
});
}
}
package com.cx.cn.cxquartz.config;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
//@Configuration
public class RabbitConfig {
@Bean
public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
RabbitTemplate template = new RabbitTemplate(connectionFactory);
template.setMessageConverter(new Jackson2JsonMessageConverter());
return template;
}
@Bean
public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
factory.setConnectionFactory(connectionFactory);
factory.setMessageConverter(new Jackson2JsonMessageConverter());
factory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
return factory;
}
}
...@@ -8,7 +8,6 @@ import org.springframework.cache.annotation.EnableCaching; ...@@ -8,7 +8,6 @@ import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.*; import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer;
...@@ -73,15 +72,15 @@ import org.springframework.data.redis.serializer.StringRedisSerializer; ...@@ -73,15 +72,15 @@ import org.springframework.data.redis.serializer.StringRedisSerializer;
public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) { public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForValue(); return redisTemplate.opsForValue();
} }
@Bean // @Bean
public JedisConnectionFactory redisConnectionFactory() { // public JedisConnectionFactory redisConnectionFactory() {
JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(); // JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
jedisConnectionFactory.setHostName("<server-hostname-here>"); // jedisConnectionFactory.setHostName("<server-hostname-here>");
jedisConnectionFactory.setPort(6379); // jedisConnectionFactory.setPort(6379);
jedisConnectionFactory.setPassword("<server-password-here>"); // jedisConnectionFactory.setPassword("<server-password-here>");
jedisConnectionFactory.afterPropertiesSet(); // jedisConnectionFactory.afterPropertiesSet();
return jedisConnectionFactory; // return jedisConnectionFactory;
} // }
/** /**
* 对链表类型的数据操作 * 对链表类型的数据操作
* *
......
package com.cx.cn.cxquartz.config;
import com.cx.cn.cxquartz.redis.Consumer;
import com.cx.cn.cxquartz.redis.OrderConsumer;
import com.cx.cn.cxquartz.redis.QueueConfiguration;
import com.cx.cn.cxquartz.redis.container.RedisMQConsumerContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RedisPCQueueConfig {
@Autowired
RedisMQConsumerContainer mqContainer;
// 初始化完毕后调取 init
@Bean(initMethod = "init", destroyMethod = "destroy")
public RedisMQConsumerContainer redisQueueConsumerContainer() {
for(int i=0;i<6;i++) {
Consumer orderConsumer = new OrderConsumer();
mqContainer.addConsumer(
QueueConfiguration.builder().queue("taskinfo").consumer(orderConsumer).build()
);
}
return mqContainer;
}
}
package com.cx.cn.cxquartz.config; package com.cx.cn.cxquartz.config;
import com.cx.cn.cxquartz.redis.Consumer;
import com.cx.cn.cxquartz.redis.OrderConsumer;
import com.cx.cn.cxquartz.redis.QueueConfiguration;
import com.cx.cn.cxquartz.redis.container.RedisMQConsumerContainer;
import com.cx.cn.cxquartz.service.quartz.SbtdspsrService; import com.cx.cn.cxquartz.service.quartz.SbtdspsrService;
import com.cx.cn.cxquartz.util.RestUtil; import com.cx.cn.cxquartz.util.RestUtil;
import com.cx.cn.cxquartz.vo.Sbtdspsr; import com.cx.cn.cxquartz.vo.Sbtdspsr;
...@@ -9,19 +14,22 @@ import org.springframework.context.annotation.Configuration; ...@@ -9,19 +14,22 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.Scheduled;
import java.util.Calendar;
import java.util.List; import java.util.List;
@Configuration @Configuration
@EnableScheduling @EnableScheduling
public class ScheduleTaskConfig { public class ScheduleTaskConfig {
@Value("${file.getrtspbyurl}")
private String getrtspbyurl;
@Autowired @Autowired
private SbtdspsrService sbtdspsrService; private SbtdspsrService sbtdspsrService;
@Value("${file.getrtspbyurl}") //
private String getrtspbyurl; // @Autowired
// RedisMQConsumerContainer mqContainer;
RestUtil restUtil=new RestUtil(); RestUtil restUtil=new RestUtil();
// /*** // /***
// * 每隔20分钟执行一遍判断rtsp 是否变换 // * 每隔20分钟执行一遍判断rtsp 是否变换
// */ // */
...@@ -35,15 +43,12 @@ public class ScheduleTaskConfig { ...@@ -35,15 +43,12 @@ public class ScheduleTaskConfig {
// restUtil.rtspChangeVlue(sbtd.getSbbh(),sbtd.getSqurllj(),getrtspbyurl); // restUtil.rtspChangeVlue(sbtd.getSbbh(),sbtd.getSqurllj(),getrtspbyurl);
// } // }
// } // }
// @Scheduled(cron = "0/5 * * * * ?")
// @Scheduled(cron = "0 30/5 6-19 * * ?")//每隔5分钟统计当天目前为止的数据
// private void statistoday() { // private void statistoday() {
// //判断是否为空表 // Consumer orderConsumer = new OrderConsumer();
// //执行查询存在更新,不存在新增 // mqContainer.addConsumer(
// log.info("每隔5分钟"); // QueueConfiguration.builder().queue("taskinfo").consumer(orderConsumer).build()
// Integer result= traffFlowService.insertOrUpdatevehicleTodaystatistic(); // );
// log.info("today"+result);
// //
// } // }
......
package com.cx.cn.cxquartz.config;
import com.cx.cn.cxquartz.rabbitmq.QueueConstants;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 生产者申明一个direct类型(直连型)交换机,然后发送消息到这个交换机指定路由键。
* 消费者指定消费这个交换机的这个路由键,即可接收到消息,其他消费者收不到。
* 用户登录直连型交换机配置
* 1. 声明Exchange交换器;
* 2. 声明Queue队列;
* 3. 绑定BindingBuilder绑定队列到交换器,并设置路由键;
* 消费者单纯的使用,其实可以不用添加这个配置,直接建后面的监听就好,使用注解来让监听器监听对应的队列即可。
* * 配置上了的话,其实消费者也是生成者的身份,也能推送该消息。
*/
@Configuration
public class SendToDXConfig {
/**
* 创建交换机
*
* @return
*/
@Bean
public DirectExchange sendToDXDirectExchange() {
return new DirectExchange(QueueConstants.QueueSendToDXEnum.QUEUE_SEND_TO_DX_ENUM.getExchange());
}
/**
* 创建队列 true表示是否持久
*
* @return
*/
@Bean
public Queue sendToDXDirectQueue() {
return new Queue(QueueConstants.QueueSendToDXEnum.QUEUE_SEND_TO_DX_ENUM.getQueue(), true);
}
/**
* 将队列和交换机绑定,并设置用于匹配路由键
*
* @return
*/
@Bean
public Binding BindingSendToDXDirect() {
return BindingBuilder.bind(sendToDXDirectQueue()).to(sendToDXDirectExchange()).with(QueueConstants.QueueSendToDXEnum.QUEUE_SEND_TO_DX_ENUM.getRouteKey());
}
}
\ No newline at end of file
package com.cx.cn.cxquartz.config;
import com.cx.cn.cxquartz.rabbitmq.QueueConstants;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 生产者申明一个direct类型(直连型)交换机,然后发送消息到这个交换机指定路由键。
* 消费者指定消费这个交换机的这个路由键,即可接收到消息,其他消费者收不到。
* 用户登录直连型交换机配置
* 1. 声明Exchange交换器;
* 2. 声明Queue队列;
* 3. 绑定BindingBuilder绑定队列到交换器,并设置路由键;
* 消费者单纯的使用,其实可以不用添加这个配置,直接建后面的监听就好,使用注解来让监听器监听对应的队列即可。
* 配置上了的话,其实消费者也是生成者的身份,也能推送该消息。
*/
@Configuration
public class SendToVoiceConfig {
/**
* 创建交换机
*
* @return
*/
@Bean
public DirectExchange sendToVoiceDirectExchange() {
return new DirectExchange(QueueConstants.QueueSendToVoiceEnum.QUEUE_SEND_TO_VOICE_ENUM.getExchange());
}
/**
* 创建队列 true表示是否持久
*
* @return
*/
@Bean
public Queue sendToVoiceDirectQueue() {
return new Queue(QueueConstants.QueueSendToVoiceEnum.QUEUE_SEND_TO_VOICE_ENUM.getQueue(), true);
}
/**
* 将队列和交换机绑定,并设置用于匹配路由键
*
* @return
*/
@Bean
public Binding BindingSendToVoiceDirect() {
return BindingBuilder.bind(sendToVoiceDirectQueue()).to(sendToVoiceDirectExchange()).with(QueueConstants.QueueSendToVoiceEnum.QUEUE_SEND_TO_VOICE_ENUM.getRouteKey());
}
}
\ No newline at end of file
package com.cx.cn.cxquartz.config;
import com.cx.cn.cxquartz.rabbitmq.QueueConstants;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 视频图片直连型交换机配置
* 1. 声明Exchange交换器;
* 2. 声明Queue队列;
* 3. 绑定BindingBuilder绑定队列到交换器,并设置路由键;
* 消费者单纯的使用,其实可以不用添加这个配置,直接建后面的监听就好,使用注解来让监听器监听对应的队列即可。
* 配置上了的话,其实消费者也是生成者的身份,也能推送该消息。
*/
@Configuration
public class TaskComsumExchangeConfig {
/**
* 创建交换机
*
* @return
*/
@Bean
public DirectExchange OrderCancelDirectExchange() {
return new DirectExchange(QueueConstants.QueueTaskEnum.QUEUE_TASK_ENUM.getExchange());
}
// /**
// * 创建队列 true表示是否持久
// *
// * @return
// */
// @Bean
// public Queue OrderCancelDirectQueue() {
// return new Queue(QueueConstants.QueueTaskEnum.QUEUE_TASK_ENUM.getQueue(), true);
// }
/**
* 创建队列 true表示是否持久
*
* @return
*/
@Bean
public Queue Model1DirectQueue() {
return new Queue(QueueConstants.QueueTaskEnum.QUEUE_TASK_ENUM.getQueue()+"_1", true);
}
/**
* 创建队列 true表示是否持久
*
* @return
*/
@Bean
public Queue Model2DirectQueue() {
return new Queue(QueueConstants.QueueTaskEnum.QUEUE_TASK_ENUM.getQueue()+"_2", true);
}
/**
* 创建队列 true表示是否持久
*
* @return
*/
@Bean
public Queue Model3DirectQueue() {
return new Queue(QueueConstants.QueueTaskEnum.QUEUE_TASK_ENUM.getQueue()+"_3", true);
}
/**
* 创建队列 true表示是否持久
*
* @return
*/
@Bean
public Queue Model4DirectQueue() {
return new Queue(QueueConstants.QueueTaskEnum.QUEUE_TASK_ENUM.getQueue()+"_4", true);
}
/**
* 创建队列 true表示是否持久
*
* @return
*/
@Bean
public Queue Model5DirectQueue() {
return new Queue(QueueConstants.QueueTaskEnum.QUEUE_TASK_ENUM.getQueue()+"_5", true);
}
/**
* 创建队列 true表示是否持久
*
* @return
*/
@Bean
public Queue Model0DirectQueue() {
return new Queue(QueueConstants.QueueTaskEnum.QUEUE_TASK_ENUM.getQueue()+"_0", true);
}
/**
* 将队列和交换机绑定,并设置用于匹配路由键
*
* @return
*/
@Bean
public Binding BindingDirect() {
BindingBuilder.bind(Model1DirectQueue()).to(OrderCancelDirectExchange()).with(QueueConstants.QueueTaskEnum.QUEUE_TASK_ENUM.getRouteKey()+"_1");
BindingBuilder.bind(Model2DirectQueue()).to(OrderCancelDirectExchange()).with(QueueConstants.QueueTaskEnum.QUEUE_TASK_ENUM.getRouteKey()+"_2");
BindingBuilder.bind(Model3DirectQueue()).to(OrderCancelDirectExchange()).with(QueueConstants.QueueTaskEnum.QUEUE_TASK_ENUM.getRouteKey()+"_3");
BindingBuilder.bind(Model4DirectQueue()).to(OrderCancelDirectExchange()).with(QueueConstants.QueueTaskEnum.QUEUE_TASK_ENUM.getRouteKey()+"_4");
BindingBuilder.bind(Model5DirectQueue()).to(OrderCancelDirectExchange()).with(QueueConstants.QueueTaskEnum.QUEUE_TASK_ENUM.getRouteKey()+"_5");
return BindingBuilder.bind(Model0DirectQueue()).to(OrderCancelDirectExchange()).with(QueueConstants.QueueTaskEnum.QUEUE_TASK_ENUM.getRouteKey()+"_0");
}
}
package com.cx.cn.cxquartz.config;
import com.cx.cn.cxquartz.rabbitmq.QueueConstants;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 生产者申明一个direct类型(直连型)交换机,然后发送消息到这个交换机指定路由键。
* 消费者指定消费这个交换机的这个路由键,即可接收到消息,其他消费者收不到。
* 用户登录直连型交换机配置
* 1. 声明Exchange交换器;
* 2. 声明Queue队列;
* 3. 绑定BindingBuilder绑定队列到交换器,并设置路由键;
* 消费者单纯的使用,其实可以不用添加这个配置,直接建后面的监听就好,使用注解来让监听器监听对应的队列即可。
* 配置上了的话,其实消费者也是生成者的身份,也能推送该消息。
*/
@Configuration
public class getSnapShotConfig {
/**
* 创建交换机
*
* @return
*/
@Bean
public DirectExchange sendToVoiceDirectExchange() {
return new DirectExchange(QueueConstants.QueueRTSPEnum.QUEUE_RTSP_ENUM.getExchange());
}
/**
* 创建队列 true表示是否持久
*
* @return
*/
@Bean
public Queue sendToVoiceDirectQueue() {
return new Queue(QueueConstants.QueueRTSPEnum.QUEUE_RTSP_ENUM.getQueue(), true);
}
/**
* 将队列和交换机绑定,并设置用于匹配路由键
*
* @return
*/
@Bean
public Binding BindingSendToVoiceDirect() {
return BindingBuilder.bind(sendToVoiceDirectQueue()).to(sendToVoiceDirectExchange()).with(QueueConstants.QueueRTSPEnum.QUEUE_RTSP_ENUM.getRouteKey());
}
}
\ No newline at end of file
...@@ -27,8 +27,6 @@ import java.util.List; ...@@ -27,8 +27,6 @@ import java.util.List;
@PropertySource("classpath:file.properties") @PropertySource("classpath:file.properties")
public class ExtController { public class ExtController {
private static final Logger logger = LoggerFactory.getLogger(ExtController.class); private static final Logger logger = LoggerFactory.getLogger(ExtController.class);
@Autowired
private QuartzService quartzService;
@Value("${file.rtspurl}") @Value("${file.rtspurl}")
private String rtspurl; private String rtspurl;
@Value("${file.recogurl}") @Value("${file.recogurl}")
...@@ -217,7 +215,8 @@ public class ExtController { ...@@ -217,7 +215,8 @@ public class ExtController {
} }
//获得点位 //获得点位
logger.info("获得点位"); logger.info("获得点位");
TraffpictureParam traffpictureParamresult = eventWriteService.getResult(Integer.parseInt(taskinfo.getMetatype()) TraffpictureParam traffpictureParamresult = new TraffpictureParam();
traffpictureParamresult = eventWriteService.getResult(traffpictureParamresult,Integer.parseInt(taskinfo.getMetatype())
, roiarray, imageurl, objectresult, jobTjParam, points); , roiarray, imageurl, objectresult, jobTjParam, points);
if(null==traffpictureParamresult){ if(null==traffpictureParamresult){
logger.info("人群密度未超或目标未出现"); logger.info("人群密度未超或目标未出现");
...@@ -231,7 +230,7 @@ public class ExtController { ...@@ -231,7 +230,7 @@ public class ExtController {
String basepath = DateUtils.formatCurrDayYM() + String basepath = DateUtils.formatCurrDayYM() +
File.separator + DateUtils.formatCurrDayDD() + File.separator + File.separator + DateUtils.formatCurrDayDD() + File.separator +
devicecode; devicecode;
String filename = devicecode + "_" + DateUtils.formatCurrDateNoSign() +"_"+ recordtype+"_result.jpg"; String filename = devicecode + "_" + DateUtils.parseDateToStrNoSign(transferRecord.getRecordtime()) +"_"+ recordtype+"_result.jpg";
eventWriteService.uploadPicture(traffpictureParamresult, transferRecord.getImg1urlfrom(), points, basepath, filename); eventWriteService.uploadPicture(traffpictureParamresult, transferRecord.getImg1urlfrom(), points, basepath, filename);
String filenameurl = File.separator + outpath + File.separator + basepath + File.separator + filename; String filenameurl = File.separator + outpath + File.separator + basepath + File.separator + filename;
jobTjParam.setImageUrl(weburl + filenameurl); jobTjParam.setImageUrl(weburl + filenameurl);
......
package com.cx.cn.cxquartz.controller; package com.cx.cn.cxquartz.controller;
import com.cx.cn.cxquartz.bean.QuartzTaskInformations;
import com.cx.cn.cxquartz.service.quartz.QuartzService;
import com.cx.cn.cxquartz.service.quartz.TraffPictureService; import com.cx.cn.cxquartz.service.quartz.TraffPictureService;
import com.cx.cn.cxquartz.util.Page;
import com.cx.cn.cxquartz.vo.GoalStructureParam;
import com.cx.cn.cxquartz.vo.JobParam;
import com.cx.cn.cxquartz.vo.TaskResultObj;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
import sun.net.www.protocol.ftp.FtpURLConnection;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
@Controller @Controller
public class IndexController { public class IndexController {
private static final Logger logger = LoggerFactory.getLogger(IndexController.class); private static final Logger logger = LoggerFactory.getLogger(IndexController.class);
@Autowired
private QuartzService quartzService;
@Autowired @Autowired
......
package com.cx.cn.cxquartz.controller;
import com.cx.cn.cxquartz.bean.QuartzTaskErrors;
import com.cx.cn.cxquartz.bean.QuartzTaskInformations;
import com.cx.cn.cxquartz.service.quartz.FtpService;
import com.cx.cn.cxquartz.service.quartz.QuartzService;
import com.cx.cn.cxquartz.service.quartz.SbtdspsrService;
import com.cx.cn.cxquartz.util.*;
import com.cx.cn.cxquartz.vo.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping("/ai")
public class QuartzController {
private static final Logger logger = LoggerFactory.getLogger(QuartzController.class);
@Autowired
private QuartzService quartzService;
@Value("${file.getrtspbyurl}")
private String getrtspbyurl;
@Value("${file.rtspurl}")
private String rtspurl;
@Value("${file.ftppath}")
private String ftppath;
@Autowired
private SbtdspsrService sbtdspsrService;
@Autowired
private RestTemplate restTemplate;
// @Autowired
// FtpService ftpService;
//
// @RequestMapping(value = "/add/taskpage", method = RequestMethod.GET)
// public String addTaskpage() {
// return "addtask";
// }
//
// @ResponseBody
// @RequestMapping(value = "/add/task", method = RequestMethod.POST)
// public String addTask(QuartzTaskInformations taskInformations) {
// try {
// taskInformations.setSchedulerrule("*/" + taskInformations.getSchedulerrule() + " * * * * ?");
// String result = quartzService.addTask(taskInformations);
// return result;
// } catch (Exception e) {
// logger.error("/add/task exception={}", e);
// return ResultUtil.fail();
// }
// }
@PostMapping("/task")
@ResponseBody
public TaskResultObj scheduleJob(@RequestBody JobParam jobParam) {
String taskno="fx_" + jobParam.getDeviceId() + "_" + jobParam.getDetectType();
String cztaskno="cz_" + jobParam.getDeviceId() + "_" + jobParam.getDetectType();
QuartzTaskInformations taskInformations = new QuartzTaskInformations();
taskInformations.setExecuteparamter(jobParam.getDeviceId());
taskInformations.setMetatype(jobParam.getDetectType());
//查询是否有抽帧服务
List<QuartzTaskInformations> tasks = quartzService.getTaskSByDeviceCode(jobParam.getDeviceId());
Map<String, Integer> map = getTaskCzAndFxNumer(tasks);
Integer cznum = map.get("cznum");
Integer fxnum = map.get("fxnum");
Long[] roiarray=new Long[4];
if ("0".equals(jobParam.getType())) {//0新增 1开启 2停止 3删除
//判断是否存在抽帧任务,存在则直接新增分析任务,不存在则新增
taskInformations.setFrozenstatus("UNFROZEN");
taskInformations.setSchedulerrule("*/" + jobParam.getParams().get("schedulerRule").toString() + " * * * * ?");
List<Point> listpoint=jobParam.getArea();
PointUtil.getXYWH(listpoint,roiarray);
taskInformations.setObjectx(roiarray[0]);
taskInformations.setObjecty(roiarray[1]);
taskInformations.setObjectw(roiarray[2]);
taskInformations.setObjecth(roiarray[3]);
taskInformations.setMetatype( jobParam.getParams().get("thresholdValue").toString());
taskInformations.setUrl(jobParam.getCallBackUrl());
taskInformations.setExecutorno(taskno);
taskInformations.setTaskno(taskInformations.getExecutorno());
taskInformations.setTaskname(jobParam.getName());
taskInformations.setVideoid(jobParam.getDeviceId() );
taskInformations.setRecordtype(jobParam.getDetectType());
String result = quartzService.addTask(taskInformations);
try {
quartzService.startJob(taskno, "UNFROZEN");
}catch (Exception ex){
logger.error(taskno+" fx startJob error:"+ex.toString());
}
//查询是否有抽帧服务
if (cznum == 0) {
taskInformations.setExecutorno(cztaskno);
taskInformations.setTaskno(cztaskno);
quartzService.addTask(taskInformations);
try {
quartzService.startJob(cztaskno, "UNFROZEN");
}catch (Exception ex){
logger.error(cztaskno+"cz startJob error:"+ex.toString());
}
}
} else if ("1".equals(jobParam.getType()))//开启
{
try {
if (fxnum == 1) {
quartzService.startOrStopJob(cztaskno,"UNFROZEN");
}//开启分析服务,开启抽帧
quartzService.startOrStopJob(taskno,"UNFROZEN");
} catch (Exception ex) {
logger.error(ex.toString());
}
} else if ("2".equals(jobParam.getType()) ) {//停止
//一抽帧多分析,停止不停抽帧服务
try {
if (fxnum == 1) {
quartzService.startOrStopJob(cztaskno,"FROZEN");
}
quartzService.startOrStopJob(taskno, "FROZEN");
} catch (Exception ex) {
logger.error(ex.toString());
}
} else if ("3".equals(jobParam.getType())) {//删除
try {
quartzService.startOrStopJob(taskno, "FROZEN");
quartzService.deletetask(taskno);
if(fxnum==1){
quartzService.startOrStopJob(cztaskno, "FROZEN");
quartzService.deletetask(cztaskno);
}
} catch (Exception ex) {
logger.error(ex.toString());
}
//quartzService.("fx_" + jobParam.getDeviceId() + "_" + jobParam.getDetectType(), fxnum);
}
return TaskResultObj.ok();
}
public Map getTaskCzAndFxNumer(List<QuartzTaskInformations> tasks) {
Map<String, Integer> map = new HashMap();
int cznum = 0, fxnum = 0;
if (tasks.size() > 0) {
//一抽多分析
for (QuartzTaskInformations item : tasks) {
if (item.getTaskno().contains("cz")) {
cznum++;
} else if (item.getTaskno().contains("fx")) {
fxnum++;
}
}
}
map.put("cznum", cznum);
map.put("fxnum", fxnum);
return map;
}
//
// @RequestMapping(value = "/edit/taskpage", method = RequestMethod.GET)
// public String editTaskpage(Model model, String id) {
// QuartzTaskInformations taskInformation = quartzService.getTaskById(id);
// taskInformation.setSchedulerrule(taskInformation.getSchedulerrule().replaceAll("\\?", "").replaceAll("\\*", "").replaceAll("\\/", ""));
// model.addAttribute("taskInformation", taskInformation);
// return "updatetask";
// }
//
// @ResponseBody
// @RequestMapping(value = "/edit/task", method = RequestMethod.POST)
// public String editTask(QuartzTaskInformations taskInformations) {
// try {
// taskInformations.setSchedulerrule("*/" + taskInformations.getSchedulerrule() + " * * * * ?");
// String result = quartzService.updateTask(taskInformations);
// if (null != taskInformations.getExecuteparamter() && !taskInformations.getExecuteparamter().contains("rtsp:")) {
// int upresult = sbtdspsrService.updateRecogByRtsp(taskInformations.getRtsp(), taskInformations.getVideoid());
//
// if (upresult > 0) {
// logger.info("更新sbtddspsr squrllj 的值为:" + taskInformations.getExecuteparamter());
// }
// }
// return result;
// } catch (Exception e) {
// logger.error("/edit/task exception={}", e);
// return ResultUtil.fail();
// }
// }
//
// /**
// * 启动 或者 暂定定时任务
// *
// * @param taskNo
// * @return
// */
// @ResponseBody
// @RequestMapping(value = "/list/optionjob", method = RequestMethod.GET)
// public String optionJob(String taskNo) {
// logger.info("");
// if (StringUtils.isEmpty(taskNo)) {
// return ResultUtil.success(ResultEnum.PARAM_EMPTY.getCode(), ResultEnum.PARAM_EMPTY.getMessage());
// }
// try {
// return quartzService.startJob(taskNo,null);
// } catch (Exception e) {
// logger.error("/list/optionjob exception={}", e);
// return ResultUtil.fail();
// }
// }
//
// /**
// * 定时任务执行情况
// *
// * @param taskNo
// * @param model
// * @return
// */
// @RequestMapping(value = "/taskrecords", method = RequestMethod.GET)
// public String taskRecordsPage(@RequestParam(value = "taskno", required = false) String taskNo, Model model) {
// logger.info("");
// try {
// if (StringUtils.isEmpty(taskNo)) {
// return "redirect:/";
// }
// List<QuartzTaskRecordsVo> quartzTaskRecords = quartzService.taskRecords(taskNo);
// model.addAttribute("quartzTaskRecords", quartzTaskRecords);
// } catch (Exception e) {
// logger.error("");
// return "redirect:/";
// }
// return "taskrecords";
// }
//
// /**
// * 立即运行一次定时任务
// *
// * @param taskNo
// * @param model
// * @return
// */
// @ResponseBody
// @RequestMapping(value = "/runtask/rightnow", method = RequestMethod.GET)
// public String runTaskRightNow(@RequestParam(value = "taskno", required = false) String taskNo, Model model) {
// logger.info("");
// try {
// if (StringUtils.isEmpty(taskNo)) {
// return ResultUtil.success(ResultEnum.PARAM_EMPTY.getCode(), ResultEnum.PARAM_EMPTY.getMessage());
// }
// return quartzService.runTaskRightNow(taskNo);
// } catch (Exception e) {
// logger.error("");
// return ResultUtil.success(ResultEnum.FAIL.getCode(), ResultEnum.FAIL.getMessage());
// }
// }
//
// /**
// * 定时任务失败详情
// *
// * @param recordId
// * @param model
// * @return
// */
// @RequestMapping(value = "/task/errors", method = RequestMethod.GET)
// public String detailTaskErrors(@RequestParam(value = "recordid", required = false) String recordId, Model model) {
// logger.info("");
// try {
// if (StringUtils.isEmpty(recordId)) {
// return ResultUtil.success(ResultEnum.PARAM_EMPTY.getCode(), ResultEnum.PARAM_EMPTY.getMessage());
// }
// QuartzTaskErrors taskErrors = quartzService.detailTaskErrors(recordId);
// model.addAttribute("taskErrors", taskErrors);
// return "taskerrors";
// } catch (Exception e) {
// logger.error("");
// return "redirect:/";
// }
// }
// @RequestMapping(value = "/getRtsp", method = RequestMethod.POST)
// @ResponseBody
// public String getRTSP(@RequestBody JSONObject devicecode) {
// //判断rtsp 是否过期http://212.129.142.17:8281/gh/device/test?deviceCode=3YSCA44445TFCPX
// //判断是否是rtsp 地址
// String rtspValue = devicecode.getString("data");
// if (!rtspValue.contains("rtsp://")) {
// Map<String, String> map = new HashMap<>();
// map.put("deviceCode", rtspValue);
// ResponseEntity<String> responseEntity = restTemplate.getForEntity(getrtspbyurl + "?deviceCode={deviceCode}", String.class, map);
// JSONObject json = JSONObject.parseObject(responseEntity.getBody());
// if (null != json.getString("errorCode") && json.getString("errorCode").equals("0")) {
// //返回rtsp 地址,更新 sbtdspsr 地址
// json = JSONObject.parseObject(json.getString("data"));
// rtspValue = String.valueOf(json.get("rtspUri"));
// }
// }
//
// //获得抽帧图片
// Map maps = new HashMap<>();
// maps.put("rtspvalue", rtspValue);
// maps.put("refresh", 1);
// try {
// ResponseEntity<String> result = restTemplate.exchange(rtspurl + "?url={rtspvalue}&refresh={refresh}",
// HttpMethod.GET, null, String.class, maps);
// JSONObject jsonresult = JSONObject.parseObject(result.getBody());
// logger.info("getRtsp:{}", jsonresult);
// if (null != jsonresult.getString("ret") && jsonresult.getString("ret").equals("0") && !"".equals(jsonresult.getString("url"))) {
// //获得图片地址,存放到ftp上面
// //将图片存储到ftp 上去,jsonresult.getString("url")
// Ftp ftp = ftpService.reloadFtp();
// String ftpfilepath = FileTransferManager.urlTransToFtp(jsonresult.getString("url"), ftp, "gstraff/picturedemo/");
// logger.info("ftppath" + ftpfilepath);
// ftpfilepath = ftpfilepath.replace("ftp://" + ftppath + "/", "");
// // return ResultUtil.success(ResultEnum.SUCCESS.getCode(), jsonresult.getString("url")+ "," + rtspValue);
//
// return ResultUtil.success(ResultEnum.SUCCESS.getCode(), ftpfilepath + "," + rtspValue);
// }
// return ResultUtil.fail();
// } catch (Exception ex) {
// logger.info(ex.toString());
// return ResultUtil.fail();
// }
// }
}
package com.cx.cn.cxquartz.controller; package com.cx.cn.cxquartz.controller;
import com.cx.cn.cxquartz.bean.QuartzTaskErrors;
import com.cx.cn.cxquartz.bean.QuartzTaskInformations;
import com.cx.cn.cxquartz.service.quartz.QuartzService;
import com.cx.cn.cxquartz.service.quartz.QuartzTaskRecordsService;
import com.cx.cn.cxquartz.service.quartz.SbtdspsrService; import com.cx.cn.cxquartz.service.quartz.SbtdspsrService;
import com.cx.cn.cxquartz.util.ResultEnum;
import com.cx.cn.cxquartz.util.ResultUtil;
import com.cx.cn.cxquartz.vo.QuartzTaskRecordsVo;
import com.cx.cn.cxquartz.vo.Sbtdspsr;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller @Controller
@RequestMapping("/video") @RequestMapping("/video")
......
package com.cx.cn.cxquartz.dao;
import com.cx.cn.cxquartz.bean.QuartzTaskErrors;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface QuartzTaskErrorsMapper {
int deleteByPrimaryKey(Long id);
int insert(QuartzTaskErrors record);
int insertSelective(QuartzTaskErrors record);
QuartzTaskErrors selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(QuartzTaskErrors record);
int updateByPrimaryKeyWithBLOBs(QuartzTaskErrors record);
int updateByPrimaryKey(QuartzTaskErrors record);
QuartzTaskErrors detailTaskErrors(String recordId);
}
package com.cx.cn.cxquartz.dao;
import com.cx.cn.cxquartz.bean.PatrolCtrlAlarm;
import com.cx.cn.cxquartz.bean.PatrolCtrlRecord;
import com.cx.cn.cxquartz.bean.PictureTime;
import com.cx.cn.cxquartz.bean.QuartzTaskInformations;
import com.cx.cn.cxquartz.vo.Sbtdspsr;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
import java.util.Map;
@Mapper
public interface QuartzTaskInformationsMapper {
int deleteByPrimaryKey(Long id);
int insert(QuartzTaskInformations record);
int insertSelective(QuartzTaskInformations record);
QuartzTaskInformations selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(QuartzTaskInformations record);
int updateByPrimaryKey(QuartzTaskInformations record);
List<QuartzTaskInformations> selectList(Map<String, Object> map);
Integer selectByTaskNo(String taskNo);
QuartzTaskInformations getTaskByTaskNo(String taskNo);
List<QuartzTaskInformations> getUnfrozenTasks(String status);
int insertRecord(PatrolCtrlRecord record);
int insertAlarm(PatrolCtrlAlarm alarm);
List<PictureTime> findLastPicTime();
List< PatrolCtrlRecord> queryCameraCode(List<String> ids);
List<Sbtdspsr> selectByRtsp(String rtsp);
Integer UpdateExecuteParam(Map map);
List<QuartzTaskInformations> getTaskSByDeviceCode(String devicecode);
Integer deletetask(String tasKno);
}
package com.cx.cn.cxquartz.dao;
import com.cx.cn.cxquartz.bean.QuartzTaskRecords;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface QuartzTaskRecordsMapper {
int deleteByPrimaryKey(Long id);
long insert(QuartzTaskRecords record);
int insertSelective(QuartzTaskRecords record);
QuartzTaskRecords selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(QuartzTaskRecords record);
int updateByPrimaryKey(QuartzTaskRecords record);
List<QuartzTaskRecords> getTaskRecordsByTaskNo(String taskNo);
}
...@@ -4,7 +4,6 @@ package com.cx.cn.cxquartz.dao; ...@@ -4,7 +4,6 @@ package com.cx.cn.cxquartz.dao;
import com.cx.cn.cxquartz.bean.QuartzTaskInformations; import com.cx.cn.cxquartz.bean.QuartzTaskInformations;
import com.cx.cn.cxquartz.vo.Sbtdspsr; import com.cx.cn.cxquartz.vo.Sbtdspsr;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
...@@ -15,4 +14,10 @@ public interface SbtdspsrMapper { ...@@ -15,4 +14,10 @@ public interface SbtdspsrMapper {
List<Sbtdspsr> list( ); List<Sbtdspsr> list( );
List<QuartzTaskInformations> selectRecogByRtsp(String rtsp); List<QuartzTaskInformations> selectRecogByRtsp(String rtsp);
int updateRecogByRtsp(Map map); int updateRecogByRtsp(Map map);
int updateRTSPorHLSParam(Sbtdspsr sbtdspsr);
Long getPeriodicseconds();
String getRtspOrHLSByDeviceCode(String deviceCode);
List<Sbtdspsr> getPerformedTasks();
} }
package com.cx.cn.cxquartz.dao;
import com.cx.cn.cxquartz.vo.Taskinfo;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
import java.util.Map;
@Mapper
public interface TaskinfoMapper {
List<Taskinfo> getTaskinfoByMutiParam (Map map);
int addTaskinfo(Taskinfo taskinfo);
int updateTaskinfo(Taskinfo taskinfo);
int delTaskinfoByid(String id);
}
package com.cx.cn.cxquartz.helper;
import com.cx.cn.cxquartz.util.JsonUtil;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
/**
* RabbitMQ消息处理类
*/
public class MessageHelper {
public static Message objToMsg(Object obj) {
if (null == obj) {
return null;
}
Message message = MessageBuilder.withBody(JsonUtil.objToStr(obj).getBytes()).build();
// 消息持久化
message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
message.getMessageProperties().setContentType(MessageProperties.CONTENT_TYPE_JSON);
return message;
}
public static Message msgToMsg(String mess) {
if (null == mess) {
return null;
}
Message message = MessageBuilder.withBody(mess.getBytes()).build();
// 消息持久化
message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
message.getMessageProperties().setContentType(MessageProperties.CONTENT_TYPE_JSON);
return message;
}
public static <T> T msgToObj(Message message, Class<T> clazz) {
if (null == message || null == clazz) {
return null;
}
String str = new String(message.getBody());
return JsonUtil.strToObj(str, clazz);
}
}
package com.cx.cn.cxquartz.job;
import com.cx.cn.cxquartz.bean.QuartzTaskInformations;
import com.cx.cn.cxquartz.service.quartz.QuartzService;
import com.cx.cn.cxquartz.util.CommonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.concurrent.atomic.AtomicInteger;
@Component
public class KafkaListener {
@Autowired
private QuartzService quartzService;
private static final Logger logger = LoggerFactory.getLogger(KafkaListener.class);
private AtomicInteger atomicInteger;
public void messageConsumerHandler(String content) {
logger.info("监听到消息:{}", content);
atomicInteger = new AtomicInteger(0);
String id = "";
String taskNo = "";
try {
// message格式 ---------> taskNo:id:executeParameter;
String[] split = ":".split(content);
id = split[1];
taskNo = split[0];
//TODO kafka逻辑
} catch (Exception ex) {
logger.error("");
atomicInteger.incrementAndGet();
quartzService.addTaskErrorRecord(id, taskNo + ":" + ex.getMessage(), CommonUtil.getExceptionDetail(ex));
}
quartzService.updateRecordById(atomicInteger.get(), Long.parseLong(id));
QuartzTaskInformations quartzTaskInformation = new QuartzTaskInformations();
quartzTaskInformation.setId(Long.parseLong(id));
quartzTaskInformation.setLastmodifytime(System.currentTimeMillis());
quartzService.updateTask(quartzTaskInformation);
}
}
package com.cx.cn.cxquartz.job;
import com.cx.cn.cxquartz.bean.QuartzTaskInformations;
import com.cx.cn.cxquartz.bean.QuartzTaskRecords;
import com.cx.cn.cxquartz.service.quartz.QuartzService;
import com.cx.cn.cxquartz.service.quartz.impl.QuartzServiceImpl;
import com.cx.cn.cxquartz.util.ApplicationContextHolder;
import com.cx.cn.cxquartz.util.CommonUtil;
import com.cx.cn.cxquartz.util.HttpClientUtil;
import com.cx.cn.cxquartz.util.ResultEnum;
import org.apache.commons.lang.StringUtils;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import java.util.concurrent.atomic.AtomicInteger;
@DisallowConcurrentExecution
public class QuartzMainJobFactory implements Job {
private static Logger logger = LoggerFactory.getLogger(QuartzMainJobFactory.class);
private AtomicInteger atomicInteger;
@Value("${local.czurl}")
private String czurl;
@Value("${local.fxurl}")
private String fxurl;
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
atomicInteger = new AtomicInteger(0);
JobDataMap jobDataMap = jobExecutionContext.getMergedJobDataMap();
String id = jobDataMap.getString("id");
String taskNo = jobDataMap.getString("taskNo");
String executorNo = jobDataMap.getString("executorNo");
String url = jobDataMap.getString("url");
String executeParameter = jobDataMap.getString("executeParameter");
logger.info("定时任务被执行:taskNo={},executorNo={},url={},executeParameter={}", taskNo, executorNo, url, executeParameter);
QuartzService quartzService = (QuartzServiceImpl) ApplicationContextHolder.getBean("quartzServiceImpl");
QuartzTaskRecords records = null;
try {
//保存定时任务的执行记录
records = quartzService.addTaskRecords(taskNo);
if (null == records || !ResultEnum.INIT.name().equals(records.getTaskstatus())) {
logger.info("taskNo={}保存执行记录失败", taskNo);
return;
}
//if (ResultEnum.HTTP.getMessage().equals(sendType)) {
try {
String result = HttpClientUtil.doPost(taskNo.contains("cz_") ? czurl : fxurl, "text/json", executeParameter);
logger.info("taskNo={},执行结果result{}", taskNo, result);
if (StringUtils.isEmpty(result)) {
throw new RuntimeException("taskNo=" + taskNo + "http方式返回null");
}
} catch (Exception ex) {
logger.error("");
throw ex;
}
// } else if (ResultEnum.KAFKA.getMessage().equals(sendType)) {
// try {
// String message = new StringBuffer(taskNo).append(":").append(id).append(":").append(executeParameter).toString();
// quartzService.sendMessage(message);
// logger.info("taskNo={},sendtype={}推送至kafka成功", taskNo, sendType);
// } catch (Exception ex) {
// logger.error("");
// throw ex;
// }
// }
} catch (Exception ex) {
String exception=CommonUtil.getExceptionDetail(ex);
logger.error(exception);
atomicInteger.incrementAndGet();
quartzService.addTaskErrorRecord(records.getId().toString(), taskNo + ":" + ex.getMessage(), exception);
}
// quartzService.updateRecordById(atomicInteger.get(), records.getId());
//QuartzTaskInformations quartzTaskInformation = new QuartzTaskInformations();
//quartzTaskInformation.setId(Long.parseLong(id));
//quartzTaskInformation.setLastmodifytime(System.currentTimeMillis());
//quartzService.updateTask(quartzTaskInformation);
}
}
package com.cx.cn.cxquartz.job; package com.cx.cn.cxquartz.job;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.websocket.*; import javax.websocket.*;
...@@ -12,7 +14,7 @@ import java.util.concurrent.ConcurrentHashMap; ...@@ -12,7 +14,7 @@ import java.util.concurrent.ConcurrentHashMap;
@Component @Component
@ServerEndpoint("/websocket/{name}") @ServerEndpoint("/websocket/{name}")
public class WebSocket { public class WebSocket {
private static final Logger logger = LoggerFactory.getLogger(WebSocket.class);
/** /**
* 与某个客户端的连接对话,需要通过它来给客户端发送消息 * 与某个客户端的连接对话,需要通过它来给客户端发送消息
*/ */
...@@ -64,7 +66,7 @@ public class WebSocket { ...@@ -64,7 +66,7 @@ public class WebSocket {
AppointSending(name, new ObjectMapper().writeValueAsString(map)); AppointSending(name, new ObjectMapper().writeValueAsString(map));
}catch (Exception ex) }catch (Exception ex)
{ {
ex.printStackTrace(); logger.error("websocket->OnMessage eror:{}",ex.toString());
} }
} }
} }
...@@ -80,7 +82,7 @@ public class WebSocket { ...@@ -80,7 +82,7 @@ public class WebSocket {
if (null != webSocketSet.get(name) && null != webSocketSet.get(name).session && null != webSocketSet.get(name).session.getBasicRemote()) if (null != webSocketSet.get(name) && null != webSocketSet.get(name).session && null != webSocketSet.get(name).session.getBasicRemote())
webSocketSet.get(name).session.getBasicRemote().sendText(message); webSocketSet.get(name).session.getBasicRemote().sendText(message);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); logger.error("websocket->GroupSending eror:{}",e.toString());
} }
} }
} }
...@@ -99,7 +101,7 @@ public class WebSocket { ...@@ -99,7 +101,7 @@ public class WebSocket {
webSocketSet.get(name).session.getBasicRemote().sendText(message); webSocketSet.get(name).session.getBasicRemote().sendText(message);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); logger.error("websocket->AppointSending eror:{}",e.toString());
} }
} }
} }
......
package com.cx.cn.cxquartz.rabbitmq;
/**
* 消息队列常量
*/
public class QueueConstants {
/**
* 任务队列常量
*/
public interface QueueTaskConsumer{
/**
* 交换机名称
*/
String EXCHANGE = "RabbitMQ.DirectExchange.TaskConsumer";
/**
* 队列名称
*/
String QUEUE = "RabbitMQ.DirectQueue.TaskConsumer";
/**
* 路由键
*/
String ROUTEKEY = "RabbitMQ.RouteKey.TaskConsumer";
}
/**
* 消息通知队列
*/
public enum QueueTaskEnum {
QUEUE_TASK_ENUM(QueueConstants.QueueTaskConsumer.EXCHANGE, QueueConstants.QueueTaskConsumer.QUEUE,
QueueConstants.QueueTaskConsumer.ROUTEKEY);
/**
* 交换机名称
*/
private String exchange;
/**
* 队列名称
*/
private String queue;
/**
* 路由键
*/
private String routeKey;
QueueTaskEnum(String exchange, String queue, String routeKey) {
this.exchange = exchange;
this.queue = queue;
this.routeKey = routeKey;
}
public String getExchange() {
return exchange;
}
public void setExchange(String exchange) {
this.exchange = exchange;
}
public String getQueue() {
return queue;
}
public void setQueue(String queue) {
this.queue = queue;
}
public String getRouteKey() {
return routeKey;
}
public void setRouteKey(String routeKey) {
this.routeKey = routeKey;
}
}
/**
* t推送第三方队列常量
*/
public interface QueueSendToDXConsumer{
/**
* 交换机名称
*/
String EXCHANGE = "RabbitMQ.DirectExchange.SendToDXConsumer";
/**
* 队列名称
*/
String QUEUE = "RabbitMQ.DirectQueue.SendToDXConsumer";
/**
* 路由键
*/
String ROUTEKEY = "RabbitMQ.RouteKey.SendToDXConsumer";
}
/**
* 消息第三方声音告警队列
*/
public enum QueueSendToDXEnum {
QUEUE_SEND_TO_DX_ENUM(QueueConstants.QueueSendToDXConsumer.EXCHANGE, QueueConstants.QueueSendToDXConsumer.QUEUE,
QueueConstants.QueueSendToDXConsumer.ROUTEKEY);
/**
* 交换机名称
*/
private String exchange;
/**
* 队列名称
*/
private String queue;
/**
* 路由键
*/
private String routeKey;
QueueSendToDXEnum(String exchange, String queue, String routeKey) {
this.exchange = exchange;
this.queue = queue;
this.routeKey = routeKey;
}
public String getExchange() {
return exchange;
}
public void setExchange(String exchange) {
this.exchange = exchange;
}
public String getQueue() {
return queue;
}
public void setQueue(String queue) {
this.queue = queue;
}
public String getRouteKey() {
return routeKey;
}
public void setRouteKey(String routeKey) {
this.routeKey = routeKey;
}
}
/**
* 推送第三方队列常量
*/
public interface QueueSendToVoiceConsumer{
/**
* 交换机名称
*/
String EXCHANGE = "RabbitMQ.DirectExchange.SendToVoiceConsumer";
/**
* 队列名称
*/
String QUEUE = "RabbitMQ.DirectQueue.SendToVoiceConsumer";
/**
* 路由键
*/
String ROUTEKEY = "RabbitMQ.RouteKey.SendToVoiceConsumer";
}
/**
* 消息第三方队列
*/
public enum QueueSendToVoiceEnum {
QUEUE_SEND_TO_VOICE_ENUM(QueueConstants.QueueSendToVoiceConsumer.EXCHANGE, QueueConstants.QueueSendToVoiceConsumer.QUEUE,
QueueConstants.QueueSendToVoiceConsumer.ROUTEKEY);
/**
* 交换机名称
*/
private String exchange;
/**
* 队列名称
*/
private String queue;
/**
* 路由键
*/
private String routeKey;
QueueSendToVoiceEnum(String exchange, String queue, String routeKey) {
this.exchange = exchange;
this.queue = queue;
this.routeKey = routeKey;
}
public String getExchange() {
return exchange;
}
public void setExchange(String exchange) {
this.exchange = exchange;
}
public String getQueue() {
return queue;
}
public void setQueue(String queue) {
this.queue = queue;
}
public String getRouteKey() {
return routeKey;
}
public void setRouteKey(String routeKey) {
this.routeKey = routeKey;
}
}
/**
* 获得rtsp 或者hls的队列
*/
public interface QueueRTSPConsumer{
/**
* 交换机名称
*/
String EXCHANGE = "RabbitMQ.DirectExchange.RTSPConsumer";
/**
* 队列名称
*/
String QUEUE = "RabbitMQ.DirectQueue.RTSPConsumer";
/**
* 路由键
*/
String ROUTEKEY = "RabbitMQ.RouteKey.RTSPConsumer";
}
/**
* 消息第三方队列
*/
public enum QueueRTSPEnum {
QUEUE_RTSP_ENUM(QueueConstants.QueueRTSPConsumer.EXCHANGE, QueueConstants.QueueRTSPConsumer.QUEUE,
QueueConstants.QueueRTSPConsumer.ROUTEKEY);
/**
* 交换机名称
*/
private String exchange;
/**
* 队列名称
*/
private String queue;
/**
* 路由键
*/
private String routeKey;
QueueRTSPEnum(String exchange, String queue, String routeKey) {
this.exchange = exchange;
this.queue = queue;
this.routeKey = routeKey;
}
public String getExchange() {
return exchange;
}
public void setExchange(String exchange) {
this.exchange = exchange;
}
public String getQueue() {
return queue;
}
public void setQueue(String queue) {
this.queue = queue;
}
public String getRouteKey() {
return routeKey;
}
public void setRouteKey(String routeKey) {
this.routeKey = routeKey;
}
}
}
package com.cx.cn.cxquartz.rabbitmq.comsumer;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import java.io.IOException;
public interface BaseConsumer {
/**
* 消息消费入口
*
* @param message
* @param channel
* @throws IOException
*/
void consume(Message message, Channel channel) throws IOException;
}
\ No newline at end of file
package com.cx.cn.cxquartz.rabbitmq.comsumer;
import com.cx.cn.cxquartz.service.quartz.TraffPictureService;
import com.cx.cn.cxquartz.service.quartz.impl.ResultService;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.beans.factory.annotation.Autowired;
import java.lang.reflect.Proxy;
import java.util.Map;
/**
* 在Consumer中, 真正的业务逻辑其实只是保存消息到各自的数据表中, 但我们又不得不在调用consume方法之前校验消费幂等性, 发送后, 还要更新消息状态为"已消费"状态, 并手动ack。
* 实际项目中, 可能还有很多生产者-消费者的应用场景, 如记录日志, 发送短信等等, 都需要rabbitmq, 如果每次都写这些重复的公用代码, 没必要, 也难以维护。
* 所以, 我们可以将公共代码抽离出来, 让核心业务逻辑只关心自己的实现, 而不用做其他操作, 其实就是AOP。
* <p>
* 为达到这个目的, 有很多方法, 可以用spring aop, 可以用拦截器, 可以用静态代理, 也可以用动态代理, 在这里用的是动态代理。
*/
public class BaseConsumerProxy {
private static final Logger logger = LoggerFactory.getLogger(BaseConsumerProxy.class);
/**
* 代理对象
*/
private Object target;
/**
* 消息业务操作对象
*/
@Autowired
TraffPictureService traffPictureService;
@Autowired
ResultService resultService;
public BaseConsumerProxy(Object target, TraffPictureService traffPictureService) {
this.target = target;
this.traffPictureService = traffPictureService;
}
public BaseConsumerProxy(Object target) {
this.target = target;
}
/**
* 使用动态代理实现消费端幂等性验证和消费确认(ack)
*
* @return
*/
public Object getProxy() {
ClassLoader classLoader = target.getClass().getClassLoader();
Class[] interfaces = target.getClass().getInterfaces();
//Lambda表达式方式实现InvocationHandler接口
return Proxy.newProxyInstance(classLoader, interfaces, (proxy, method, args) -> {
Message message = (Message) args[0];
Channel channel = (Channel) args[1];
//String correlationId = getCorrelationId(message);
// 消费幂等性, 防止消息被重复消费
// 重启服务器, 由于有一条未被ack的消息, 所以重启后监听到消息, 进行消费, 但是由于消费前会判断该消息的状态是否未被消费, 发现status=3, 即已消费,
// 所以, 直接return, 这样就保证了消费端的幂等性, 即使由于网络等原因投递成功而未触发回调, 从而多次投递, 也不会重复消费进而发生业务异常。
// if (isConsumed(correlationId)) {
// logger.info("重复消费, correlationId: {}", correlationId);
// return null;
// }
MessageProperties properties = message.getMessageProperties();
long tag = properties.getDeliveryTag();
try {
// 真正消费的业务逻辑
Object result = method.invoke(target, args);
//traffPictureService.updateStatus(correlationId, QueueConstants.MessageLogStatus.CONSUMED_SUCCESS);
// 消费确认 虽然消息确实被消费了, 但是由于是手动确认模式, 而最后又没手动确认, 所以, 消息仍被rabbitmq保存。
// 所以, 手动ack能够保证消息一定被消费, 但一定要记得basicAck。
channel.basicAck(tag, false);
return result;
} catch (Exception e) {
logger.error("getProxy error", e);
channel.basicNack(tag, false,true);
return null;
}
});
}
/**
* 获取CorrelationId
*
* @param message
* @return
*/
private String getCorrelationId(Message message) {
String correlationId = null;
MessageProperties properties = message.getMessageProperties();
Map<String, Object> headers = properties.getHeaders();
for (Map.Entry entry : headers.entrySet()) {
String key = (String) entry.getKey();
String value = (String) entry.getValue();
if (key.equals("spring_returned_message_correlation")) {
correlationId = value;
}
}
return correlationId;
}
/**
* 消息是否已被消费
*
* @param correlationId
* @return
*/
private boolean isConsumed(String correlationId) {
//查看数据是否入表
return false;
// MessageLog msgLog = msgLogService.selectByMsgId(correlationId);
// return null == msgLog || msgLog.getStatus().equals(QueueConstants.MessageLogStatus.CONSUMED_SUCCESS);
}
}
\ No newline at end of file
package com.cx.cn.cxquartz.rabbitmq.comsumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
//@Component
public class ResendMessage {
private static final Logger logger = LoggerFactory.getLogger(ResendMessage.class);
@Autowired
private RabbitTemplate rabbitTemplate;
// 最大投递次数
private static final int MAX_TRY_COUNT = 3;
/**
* 每30s拉取投递失败的消息, 保证消息100%投递成功并被消费.
* 实际应用场景中, 可能由于网络原因, 或者消息未被持久化MQ就宕机了, 使得投递确认的回调方法ConfirmCallback没有被执行,
* 从而导致数据库该消息状态一直是投递中的状态, 此时就需要进行消息重投, 即使也许消息已经被消费了。
* 定时任务只是保证消息100%投递成功, 而多次投递的消费幂等性需要消费端自己保证。
* 我们可以将回调和消费成功后更新消息状态的代码注释掉, 开启定时任务, 查看是否重投。
*/
@Scheduled(cron = "0/30 * * * * ?")
public void resend() {
logger.info("开始执行定时任务(重新投递消息)");
// List<MessageLog> msgLogs = msgLogService.selectTimeoutMsg();
// //查询推送给失败的数据,重新投递,投递最大次数为三次
// msgLogs.forEach(msgLog -> {
// String msgId = msgLog.getMsgId();
// if (msgLog.getTryCount() >= MAX_TRY_COUNT) {
// msgLogService.updateStatus(msgId, QueueConstants.MessageLogStatus.DELIVER_FAIL);
// logger.info("超过最大重试次数, 消息投递失败, msgId: {}", msgId);
// } else {
// // 投递次数+1
// msgLogService.updateTryCount(msgId, msgLog.getNextTryTime());
//
// CorrelationData correlationData = new CorrelationData(msgId);
// // 重新投递
// rabbitTemplate.convertAndSend(msgLog.getExchange(), msgLog.getRoutingKey(),
// MessageHelper.objToMsg(msgLog.getMsg()), correlationData);
//
// logger.info("第 " + (msgLog.getTryCount() + 1) + " 次重新投递 MsgID:" + msgId + "的消息!");
// }
// });
logger.info("定时任务执行结束(重新投递消息)");
}
}
package com.cx.cn.cxquartz.rabbitmq.comsumer;
import com.cx.cn.cxquartz.helper.MessageHelper;
import com.cx.cn.cxquartz.service.quartz.TraffAlarmRecordService;
import com.cx.cn.cxquartz.service.quartz.impl.EventWriteService;
import com.cx.cn.cxquartz.util.JsonUtil;
import com.cx.cn.cxquartz.vo.JobTjParam;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.Map;
/**
* 消息处理并推送第三方
*/
@Component
public class SendToDXConsumer implements BaseConsumer {
private static final Logger logger = LoggerFactory.getLogger(SendToDXConsumer.class);
@Autowired
TraffAlarmRecordService traffAlarmRecordService;
@Autowired
EventWriteService eventWriteService;
/**
* 消息消费入口
*
* @param message
* @param channel
* @throws IOException
*/
@Override
public void consume(Message message, Channel channel) throws IOException {
logger.info("SendToDXConsumer 收到消息: {}", message.toString());
Map result = MessageHelper.msgToObj(message, Map.class);
if (null != result.get("id") && null!=result.get("traff") && null!=result.get("callback")) {
JobTjParam jobTjParam=JsonUtil.strToObj(result.get("traff").toString(),JobTjParam.class);
if(null!=jobTjParam) {
// eventWriteService.sendEventByCallUrl(Long.parseLong(result.get("id").toString())
// , jobTjParam, result.get("callback").toString());
}
}
}
}
package com.cx.cn.cxquartz.rabbitmq.comsumer;
import com.cx.cn.cxquartz.helper.MessageHelper;
import com.cx.cn.cxquartz.service.quartz.TraffAlarmRecordService;
import com.cx.cn.cxquartz.service.quartz.impl.EventWriteService;
import com.cx.cn.cxquartz.util.JsonUtil;
import com.cx.cn.cxquartz.vo.JobTjParam;
import com.cx.cn.cxquartz.vo.Voice;
import com.cx.cn.cxquartz.vo.VoiceData;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.Map;
/**
* 消息处理并推送第三方
*/
@Component
public class SendToVoiceConsumer implements BaseConsumer {
private static final Logger logger = LoggerFactory.getLogger(SendToVoiceConsumer.class);
@Autowired
TraffAlarmRecordService traffAlarmRecordService;
@Autowired
EventWriteService eventWriteService;
@Value("${voice.unionId}")
private String unionId;
@Value("${voice.appKey}")
private String appKey;
@Value("${voice.corpId}")
private String corpId;
@Value("${voice.eventId}")
private Integer eventId;
/**
* 消息消费入口
*
* @param message
* @param channel
* @throws IOException
*/
@Override
public void consume(Message message, Channel channel) {
logger.info("SendToVoiceConsumer 收到消息: {}", message.toString());
Map result = MessageHelper.msgToObj(message, Map.class);
if (null != result.get("id") && null!=result.get("traff") && null!=result.get("callback")) {
JobTjParam jobTjParam=JsonUtil.strToObj(result.get("traff").toString(), JobTjParam.class);
//回调声音触发事件
if (null!=jobTjParam &&unionId.contains(jobTjParam.getDeviceId())) {
VoiceData voicedata = new VoiceData();
voicedata.setAppKey(appKey);
voicedata.setCorpId(corpId);
voicedata.setRequestData(new Voice(eventId,unionId));
// logger.info(" send to voice: {}", new ObjectMapper().writeValueAsString(voicedata));
//同步推送
// eventWriteService.sendVoice(voicedata);
}
//推送告警到前端
// webSocket.GroupSending(JsonUtil.objToStr(traffpictureParamresult));
}
}
}
package com.cx.cn.cxquartz.rabbitmq.comsumer;
import com.cx.cn.cxquartz.bean.QuartzTaskInformations;
import com.cx.cn.cxquartz.helper.MessageHelper;
import com.cx.cn.cxquartz.service.quartz.TraffAlarmRecordService;
import com.cx.cn.cxquartz.service.quartz.impl.ResultService;
import com.cx.cn.cxquartz.service.quartz.impl.VideoRTSPorURLService;
import com.cx.cn.cxquartz.util.JsonUtil;
import com.cx.cn.cxquartz.vo.Sbtdspsr;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.Map;
@Component
public class SnapShotConsumer implements BaseConsumer{
private static final Logger logger = LoggerFactory.getLogger(TaskConsumConsumer.class);
@Autowired
VideoRTSPorURLService videoRTSPorURLService;
@Override
public void consume(Message message, Channel channel) throws IOException {
logger.info("SnapShotConsumer 收到消息: {}", message.toString());
Sbtdspsr result = MessageHelper.msgToObj(message, Sbtdspsr.class);
if (result.getTdlx().equals("1")) {
//调用rtsp 的服务
String token=videoRTSPorURLService.getRTSPAccessToekenByDeviceCode(result.getSbbh());
videoRTSPorURLService.getRTSPByDeviceCode(token,result.getSbbh());
}
else{
//调用hls 的服务
String token=videoRTSPorURLService.getHLSToekenByDeviceCode(result.getSbbh());
videoRTSPorURLService.getHLSByDeviceCode(token,result.getSbbh());
}
}
}
package com.cx.cn.cxquartz.rabbitmq.comsumer;
import com.cx.cn.cxquartz.helper.MessageHelper;
import com.cx.cn.cxquartz.service.quartz.TraffAlarmRecordService;
import com.cx.cn.cxquartz.service.quartz.impl.ResultService;
import com.cx.cn.cxquartz.util.JsonUtil;
import com.cx.cn.cxquartz.bean.QuartzTaskInformations;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.IOException;
import java.util.Map;
/**
* 消息处理并推送第三方
*/
//@Component
public class TaskConsumConsumer implements BaseConsumer {
private static final Logger logger = LoggerFactory.getLogger(TaskConsumConsumer.class);
@Autowired
TraffAlarmRecordService traffAlarmRecordService;
@Autowired
ResultService resultService;
/**
* 消息消费入口
*
* @param message
* @param channel
* @throws IOException
*/
@Override
public void consume(Message message, Channel channel) throws IOException {
logger.info("TaskConsumConsumer 收到消息: {}", message.toString());
Map result = MessageHelper.msgToObj(message, Map.class);
if (null != result.get("task")) {
QuartzTaskInformations taskinfo = JsonUtil.strToObj( result.get("task").toString(),QuartzTaskInformations.class);
if (null != result.get("result")) {
Map objresult = JsonUtil.strToObj(result.get("result").toString(), Map.class);
//处理消息
resultService.processResult(taskinfo, objresult);
}
}
}
}
package com.cx.cn.cxquartz.rabbitmq.comsumer.listener;
import com.cx.cn.cxquartz.rabbitmq.QueueConstants;
import com.cx.cn.cxquartz.rabbitmq.comsumer.BaseConsumer;
import com.cx.cn.cxquartz.rabbitmq.comsumer.BaseConsumerProxy;
import com.cx.cn.cxquartz.rabbitmq.comsumer.TaskConsumConsumer;
import com.cx.cn.cxquartz.service.quartz.TraffPictureService;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* 任务消息监听接受器
*/
//@Component
public class OrderCancelReceiver {
private static final Logger logger = LoggerFactory.getLogger(OrderCancelReceiver.class);
@Autowired
private TaskConsumConsumer taskConsumConsumer;
@Autowired
private TraffPictureService traffPictureService;
@RabbitListener(queues = QueueConstants.QueueTaskConsumer.QUEUE,containerFactory="rabbitListenerContainerFactory")
public void process(Message message, Channel channel) {
try {
logger.info("consumer->OrderCancelReceiver消费者收到消息 : " + message.toString());
BaseConsumerProxy baseConsumerProxy = new BaseConsumerProxy(taskConsumConsumer, traffPictureService);
BaseConsumer proxy = (BaseConsumer) baseConsumerProxy.getProxy();
if (null != proxy) {
proxy.consume(message, channel);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.cx.cn.cxquartz.rabbitmq.comsumer.listener;
import com.cx.cn.cxquartz.rabbitmq.QueueConstants;
import com.cx.cn.cxquartz.rabbitmq.comsumer.BaseConsumer;
import com.cx.cn.cxquartz.rabbitmq.comsumer.BaseConsumerProxy;
import com.cx.cn.cxquartz.rabbitmq.comsumer.SnapShotConsumer;
import com.cx.cn.cxquartz.rabbitmq.comsumer.TaskConsumConsumer;
import com.cx.cn.cxquartz.service.quartz.TraffAlarmRecordService;
import com.cx.cn.cxquartz.service.quartz.TraffPictureService;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* 任务消息监听接受器
*/
@Component
public class RTSPorHLSReceiver {
private static final Logger logger = LoggerFactory.getLogger(RTSPorHLSReceiver.class);
@Autowired
private SnapShotConsumer snapShotConsumer;
@RabbitListener(queues = QueueConstants.QueueRTSPConsumer.QUEUE,containerFactory="rabbitListenerContainerFactory")
public void process(Message message, Channel channel) {
try {
logger.info("consumer->RTSPorHLSReceiver消费者收到消息 : " + message.toString());
BaseConsumerProxy baseConsumerProxy = new BaseConsumerProxy(snapShotConsumer);
BaseConsumer proxy = (BaseConsumer) baseConsumerProxy.getProxy();
if (null != proxy) {
proxy.consume(message, channel);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.cx.cn.cxquartz.rabbitmq.comsumer.listener;
import com.cx.cn.cxquartz.rabbitmq.QueueConstants;
import com.cx.cn.cxquartz.rabbitmq.comsumer.BaseConsumer;
import com.cx.cn.cxquartz.rabbitmq.comsumer.BaseConsumerProxy;
import com.cx.cn.cxquartz.rabbitmq.comsumer.SendToDXConsumer;
import com.cx.cn.cxquartz.rabbitmq.comsumer.TaskConsumConsumer;
import com.cx.cn.cxquartz.service.quartz.impl.ResultService;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
/**
* 推送给第三方队列的监听
*/
@Component
public class SendtoDXReceiver {
private static final Logger logger = LoggerFactory.getLogger(SendtoDXReceiver.class);
@Autowired
private SendToDXConsumer sendToDXConsumer;
/**
* 消息接收处理
*
* @param message
* @param channel
* @throws IOException
*/
// @RabbitListener(queues = QueueConstants.QueueSendToDXConsumer.QUEUE,containerFactory="rabbitListenerContainerFactory")
// public void consume(Message message, Channel channel) throws IOException {
// logger.info("consumer->QueueSendToDXConsumer 消费者收到消息 : " + message.toString());
// BaseConsumerProxy baseConsumerProxy = new BaseConsumerProxy(sendToDXConsumer);
// BaseConsumer proxy = (BaseConsumer) baseConsumerProxy.getProxy();
// if (null != proxy) {
// proxy.consume(message, channel);
// }
// }
}
package com.cx.cn.cxquartz.rabbitmq.comsumer.listener;
import com.cx.cn.cxquartz.rabbitmq.QueueConstants;
import com.cx.cn.cxquartz.rabbitmq.comsumer.BaseConsumer;
import com.cx.cn.cxquartz.rabbitmq.comsumer.BaseConsumerProxy;
import com.cx.cn.cxquartz.rabbitmq.comsumer.SendToVoiceConsumer;
import com.cx.cn.cxquartz.service.quartz.impl.ResultService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
/**
* 推送给声音告警队列的监听
*/
@Component
public class SendtoVoiceAlarmReceiver {
@Autowired
private SendToVoiceConsumer sendToVoiceConsumer;
/**
* 消息接收处理
*
* @param message
* @param channel
* @throws IOException
*/
@RabbitListener(queues = QueueConstants.QueueSendToVoiceConsumer.QUEUE,containerFactory="rabbitListenerContainerFactory")
public void consume(Message message, Channel channel) throws IOException {
BaseConsumerProxy baseConsumerProxy = new BaseConsumerProxy(sendToVoiceConsumer);
BaseConsumer proxy = (BaseConsumer) baseConsumerProxy.getProxy();
if (null != proxy) {
proxy.consume(message, channel);
}
}
}
package com.cx.cn.cxquartz.rabbitmq.comsumer.listener;
import com.cx.cn.cxquartz.rabbitmq.QueueConstants;
import com.cx.cn.cxquartz.rabbitmq.comsumer.BaseConsumer;
import com.cx.cn.cxquartz.rabbitmq.comsumer.BaseConsumerProxy;
import com.cx.cn.cxquartz.rabbitmq.comsumer.SnapShotConsumer;
import com.cx.cn.cxquartz.service.quartz.TraffPictureService;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* 任务消息监听接受器
*/
@Component
public class SnapShotReceiver {
private static final Logger logger = LoggerFactory.getLogger(SnapShotReceiver.class);
@Autowired
private SnapShotConsumer snapShotConsumer;
@Autowired
private TraffPictureService traffPictureService;
@RabbitListener(queues = QueueConstants.QueueRTSPConsumer.QUEUE)
public void process(Message message, Channel channel) {
try {
logger.info("consumer->OrderCancelReceiver消费者收到消息 : " + message.toString());
BaseConsumerProxy baseConsumerProxy = new BaseConsumerProxy(snapShotConsumer, traffPictureService);
BaseConsumer proxy = (BaseConsumer) baseConsumerProxy.getProxy();
if (null != proxy) {
proxy.consume(message, channel);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.cx.cn.cxquartz.rabbitmq.producer.callback;
import com.cx.cn.cxquartz.controller.ExtController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;
/**
* 消息发送确认的回调
* 实现接口:implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback
* ConfirmCallback:只确认消息是否正确到达交换机中,不管是否到达交换机,该回调都会执行;
* ReturnCallback:如果消息从交换机未正确到达队列中将会执行,正确到达则不执行;
*/
@Component
public class ConsumerConfirmAndReturnCallback implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback {
private static final Logger logger = LoggerFactory.getLogger(ExtController.class);
@Autowired
private RabbitTemplate rabbitTemplate;
/**
* PostConstruct: 用于在依赖关系注入完成之后需要执行的方法上,以执行任何初始化.
*/
@PostConstruct
public void init() {
//指定 ConfirmCallback
rabbitTemplate.setConfirmCallback(this);
//指定 ReturnCallback
rabbitTemplate.setReturnCallback(this);
}
/**
* 消息从交换机成功到达队列,则returnedMessage方法不会执行;
* 消息从交换机未能成功到达队列,则returnedMessage方法会执行;
* 需要开启 return 确认机制
* spring.rabbitmq.publisher-returns=true
*/
@Override
public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
logger.info("returnedMessage回调方法->" + new String(message.getBody(), StandardCharsets.UTF_8) + ",\n replyCode:" + replyCode
+ "\n replyText:" + replyText + "\n exchange:" + exchange + ",\\n routingKey:" + routingKey);
}
/**
* 消息找不到对应的Exchange会先触发此方法
* 如果消息没有到达交换机,则该方法中isSendSuccess = false,error为错误信息;
* 如果消息正确到达交换机,则该方法中isSendSuccess = true;
* 需要开启 confirm 确认机制
* spring.rabbitmq.publisher-confirms=true
*/
@Override
public void confirm(CorrelationData correlationData, boolean isSendSuccess, String error) {
if (correlationData != null) {
// logger.info("confirm回调方法->回调消息ID为: " + correlationData.getId());
if (isSendSuccess) {
logger.info("confirm回调方法->消息成功发送到交换机!");
} else {
logger.info("confirm回调方法->消息[{}]发送到交换机失败!,原因 : [{}]", correlationData, error);
}
}
}
}
package com.cx.cn.cxquartz.redis;
public interface Consumer {
void consume(Object message);
}
package com.cx.cn.cxquartz.redis;
import com.cx.cn.cxquartz.bean.QuartzTaskInformations;
import com.cx.cn.cxquartz.helper.MessageHelper;
import com.cx.cn.cxquartz.rabbitmq.QueueConstants;
import com.cx.cn.cxquartz.service.quartz.SbtdspsrService;
import com.cx.cn.cxquartz.service.quartz.impl.VideoRTSPorURLService;
import com.cx.cn.cxquartz.util.HttpClientUtil;
import com.cx.cn.cxquartz.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.*;
@Component
public class OrderConsumer implements Consumer {
public static final Logger log = LoggerFactory.getLogger(OrderConsumer.class);
@Value("${local.czurl}")
private String czurl;
@Value("${local.fxurl}")
private String fxurl;
@Value("${file.recogurl}")
private String recogurl;
@Value("${file.model}")
private String model;
@Autowired
private RabbitTemplate rabbitTemplate;
@Autowired
private VideoRTSPorURLService videoRTSPorURLService;
@Autowired
private SbtdspsrService sbtdspsrService;
private static OrderConsumer orderConsumer;
@PostConstruct
public void init() {
orderConsumer = this;
orderConsumer.rabbitTemplate = this.rabbitTemplate;
orderConsumer.czurl=this.czurl;
orderConsumer.fxurl=this.fxurl;
orderConsumer.recogurl=this.recogurl;
orderConsumer.model=this.model;
orderConsumer.videoRTSPorURLService=this.videoRTSPorURLService;
orderConsumer.sbtdspsrService=this.sbtdspsrService;
}
public OrderConsumer(){
}
@Override
public void consume(Object message) {
if(message instanceof QuartzTaskInformations){
QuartzTaskInformations msg =(QuartzTaskInformations) message;
try {
//调用抽帧服务
String devicecode=msg.getExecuteparamter();
log.info("开始消费消息{}", msg.getId());
//如果设备编号是用一次废一次的,此刻需要现场取得rtsp
if(null!=devicecode&&devicecode.startsWith("33") && devicecode.length()==18){
//调用抽帧服务
String token= orderConsumer.videoRTSPorURLService.getRTSPAccessToekenByDeviceCode(devicecode);
String rtsp=orderConsumer.videoRTSPorURLService.getRTSPByDeviceCode(token,devicecode);
}
else{
//取表里最新的rtsp 或者hls 的值
String rtsp=orderConsumer.sbtdspsrService.getRtspOrHLSByDeviceCode(devicecode);
}
//将rtsp 作为参数调用抽帧服务
String result="{\n" +
" \"ret\": 0,\n" +
" \"desc\": \"succ!\",\n" +
" \"url\": \"http://zjh189.ncpoi.cc:7080/download/202109/08/33050300001327599605/33050300001327599605_20210908_134131031.jpg\",\n" +
" \"localuri\": \"/home/ubuntu/pictures/slice/202109/08/33050300001327599605/33050300001327599605_20210908_134131031.jpg\",\n" +
" \"timestamp\": \"2021-09-08 13:41:31.031\",\n" +
" \"devicecode\": \"33050300001327599605\"\n" +
"}";
//抽帧结果放到rabbttmq 中,根据msg 的检测metatype ,分别派发到不同的queue中,方便以后10条10条的去皮皮昂分析
Map m = new HashMap();
// m.put("deviceSnapshot", JsonUtil.objToStr(msg));
// m.put("result", result);
String msgId = UUID.randomUUID().toString();
CorrelationData correlationData = new CorrelationData(msgId);
orderConsumer.rabbitTemplate.convertAndSend(QueueConstants.QueueTaskEnum.QUEUE_TASK_ENUM.getExchange(),
QueueConstants.QueueTaskEnum.QUEUE_TASK_ENUM.getRouteKey()+"_"+msg.getObjectType(),
MessageHelper.objToMsg(result),
correlationData);
// String roistr= URLEncoder.encode("[")+msg.getObjectx()+","+msg.getObjecty()+","+msg.getObjectw()+","+msg.getObjecth()+URLEncoder.encode("]");
// String result= CompletableFuture.supplyAsync(() -> HttpClientUtil.doGet(orderConsumer.recogurl + "?deviceCode="+msg.getExecuteparamter()+"&model="+orderConsumer.model+"&roi="+roistr)).get(2, TimeUnit.SECONDS);
// String roistr= URLEncoder.encode("[")+msg.getObjectx()+","+msg.getObjecty()+","+msg.getObjectw()+","+msg.getObjecth()+URLEncoder.encode("]");
//// String result= CompletableFuture.supplyAsync(() -> HttpClientUtil.doGet(orderConsumer.recogurl + "?deviceCode="+msg.getExecuteparamter()+"&model="+orderConsumer.model+"&roi="+roiarray)).get(2, TimeUnit.SECONDS);
// log.info(" deviceCode:{} ",msg.getExecuteparamter());
// String result = HttpClientUtil.doGet(orderConsumer.recogurl + "?deviceCode=" + msg.getExecuteparamter() + "&model=" + orderConsumer.model + "&roi=" + roistr);
// log.info(" picture result:{} ",result);
// if (null != result && result.contains("ret"))//放入rabbitmq.数据由消费者去处理
// {
// Map objresult = JsonUtil.strToObj(result, Map.class);
// //处理消息
// if (null != objresult.get("ret") && objresult.get("ret").toString().equals("0")
// && null != objresult.get("desc")
// && objresult.get("desc").toString().contains("succ")) {
// Map m = new HashMap();
// m.put("task", JsonUtil.objToStr(msg));
// m.put("result", result);
// String msgId = UUID.randomUUID().toString();
// CorrelationData correlationData = new CorrelationData(msgId);
// //根绝不同的检测事件对象metatype分发到不同的通道
//
// orderConsumer.rabbitTemplate.convertAndSend(QueueConstants.QueueTaskEnum.QUEUE_TASK_ENUM.getExchange(),
// QueueConstants.QueueTaskEnum.QUEUE_TASK_ENUM.getRouteKey(),
// MessageHelper.objToMsg(m),
// correlationData);
// }
// }
//添加具体的消费逻辑,修改数据库什么的
log.info("消费消息{}完成", msg.getId());
}catch (Exception ex){
log.error("消费消息{}error:{}", msg.getId(), ex.toString());
}
}
}
}
package com.cx.cn.cxquartz.redis;
public class QueueConfiguration {
private String queue;
private Consumer consumer;
public static Builder builder(){
return new Builder();
}
public static class Builder{
private QueueConfiguration configuration = new QueueConfiguration();
public Builder queue(String queue) {
configuration.queue = queue;
return this;
}
public Builder consumer(Consumer consumer) {
configuration.consumer = consumer;
return this;
}
public QueueConfiguration build() {
if (configuration.queue == null || configuration.queue.length() == 0) {
if (configuration.consumer != null) {
configuration.queue = configuration.getClass().getSimpleName();
}
}
return configuration;
}
}
public void setQueue(String queue) {
this.queue = queue;
}
public void setConsumer(Consumer consumer) {
this.consumer = consumer;
}
public String getQueue() {
return queue;
}
public Consumer getConsumer() {
return consumer;
}
}
package com.cx.cn.cxquartz.redis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
@Service
public class QueueSender {
@Autowired
private RedisTemplate redisTemplate;
public QueueSender(RedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
public void sendMsg(String queue, Object msg) {
redisTemplate.opsForList().leftPush(queue, msg);
}
}
package com.cx.cn.cxquartz.redis.container;
import com.cx.cn.cxquartz.bean.QuartzTaskInformations;
import com.cx.cn.cxquartz.redis.Consumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import java.util.concurrent.TimeUnit;
public class QueueListener implements Runnable {
public static final Logger log = LoggerFactory.getLogger(QueueListener.class);
private RedisTemplate redisTemplate;
private String queue;
private Consumer consumer;
public QueueListener(RedisTemplate redisTemplate, String queue, Consumer consumer) {
this.redisTemplate = redisTemplate;
this.queue = queue;
this.consumer = consumer;
}
public QueueListener() {
}
/**
* 使用队列右出获取消息
* 没获取到消息则线程 sleep 一秒,减少资源浪费
* 实现了 Runnable 接口,可以作为线程任务执行
*/
@Override
public void run() {
while (RedisMQConsumerContainer.RUNNING){
Object message = redisTemplate.opsForList().rightPop(queue,500,TimeUnit.MICROSECONDS);
if( message instanceof QuartzTaskInformations){
consumer.consume(message);
}else{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
\ No newline at end of file
package com.cx.cn.cxquartz.redis.container;
import com.cx.cn.cxquartz.redis.QueueConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
@Component
public class RedisMQConsumerContainer {
public static final Logger log = LoggerFactory.getLogger(RedisMQConsumerContainer.class);
public static boolean RUNNING;
@Autowired
private RedisTemplate redisTemplate;
private Map<String,QueueConfiguration> consumerMap= new HashMap<>();
private ExecutorService executor;
public RedisMQConsumerContainer() {
init();
}
public void addConsumer(QueueConfiguration configuration) {
// if (consumerMap.containsKey(configuration.getQueue())) {
// log.warn("Key:{} this key already exists, and it will be replaced", configuration.getQueue());
// }
if (configuration.getConsumer() == null) {
log.warn("Key:{} consumer cannot be null, this configuration will be skipped", configuration.getQueue());
}
// consumerMap.put(configuration.getQueue(), configuration);
executor.submit(new QueueListener(redisTemplate,configuration.getQueue(),configuration.getConsumer()));
log.info("队列 {} 提交消息任务",configuration.getQueue());
}
public void destroy() {
log.info("Redis消息队列线程池关闭中");
RUNNING = false;
this.executor.shutdown();
log.info("QueueListener exiting.");
while (!this.executor.isTerminated()) {
}
log.info("QueueListener exited.");
}
public void init() {
log.info("消息队列线程池初始化");
RUNNING = true;
this.executor = Executors.newCachedThreadPool(r -> {
final AtomicInteger threadNumber = new AtomicInteger(6);
return new Thread(r, "RedisMQListener-" + threadNumber.getAndIncrement());
});
}
}
\ No newline at end of file
package com.cx.cn.cxquartz.service.quartz;
import com.cx.cn.cxquartz.bean.PatrolCtrlAlarm;
import com.cx.cn.cxquartz.bean.PatrolCtrlRecord;
import com.cx.cn.cxquartz.bean.*;
public interface ExtService {
int insertRecord(PatrolCtrlRecord record);
int insertAlarm(PatrolCtrlAlarm alarm);
}
package com.cx.cn.cxquartz.service.quartz;
import com.cx.cn.cxquartz.bean.*;
import com.cx.cn.cxquartz.vo.QuartzTaskRecordsVo;
import org.quartz.SchedulerException;
import java.util.List;
import java.util.Map;
public interface QuartzService {
String addTask(QuartzTaskInformations quartzTaskInformations);
List<QuartzTaskInformations> getTaskList(String taskNo, String currentPage);
QuartzTaskInformations getTaskById(String id);
String updateTask(QuartzTaskInformations quartzTaskInformations);
Integer UpdateExecuteParam(Map map);
String startJob(String taskNo,String status) throws SchedulerException;
String startOrStopJob(String taskNo,String status) throws SchedulerException;
void initLoadOnlineTasks();
void sendMessage(String message);
QuartzTaskRecords addTaskRecords(String taskNo);
Integer updateRecordById(Integer count, Long id);
Integer updateModifyTimeById(QuartzTaskInformations quartzTaskInformations);
Integer addTaskErrorRecord(String id, String errorKey, String errorValue);
List<QuartzTaskRecordsVo> taskRecords(String taskNo);
String runTaskRightNow(String taskNo);
QuartzTaskErrors detailTaskErrors(String recordId);
Integer insertRecord(PatrolCtrlRecord record);
Integer insertAlarm(PatrolCtrlAlarm alarm);
List<PictureTime> findLastPicTime();
List< PatrolCtrlRecord> queryCameraCode(List<String> ids);
List<QuartzTaskInformations> getTaskSByDeviceCode(String devicecode);
Integer deletetask(String taskno);
}
package com.cx.cn.cxquartz.service.quartz;
import com.cx.cn.cxquartz.bean.QuartzTaskErrors;
public interface QuartzTaskErrorsService {
Integer addTaskErrorRecord(QuartzTaskErrors quartzTaskErrors);
QuartzTaskErrors detailTaskErrors(String recordId);
}
package com.cx.cn.cxquartz.service.quartz;
import com.cx.cn.cxquartz.bean.PatrolCtrlAlarm;
import com.cx.cn.cxquartz.bean.PatrolCtrlRecord;
import com.cx.cn.cxquartz.bean.PictureTime;
import com.cx.cn.cxquartz.bean.QuartzTaskInformations;
import java.util.List;
import java.util.Map;
public interface QuartzTaskInformationsService {
String insert(QuartzTaskInformations quartzTaskInformations);
List<QuartzTaskInformations> selectList(String taskNo, String currentPage);
QuartzTaskInformations getTaskById(String id);
String updateTask(QuartzTaskInformations quartzTaskInformations);
Integer UpdateExecuteParam(Map map);
QuartzTaskInformations getTaskByTaskNo(String taskNo);
Integer updateStatusById(QuartzTaskInformations quartzTaskInformations);
List<QuartzTaskInformations> getUnnfrozenTasks(String status);
Integer updateModifyTimeById(QuartzTaskInformations quartzTaskInformations);
Integer insertRecord(PatrolCtrlRecord record);
Integer insertAlarm(PatrolCtrlAlarm alarm);
List<PictureTime> findLastPicTime();
List< PatrolCtrlRecord> queryCameraCode(List<String> ids);
List<QuartzTaskInformations> getTaskSByDeviceCode(String devicecode);
Integer deletetask(String taskno);
}
package com.cx.cn.cxquartz.service.quartz;
import com.cx.cn.cxquartz.bean.QuartzTaskRecords;
import java.util.List;
public interface QuartzTaskRecordsService {
long addTaskRecords(QuartzTaskRecords quartzTaskRecords);
Integer updateTaskRecords(QuartzTaskRecords quartzTaskRecords);
List<QuartzTaskRecords> listTaskRecordsByTaskNo(String taskNo);
}
...@@ -4,11 +4,14 @@ import com.cx.cn.cxquartz.bean.QuartzTaskInformations; ...@@ -4,11 +4,14 @@ import com.cx.cn.cxquartz.bean.QuartzTaskInformations;
import com.cx.cn.cxquartz.vo.Sbtdspsr; import com.cx.cn.cxquartz.vo.Sbtdspsr;
import java.util.List; import java.util.List;
import java.util.Map;
public interface SbtdspsrService { public interface SbtdspsrService {
List<Sbtdspsr> selectByRtsp(String videoid); List<Sbtdspsr> selectByRtsp(String videoid);
List<QuartzTaskInformations> selectRecogByRtsp(String rtsp); List<QuartzTaskInformations> selectRecogByRtsp(String rtsp);
int updateRecogByRtsp(String rtsp,String devicecode); int updateRecogByRtsp(String rtsp,String devicecode);
List<Sbtdspsr> list(); List<Sbtdspsr> list();
int updateRTSPorHLSParam(Sbtdspsr sbtdspsr);
List<Sbtdspsr> getPerformedTasks();
Long getPeriodicseconds();
String getRtspOrHLSByDeviceCode(String devicecode);
} }
package com.cx.cn.cxquartz.service.quartz;
import com.cx.cn.cxquartz.vo.Taskinfo;
import java.util.List;
import java.util.Map;
public interface TaskinfoService {
List<Taskinfo> getTaskinfoByMutiParam (Map map);
int addTaskinfo(Taskinfo taskinfo);
int updateTaskinfo(Taskinfo taskinfo);
int delTaskinfoByid(String id);
}
...@@ -127,7 +127,7 @@ public class EventWriteService { ...@@ -127,7 +127,7 @@ public class EventWriteService {
if (result.getCode() == 1) { if (result.getCode() == 1) {
log.info(" push to voice success"); log.info(" push to voice success");
} else { } else {
log.info(" push to voice result", new ObjectMapper().writeValueAsString(result)); log.info(" push to voice result:{}", JsonUtil.objToStr(result));
} }
} catch (TimeoutException e) { } catch (TimeoutException e) {
log.error("push to voice 请求超时:" + e.toString()); log.error("push to voice 请求超时:" + e.toString());
...@@ -154,7 +154,12 @@ public class EventWriteService { ...@@ -154,7 +154,12 @@ public class EventWriteService {
HttpEntity<JobTjParam> requestEntity = new HttpEntity<>(jobTjParam, headers); HttpEntity<JobTjParam> requestEntity = new HttpEntity<>(jobTjParam, headers);
return CompletableFuture.supplyAsync(() -> restTemplate.postForObject(callbackurl, requestEntity, ResultObj.class)).get(timeout, TimeUnit.SECONDS); return CompletableFuture.supplyAsync(() -> restTemplate.postForObject(callbackurl, requestEntity, ResultObj.class)).get(timeout, TimeUnit.SECONDS);
} }
private ResultObj sendToCalluriSync(JobTjParam jobTjParam, String callbackurl) throws InterruptedException, ExecutionException, TimeoutException {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
HttpEntity<JobTjParam> requestEntity = new HttpEntity<>(jobTjParam, headers);
return restTemplate.postForObject(callbackurl, requestEntity, ResultObj.class);
}
public void sendEventByCallUrl(TraffpictureParam traffpictureParamresult, JobTjParam jobTjParam, String callbackurl) { public void sendEventByCallUrl(TraffpictureParam traffpictureParamresult, JobTjParam jobTjParam, String callbackurl) {
ResultObj resultObj; ResultObj resultObj;
...@@ -172,6 +177,7 @@ public class EventWriteService { ...@@ -172,6 +177,7 @@ public class EventWriteService {
/* 其他失败 */ /* 其他失败 */
} catch (Exception e) { } catch (Exception e) {
traffpictureParamresult.setProcessstatus("-2");
traffpictureParamresult.setPushdesc("推送第三方失败"); traffpictureParamresult.setPushdesc("推送第三方失败");
log.error("eventwrite - sendEventByCallUrl 异常:" + e.toString()); log.error("eventwrite - sendEventByCallUrl 异常:" + e.toString());
//return ResultObj.error(ResponseEnum.E_9999.getCode(), e.toString()); //return ResultObj.error(ResponseEnum.E_9999.getCode(), e.toString());
...@@ -179,12 +185,36 @@ public class EventWriteService { ...@@ -179,12 +185,36 @@ public class EventWriteService {
traffpictureParamresult.setPushstatus(-1); traffpictureParamresult.setPushstatus(-1);
traffPictureMapper.updateTraffpicturePushStatus(traffpictureParamresult); traffPictureMapper.updateTraffpicturePushStatus(traffpictureParamresult);
} }
public void sendEventByCallUrl(Long id, JobTjParam jobTjParam, String callbackurl) {
ResultObj resultObj;
TraffpictureParam traffpictureParamresult=new TraffpictureParam();
traffpictureParamresult.setId(id);
try {
resultObj = sendToCalluriSync(jobTjParam, callbackurl);
traffpictureParamresult.setPushdesc(resultObj.getMsg());
/* 成功 */
if ("0".equals(resultObj.getCode())) {
traffpictureParamresult.setPushstatus(0);
//traffpictureParamresult.setPushdesc("推送第三方成功");
traffPictureMapper.updateTraffpicturePushStatus(traffpictureParamresult);
return;
}
/* 其他失败 */
} catch (Exception e) {
traffpictureParamresult.setProcessstatus("-2");
traffpictureParamresult.setPushdesc("推送第三方失败");
log.error("eventwrite - sendEventByCallUrl 异常:" + e.toString());
//return ResultObj.error(ResponseEnum.E_9999.getCode(), e.toString());
}
traffpictureParamresult.setPushstatus(-1);
traffPictureMapper.updateTraffpicturePushStatus(traffpictureParamresult);
}
private VoiceResultObj sendVoioceMessage(VoiceData voiceData) throws InterruptedException, ExecutionException, TimeoutException { private VoiceResultObj sendVoioceMessage(VoiceData voiceData) throws InterruptedException, ExecutionException, TimeoutException {
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
HttpEntity<VoiceData> requestEntity = new HttpEntity<>(voiceData, headers); HttpEntity<VoiceData> requestEntity = new HttpEntity<>(voiceData, headers);
return CompletableFuture.supplyAsync(() -> restTemplate.postForObject(voiceurl, requestEntity, VoiceResultObj.class)).get(timeout, TimeUnit.SECONDS); return restTemplate.postForObject(voiceurl, requestEntity, VoiceResultObj.class);
} }
public String sendToService(JobKey jobKey, String jsondata) { public String sendToService(JobKey jobKey, String jsondata) {
...@@ -200,13 +230,12 @@ public class EventWriteService { ...@@ -200,13 +230,12 @@ public class EventWriteService {
} }
public TraffpictureParam getResult(int tarnum, Long[] roiarray, String imgurl, public TraffpictureParam getResult(TraffpictureParam traffpictureParamresult,int tarnum, Long[] roiarray, String imgurl,
List<Map> objectList, List<Map> objectList,
JobTjParam jobTjParam, List<Map> detectObjects) { JobTjParam jobTjParam, List<Map> detectObjects) {
Map obj = new HashMap(); Map obj = new HashMap();
String recordtype = jobTjParam.getDetectType(); String recordtype = jobTjParam.getDetectType();
//判断是否统计结构化数据 //判断是否统计结构化数据
TraffpictureParam traffpictureParamresult = new TraffpictureParam();
traffpictureParamresult.setImagedata(imgurl); traffpictureParamresult.setImagedata(imgurl);
//人群统计 //人群统计
if ("10".equals(recordtype)) { if ("10".equals(recordtype)) {
...@@ -261,7 +290,8 @@ public class EventWriteService { ...@@ -261,7 +290,8 @@ public class EventWriteService {
} else { } else {
traffpictureParam.setCreatetime(createtime); traffpictureParam.setCreatetime(createtime);
} }
//默认推送成功,如果异常则更新状态为异常,该条记录会在30s 轮询中查出来,重新推送
traffpictureParam.setProcessstatus("-1");
traffpictureParam.setRecordtype(recordtype); traffpictureParam.setRecordtype(recordtype);
//新增到picture //新增到picture
traffPictureService.inserTraffpicture(traffpictureParam); traffPictureService.inserTraffpicture(traffpictureParam);
...@@ -417,12 +447,12 @@ public class EventWriteService { ...@@ -417,12 +447,12 @@ public class EventWriteService {
public void uploadPicture(TraffpictureParam traffpictureParam, String url, List<Map> points, String basepath, String filename) { public void uploadPicture(TraffpictureParam traffpictureParam, String url, List<Map> points, String basepath, String filename) {
try { try {
completionService.submit(() -> { //completionService.submit(() -> {
InputStream streanm = RestUtil.ReadFromURL(url); InputStream streanm = RestUtil.ReadFromURL(url);
ByteArrayOutputStream bos = PointUtil.drawByPoints(streanm, points); ByteArrayOutputStream bos = PointUtil.drawByPoints(streanm, points);
if (null == bos) { if (null == bos) {
log.error("picture is null"); log.error("picture is null");
return false; // return false;
} }
File file = FileUtil.uploadToLocal(filerootpath + File.separator + File file = FileUtil.uploadToLocal(filerootpath + File.separator +
...@@ -484,8 +514,8 @@ public class EventWriteService { ...@@ -484,8 +514,8 @@ public class EventWriteService {
// return true; // return true;
// } // }
return true; // return true;
}).get(timeout, TimeUnit.SECONDS); // }).get(timeout, TimeUnit.SECONDS);
} catch (Exception ex) { } catch (Exception ex) {
log.error(" uplaod file:{}", ex.toString()); log.error(" uplaod file:{}", ex.toString());
} }
......
package com.cx.cn.cxquartz.service.quartz.impl;
import com.cx.cn.cxquartz.bean.PatrolCtrlAlarm;
import com.cx.cn.cxquartz.bean.PatrolCtrlRecord;
import com.cx.cn.cxquartz.service.quartz.ExtService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ExtServiceImpl implements ExtService {
private static final Logger logger = LoggerFactory.getLogger(ExtServiceImpl.class);
@Autowired
private ExtService extService;
@Override
public int insertAlarm(PatrolCtrlAlarm alarm) {
int result = extService.insertAlarm(alarm);
return result;
}
/**
* 新增图片
*
* @param record
* @returnString
*/
@Override
public int insertRecord(PatrolCtrlRecord record) {
int result = extService.insertRecord(record);
return result;
}
}
package com.cx.cn.cxquartz.service.quartz.impl;
import com.cx.cn.cxquartz.bean.*;
import com.cx.cn.cxquartz.job.QuartzMainJobFactory;
import com.cx.cn.cxquartz.service.quartz.QuartzService;
import com.cx.cn.cxquartz.service.quartz.QuartzTaskErrorsService;
import com.cx.cn.cxquartz.service.quartz.QuartzTaskInformationsService;
import com.cx.cn.cxquartz.service.quartz.QuartzTaskRecordsService;
import com.cx.cn.cxquartz.util.CommonUtil;
import com.cx.cn.cxquartz.util.HttpClientUtil;
import com.cx.cn.cxquartz.util.ResultEnum;
import com.cx.cn.cxquartz.util.ResultUtil;
import com.cx.cn.cxquartz.vo.QuartzTaskRecordsVo;
import org.apache.commons.collections.CollectionUtils;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
@Service
@Configuration
public class QuartzServiceImpl implements QuartzService, InitializingBean {
private static final Logger logger = LoggerFactory.getLogger(QuartzServiceImpl.class);
public static final String QUARTZ_TOPIC = "quartztopic";
private AtomicInteger atomicInteger;
@Autowired
private KafkaTemplate kafkaTemplate;
@Autowired
private QuartzTaskInformationsService quartzTaskInformationsService;
@Autowired
private QuartzTaskErrorsService quartzTaskErrorsService;
@Autowired
private QuartzTaskRecordsService quartzTaskRecordsService;
@Autowired
private SchedulerFactoryBean schedulerBean;
@Value("${local.czurl}")
private String czurl;
@Value("${local.fxurl}")
private String fxurl;
/**
* 列表查询所有定时任务
*
* @return
*/
@Override
public List<QuartzTaskInformations> getTaskList(String taskNo, String currentPage) {
List<QuartzTaskInformations> quartzTaskInformations = quartzTaskInformationsService.selectList(taskNo, currentPage);
return quartzTaskInformations;
}
/**
* 新增定时任务
*
* @param quartzTaskInformations
* @return
*/
@Override
public String addTask(QuartzTaskInformations quartzTaskInformations) {
String result = quartzTaskInformationsService.insert(quartzTaskInformations);
return result;
}
@Override
public QuartzTaskInformations getTaskById(String id) {
return quartzTaskInformationsService.getTaskById(id);
}
@Override
public String updateTask(QuartzTaskInformations quartzTaskInformations) {
return quartzTaskInformationsService.updateTask(quartzTaskInformations);
}
@Override
public Integer UpdateExecuteParam(Map map) {
return quartzTaskInformationsService.UpdateExecuteParam(map);
}
/**
* 启动 or 暂停定时任务
*
* @param taskNo
* @return
* @throws SchedulerException
*/
@Override
@Transactional
public String startJob(String taskNo,String status) throws SchedulerException {
QuartzTaskInformations quartzTaskInformation = quartzTaskInformationsService.getTaskByTaskNo(taskNo);
if (quartzTaskInformation == null) {
return ResultUtil.success(ResultEnum.NO_DATA.getCode(), ResultEnum.NO_DATA.getMessage());
}
//String status = quartzTaskInformation.getFrozenstatus();
Scheduler scheduler = schedulerBean.getScheduler();
long currentTimeMillis = System.currentTimeMillis();
QuartzTaskInformations task = new QuartzTaskInformations();
task.setId(quartzTaskInformation.getId());
task.setVersion(quartzTaskInformation.getVersion());
//说明要暂停
if (ResultEnum.FROZEN.name().equals(status)) {
//删除
//暂停
scheduler.pauseTrigger(new TriggerKey(taskNo));
// 移除触发器中的任务
scheduler.unscheduleJob(new TriggerKey(taskNo));
scheduler.deleteJob(new JobKey(taskNo));
task.setFrozentime(currentTimeMillis);
task.setFrozenstatus(ResultEnum.FROZEN.name());
} else if (ResultEnum.UNFROZEN.name().equals(status)) {
//删除后启动
//暂停
scheduler.pauseTrigger(new TriggerKey(taskNo));
// 移除触发器中的任务
scheduler.unscheduleJob(new TriggerKey(taskNo));
scheduler.deleteJob(new JobKey(taskNo));
this.schedule(quartzTaskInformation, scheduler);
task.setUnfrozentime(currentTimeMillis);
task.setFrozenstatus(ResultEnum.UNFROZEN.name());
}
// task.setLastmodifytime(currentTimeMillis);
//quartzTaskInformationsService.updateStatusById(task);
// logger.info("taskNo={},taskName={},scheduleRule={},任务{}成功", quartzTaskInformation.getTaskno(), quartzTaskInformation.getTaskname(), quartzTaskInformation.getSchedulerrule(), ResultEnum.FROZEN.name().equals(status) ? "启动" : "暂停");
return ResultUtil.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMessage());
}
public String startOrStopJob(String taskNo,String status) throws SchedulerException {
QuartzTaskInformations quartzTaskInformation = quartzTaskInformationsService.getTaskByTaskNo(taskNo);
if (quartzTaskInformation == null) {
return ResultUtil.success(ResultEnum.NO_DATA.getCode(), ResultEnum.NO_DATA.getMessage());
}
Scheduler scheduler = schedulerBean.getScheduler();
long currentTimeMillis = System.currentTimeMillis();
QuartzTaskInformations task = new QuartzTaskInformations();
task.setId(quartzTaskInformation.getId());
task.setVersion(quartzTaskInformation.getVersion());
//暂停
scheduler.pauseTrigger(new TriggerKey(taskNo));
// 移除触发器中的任务
scheduler.unscheduleJob(new TriggerKey(taskNo));
scheduler.deleteJob(new JobKey(taskNo));
task.setFrozentime(currentTimeMillis);
if (ResultEnum.FROZEN.name().equals(status)) {
task.setFrozenstatus(ResultEnum.FROZEN.name());
//启动
} else if (ResultEnum.UNFROZEN.name().equals(status)) {
this.schedule(quartzTaskInformation, scheduler);
task.setFrozenstatus(ResultEnum.UNFROZEN.name());
}
task.setLastmodifytime(currentTimeMillis);
quartzTaskInformationsService.updateStatusById(task);
logger.info("taskNo={},taskName={},scheduleRule={},任务{}成功", quartzTaskInformation.getTaskno(), quartzTaskInformation.getTaskname(), quartzTaskInformation.getSchedulerrule(), ResultEnum.FROZEN.name().equals(status) ? "启动" : "暂停");
return ResultUtil.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMessage());
}
/**
* 初始化加载定时任务
*
* @throws Exception
*/
@Override
public void initLoadOnlineTasks() {
List<QuartzTaskInformations> unnfrozenTasks = quartzTaskInformationsService.getUnnfrozenTasks(ResultEnum.UNFROZEN.name());
if (CollectionUtils.isEmpty(unnfrozenTasks)) {
logger.info("没有需要初始化加载的定时任务");
return;
}
Scheduler scheduler = schedulerBean.getScheduler();
for (QuartzTaskInformations unnfrozenTask : unnfrozenTasks) {
try {
this.schedule(unnfrozenTask, scheduler);
} catch (Exception e) {
logger.error("系统初始化加载定时任务:taskno={},taskname={}失败原因exception={}", unnfrozenTask.getTaskno(), unnfrozenTask.getTaskname(), e);
}
}
}
/**
* 初始化加载定时任务
*
* @throws Exception
*/
@Override
public void afterPropertiesSet() throws Exception {
this.initLoadOnlineTasks();
}
@Override
public QuartzTaskRecords addTaskRecords(String taskNo) {
QuartzTaskRecords quartzTaskRecords = null;
try {
QuartzTaskInformations quartzTaskInformation = quartzTaskInformationsService.getTaskByTaskNo(taskNo);
if (null == quartzTaskInformation || ResultEnum.FROZEN.name().equals(quartzTaskInformation.getFrozenstatus())) {
logger.info("taskNo={} not exist or status is frozen!");
return null;
}
long currentTimeMillis = System.currentTimeMillis();
//QuartzTaskInformations task = new QuartzTaskInformations();
//task.setId(quartzTaskInformation.getId());
// task.setLastmodifytime(currentTimeMillis);
// quartzTaskInformationsService.updateTask(task);
//logger.info("taskNo={},taskName={}更新最后修改时间成功", quartzTaskInformation.getTaskno(), quartzTaskInformation.getTaskname());
quartzTaskRecords = new QuartzTaskRecords();
quartzTaskRecords.setTaskno(taskNo);
quartzTaskRecords.setTimekeyvalue(quartzTaskInformation.getTimekey());
quartzTaskRecords.setExecutetime(currentTimeMillis);
quartzTaskRecords.setTaskstatus(ResultEnum.INIT.name());
quartzTaskRecords.setFailcount(0);
quartzTaskRecords.setFailreason("");
quartzTaskRecords.setCreatetime(currentTimeMillis);
quartzTaskRecords.setLastmodifytime(currentTimeMillis);
quartzTaskRecordsService.addTaskRecords(quartzTaskRecords);
logger.info("taskNo={},taskName={}添加执行记录表成功", quartzTaskInformation.getTaskno(), quartzTaskInformation.getTaskname());
} catch (Exception ex) {
logger.error("添加执行记录表异常exceptio={}", ex);
return null;
}
return quartzTaskRecords;
}
@Override
public Integer updateRecordById(Integer count, Long id) {
QuartzTaskRecords records = new QuartzTaskRecords();
records.setId(id);
records.setFailcount(count);
records.setLastmodifytime(System.currentTimeMillis());
if (count > 0) {
records.setTaskstatus(ResultEnum.FAIL.name());
} else {
records.setTaskstatus(ResultEnum.SUCCESS.name());
}
return quartzTaskRecordsService.updateTaskRecords(records);
}
@Override
public Integer updateModifyTimeById(QuartzTaskInformations quartzTaskInformations) {
return quartzTaskInformationsService.updateModifyTimeById(quartzTaskInformations);
}
@Override
public Integer addTaskErrorRecord(String id, String errorKey, String errorValue) {
QuartzTaskErrors taskErrors = new QuartzTaskErrors();
taskErrors.setTaskexecuterecordid(String.valueOf(id));
taskErrors.setErrorkey(errorKey);
taskErrors.setCreatetime(System.currentTimeMillis());
taskErrors.setLastmodifytime(System.currentTimeMillis());
taskErrors.setErrorvalue(errorValue);
return quartzTaskErrorsService.addTaskErrorRecord(taskErrors);
}
public void schedule(QuartzTaskInformations quartzTaskInfo, Scheduler scheduler) throws SchedulerException {
TriggerKey triggerKey = TriggerKey.triggerKey(quartzTaskInfo.getTaskno(), Scheduler.DEFAULT_GROUP);
JobDetail jobDetail = JobBuilder.newJob(QuartzMainJobFactory.class).withDescription(quartzTaskInfo.getTaskname()).withIdentity(quartzTaskInfo.getTaskno(), Scheduler.DEFAULT_GROUP).build();
JobDataMap jobDataMap = jobDetail.getJobDataMap();
jobDataMap.put("id", quartzTaskInfo.getId().toString());
jobDataMap.put("taskNo", quartzTaskInfo.getTaskno());
jobDataMap.put("executorNo", quartzTaskInfo.getExecutorno());
jobDataMap.put("sendType", quartzTaskInfo.getSendtype());
jobDataMap.put("url", quartzTaskInfo.getUrl());
jobDataMap.put("executeParameter", quartzTaskInfo.getExecuteparamter());
CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(quartzTaskInfo.getSchedulerrule());
CronTrigger cronTrigger = TriggerBuilder.newTrigger().withDescription(quartzTaskInfo.getTaskname()).withIdentity(triggerKey).withSchedule(cronScheduleBuilder).build();
scheduler.scheduleJob(jobDetail, cronTrigger);
logger.info("taskNo={},taskName={},scheduleRule={} load to quartz success!", quartzTaskInfo.getTaskno(), quartzTaskInfo.getTaskname(), quartzTaskInfo.getSchedulerrule());
}
/**
* kafka推送消息
*
* @param message
*/
@Override
public void sendMessage(String message) {
kafkaTemplate.send(QUARTZ_TOPIC, message);
logger.info("给kafka推送消息message={}成功", message);
}
@Override
public List<QuartzTaskRecordsVo> taskRecords(String taskNo) {
List<QuartzTaskRecords> quartzTaskRecords = quartzTaskRecordsService.listTaskRecordsByTaskNo(taskNo);
QuartzTaskRecordsVo recordsVo = null;
List<QuartzTaskRecordsVo> voList = new ArrayList<>();
for (QuartzTaskRecords quartzTaskRecord : quartzTaskRecords) {
recordsVo = new QuartzTaskRecordsVo();
BeanUtils.copyProperties(quartzTaskRecord, recordsVo);
recordsVo.setTime(quartzTaskRecord.getLastmodifytime() - quartzTaskRecord.getCreatetime());
voList.add(recordsVo);
}
return voList;
}
/**
* 立即运行一次定时任务
*
* @param taskNo
* @return
*/
@Override
public String runTaskRightNow(String taskNo) {
atomicInteger = new AtomicInteger(0);
QuartzTaskInformations quartzTaskInformations = quartzTaskInformationsService.getTaskByTaskNo(taskNo);
if (quartzTaskInformations == null) {
return ResultUtil.success(ResultEnum.NO_DATA.getCode(), ResultEnum.NO_DATA.getMessage());
}
// Long id = quartzTaskInformations.getId();
//String sendType = quartzTaskInformations.getSendtype();
//String executorNo = quartzTaskInformations.getExecutorno();
// String url = quartzTaskInformations.getUrl();
String executeParameter = quartzTaskInformations.getExecuteparamter();
// logger.info("定时任务被执行:taskNo={},executorNo={},sendType={},url={},executeParameter={}", taskNo, executorNo, sendType, url, executeParameter);
QuartzTaskRecords records = null;
try {
//保存定时任务的执行记录
//records = this.addTaskRecords(taskNo);
if (null == records || !ResultEnum.INIT.name().equals(records.getTaskstatus())) {
logger.info("taskNo={}立即运行失--->>保存执行记录失败", taskNo);
return ResultUtil.success(ResultEnum.RUN_NOW_FAIL.getCode(), ResultEnum.RUN_NOW_FAIL.getMessage());
}
// if (ResultEnum.HTTP.getMessage().equals(sendType)) {
try {
HttpClientUtil.doPost(taskNo.contains("cz_") ? czurl : fxurl, "text/json", executeParameter);
logger.info("");
} catch (Exception ex) {
logger.error("");
atomicInteger.incrementAndGet();
throw ex;
}
// } else if (ResultEnum.KAFKA.getMessage().equals(sendType)) {
// try {
// String message = new StringBuffer(taskNo).append(":").append(executeParameter).toString();
// this.sendMessage(message);
// } catch (Exception ex) {
// logger.error("");
// atomicInteger.incrementAndGet();
// throw ex;
// }
// }
} catch (Exception ex) {
logger.error("");
atomicInteger.incrementAndGet();
this.addTaskErrorRecord(records.getId().toString(), taskNo + ":" + ex.getMessage(), CommonUtil.getExceptionDetail(ex));
}
//更改record表的执行状态、最后修改时间、失败个数
// this.updateRecordById(atomicInteger.get(), records.getId());
//更新taskinfo表的最后修改时间
// QuartzTaskInformations quartzTaskInformation = new QuartzTaskInformations();
// quartzTaskInformation.setId(id);
//quartzTaskInformation.setLastmodifytime(System.currentTimeMillis());
// this.updateTask(quartzTaskInformation);
return ResultUtil.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMessage());
}
@Override
public QuartzTaskErrors detailTaskErrors(String recordId) {
return quartzTaskErrorsService.detailTaskErrors(recordId);
}
@Override
public Integer insertRecord(PatrolCtrlRecord record) {
return quartzTaskInformationsService.insertRecord(record);
}
@Override
public Integer insertAlarm(PatrolCtrlAlarm alarm) {
return quartzTaskInformationsService.insertAlarm(alarm);
}
@Override
public List<PictureTime> findLastPicTime() {
return quartzTaskInformationsService.findLastPicTime();
}
@Override
public List< PatrolCtrlRecord> queryCameraCode(List<String> ids){
return quartzTaskInformationsService.queryCameraCode(ids);
}
@Override
public List<QuartzTaskInformations> getTaskSByDeviceCode(String devicecode) {
return quartzTaskInformationsService.getTaskSByDeviceCode(devicecode);
}
@Override
public Integer deletetask(String taskno) {
return quartzTaskInformationsService.deletetask(taskno);
}
}
package com.cx.cn.cxquartz.service.quartz.impl;
import com.cx.cn.cxquartz.bean.QuartzTaskErrors;
import com.cx.cn.cxquartz.dao.QuartzTaskErrorsMapper;
import com.cx.cn.cxquartz.service.quartz.QuartzTaskErrorsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class QuartzTaskErrorsServiceImpl implements QuartzTaskErrorsService {
@Autowired
private QuartzTaskErrorsMapper quartzTaskErrorsMapper;
@Override
public Integer addTaskErrorRecord(QuartzTaskErrors quartzTaskErrors) {
return quartzTaskErrorsMapper.insert(quartzTaskErrors);
}
@Override
public QuartzTaskErrors detailTaskErrors(String recordId) {
return quartzTaskErrorsMapper.detailTaskErrors(recordId);
}
}
package com.cx.cn.cxquartz.service.quartz.impl;
import com.cx.cn.cxquartz.bean.PatrolCtrlAlarm;
import com.cx.cn.cxquartz.bean.PatrolCtrlRecord;
import com.cx.cn.cxquartz.bean.PictureTime;
import com.cx.cn.cxquartz.bean.QuartzTaskInformations;
import com.cx.cn.cxquartz.dao.QuartzTaskInformationsMapper;
import com.cx.cn.cxquartz.service.quartz.QuartzTaskInformationsService;
import com.cx.cn.cxquartz.util.ResultEnum;
import com.cx.cn.cxquartz.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class QuartzTaskInformationsServiceImpl implements QuartzTaskInformationsService {
@Autowired
private QuartzTaskInformationsMapper quartzTaskInformationsMapper;
@Override
public String insert(QuartzTaskInformations quartzTaskInformations) {
String taskNo = quartzTaskInformations.getTaskno();
quartzTaskInformations.setVersion(0);
quartzTaskInformations.setCreatetime(System.currentTimeMillis());
quartzTaskInformations.setLastmodifytime(System.currentTimeMillis());
Integer count = quartzTaskInformationsMapper.selectByTaskNo(taskNo);
//判断是否重复任务编号
if (count > 0) {
return ResultUtil.success(ResultEnum.TASKNO_EXIST.getCode(), ResultEnum.TASKNO_EXIST.getMessage());
}
int insert = quartzTaskInformationsMapper.insert(quartzTaskInformations);
if (insert < 1) {
return ResultUtil.success(ResultEnum.FAIL.getCode(), ResultEnum.FAIL.getMessage());
}
return ResultUtil.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMessage());
}
@Override
public List<QuartzTaskInformations> selectList(String taskNo, String currentPage) {
Map<String, Object> map = new HashMap<>();
Integer start = Integer.parseInt(currentPage);
map.put("taskNo", taskNo);
map.put("startIndex", 10 * (start - 1));
return quartzTaskInformationsMapper.selectList(map);
}
@Override
public QuartzTaskInformations getTaskById(String id) {
return quartzTaskInformationsMapper.selectByPrimaryKey(Long.parseLong(id));
}
@Override
public String updateTask(QuartzTaskInformations quartzTaskInformations) {
Integer count = quartzTaskInformationsMapper.selectByTaskNo(quartzTaskInformations.getTaskno());
//判断是否重复任务编号
if (count >= 2) {
return ResultUtil.success(ResultEnum.TASKNO_EXIST.getCode(), ResultEnum.TASKNO_EXIST.getMessage());
}
//设置解冻时间或冻结时间及最后修改时间
if (ResultEnum.FROZEN.name().equals(quartzTaskInformations.getFrozenstatus())) {
quartzTaskInformations.setFrozentime(System.currentTimeMillis());
} else if (ResultEnum.UNFROZEN.name().equals(quartzTaskInformations.getFrozenstatus())) {
quartzTaskInformations.setUnfrozentime(System.currentTimeMillis());
}
quartzTaskInformations.setLastmodifytime(System.currentTimeMillis());
int updateCount = quartzTaskInformationsMapper.updateByPrimaryKeySelective(quartzTaskInformations);
//乐观锁控制并发修改
if (updateCount < 1) {
return ResultUtil.success(ResultEnum.UPDATE_FAIL.getCode(), ResultEnum.UPDATE_FAIL.getMessage());
}
return ResultUtil.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMessage());
}
@Override
public Integer UpdateExecuteParam(Map map) {
return quartzTaskInformationsMapper.UpdateExecuteParam(map);
}
@Override
public QuartzTaskInformations getTaskByTaskNo(String taskNo) {
return quartzTaskInformationsMapper.getTaskByTaskNo(taskNo);
}
@Override
public Integer updateStatusById(QuartzTaskInformations quartzTaskInformations) {
return quartzTaskInformationsMapper.updateByPrimaryKeySelective(quartzTaskInformations);
}
@Override
public List<QuartzTaskInformations> getUnnfrozenTasks(String status) {
return quartzTaskInformationsMapper.getUnfrozenTasks(status);
}
@Override
public Integer updateModifyTimeById(QuartzTaskInformations quartzTaskInformations) {
return quartzTaskInformationsMapper.updateByPrimaryKeySelective(quartzTaskInformations);
}
@Override
public Integer insertRecord(PatrolCtrlRecord record) {
return quartzTaskInformationsMapper.insertRecord(record);
}
@Override
public Integer insertAlarm(PatrolCtrlAlarm alarm) {
return quartzTaskInformationsMapper.insertAlarm(alarm);
}
@Override
public List<PictureTime> findLastPicTime() {
return quartzTaskInformationsMapper.findLastPicTime();
}
@Override
public List<PatrolCtrlRecord> queryCameraCode(List<String> ids){
return quartzTaskInformationsMapper.queryCameraCode(ids);
}
@Override
public List<QuartzTaskInformations> getTaskSByDeviceCode(String devicecode) {
return quartzTaskInformationsMapper.getTaskSByDeviceCode(devicecode);
}
@Override
public Integer deletetask(String taskno) {
return quartzTaskInformationsMapper.deletetask(taskno);
}
}
package com.cx.cn.cxquartz.service.quartz.impl;
import com.cx.cn.cxquartz.bean.QuartzTaskRecords;
import com.cx.cn.cxquartz.dao.QuartzTaskRecordsMapper;
import com.cx.cn.cxquartz.service.quartz.QuartzTaskRecordsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class QuartzTaskRecordsServiceImpl implements QuartzTaskRecordsService {
@Autowired
private QuartzTaskRecordsMapper quartzTaskRecordsMapper;
@Override
public long addTaskRecords(QuartzTaskRecords quartzTaskRecords) {
return quartzTaskRecordsMapper.insert(quartzTaskRecords);
}
@Override
public Integer updateTaskRecords(QuartzTaskRecords quartzTaskRecords) {
return quartzTaskRecordsMapper.updateByPrimaryKeySelective(quartzTaskRecords);
}
public List<QuartzTaskRecords> listTaskRecordsByTaskNo(String taskNo) {
return quartzTaskRecordsMapper.getTaskRecordsByTaskNo(taskNo);
}
;
}
package com.cx.cn.cxquartz.service.quartz.impl;
import com.cx.cn.cxquartz.helper.MessageHelper;
import com.cx.cn.cxquartz.job.WebSocket;
import com.cx.cn.cxquartz.rabbitmq.QueueConstants;
import com.cx.cn.cxquartz.service.quartz.TraffPictureService;
import com.cx.cn.cxquartz.util.DateUtils;
import com.cx.cn.cxquartz.util.JsonUtil;
import com.cx.cn.cxquartz.vo.JobTjParam;
import com.cx.cn.cxquartz.bean.QuartzTaskInformations;
import com.cx.cn.cxquartz.vo.TraffpictureParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.File;
import java.util.*;
@Service
public class ResultService {
@Autowired
EventWriteService eventWriteService;
@Autowired
TraffPictureService traffPictureService;
@Value("${file.outpath}")
private String outpath;
@Value("${voice.unionId}")
private String unionId;
@Value("${countryside.callbackurl}")
private String callbackurl;
@Value("${web.url}")
private String weburl;
@Value("${file.publicpictureurl}")
private String publicpictureurl;
@Value("${voice.appKey}")
private String appKey;
@Value("${voice.corpId}")
private String corpId;
@Value("${voice.eventId}")
private Integer eventId;
@Value("${file.rootpath}")
private String filerootpath;
@Autowired
WebSocket webSocket;
@Autowired
RabbitTemplate rabbitTemplate;
public static final Logger logger = LoggerFactory.getLogger(ResultService.class);
public void processResult(QuartzTaskInformations taskinfo, Map objectList) {
String devicecode=taskinfo.getExecuteparamter();
String recordtype = taskinfo.getRecordtype();
JobTjParam jobTjParam = new JobTjParam();
jobTjParam.setDeviceId(devicecode);
jobTjParam.setDetectType(recordtype);
String imageurl = objectList.get("url").toString();
TraffpictureParam traffpictureParamresult=new TraffpictureParam();
try {
Map maprecogdata = JsonUtil.strToObj(objectList.get("recogdata").toString(), Map.class);
List<Map> points = new ArrayList<>();
//分析结果数据
if (null != maprecogdata) {
List<Map> objectresult = (List<Map>) maprecogdata.get("ObjectList");
if (objectresult.size() < 1) {
logger.info(" objectresult is empty");
} else {
Long[] roiarray = new Long[4];
roiarray[0] = new Long(taskinfo.getObjectx());
roiarray[1] = new Long(taskinfo.getObjecty());
roiarray[2] = new Long(taskinfo.getObjectw());
roiarray[3] = new Long(taskinfo.getObjecth());
//图片划线并上传
String basepath = DateUtils.formatCurrDayYM() + File.separator + DateUtils.formatCurrDayDD() + File.separator + devicecode;
String filename = devicecode + "_" + DateUtils.parseDateToStrNoSign(objectList.get("timestamp").toString()) + "_result.jpg";
String filenameurl = File.separator + outpath + File.separator + basepath + File.separator + filename;
jobTjParam.setImageUrl(weburl + filenameurl);
traffpictureParamresult.setImagedata(filenameurl); //获得点位
traffpictureParamresult = eventWriteService.getResult(traffpictureParamresult, Integer.parseInt(taskinfo.getMetatype())
, roiarray, imageurl, objectresult, jobTjParam, points);
if (null == traffpictureParamresult) {
logger.info("人群密度未超或目标未出现");
} else {
//同步上传文件
eventWriteService.uploadPicture(traffpictureParamresult, imageurl, points, basepath, filename);
//新增
eventWriteService.setTraffpictureParam(recordtype, devicecode,
objectList.get("timestamp").toString(),
traffpictureParamresult);
Map sendtodxmap = new HashMap();
sendtodxmap.put("id", traffpictureParamresult.getId());
sendtodxmap.put("traff", JsonUtil.objToStr(jobTjParam));
sendtodxmap.put("callback", taskinfo.getUrl().equals("") ? callbackurl : taskinfo.getUrl());
CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
rabbitTemplate.convertAndSend(QueueConstants.QueueSendToDXEnum.QUEUE_SEND_TO_DX_ENUM.getExchange(),
QueueConstants.QueueSendToDXEnum.QUEUE_SEND_TO_DX_ENUM.getRouteKey(),
MessageHelper.objToMsg(sendtodxmap),
correlationData);
rabbitTemplate.convertAndSend(QueueConstants.QueueSendToVoiceEnum.QUEUE_SEND_TO_VOICE_ENUM.getExchange(),
QueueConstants.QueueSendToVoiceEnum.QUEUE_SEND_TO_VOICE_ENUM.getRouteKey(),
MessageHelper.objToMsg(sendtodxmap),
correlationData);
// //回调第三方接口
//// logger.info("send to dianxin data:{}",JSONObject.toJSONString(jobTjParam));
// eventWriteService.sendEventByCallUrl(traffpictureParamresult, jobTjParam, taskinfo.getUrl().equals("") ? callbackurl : taskinfo.getUrl());
}
}
}
} catch(Exception ex){
logger.error(" processResult error:{}", ex.toString());
}
}
}
package com.cx.cn.cxquartz.service.quartz.impl; package com.cx.cn.cxquartz.service.quartz.impl;
import com.cx.cn.cxquartz.bean.QuartzTaskInformations;
import com.cx.cn.cxquartz.dao.SbtdspsrMapper; import com.cx.cn.cxquartz.dao.SbtdspsrMapper;
import com.cx.cn.cxquartz.service.quartz.SbtdspsrService; import com.cx.cn.cxquartz.service.quartz.SbtdspsrService;
import com.cx.cn.cxquartz.bean.QuartzTaskInformations;
import com.cx.cn.cxquartz.vo.Sbtdspsr; import com.cx.cn.cxquartz.vo.Sbtdspsr;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
...@@ -41,4 +41,25 @@ public class SbtdspsrImpl implements SbtdspsrService { ...@@ -41,4 +41,25 @@ public class SbtdspsrImpl implements SbtdspsrService {
return sbtdspsrMapper.list(); return sbtdspsrMapper.list();
} }
@Override
public int updateRTSPorHLSParam(Sbtdspsr sbtdspsr) {
return sbtdspsrMapper.updateRTSPorHLSParam(sbtdspsr);
}
@Override
public List<Sbtdspsr> getPerformedTasks() {
return sbtdspsrMapper.getPerformedTasks();
}
@Override
public Long getPeriodicseconds() {
return sbtdspsrMapper.getPeriodicseconds();
}
@Override
public String getRtspOrHLSByDeviceCode(String devicecode) {
return sbtdspsrMapper.getRtspOrHLSByDeviceCode(devicecode);
}
} }
package com.cx.cn.cxquartz.service.quartz.impl;
import com.cx.cn.cxquartz.dao.TaskinfoMapper;
import com.cx.cn.cxquartz.service.quartz.TaskinfoService;
import com.cx.cn.cxquartz.vo.Taskinfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
@Service
public class TaskinfoServiceImpl implements TaskinfoService {
@Autowired
private TaskinfoMapper taskinfoMapper;
@Override
public List<Taskinfo> getTaskinfoByMutiParam(Map map ) {
return taskinfoMapper.getTaskinfoByMutiParam(map);
}
@Override
public int addTaskinfo(Taskinfo taskinfo) {
return taskinfoMapper.addTaskinfo(taskinfo);
}
@Override
public int updateTaskinfo(Taskinfo taskinfo) {
return taskinfoMapper.updateTaskinfo(taskinfo);
}
@Override
public int delTaskinfoByid(String id) {
return taskinfoMapper.delTaskinfoByid(id);
}
}
...@@ -3,9 +3,12 @@ package com.cx.cn.cxquartz.service.quartz.impl; ...@@ -3,9 +3,12 @@ package com.cx.cn.cxquartz.service.quartz.impl;
import com.cx.cn.cxquartz.dao.TraffPictureMapper; import com.cx.cn.cxquartz.dao.TraffPictureMapper;
import com.cx.cn.cxquartz.service.quartz.TraffPictureService; import com.cx.cn.cxquartz.service.quartz.TraffPictureService;
import com.cx.cn.cxquartz.vo.TraffpictureParam; import com.cx.cn.cxquartz.vo.TraffpictureParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
/** /**
* <p> * <p>
* 服务实现类 * 服务实现类
...@@ -16,7 +19,6 @@ import org.springframework.stereotype.Service; ...@@ -16,7 +19,6 @@ import org.springframework.stereotype.Service;
*/ */
@Service @Service
public class TraffpictureServiceImpl implements TraffPictureService { public class TraffpictureServiceImpl implements TraffPictureService {
@Autowired @Autowired
private TraffPictureMapper traffPictureMapper; private TraffPictureMapper traffPictureMapper;
...@@ -41,4 +43,5 @@ public class TraffpictureServiceImpl implements TraffPictureService { ...@@ -41,4 +43,5 @@ public class TraffpictureServiceImpl implements TraffPictureService {
return traffPictureMapper.queryimgdataByid(id); return traffPictureMapper.queryimgdataByid(id);
} }
} }
package com.cx.cn.cxquartz.service.quartz.impl;
import com.cx.cn.cxquartz.service.quartz.SbtdspsrService;
import com.cx.cn.cxquartz.util.DateUtils;
import com.cx.cn.cxquartz.vo.Sbtdspsr;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.client.RestTemplate;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Service
public class VideoRTSPorURLService {
private static final Logger logger = LoggerFactory.getLogger(VideoRTSPorURLService.class);
@Autowired
private RestTemplate restTemplate;
@Autowired
private SbtdspsrService sbtdspsrService;
@Value("${hlsurl.token}")
private String hlsurltoken;
@Value("${hlsurl.url}")
private String hlsurl;
@Value("${rtspurl.token}")
private String rtspurltoken;
@Value("${rtspurl.url}")
private String rtspurl;
@Value("${rtspurl.appid}")
private String appid;
@Value("${rtspurl.appsecret}")
private String appsecret;
@Value("${rtspurl.params}")
private String params;
public String getHLSToekenByDeviceCode(String deviceCode){
// "resultCode": "0",
// "httpStatus": 200,
// "resultMsg": "成功",
// "obj": "5f8d4fefb3670e1a7c64ed3bbf0202a006620f1d98ff8ea4ef504d1111188509",
// "serverTime": "2021-07-21 10:37:26"
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
Map map=new HashMap();
map.put("appId","WIMZjxpJ");
map.put("sign", DigestUtils.md5DigestAsHex(("appId=WIMZjxpJappSecret=686303f6571a232946746856484ea42730fde5bdtimestamp="+ DateUtils.getTimeStamps()).getBytes()));
HttpEntity<Map> requestEntity = new HttpEntity<>(map, headers);
Map result= restTemplate.postForObject(hlsurltoken,requestEntity,Map.class);
if(null!=result.get("resultCode") && "0".equals(result.get("resultCode").toString())
&& null!=result.get("httpStatus") && Integer.parseInt(result.get("httpStatus").toString())==200)
{
//获得token 成功,更新表数据
String token= String.valueOf(result.get("obj"));
String serverHlsTokenNextTime =DateUtils.addMin(String.valueOf(result.get("serverTime")),5);
//根据设备编号更新token 及token 过期数据
Sbtdspsr sbtdspsr=new Sbtdspsr();
sbtdspsr.setSbbh(deviceCode);
sbtdspsr.setToken(token);
sbtdspsr.setTokennexttime(serverHlsTokenNextTime);
sbtdspsr.setResourcetype("2");
sbtdspsrService.updateRTSPorHLSParam(sbtdspsr);
return token;
//根据token获得rtsp 地址
}
return null;
}
/***
* 根据token 获得hls 地址
* @param token
* @return
*/
public String getHLSByDeviceCode(String token,String devicecode){
//token 保活
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
headers.add("token", token);
HttpEntity<String> httpEntity = new HttpEntity(headers);
ResponseEntity<String> exchange = restTemplate.exchange(hlsurl+"?cameraIndexCode="+devicecode, HttpMethod.GET ,httpEntity,String.class);
String body=exchange.getBody();
try {
Map result = new ObjectMapper().readValue(body, Map.class);
if (null != result.get("resultCode") && "0".equals(result.get("resultCode").toString())
&& null != result.get("httpStatus") && Integer.parseInt(result.get("httpStatus").toString()) == 200) {
//获得token 成功,更新表数据
String hls = String.valueOf(result.get("obj"));
// "obj": "http://183.131.123.32:83/openUrl/fEBpgNq/live.m3u8",
// "httpStatus": 200,
// "resultCode": "0",
// "serverTime": "2021-07-21 12:40:06",
// "resultMsg": "成功"
//根据设备编号更新hls和下次执行时间 数据,hls 有效期是5分钟
String serverHlsNextTime =DateUtils.addMin(String.valueOf(result.get("serverTime")),5);
Sbtdspsr sbtdspsr=new Sbtdspsr();
sbtdspsr.setSbbh(devicecode);
sbtdspsr.setUrlnexttime(serverHlsNextTime);
sbtdspsr.setSqurllj(hls);
sbtdspsrService.updateRTSPorHLSParam(sbtdspsr);
return hls;
//根据token获得rtsp 地址
}
}catch (Exception ex){
logger.error("getHLSByDeviceCode"+ex.toString());
}
return null;
}
/***
* 获得rtsp token书籍
* @param deviceCode
* @return
*/
public String getRTSPAccessToekenByDeviceCode(String deviceCode){
//token 保活
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
Map result=restTemplate.getForObject(rtspurltoken+"?appid="+appid+"&appsecret="+appsecret,Map.class);
if(null!=result.get("code") && "0".equals(result.get("code").toString())){
// {
// "code": "0",
// "msg": null,
// "obj": {
// "expire": 1624435058554,
// "accessToken": "22712f9c6c8c889061513188878fb27a5ff5d1bd11bd4f80cc860170e24cf432a06118acf70d8e490fee04d73e676af76e8e2299b7a919d04a1d879e62069c9087e8c703ca0265c3"
// }
//获得token 成功,更新表数据
Map obj=(Map) result.get("obj");
String token=String.valueOf(obj.get("accessToken"));
String serverRTSPTokenNextTime=DateUtils.formatDate(new Date(String.valueOf(obj.get("expire"))));
//根据设备编号更新token 及token 过期数据
Sbtdspsr sbtdspsr=new Sbtdspsr();
sbtdspsr.setSbbh(deviceCode);
sbtdspsr.setTokennexttime(serverRTSPTokenNextTime);
sbtdspsr.setToken(token);
sbtdspsrService.updateRTSPorHLSParam(sbtdspsr);
return token;
//根据token获得rtsp 地址
}
return null;
}
public String getRTSPByDeviceCode(String token,String deviceCode) {
String timestamp = String.valueOf(new Date().getTime());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
headers.add("accessToken", token);
headers.add("timestamp", timestamp);
headers.add("sign", DigestUtils.md5DigestAsHex((params + deviceCode + "key" + timestamp).getBytes()));
HttpEntity<String> httpEntity = new HttpEntity(headers);
ResponseEntity<String> exchange = restTemplate.exchange(rtspurl + "?deviceCode=" + deviceCode, HttpMethod.GET, httpEntity, String.class);
String body = exchange.getBody();
try {
Map result = new ObjectMapper().readValue(body, Map.class);
if (null != result.get("errorCode") && "0".equals(result.get("errorCode").toString())) {
//获得token 成功,更新表数据
Map data = (Map) result.get("data");
// {
// "data": {
// "hlsUri": "http://183.131.55.15:5079/hls/33010200001327361919.m3u8",
// "rtmpUri": "rtmp://183.131.55.25:30011/pssWork_2/l_194116",
// "rtspUri": "rtsp://183.131.55.25:30010/pssWork_2/l_194116"
// },
// "errorCode": "0",
// "errorMsg": "success"
// }
String rtsp = String.valueOf(data.get("rtspUri"));
//省内设备 = 地址只能用一次 ,33开头的18位
// //集团设备 = 地址可以用20分钟,15位
Sbtdspsr sbtdspsr = new Sbtdspsr();
sbtdspsr.setSqurllj(rtsp);
sbtdspsr.setSbbh(deviceCode);
if (deviceCode.length() == 15) {
String serverHlsNextTime = DateUtils.addMin(new Date(), 20);
sbtdspsr.setUrlnexttime(serverHlsNextTime);
} else if (deviceCode.startsWith("33") && deviceCode.length() == 18) {
//无需更新,抽帧的时候再去调用,将设备的rtsp 地址换成null
sbtdspsr.setUrlnexttime(null);
}
//更新表里的数据
sbtdspsrService.updateRTSPorHLSParam(sbtdspsr);
return rtsp;
//根据token获得rtsp 地址
}
} catch (Exception ex) {
logger.error("getRTSPByDeviceCode" + ex.toString());
}
return null;
}
/***
* 根据rtsp 或者hls 去抽帧
*/
}
package com.cx.cn.cxquartz.util; package com.cx.cn.cxquartz.util;
import com.cx.cn.cxquartz.bean.PictureTime;
import java.io.File;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.io.StringWriter; import java.io.StringWriter;
import java.util.List;
public class CommonUtil { public class CommonUtil {
...@@ -25,21 +22,4 @@ public class CommonUtil { ...@@ -25,21 +22,4 @@ public class CommonUtil {
pw.close(); pw.close();
} }
} }
public static void removeFinishFiles( List<File> jsonFile, List<PictureTime> picturses)
{
if (picturses.size() > 0) {
//根据每个设备最新的时间进行过滤D:\imp\VideoPic\202009021049435991_0\20200906\112004.jpeg
String filetime = "";
for (int i = 0; i < jsonFile.size(); i++) {
String[] str = jsonFile.get(i).getAbsolutePath().split("\\\\");
for (PictureTime pic : picturses) {
filetime = str[str.length - 2] + str[str.length - 1].replace(".jpeg", "");
if (str[str.length - 3].equals(pic.getDeviceid())
&& pic.getLasttime().compareTo(filetime) != -1) {
jsonFile.remove(i--);
}
}
}
}
}
} }
...@@ -23,6 +23,7 @@ public class DateUtils { ...@@ -23,6 +23,7 @@ public class DateUtils {
return formatCurrDateByType(YMDHMS); return formatCurrDateByType(YMDHMS);
} }
public static String formatCurrDateYMD(){ public static String formatCurrDateYMD(){
return formatCurrDateByType(Y_M_D); return formatCurrDateByType(Y_M_D);
} }
...@@ -45,6 +46,14 @@ public class DateUtils { ...@@ -45,6 +46,14 @@ public class DateUtils {
return DateTime.parse(date,YMDHMS).toDate(); return DateTime.parse(date,YMDHMS).toDate();
} }
public static String parseDateToStrNoSign(String date){
return DateTime.parse(date,YMD_HMS).toString(YMDHMS);
}
public static String parseDateToStrNoSign(Date date){
return new DateTime(date).toString(YMDHMS);
}
public static String getYesterday(int day){ public static String getYesterday(int day){
Date date= addDay(new Date(),day); Date date= addDay(new Date(),day);
return new DateTime(date).toString(YMD_HMS); return new DateTime(date).toString(YMD_HMS);
...@@ -107,5 +116,18 @@ public class DateUtils { ...@@ -107,5 +116,18 @@ public class DateUtils {
return Days.daysBetween(dt1, dt2).getDays(); return Days.daysBetween(dt1, dt2).getDays();
} }
public static String getTimeStamps(){
return String.valueOf(new Date().getTime());
}
public static String addMin(String datestr,int min){
return new DateTime(DateTime.parse(datestr,YMD_HMS)).plusMinutes(min).toString(YMD_HMS);
}
public static String addMin(Date date,int min){
return new DateTime(date).plusMinutes(min).toString(YMD_HMS);
}
} }
package com.cx.cn.cxquartz.util;
import com.cx.cn.cxquartz.controller.ExtController;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.SimpleDateFormat;
/**
* JSON工具类
*/
public class JsonUtil {
private static final Logger log = LoggerFactory.getLogger(ExtController.class);
private final static ObjectMapper objectMapper = new ObjectMapper();
private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
static {
// 对象的所有字段全部列入
objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
// 取消默认转换timestamps形式
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
// 忽略空bean转json的错误
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
// 统一日期格式
objectMapper.setDateFormat(new SimpleDateFormat(DATE_FORMAT));
// 忽略在json字符串中存在, 但在java对象中不存在对应属性的情况, 防止错误
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
public static <T> String objToStr(T obj) {
if (null == obj) {
return null;
}
try {
return obj instanceof String ? (String) obj : objectMapper.writeValueAsString(obj);
} catch (Exception e) {
log.warn("objToStr error: ", e);
return null;
}
}
public static <T> T strToObj(String str, Class<T> clazz) {
if (StringUtils.isBlank(str) || null == clazz) {
return null;
}
try {
return clazz.equals(String.class) ? (T) str : objectMapper.readValue(str, clazz);
} catch (Exception e) {
log.warn("strToObj error: ", e);
return null;
}
}
public static <T> T strToObj(String str, TypeReference<T> typeReference) {
if (StringUtils.isBlank(str) || null == typeReference) {
return null;
}
try {
return (T) (typeReference.getType().equals(String.class) ? str : objectMapper.readValue(str,
typeReference));
} catch (Exception e) {
log.error("strToObj error", e);
return null;
}
}
}
package com.cx.cn.cxquartz.vo; package com.cx.cn.cxquartz.vo;
import java.util.Map;
public class JobTjParam { public class JobTjParam {
private String detectType; private String detectType;
private String deviceId; private String deviceId;
private String imageUrl; private String imageUrl;
private Object detectInfo; private Map detectInfo;
private Long timestamp; private Long timestamp;
public String getDetectType() { public String getDetectType() {
...@@ -31,11 +33,11 @@ public class JobTjParam { ...@@ -31,11 +33,11 @@ public class JobTjParam {
this.imageUrl = imageUrl; this.imageUrl = imageUrl;
} }
public Object getDetectInfo() { public Map getDetectInfo() {
return detectInfo; return detectInfo;
} }
public void setDetectInfo(Object detectInfo) { public void setDetectInfo(Map detectInfo) {
this.detectInfo = detectInfo; this.detectInfo = detectInfo;
} }
......
...@@ -143,6 +143,42 @@ public class Sbtdspsr { ...@@ -143,6 +143,42 @@ public class Sbtdspsr {
private String kz3; private String kz3;
private String kz4; private String kz4;
private String token;
private String tokennexttime;
private String resourcetype;
private String urlnexttime;
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getTokennexttime() {
return tokennexttime;
}
public void setTokennexttime(String tokennexttime) {
this.tokennexttime = tokennexttime;
}
public String getResourcetype() {
return resourcetype;
}
public void setResourcetype(String resourcetype) {
this.resourcetype = resourcetype;
}
public String getUrlnexttime() {
return urlnexttime;
}
public void setUrlnexttime(String urlnexttime) {
this.urlnexttime = urlnexttime;
}
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
......
package com.cx.cn.cxquartz.vo;
public class Taskinfo {
private Integer id;
private Integer traffid;
private String handler;
private String handlertime;
private int state;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getTraffid() {
return traffid;
}
public void setTraffid(Integer traffid) {
this.traffid = traffid;
}
public String getHandler() {
return handler;
}
public void setHandler(String handler) {
this.handler = handler;
}
public String getHandlertime() {
return handlertime;
}
public void setHandlertime(String handlertime) {
this.handlertime = handlertime;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
}
...@@ -13,6 +13,14 @@ public class Voice { ...@@ -13,6 +13,14 @@ public class Voice {
private Integer eventId; private Integer eventId;
private String unionId; private String unionId;
public Voice(Integer eventId, String unionId) {
this.eventId = eventId;
this.unionId = unionId;
}
public Voice() {
}
public Integer getEventId() { public Integer getEventId() {
return eventId; return eventId;
} }
......
...@@ -22,5 +22,6 @@ spring: ...@@ -22,5 +22,6 @@ spring:
local: local:
job: 0
czurl: http://localhost:4082/ext/getRTSP/1 czurl: http://localhost:4082/ext/getRTSP/1
fxurl: http://localhost:4082/ext/getDeviceSnapshotAndRecognize fxurl: http://localhost:4082/ext/getDeviceSnapshotAndRecognize
...@@ -21,5 +21,6 @@ spring: ...@@ -21,5 +21,6 @@ spring:
maxOpenPreparedStatements: 20 maxOpenPreparedStatements: 20
local: local:
job: 0
czurl: http://localhost:4085/ext/getRTSP/1 czurl: http://localhost:4085/ext/getRTSP/1
fxurl: http://localhost:4085/ext/getDeviceSnapshotAndRecognize fxurl: http://localhost:4085/ext/getDeviceSnapshotAndRecognize
\ No newline at end of file
server:
port: 4084
spring:
datasource:
url: jdbc:mysql://172.16.24.29:3306/imagepro?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
filters: stat
maxActive: 1000
initialSize: 100
maxWait: 60000
minIdle: 500
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxOpenPreparedStatements: 20
local:
job: 1
czurl: http://localhost:4082/ext/getRTSP/1
fxurl: http://localhost:4082/ext/getDeviceSnapshotAndRecognize
...@@ -2,9 +2,9 @@ server: ...@@ -2,9 +2,9 @@ server:
port: 8089 port: 8089
spring: spring:
datasource: datasource:
url: jdbc:mysql://192.168.168.110:3306/imagepro?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true url: jdbc:mysql://localhost:3306/imagepro?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
username: root username: root
password: 123456 password: root
driver-class-name: com.mysql.jdbc.Driver driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource type: com.alibaba.druid.pool.DruidDataSource
filters: stat filters: stat
...@@ -19,7 +19,33 @@ spring: ...@@ -19,7 +19,33 @@ spring:
testOnReturn: false testOnReturn: false
poolPreparedStatements: true poolPreparedStatements: true
maxOpenPreparedStatements: 20 maxOpenPreparedStatements: 20
rabbitmq:
host: 127.0.0.1
port: 5672
username: guest
password: guest
virtual-host: /
#消息发送到交换机确认机制,是否确认回调
publisher-confirms: true
##消息发送到交换机确认机制,是否返回回调
publisher-returns: true
#启用强制信息;默认false
template.mandatory: true
#设置为 true 后 消费者在消息没有被路由到合适队列情况下会被return监听,而不会自动删除
listener:
simple:
#设置手动确认(ack)
acknowledge-mode: manual
concurrency: 5
max-concurrency: 10
prefetch: 10
#开启消费者重试
retry:
enabled: true
#重试时间间隔
initial-interval: 3000
#最大重试次数
max-attempts: 3
redis: redis:
database: 0 database: 0
host: 127.0.0.1 host: 127.0.0.1
...@@ -30,16 +56,28 @@ redis: ...@@ -30,16 +56,28 @@ redis:
# root: # root:
# info # info
local: local:
job: 0
czurl: http://localhost:8089/ext/getRTSP/1 czurl: http://localhost:8089/ext/getRTSP/1
fxurl: http://localhost:8089/ext/getDeviceSnapshotAndRecognize fxurl: http://localhost:8089/ext/getDeviceSnapshotAndRecognize
file: file:
rtspurl: http://zjh189.ncpoi.cc:7080/getDeviceSnapshot rtspurl: http://zjh189.ncpoi.cc:7080/getDeviceSnapshot
recogurl: http://zjh189.ncpoi.cc:9098/images/recog recogurl: http://zjh189.ncpoi.cc:7080/getDeviceSnapshotAndRecognize
uploadurl: http://home2.ncpoi.cc:7080/uploadResultFile uploadurl: http://home2.ncpoi.cc:7080/uploadResultFile
model: 1
countryside: countryside:
callbackurl: http://kvideo.51iwifi.com/hesc-mq/hesc callbackurl: http://kvideo.51iwifi.com/hesc-mq/hesc
hlsurl:
token: http://183.131.122.215:85/appApi/authenticate/getToken
url: http://183.131.122.215:85/appApi/forward/byCode/57240035916824
rtspurl:
token: http://kvideo.51iwifi.com/home_gw/getAccessToken
url: http://kvideo.51iwifi.com/home_gw/heschome_api/api/hesc/open/getRtsp
appid: 8e9c7ff0fc6c11eac5efb5371726daaf
appsecret: 8e9ca700fc6c11eac5efb5371726daaf
params: account18888888888deviceCode
logging: logging:
level: level:
......
...@@ -21,6 +21,7 @@ spring: ...@@ -21,6 +21,7 @@ spring:
maxOpenPreparedStatements: 20 maxOpenPreparedStatements: 20
local: local:
job: 0
czurl: http://localhost:8089/ext/getRTSP/1 czurl: http://localhost:8089/ext/getRTSP/1
fxurl: http://localhost:8089/ext/getDeviceSnapshotAndRecognize fxurl: http://localhost:8089/ext/getDeviceSnapshotAndRecognize
......
spring: spring:
profiles: profiles:
active: dev85 active: local
mybatis: mybatis:
type-aliases-package: com.cx.cn.cxquartz.bean type-aliases-package: com.cx.cn.cxquartz.bean
......
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.cx.cn.cxquartz.dao.QuartzTaskErrorsMapper">
<resultMap id="BaseResultMap" type="com.cx.cn.cxquartz.bean.QuartzTaskErrors">
<id column="id" property="id" jdbcType="BIGINT"/>
<result column="taskExecuteRecordId" property="taskexecuterecordid" jdbcType="VARCHAR"/>
<result column="errorKey" property="errorkey" jdbcType="VARCHAR"/>
<result column="createTime" property="createtime" jdbcType="BIGINT"/>
<result column="lastModifyTime" property="lastmodifytime" jdbcType="BIGINT"/>
</resultMap>
<resultMap id="ResultMapWithBLOBs" type="com.cx.cn.cxquartz.bean.QuartzTaskErrors"
extends="BaseResultMap">
<result column="errorValue" property="errorvalue" jdbcType="LONGVARCHAR"/>
</resultMap>
<sql id="Base_Column_List">
id, taskExecuteRecordId, errorKey, createTime, lastModifyTime
</sql>
<sql id="Base_Column_List_With_ErrorValue">
id, taskExecuteRecordId, errorKey, errorValue ,createTime, lastModifyTime
</sql>
<sql id="Blob_Column_List">
errorValue
</sql>
<select id="selectByPrimaryKey" resultMap="ResultMapWithBLOBs" parameterType="java.lang.Long">
select
<include refid="Base_Column_List"/>
,
<include refid="Blob_Column_List"/>
from quartz_task_errors
where id = #{id,jdbcType=BIGINT}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
delete from quartz_task_errors
where id = #{id,jdbcType=BIGINT}
</delete>
<insert id="insert" parameterType="com.cx.cn.cxquartz.bean.QuartzTaskErrors">
insert into quartz_task_errors (id, taskExecuteRecordId, errorKey,
createTime, lastModifyTime, errorValue
)
values (#{id,jdbcType=BIGINT}, #{taskexecuterecordid,jdbcType=VARCHAR}, #{errorkey,jdbcType=VARCHAR},
#{createtime,jdbcType=BIGINT}, #{lastmodifytime,jdbcType=BIGINT}, #{errorvalue,jdbcType=LONGVARCHAR}
)
</insert>
<insert id="insertSelective" parameterType="com.cx.cn.cxquartz.bean.QuartzTaskErrors">
insert into quartz_task_errors
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="taskexecuterecordid != null">
taskExecuteRecordId,
</if>
<if test="errorkey != null">
errorKey,
</if>
<if test="createtime != null">
createTime,
</if>
<if test="lastmodifytime != null">
lastModifyTime,
</if>
<if test="errorvalue != null">
errorValue,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=BIGINT},
</if>
<if test="taskexecuterecordid != null">
#{taskexecuterecordid,jdbcType=VARCHAR},
</if>
<if test="errorkey != null">
#{errorkey,jdbcType=VARCHAR},
</if>
<if test="createtime != null">
#{createtime,jdbcType=BIGINT},
</if>
<if test="lastmodifytime != null">
#{lastmodifytime,jdbcType=BIGINT},
</if>
<if test="errorvalue != null">
#{errorvalue,jdbcType=LONGVARCHAR},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.cx.cn.cxquartz.bean.QuartzTaskErrors">
update quartz_task_errors
<set>
<if test="taskexecuterecordid != null">
taskExecuteRecordId = #{taskexecuterecordid,jdbcType=VARCHAR},
</if>
<if test="errorkey != null">
errorKey = #{errorkey,jdbcType=VARCHAR},
</if>
<if test="createtime != null">
createTime = #{createtime,jdbcType=BIGINT},
</if>
<if test="lastmodifytime != null">
lastModifyTime = #{lastmodifytime,jdbcType=BIGINT},
</if>
<if test="errorvalue != null">
errorValue = #{errorvalue,jdbcType=LONGVARCHAR},
</if>
</set>
where id = #{id,jdbcType=BIGINT}
</update>
<update id="updateByPrimaryKeyWithBLOBs" parameterType="com.cx.cn.cxquartz.bean.QuartzTaskErrors">
update quartz_task_errors
set taskExecuteRecordId = #{taskexecuterecordid,jdbcType=VARCHAR},
errorKey = #{errorkey,jdbcType=VARCHAR},
createTime = #{createtime,jdbcType=BIGINT},
lastModifyTime = #{lastmodifytime,jdbcType=BIGINT},
errorValue = #{errorvalue,jdbcType=LONGVARCHAR}
where id = #{id,jdbcType=BIGINT}
</update>
<update id="updateByPrimaryKey" parameterType="com.cx.cn.cxquartz.bean.QuartzTaskErrors">
update quartz_task_errors
set taskExecuteRecordId = #{taskexecuterecordid,jdbcType=VARCHAR},
errorKey = #{errorkey,jdbcType=VARCHAR},
createTime = #{createtime,jdbcType=BIGINT},
lastModifyTime = #{lastmodifytime,jdbcType=BIGINT}
where id = #{id,jdbcType=BIGINT}
</update>
<select id="detailTaskErrors" parameterType="java.lang.String"
resultType="com.cx.cn.cxquartz.bean.QuartzTaskErrors">
select
<include refid="Base_Column_List_With_ErrorValue"/>
from quartz_task_errors where taskExecuteRecordId = #{recordId}
</select>
</mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.cx.cn.cxquartz.dao.QuartzTaskInformationsMapper">
<resultMap id="BaseResultMap" type="com.cx.cn.cxquartz.bean.QuartzTaskInformations">
<id column="id" property="id" jdbcType="BIGINT"/>
<result column="version" property="version" jdbcType="INTEGER"/>
<result column="taskNo" property="taskno" jdbcType="VARCHAR"/>
<result column="taskName" property="taskname" jdbcType="VARCHAR"/>
<result column="schedulerRule" property="schedulerrule" jdbcType="VARCHAR"/>
<result column="frozenStatus" property="frozenstatus" jdbcType="VARCHAR"/>
<result column="executorNo" property="executorno" jdbcType="VARCHAR"/>
<result column="frozenTime" property="frozentime" jdbcType="BIGINT"/>
<result column="unfrozenTime" property="unfrozentime" jdbcType="BIGINT"/>
<result column="createTime" property="createtime" jdbcType="BIGINT"/>
<result column="lastModifyTime" property="lastmodifytime" jdbcType="BIGINT"/>
<result column="sendType" property="sendtype" jdbcType="VARCHAR"/>
<result column="url" property="url" jdbcType="VARCHAR"/>
<result column="executeParamter" property="executeparamter" jdbcType="VARCHAR"/>
<result column="timeKey" property="timekey" jdbcType="VARCHAR"/>
<result column="objectx" property="objectx" jdbcType="BIGINT"/>
<result column="objectx" property="objectx" jdbcType="BIGINT"/>
<result column="objecty" property="objecty" jdbcType="BIGINT"/>
<result column="objectw" property="objectw" jdbcType="BIGINT"/>
<result column="objecth" property="objecth" jdbcType="BIGINT"/>
<result column="recordtype" property="recordtype" jdbcType="VARCHAR"/>
<result column="metatype" property="metatype" jdbcType="VARCHAR"/>
<result column="rtsp" property="rtsp" jdbcType="VARCHAR"/>
<result column="videoid" property="videoid" jdbcType="VARCHAR"/>
<result column="imgsrc" property="imgsrc" jdbcType="VARCHAR"/>
</resultMap>
<resultMap id="PicResultMap" type="com.cx.cn.cxquartz.bean.PictureTime">
<id column="deviceid" property="deviceid" jdbcType="VARCHAR"/>
<result column="lasttime" property="lasttime" jdbcType="VARCHAR"/>
</resultMap>
<resultMap id="CameraResultMap" type="com.cx.cn.cxquartz.bean.PatrolCtrlRecord">
<result column="cameraName" property="cameraName" jdbcType="VARCHAR"/>
<result column="cameraCode" property="cameraCode" jdbcType="VARCHAR"/>
<result column="deviceid" property="deviceid" jdbcType="VARCHAR"/>
</resultMap>
<sql id="Base_Column_List">
id, version, taskNo, taskName, schedulerRule, frozenStatus, executorNo, frozenTime,
unfrozenTime, createTime, lastModifyTime, sendType, url, executeParamter, timeKey,
objectx , objecty ,objectw,objecth,recordtype,metatype,videoid,rtsp,imgsrc
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long">
select
<include refid="Base_Column_List"/>
from quartz_task_informations
where id = #{id,jdbcType=BIGINT}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
delete from quartz_task_informations
where id = #{id,jdbcType=BIGINT}
</delete>
<insert id="insert" parameterType="com.cx.cn.cxquartz.bean.QuartzTaskInformations">
insert into quartz_task_informations (id, version, taskNo,
taskName, schedulerRule, frozenStatus,
executorNo, frozenTime, unfrozenTime,
createTime, lastModifyTime, sendType,
url, executeParamter, timeKey,objectx,objecty,objectw,objecth,recordtype,metatype,
rtsp,imgsrc,videoid
)
values (#{id,jdbcType=BIGINT}, #{version,jdbcType=INTEGER}, #{taskno,jdbcType=VARCHAR},
#{taskname,jdbcType=VARCHAR}, #{schedulerrule,jdbcType=VARCHAR}, #{frozenstatus,jdbcType=VARCHAR},
#{executorno,jdbcType=VARCHAR}, #{frozentime,jdbcType=BIGINT}, #{unfrozentime,jdbcType=BIGINT},
#{createtime,jdbcType=BIGINT}, #{lastmodifytime,jdbcType=BIGINT}, #{sendtype,jdbcType=VARCHAR},
#{url,jdbcType=VARCHAR},
#{executeparamter,jdbcType=VARCHAR}, #{timekey,jdbcType=VARCHAR}
, #{objectx,jdbcType=BIGINT}
, #{objecty,jdbcType=BIGINT}
, #{objectw,jdbcType=BIGINT}
, #{objecth,jdbcType=BIGINT}
, #{recordtype,jdbcType=VARCHAR}
, #{metatype,jdbcType=VARCHAR}
, #{rtsp,jdbcType=VARCHAR}
, #{imgsrc,jdbcType=VARCHAR}
, #{videoid,jdbcType=VARCHAR}
)
</insert>
<insert id="insertSelective" parameterType="com.cx.cn.cxquartz.bean.QuartzTaskInformations">
insert into quartz_task_informations
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="version != null">
version,
</if>
<if test="taskno != null">
taskNo,
</if>
<if test="taskname != null">
taskName,
</if>
<if test="schedulerrule != null">
schedulerRule,
</if>
<if test="frozenstatus != null">
frozenStatus,
</if>
<if test="executorno != null">
executorNo,
</if>
<if test="frozentime != null">
frozenTime,
</if>
<if test="unfrozentime != null">
unfrozenTime,
</if>
<if test="createtime != null">
createTime,
</if>
<if test="lastmodifytime != null">
lastModifyTime,
</if>
<if test="sendtype != null">
sendType,
</if>
<if test="url != null">
url,
</if>
<if test="executeparamter != null">
executeParamter,
</if>
<if test="timekey != null">
timeKey,
</if>
<if test="objectx != null">
objectx,
</if>
<if test="objecty != null">
objecty,
</if>
<if test="objectw != null">
objectw,
</if>
<if test="objecth != null">
objecth,
</if>
<if test="recordtype != null">
recordtype,
</if>
<if test="metatype != null">
metatype,
</if>
<if test="rtsp != null">
rtsp,
</if>
<if test="imgsrc != null">
imgsrc,
</if>
<if test="videoid != null">
videoid,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=BIGINT},
</if>
<if test="version != null">
#{version,jdbcType=INTEGER},
</if>
<if test="taskno != null">
#{taskno,jdbcType=VARCHAR},
</if>
<if test="taskname != null">
#{taskname,jdbcType=VARCHAR},
</if>
<if test="schedulerrule != null">
#{schedulerrule,jdbcType=VARCHAR},
</if>
<if test="frozenstatus != null">
#{frozenstatus,jdbcType=VARCHAR},
</if>
<if test="executorno != null">
#{executorno,jdbcType=VARCHAR},
</if>
<if test="frozentime != null">
#{frozentime,jdbcType=BIGINT},
</if>
<if test="unfrozentime != null">
#{unfrozentime,jdbcType=BIGINT},
</if>
<if test="createtime != null">
#{createtime,jdbcType=BIGINT},
</if>
<if test="lastmodifytime != null">
#{lastmodifytime,jdbcType=BIGINT},
</if>
<if test="sendtype != null">
#{sendtype,jdbcType=VARCHAR},
</if>
<if test="url != null">
#{url,jdbcType=VARCHAR},
</if>
<if test="executeparamter != null">
#{executeparamter,jdbcType=VARCHAR},
</if>
<if test="timekey != null">
#{timekey,jdbcType=VARCHAR},
</if>
<if test="objectx != null">
#{objectx,jdbcType=BIGINT},
</if>
<if test="objecty != null">
#{objecty,jdbcType=BIGINT},
</if>
<if test="objectw != null">
#{objectw,jdbcType=BIGINT},
</if>
<if test="objecth != null">
#{objecth,jdbcType=BIGINT},
</if>
<if test="recordtype != null">
#{recordtype,jdbcType=VARCHAR},
</if>
<if test="metatype != null">
#{metatype,jdbcType=VARCHAR},
</if>
<if test="rtsp != null">
#{rtsp,jdbcType=VARCHAR},
</if>
<if test="imgsrc != null">
#{imgsrc,jdbcType=VARCHAR},
</if>
<if test="videoid != null">
#{videoid,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective"
parameterType="com.cx.cn.cxquartz.bean.QuartzTaskInformations">
update quartz_task_informations
<set>
<if test="version != null">
version = version+1,
</if>
<if test="taskno != null">
taskNo = #{taskno,jdbcType=VARCHAR},
</if>
<if test="taskname != null">
taskName = #{taskname,jdbcType=VARCHAR},
</if>
<if test="schedulerrule != null">
schedulerRule = #{schedulerrule,jdbcType=VARCHAR},
</if>
<if test="frozenstatus != null">
frozenStatus = #{frozenstatus,jdbcType=VARCHAR},
</if>
<if test="executorno != null">
executorNo = #{executorno,jdbcType=VARCHAR},
</if>
<if test="frozentime != null">
frozenTime = #{frozentime,jdbcType=BIGINT},
</if>
<if test="unfrozentime != null">
unfrozenTime = #{unfrozentime,jdbcType=BIGINT},
</if>
<if test="createtime != null">
createTime = #{createtime,jdbcType=BIGINT},
</if>
<if test="lastmodifytime != null">
lastModifyTime = #{lastmodifytime,jdbcType=BIGINT},
</if>
<if test="sendtype != null">
sendType = #{sendtype,jdbcType=VARCHAR},
</if>
<if test="url != null">
url = #{url,jdbcType=VARCHAR},
</if>
<if test="executeparamter != null">
executeParamter = #{executeparamter,jdbcType=VARCHAR},
</if>
<if test="timekey != null">
timeKey = #{timekey,jdbcType=VARCHAR},
</if>
<if test="objectx != null">
objectx = #{objectx,jdbcType=BIGINT},
</if>
<if test="objecty != null">
objecty = #{objecty,jdbcType=BIGINT},
</if>
<if test="objectw != null">
objectw = #{objectw,jdbcType=BIGINT},
</if>
<if test="objecth != null">
objecth = #{objecth,jdbcType=BIGINT},
</if>
<if test="recordtype != null">
recordtype = #{recordtype,jdbcType=VARCHAR},
</if>
<if test="metatype != null">
metatype = #{metatype,jdbcType=VARCHAR},
</if>
<if test="rtsp != null">
rtsp = #{rtsp,jdbcType=VARCHAR},
</if>
<if test="imgsrc != null">
imgsrc = #{imgsrc,jdbcType=VARCHAR},
</if>
<if test="videoid != null">
videoid = #{videoid,jdbcType=VARCHAR},
</if>
</set>
where id = #{id,jdbcType=BIGINT}
</update>
<update id="updateByPrimaryKey" parameterType="com.cx.cn.cxquartz.bean.QuartzTaskInformations">
update quartz_task_informations
set version = #{version,jdbcType=INTEGER},
taskNo = #{taskno,jdbcType=VARCHAR},
taskName = #{taskname,jdbcType=VARCHAR},
schedulerRule = #{schedulerrule,jdbcType=VARCHAR},
frozenStatus = #{frozenstatus,jdbcType=VARCHAR},
executorNo = #{executorno,jdbcType=VARCHAR},
frozenTime = #{frozentime,jdbcType=BIGINT},
unfrozenTime = #{unfrozentime,jdbcType=BIGINT},
createTime = #{createtime,jdbcType=BIGINT},
lastModifyTime = #{lastmodifytime,jdbcType=BIGINT},
sendType = #{sendtype,jdbcType=VARCHAR},
url = #{url,jdbcType=VARCHAR},
executeParamter = #{executeparamter,jdbcType=VARCHAR},
timeKey = #{timekey,jdbcType=VARCHAR} ,
objectx = #{objectx,jdbcType=BIGINT},
objecty = #{objecty,jdbcType=BIGINT} ,
objectw = #{lastmodifytime,jdbcType=BIGINT} ,
objecth = #{lastmodifytime,jdbcType=BIGINT},
recordtype = #{recordtype,jdbcType=VARCHAR} ,
metatype = #{metatype,jdbcType=VARCHAR},
rtsp = #{rtsp,jdbcType=VARCHAR},
videoid = #{videoid,jdbcType=VARCHAR},
imgsrc = #{imgsrc,jdbcType=VARCHAR}
where id = #{id,jdbcType=BIGINT}
</update>
<select id="selectList" parameterType="java.util.HashMap" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from quartz_task_informations
<if test="taskNo != null">
<where>
taskNo = #{taskNo}
</where>
</if>
order by id desc limit #{startIndex},10;
</select>
<select id="selectByTaskNo" parameterType="java.lang.String" resultType="java.lang.Integer">
select count(*) from quartz_task_informations where taskNo=#{taskNo}
</select>
<select id="getTaskByTaskNo" parameterType="java.lang.String"
resultType="com.cx.cn.cxquartz.bean.QuartzTaskInformations">
select
<include refid="Base_Column_List"/>
from quartz_task_informations where taskNo = #{taskNo}
</select>
<select id="getUnfrozenTasks" parameterType="java.lang.String" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from quartz_task_informations where frozenStatus = #{frozenStatus}
</select>
<insert id="insertRecord" parameterType="com.cx.cn.cxquartz.bean.PatrolCtrlRecord">
insert into patrol_ctrl_records ( cameraCode,cameraName,patrolTime,recordSrc )
values (#{cameraCode,jdbcType=VARCHAR}, #{cameraName,jdbcType=VARCHAR},
#{patrolTime,jdbcType=VARCHAR}, #{recordSrc,jdbcType=VARCHAR}
)
</insert>
<insert id="insertAlarm" parameterType="com.cx.cn.cxquartz.bean.PatrolCtrlAlarm">
insert into patrol_ctrl_alarms ( cameraCode,cameraName,time,type )
values (#{cameraCode,jdbcType=VARCHAR}, #{cameraName,jdbcType=VARCHAR},
#{time,jdbcType=VARCHAR}, #{type,jdbcType=VARCHAR}
)
</insert>
<select id="findLastPicTime" resultMap="PicResultMap">
select deviceid ,max(patroltime) lasttime from patrol_ctrl_records a ,sbxx b where a.cameracode=b.cameracode group by deviceid
</select>
<select id="queryCameraCode" resultMap="CameraResultMap">
select * from sbxx where deviceid in
<foreach item="item" index="index" collection="list" open="(" separator="," close=")">
#{item}
</foreach>
</select>
<resultMap id="RtspMap" type="com.cx.cn.cxquartz.vo.Sbtdspsr">
<result column="sbbh" jdbcType="VARCHAR" property="sbbh"/>
<result column="tdbh" jdbcType="INTEGER" property="tdbh"/>
<result column="xzbh" jdbcType="VARCHAR" property="xzbh"/>
</resultMap>
<update id="UpdateExecuteParam" parameterType="java.util.HashMap">
update quartz_task_informations set executeParamter=#{nrtsp} where executeParamter=#{ortsp}
</update>
<select id="getTaskSByDeviceCode" resultMap="BaseResultMap" parameterType="java.lang.String">
select * from quartz_task_informations where
taskno like concat(concat('%',#{devicecode}),'%')
and frozenStatus='UNFROZEN'
</select>
<delete id="deletetask">
delete from quartz_task_informations
where taskno = #{taskno,jdbcType=BIGINT}
</delete>
</mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.cx.cn.cxquartz.dao.QuartzTaskRecordsMapper">
<resultMap id="BaseResultMap" type="com.cx.cn.cxquartz.bean.QuartzTaskRecords">
<id column="id" property="id" jdbcType="BIGINT"/>
<result column="taskNo" property="taskno" jdbcType="VARCHAR"/>
<result column="timeKeyValue" property="timekeyvalue" jdbcType="VARCHAR"/>
<result column="executeTime" property="executetime" jdbcType="BIGINT"/>
<result column="taskStatus" property="taskstatus" jdbcType="VARCHAR"/>
<result column="failcount" property="failcount" jdbcType="INTEGER"/>
<result column="failReason" property="failreason" jdbcType="VARCHAR"/>
<result column="createTime" property="createtime" jdbcType="BIGINT"/>
<result column="lastModifyTime" property="lastmodifytime" jdbcType="BIGINT"/>
</resultMap>
<sql id="Base_Column_List">
id, taskNo, timeKeyValue, executeTime, taskStatus, failcount, failReason, createTime,
lastModifyTime
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long">
select
<include refid="Base_Column_List"/>
from quartz_task_records
where id = #{id,jdbcType=BIGINT}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
delete from quartz_task_records
where id = #{id,jdbcType=BIGINT}
</delete>
<insert id="insert" useGeneratedKeys="true" keyProperty="id" keyColumn="id"
parameterType="com.cx.cn.cxquartz.bean.QuartzTaskRecords">
insert into quartz_task_records (taskNo, timeKeyValue,
executeTime, taskStatus, failcount,
failReason, createTime, lastModifyTime
)
values (#{taskno,jdbcType=VARCHAR}, #{timekeyvalue,jdbcType=VARCHAR},
#{executetime,jdbcType=BIGINT}, #{taskstatus,jdbcType=VARCHAR}, #{failcount,jdbcType=INTEGER},
#{failreason,jdbcType=VARCHAR}, #{createtime,jdbcType=BIGINT}, #{lastmodifytime,jdbcType=BIGINT}
)
</insert>
<insert id="insertSelective" parameterType="com.cx.cn.cxquartz.bean.QuartzTaskRecords">
insert into quartz_task_records
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="taskno != null">
taskNo,
</if>
<if test="timekeyvalue != null">
timeKeyValue,
</if>
<if test="executetime != null">
executeTime,
</if>
<if test="taskstatus != null">
taskStatus,
</if>
<if test="failcount != null">
failcount,
</if>
<if test="failreason != null">
failReason,
</if>
<if test="createtime != null">
createTime,
</if>
<if test="lastmodifytime != null">
lastModifyTime,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=BIGINT},
</if>
<if test="taskno != null">
#{taskno,jdbcType=VARCHAR},
</if>
<if test="timekeyvalue != null">
#{timekeyvalue,jdbcType=VARCHAR},
</if>
<if test="executetime != null">
#{executetime,jdbcType=BIGINT},
</if>
<if test="taskstatus != null">
#{taskstatus,jdbcType=VARCHAR},
</if>
<if test="failcount != null">
#{failcount,jdbcType=INTEGER},
</if>
<if test="failreason != null">
#{failreason,jdbcType=VARCHAR},
</if>
<if test="createtime != null">
#{createtime,jdbcType=BIGINT},
</if>
<if test="lastmodifytime != null">
#{lastmodifytime,jdbcType=BIGINT},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.cx.cn.cxquartz.bean.QuartzTaskRecords">
update quartz_task_records
<set>
<if test="taskno != null">
taskNo = #{taskno,jdbcType=VARCHAR},
</if>
<if test="timekeyvalue != null">
timeKeyValue = #{timekeyvalue,jdbcType=VARCHAR},
</if>
<if test="executetime != null">
executeTime = #{executetime,jdbcType=BIGINT},
</if>
<if test="taskstatus != null">
taskStatus = #{taskstatus,jdbcType=VARCHAR},
</if>
<if test="failcount != null">
failcount = #{failcount,jdbcType=INTEGER},
</if>
<if test="failreason != null">
failReason = #{failreason,jdbcType=VARCHAR},
</if>
<if test="createtime != null">
createTime = #{createtime,jdbcType=BIGINT},
</if>
<if test="lastmodifytime != null">
lastModifyTime = #{lastmodifytime,jdbcType=BIGINT},
</if>
</set>
where id = #{id,jdbcType=BIGINT}
</update>
<update id="updateByPrimaryKey" parameterType="com.cx.cn.cxquartz.bean.QuartzTaskRecords">
update quartz_task_records
set taskNo = #{taskno,jdbcType=VARCHAR},
timeKeyValue = #{timekeyvalue,jdbcType=VARCHAR},
executeTime = #{executetime,jdbcType=BIGINT},
taskStatus = #{taskstatus,jdbcType=VARCHAR},
failcount = #{failcount,jdbcType=INTEGER},
failReason = #{failreason,jdbcType=VARCHAR},
createTime = #{createtime,jdbcType=BIGINT},
lastModifyTime = #{lastmodifytime,jdbcType=BIGINT}
where id = #{id,jdbcType=BIGINT}
</update>
<select id="getTaskRecordsByTaskNo" parameterType="java.lang.String" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from quartz_task_records where taskNo = #{taskNo} order by createTime desc;
</select>
</mapper>
...@@ -30,4 +30,16 @@ ...@@ -30,4 +30,16 @@
<select id="list" resultType="com.cx.cn.cxquartz.vo.Sbtdspsr"> <select id="list" resultType="com.cx.cn.cxquartz.vo.Sbtdspsr">
select * from sbtdspsr select * from sbtdspsr
</select> </select>
<select id="getPeriodicseconds" resultType="java.lang.Long">
select str_to_date(min(urlnexttime),'%Y-%m-%d %H:%i:%s')-sysdate() from sbtdspsr;
</select>
<select id="getPerformedTasks" resultType="com.cx.cn.cxquartz.vo.Sbtdspsr">
select * from sbtdspsr where str_to_date(urlnexttime,'%Y-%m-%d %H:%i:%s')-sysdate()<![CDATA[ <=]]>120
</select>
<select id="getRtspOrHLSByDeviceCode" parameterType="java.lang.String" resultType="java.lang.String">
select squrllj from sbtdspsr where sbbh=#{deviceCode}
</select>
</mapper> </mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.cx.cn.cxquartz.dao.TaskinfoMapper">
<resultMap id="BaseResultMap" type="com.cx.cn.cxquartz.vo.Taskinfo">
<result column="id" jdbcType="INTEGER" property="id"/>
<result column="traffid" jdbcType="INTEGER" property="traffid"/>
<result column="handler" jdbcType="VARCHAR" property="handler"/>
<result column="handlertime" jdbcType="VARCHAR" property="handlertime"/>
<result column="state" jdbcType="VARCHAR" property="state"/>
</resultMap>
<select id="getTaskinfoByMutiParam" parameterType="java.util.HashMap" resultType="com.cx.cn.cxquartz.vo.Taskinfo">
select * from taskinfo a, traffpicture b where a.traffid=b.id and sbbh=#{sbbh}
</select>
<insert id="addTaskinfo" parameterType="com.cx.cn.cxquartz.vo.Taskinfo">
insert into taskinfo
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id!= null">id ,</if>
<if test="traffid!= null">traffid ,</if>
<if test="handler!= null">handler ,</if>
<if test="handlertime!= null">handlertime ,</if>
<if test="state!= null">state ,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id!= null">#{id},</if>
<if test="traffid!= null">#{traffid},</if>
<if test="handler!= null">#{handler},</if>
<if test="handlertime!= null">str_to_date(#{handlertime},'%Y-%m-%d %H:%i:%s'),</if>
<if test="state!= null">#{state},</if>
</trim>
</insert>
<update id="updateTaskinfo" parameterType="com.cx.cn.cxquartz.vo.Taskinfo" >
update taskinfo set
<trim prefix="set" suffixOverrides=",">
<if test="handler != null and handler !=''">
handler =#{handler},
</if>
<if test="state != null and state !=''">
state =#{state},
</if>
<if test="handlertime != null and handlertime !=''">
handlertime =str_to_date(#{handlertime},'%Y-%m-%d %H:%i:%s'),
</if>
</trim>
where id=#{id}
</update>
<delete id="delTaskinfoByid" parameterType="java.lang.String">
delete from taskinfo where id=#{id}
</delete>
</mapper>
#===============================================================
#配置文件不是必须的,Quartz对配置项都是有默认值的,当需要自定义的时候,
#可以在classpath路径下放一个quartz.properties文件,Quartz的StdSchedulerFactory
#在启动时会自动加载该配置文件。
#===============================================================
#===============================================================
#配置主调度程序的属性
#===============================================================
org.quartz.scheduler.instanceName = DefaultQuartzScheduler
org.quartz.scheduler.rmi.export = false
org.quartz.scheduler.rmi.proxy = false
org.quartz.scheduler.wrapJobExecutionInUserTransaction = false
#当检查某个Trigger应该触发时,默认每次只Acquire一个Trigger,(为什么要有Acquire的过程呢?是为了防止多线程访问的情况下,
#同一个Trigger被不同的线程多次触发)。尤其是使用JDBC JobStore时,一次Acquire就是一个update语句,尽可能一次性的多获取
#几个Trigger,一起触发,当定时器数量非常大的时候,这是个非常有效的优化。当定时器数量比较少时,触发不是极为频繁时,
#这个优化的意义就不大了。
org.quartz.scheduler.batchTriggerAcquisitionMaxCount=30
#===============================================================
#配置线程池的属性
#===============================================================
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
#线程池里的线程数,默认值是10,当执行任务会并发执行多个耗时任务时,要根据业务特点选择线程池的大小。
org.quartz.threadPool.threadCount = 30
org.quartz.threadPool.threadPriority = 5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread = true
#===============================================================
#配置JobStore的属性
#===============================================================
org.quartz.jobStore.misfireThreshold = 60000
org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment