Commit 14353b66 authored by duanruiming's avatar duanruiming

定时任务调用远程utcService同步信号机状态功能

parent c6e24b57
...@@ -24,9 +24,15 @@ ...@@ -24,9 +24,15 @@
<mybatis-plus-version>3.5.1</mybatis-plus-version> <mybatis-plus-version>3.5.1</mybatis-plus-version>
<mybatis.generator.version>1.3.2</mybatis.generator.version> <mybatis.generator.version>1.3.2</mybatis.generator.version>
<mysql.connector.version>5.1.41</mysql.connector.version> <mysql.connector.version>5.1.41</mysql.connector.version>
<fastjson-version>1.2.83</fastjson-version>
</properties> </properties>
<dependencies> <dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson-version}</version>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId> <artifactId>spring-boot-starter-web</artifactId>
......
package net.wanji.web.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.StandardCharsets;
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
RestTemplate restTemplate = new RestTemplate(factory);
restTemplate.getMessageConverters().set(1,new StringHttpMessageConverter(StandardCharsets.UTF_8));
return restTemplate;
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(30000);
factory.setReadTimeout(30000);
return factory;
}
}
\ No newline at end of file
package net.wanji.web.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.Date;
/**
* @author duanruiming
* @date 2023/01/03 15:46
*/
@Data
@TableName("t_device_status")
public class TDeviceStatusInfo {
@ApiModelProperty(value = "id")
private Integer id;
@ApiModelProperty(value = "设备代码")
private String code;
@ApiModelProperty(value = "设备名称")
private String name;
@ApiModelProperty(value = "设备类型:1信号;2卡口;3地磁;4视频;5微波;6激光;7电警;8 MEC")
private int type;
@ApiModelProperty(value = "设备状态:0离线;1在线;2故障")
private int status;
@ApiModelProperty(value = "创建时间")
private Date gmtCreate ;
}
package net.wanji.web.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import net.wanji.web.entity.TDeviceStatusInfo;
import org.springframework.stereotype.Repository;
/**
* @author duanruiming
* @date 2023/01/03 15:53
*/
@Repository
public interface TDeviceStatusMapper extends BaseMapper<TDeviceStatusInfo> {
}
package net.wanji.web.task;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import net.wanji.web.common.entity.JsonViewObject;
import net.wanji.web.common.util.StringUtils;
import net.wanji.web.entity.TDeviceStatusInfo;
import net.wanji.web.mapper.TDeviceStatusMapper;
import net.wanji.web.util.HttpRestUtil;
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.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import static net.wanji.web.util.HttpRestUtil.buildHeader;
/**
* @author duanruiming
* @date 2023/01/03 10:43
*/
@Component
public class SignalStatusTask {
private static final Logger LOGGER = LoggerFactory.getLogger(SignalStatusTask.class);
@Autowired
private HttpRestUtil httpRestUtil;
@Value("${utcServiceUrl}")
private String utcServiceUrl;
@Value("${syncDeviceSatusUrn}")
private String syncDeviceSatusUrl;
@Autowired
private TDeviceStatusMapper tDeviceStatusMapper;
@Scheduled(fixedRate = 5 * 60 * 1000)
public void syncSignalStatus() {
// 远程通过UTC服务获取信号机状态
Map<String, String> header = buildHeader();
JsonViewObject jsonViewObject = httpRestUtil.doPost(utcServiceUrl.concat(syncDeviceSatusUrl), header, "", JsonViewObject.class);
if (Objects.isNull(jsonViewObject) || jsonViewObject.getCode() != 200) {
LOGGER.error("定时任务同步信号机设备状态远程utcService调用异常,url:".concat(utcServiceUrl.concat("/signalStatus/runningStatusAlarm")));
return;
}
List<Map<String, Object>> content = (List<Map<String, Object>>) jsonViewObject.getContent();
Map<String, Object> result = content.get(0);
String signalId = (String) result.get("signalId");
Integer currentSignalStatus = (Integer) result.get("status");
// 当前服务数据库状态
LambdaQueryWrapper<TDeviceStatusInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
if (StringUtils.isNotEmpty(signalId)) {
lambdaQueryWrapper.eq(TDeviceStatusInfo::getCode, signalId);
TDeviceStatusInfo tDeviceStatusInfo = tDeviceStatusMapper.selectOne(lambdaQueryWrapper);
if (Objects.nonNull(tDeviceStatusInfo) && currentSignalStatus != tDeviceStatusInfo.getStatus()) {
tDeviceStatusInfo.setStatus(currentSignalStatus);
tDeviceStatusMapper.updateById(tDeviceStatusInfo);
}
}
}
}
package net.wanji.web.util;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
@Component
public class HttpRestUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(HttpRestUtil.class);
@Autowired
private RestTemplate restTemplate;
public static Map<String, String> buildHeader() {
Map<String, String> header = new HashMap<>();
header.put("Content-Type", "application/json; charset=UTF-8");
header.put("Accept", MediaType.APPLICATION_JSON.toString());
return header;
}
/**
* @param url 请求URL
* @param param 请求参数
* @param classType 转换对象
* @return T 返回结果
* @description: 发送GET请求,支持转换类型,应用多变性返回值,classType返回值类型
*/
public <T> T doGet(String url, Map<String, String> headers, String param, Class<T> classType) {
long startTime = System.currentTimeMillis();
LOGGER.info("\n 请求地址 = {} || 请求方式 = {} || 请求头 = {} || 请求参数 = {}",
url, "GET", JSON.toJSONString(headers), JSON.toJSONString(param));
//封装httpEntity
HttpEntity httpEntity = getHttpEntity(headers, param);
//发送请求
ResponseEntity<T> responseEntity;
try {
responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, classType);
} catch (ResourceAccessException e) {
LOGGER.error("HttpRestUtil -> doExecute 捕获IOException异常,{}", e.getMessage());
try {
Thread.sleep(1000);
} catch (Exception ex) {
LOGGER.error("HttpRestUtil -> doExecute 暂停2S异常!", ex);
}
responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, classType);
}
//响应状态值 200 201 202
boolean statusBool = false;
if (HttpStatus.OK.equals(responseEntity.getStatusCode()) || HttpStatus.CREATED.equals(responseEntity.getStatusCode()) || HttpStatus.ACCEPTED.equals(responseEntity.getStatusCode())) {
statusBool = true;
}
if (null != responseEntity && statusBool) {
T result = responseEntity.getBody();
LOGGER.info("请求地址 = {} || 请求参数 = {} || 响应时长 = {} || 响应结果 = {}",
url, JSON.toJSONString(param), System.currentTimeMillis() - startTime, JSON.toJSONString(result));
if (StringUtils.isEmpty(result)) {
return null;
}
return result;
} else {
LOGGER.error("请求地址 = {} || 请求参数 = {} || 响应时长 = {} || 响应结果 = {}",
url, JSON.toJSONString(param), System.currentTimeMillis() - startTime, JSON.toJSONString(responseEntity.getBody()));
// throw new RuntimeException("调用接口 = " + url + " || " +
// "失败状态 = " + responseEntity.getStatusCode() + " || " +
// "响应 = " + JSON.toJSONString(responseEntity.getBody()));
throw new HttpClientErrorException(responseEntity.getStatusCode(),
"调用接口 = " + url + " || " +
"失败状态 = " + responseEntity.getStatusCode() + " || " +
"响应 = " + responseEntity.getBody());
}
}
/**
* @param url 请求URL
* @param headers 请求头
* @param param 请求参数
* @param classType 转换类型
* @return T 返回结果
* @description: 发送POST请求,支持转换类型,应用多变性返回值,classType返回值类型
*/
public <T> T doPost(String url, Map<String, String> headers, String param, Class<T> classType) {
long startTime = System.currentTimeMillis();
LOGGER.info("\n 请求地址 = {} || 请求方式 = {} || 请求头 = {} || 请求参数 = {}",
url, "POST", JSON.toJSONString(headers), JSON.toJSONString(param));
//封装httpEntity
HttpEntity httpEntity = getHttpEntity(headers, param);
ResponseEntity<T> responseEntity;
try {
responseEntity = restTemplate.postForEntity(url, httpEntity, classType);
} catch (ResourceAccessException e) {
LOGGER.error("HttpRestUtil -> doPost 捕获IOException异常,{}" + e.getMessage());
try {
Thread.sleep(2000);
} catch (Exception ex) {
LOGGER.error("HttpRestUtil -> doExecute 暂停2S异常!");
}
responseEntity = restTemplate.postForEntity(url, httpEntity, classType);
}
//响应状态值 200 201 202
boolean statusBool = false;
if (HttpStatus.OK.equals(responseEntity.getStatusCode()) || HttpStatus.CREATED.equals(responseEntity.getStatusCode()) || HttpStatus.ACCEPTED.equals(responseEntity.getStatusCode())) {
statusBool = true;
}
if (null != responseEntity && statusBool) {
T result = responseEntity.getBody();
LOGGER.info("请求地址 = {} || 请求参数 = {} || 响应时长 = {} || 响应结果 = {}",
url, JSON.toJSONString(param), System.currentTimeMillis() - startTime, JSON.toJSONString(responseEntity.getBody()));
if (StringUtils.isEmpty(result)) {
return null;
}
return result;
} else {
LOGGER.error("请求地址 = {} || 请求参数 = {} || 响应时长 = {} || 响应结果 = {}",
url, JSON.toJSONString(param), System.currentTimeMillis() - startTime, JSON.toJSONString(responseEntity.getBody()));
throw new HttpClientErrorException(responseEntity.getStatusCode(),
"调用接口 = " + url + " || " +
"失败状态 = " + responseEntity.getStatusCode() + " || " +
"响应 = " + responseEntity.getBody());
}
}
/**
* @param url 请求地址
* @param headers 请求头
* @param method 请求类型 POST、GET
* @param param 参数
* @return String 返回结果
* @description: 发送请求,返回string字符串,需要自己转换,应用返回结果简单的请求
*/
public String doExecute(String url, Map<String, String> headers, HttpMethod method, String param) {
long startTime = System.currentTimeMillis();
LOGGER.info("\n 请求地址 = {} || 请求方式 = {} || 请求头 = {} || 请求参数 = {}",
url, method.name(), JSON.toJSONString(headers), JSON.toJSONString(param));
//封装httpEntity
HttpEntity httpEntity = getHttpEntity(headers, param);
//发送请求
ResponseEntity<String> responseEntity;
try {
responseEntity = restTemplate.exchange(url, method, httpEntity, String.class);
} catch (ResourceAccessException e) {
LOGGER.error("HttpRestUtil -> doExecute 捕获IOException异常,{}", e.getMessage());
try {
Thread.sleep(2000);
} catch (Exception ex) {
LOGGER.error("HttpRestUtil -> doExecute 暂停2S异常!", ex);
}
responseEntity = restTemplate.exchange(url, method, httpEntity, String.class);
}
//ResponseEntity<String> responseEntity = get().exchange(url, method, httpEntity, String.class);
//响应状态值 200 201 202
boolean statusBool = false;
if (HttpStatus.OK.equals(responseEntity.getStatusCode()) || HttpStatus.CREATED.equals(responseEntity.getStatusCode()) || HttpStatus.ACCEPTED.equals(responseEntity.getStatusCode())) {
statusBool = true;
}
if (null != responseEntity && statusBool) {
String result = responseEntity.getBody();
LOGGER.info("请求地址 = {} || 请求参数 = {} || 响应时长 = {} || 响应结果 = {}",
url, JSON.toJSONString(param), System.currentTimeMillis() - startTime, result);
if (StringUtils.isEmpty(result)) {
return null;
}
return result;
} else {
LOGGER.error("请求地址 = {} || 请求参数 = {} || 响应时长 = {} || 响应结果 = {}",
url, JSON.toJSONString(param), System.currentTimeMillis() - startTime, responseEntity.getBody());
throw new HttpClientErrorException(responseEntity.getStatusCode(),
"调用接口 = " + url + " || " +
"失败状态 = " + responseEntity.getStatusCode() + " || " +
"响应 = " + responseEntity.getBody());
}
}
/**
* @param url 请求地址
* @param classType 请返回类型
* @param uriVariables 参数
* @return
* @description: 发送get请求,占位符方式请求
*/
public <T> T doGet(String url, Class<T> classType, Object... uriVariables) {
long startTime = System.currentTimeMillis();
LOGGER.info("\n 请求地址 = {} || 请求方式 = {} || 请求参数 = {}",
url, "GET", JSON.toJSONString(uriVariables));
//发送请求
ResponseEntity<T> responseEntity;
try {
responseEntity = restTemplate.getForEntity(url, classType, uriVariables);
} catch (ResourceAccessException e) {
LOGGER.error("HttpRestUtil -> doExecute 捕获IOException异常," + e.getMessage());
try {
Thread.sleep(2000);
} catch (Exception ex) {
LOGGER.error("HttpRestUtil -> doExecute 暂停2S异常!" + ex.getMessage());
}
responseEntity = restTemplate.getForEntity(url, classType, uriVariables);
}
//响应状态值 200 201 202
boolean statusBool = false;
if (HttpStatus.OK.equals(responseEntity.getStatusCode()) || HttpStatus.CREATED.equals(responseEntity.getStatusCode()) || HttpStatus.ACCEPTED.equals(responseEntity.getStatusCode())) {
statusBool = true;
}
if (null != responseEntity && statusBool) {
T result = responseEntity.getBody();
LOGGER.info("请求地址 = {} || 请求参数 = {} || 响应时长 = {} || 响应结果 = {}",
url, JSON.toJSONString(uriVariables), System.currentTimeMillis() - startTime, result);
if (StringUtils.isEmpty(result)) {
return null;
}
return result;
} else {
LOGGER.error("请求地址 = {} || 请求参数 = {} || 响应时长 = {} || 响应结果 = {}",
url, JSON.toJSONString(uriVariables), System.currentTimeMillis() - startTime, responseEntity.getBody());
throw new HttpClientErrorException(responseEntity.getStatusCode(),
"调用接口 = " + url + " || " +
"失败状态 = " + responseEntity.getStatusCode() + " || " +
"响应 = " + responseEntity.getBody());
}
}
/**
* 发送POST请求,表单形式提交请求
*
* @param url 请求URL
* @param classType 返回对象类型
* @param param 请求参数
* @param <T> 返回结果
* @return
*/
public <T> T doPost(String url, Class<T> classType, Map<String, Object> param) {
long startTime = System.currentTimeMillis();
LOGGER.info("\n 请求地址 = {} || 请求方式 = {} || 请求参数 = {}", url, "POST", JSON.toJSONString(param));
MultiValueMap<String, Object> postParameters = new LinkedMultiValueMap<>();
for (String key : param.keySet()) {
postParameters.add(key, param.get(key));
}
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", MediaType.APPLICATION_FORM_URLENCODED_VALUE);
HttpEntity<MultiValueMap<String, Object>> r = new HttpEntity<>(postParameters, headers);
T t = restTemplate.postForObject(url, r, classType);
LOGGER.info("请求地址 = {} || 请求参数 = {} || 响应时长 = {} || 响应结果 = {}",
url, JSON.toJSONString(param), System.currentTimeMillis() - startTime, JSON.toJSONString(t));
return t;
}
private static HttpEntity getHttpEntity(Map<String, String> headers, String param) {
HttpHeaders httpHeaders = new HttpHeaders();
Iterator iterator = headers.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = (Map.Entry) iterator.next();
String key = entry.getKey();
if (!httpHeaders.containsKey(key)) {
httpHeaders.add(key, entry.getValue());
}
}
return new HttpEntity(param, httpHeaders);
}
}
...@@ -56,3 +56,7 @@ spring: ...@@ -56,3 +56,7 @@ spring:
# 信号平台 # 信号平台
signal: signal:
#远程signalUtcService服务地址
utcServiceUrl: http://10.100.1.59/:32000/utc
syncDeviceSatusUrn: /signalStatus/runningStatusAlarm
\ 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