From af2d5942652584c65579894c4a4a680bc37dad20 Mon Sep 17 00:00:00 2001 From: dongyukun <1208714201@qq.com> Date: 星期六, 08 二月 2025 15:29:39 +0800 Subject: [PATCH] Merge remote-tracking branch 'origin/master' --- shasteel-biz/src/main/java/com/iailab/module/shasteel/common/util/FastHttpUtils.java | 405 ++++++++++++++++++++ shasteel-biz/src/main/java/com/iailab/module/shasteel/job/task/RunScheduleOnaOptTask.java | 7 shasteel-biz/src/main/java/com/iailab/module/shasteel/mq/consumer/ModelAlarmConsumer.java | 95 +++- shasteel-biz/src/main/java/com/iailab/module/shasteel/common/util/HttpsRequest.java | 228 +++++++++++ shasteel-biz/src/main/java/com/iailab/module/shasteel/mq/consumer/ModelElecPredictFinishConsumer.java | 39 + shasteel-biz/src/main/resources/application-dev.yaml | 14 shasteel-biz/src/main/resources/application-test.yaml | 10 shasteel-biz/src/main/java/com/iailab/module/shasteel/common/util/SSLClient.java | 45 ++ shasteel-biz/src/main/java/com/iailab/module/shasteel/common/package-info.java | 1 shasteel-biz/src/main/java/com/iailab/module/shasteel/job/task/SyncSegmentedDataTask.java | 135 ++++++ shasteel-biz/src/main/java/com/iailab/module/shasteel/mq/common/constant/CommonConstant.java | 28 + shasteel-biz/src/main/java/com/iailab/module/shasteel/job/vo/RequestAccessTokenVO.java | 23 + shasteel-biz/src/main/java/com/iailab/module/shasteel/job/task/RunScheduleSteamTask.java | 2 shasteel-biz/src/main/java/com/iailab/module/shasteel/mq/consumer/ModelPredictFinishConsumer.java | 152 +++++-- shasteel-biz/src/main/resources/application-prod.yaml | 10 15 files changed, 1,103 insertions(+), 91 deletions(-) diff --git a/shasteel-biz/src/main/java/com/iailab/module/shasteel/common/package-info.java b/shasteel-biz/src/main/java/com/iailab/module/shasteel/common/package-info.java new file mode 100644 index 0000000..ff19f82 --- /dev/null +++ b/shasteel-biz/src/main/java/com/iailab/module/shasteel/common/package-info.java @@ -0,0 +1 @@ +package com.iailab.module.shasteel.common; \ No newline at end of file diff --git a/shasteel-biz/src/main/java/com/iailab/module/shasteel/common/util/FastHttpUtils.java b/shasteel-biz/src/main/java/com/iailab/module/shasteel/common/util/FastHttpUtils.java new file mode 100644 index 0000000..e29a435 --- /dev/null +++ b/shasteel-biz/src/main/java/com/iailab/module/shasteel/common/util/FastHttpUtils.java @@ -0,0 +1,405 @@ +package com.iailab.module.shasteel.common.util; + +import cn.hutool.core.codec.Base64; +import cn.hutool.core.map.TableMap; +import cn.hutool.core.net.url.UrlBuilder; +import cn.hutool.core.util.ReflectUtil; +import cn.hutool.core.util.StrUtil; +import org.springframework.util.CollectionUtils; +import org.springframework.util.StringUtils; +import org.springframework.web.util.UriComponents; +import org.springframework.web.util.UriComponentsBuilder; + +import javax.servlet.http.HttpServletRequest; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.net.URI; +import java.net.URL; +import java.net.URLConnection; +import java.nio.charset.Charset; +import java.util.List; +import java.util.Map; + +/** + * HTTP 工具类 + * + * @author iailab + */ +public class FastHttpUtils { + + @SuppressWarnings("unchecked") + public static String replaceUrlQuery(String url, String key, String value) { + UrlBuilder builder = UrlBuilder.of(url, Charset.defaultCharset()); + // 先移除 + TableMap<CharSequence, CharSequence> query = (TableMap<CharSequence, CharSequence>) + ReflectUtil.getFieldValue(builder.getQuery(), "query"); + query.remove(key); + // 后添加 + builder.addQuery(key, value); + return builder.build(); + } + + private String append(String base, Map<String, ?> query, boolean fragment) { + return append(base, query, null, fragment); + } + + /** + * 拼接 URL + * + * copy from Spring Security OAuth2 的 AuthorizationEndpoint 类的 append 方法 + * + * @param base 基础 URL + * @param query 查询参数 + * @param keys query 的 key,对应的原本的 key 的映射。例如说 query 里有个 key 是 xx,实际它的 key 是 extra_xx,则通过 keys 里添加这个映射 + * @param fragment URL 的 fragment,即拼接到 # 中 + * @return 拼接后的 URL + */ + public static String append(String base, Map<String, ?> query, Map<String, String> keys, boolean fragment) { + UriComponentsBuilder template = UriComponentsBuilder.newInstance(); + UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(base); + URI redirectUri; + try { + // assume it's encoded to start with (if it came in over the wire) + redirectUri = builder.build(true).toUri(); + } catch (Exception e) { + // ... but allow client registrations to contain hard-coded non-encoded values + redirectUri = builder.build().toUri(); + builder = UriComponentsBuilder.fromUri(redirectUri); + } + template.scheme(redirectUri.getScheme()).port(redirectUri.getPort()).host(redirectUri.getHost()) + .userInfo(redirectUri.getUserInfo()).path(redirectUri.getPath()); + + if (fragment) { + StringBuilder values = new StringBuilder(); + if (redirectUri.getFragment() != null) { + String append = redirectUri.getFragment(); + values.append(append); + } + for (String key : query.keySet()) { + if (values.length() > 0) { + values.append("&"); + } + String name = key; + if (keys != null && keys.containsKey(key)) { + name = keys.get(key); + } + values.append(name).append("={").append(key).append("}"); + } + if (values.length() > 0) { + template.fragment(values.toString()); + } + UriComponents encoded = template.build().expand(query).encode(); + builder.fragment(encoded.getFragment()); + } else { + for (String key : query.keySet()) { + String name = key; + if (keys != null && keys.containsKey(key)) { + name = keys.get(key); + } + template.queryParam(name, "{" + key + "}"); + } + template.fragment(redirectUri.getFragment()); + UriComponents encoded = template.build().expand(query).encode(); + builder.query(encoded.getQuery()); + } + return builder.build().toUriString(); + } + + public static String[] obtainBasicAuthorization(HttpServletRequest request) { + String clientId; + String clientSecret; + // 先从 Header 中获取 + String authorization = request.getHeader("Authorization"); + authorization = StrUtil.subAfter(authorization, "Basic ", true); + if (StringUtils.hasText(authorization)) { + authorization = Base64.decodeStr(authorization); + clientId = StrUtil.subBefore(authorization, ":", false); + clientSecret = StrUtil.subAfter(authorization, ":", false); + // 再从 Param 中获取 + } else { + clientId = request.getParameter("client_id"); + clientSecret = request.getParameter("client_secret"); + } + + // 如果两者非空,则返回 + if (StrUtil.isNotEmpty(clientId) && StrUtil.isNotEmpty(clientSecret)) { + return new String[]{clientId, clientSecret}; + } + return null; + } + + /** + * 向指定URL发送GET方法的请求 + * + * @param url 发送请求的URL + * @return URL 所代表远程资源的响应结果 + */ + public static String sendGet(String url) { + String result = ""; + BufferedReader in = null; + try { + URL realUrl = new URL(url); + // 打开和URL之间的连接 + URLConnection connection = realUrl.openConnection(); + // 设置通用的请求属性 + connection.setRequestProperty("accept", "*/*"); + connection.setRequestProperty("Accept-Encoding", "gzip, deflate, br"); + connection.setRequestProperty("connection", "Keep-Alive"); + connection.setRequestProperty("user-agent", "PostmanRuntime/7.43.0"); + + // 建立实际的连接 + connection.connect(); + // 获取所有响应头字段 + Map<String, List<String>> map = connection.getHeaderFields(); + // 遍历所有的响应头字段 + for (String key : map.keySet()) { + System.out.println(key + "--->" + map.get(key)); + } + // 定义 BufferedReader输入流来读取URL的响应 + in = new BufferedReader(new InputStreamReader(connection.getInputStream())); + String line; + while ((line = in.readLine()) != null) { + result += line; + } + } catch (Exception e) { + System.out.println("发送GET请求出现异常!" + e); + e.printStackTrace(); + } + // 使用finally块来关闭输入流 + finally { + try { + if (in != null) { + in.close(); + } + } catch (Exception e2) { + e2.printStackTrace(); + } + } + return result; + } + + /** + * 向指定URL发送GET方法的请求 + * + * @param url 发送请求的URL + * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 + * @return URL 所代表远程资源的响应结果 + */ + public static String sendGet(String url, String param) { + String result = ""; + BufferedReader in = null; + try { + String urlNameString = url; + URL realUrl = new URL(urlNameString); + // 打开和URL之间的连接 + URLConnection connection = realUrl.openConnection(); + connection.setConnectTimeout(10000); + // 设置通用的请求属性 + connection.setRequestProperty("Host", "<calculated when request is sent>"); + connection.setRequestProperty("user-agent", "PostmanRuntime/7.43.0"); + connection.setRequestProperty("accept", "*/*"); + connection.setRequestProperty("Accept-Encoding", "gzip, deflate, br"); + connection.setRequestProperty("connection", "Keep-Alive"); + + // 建立实际的连接 + connection.connect(); + // 获取所有响应头字段 + Map<String, List<String>> map = connection.getHeaderFields(); + // 遍历所有的响应头字段 + for (String key : map.keySet()) { + System.out.println(key + "--->" + map.get(key)); + } + // 定义 BufferedReader输入流来读取URL的响应 + in = new BufferedReader(new InputStreamReader(connection.getInputStream())); + String line; + while ((line = in.readLine()) != null) { + result += line; + } + } catch (Exception e) { + System.out.println("发送GET请求出现异常!" + e); + e.printStackTrace(); + } + // 使用finally块来关闭输入流 + finally { + try { + if (in != null) { + in.close(); + } + } catch (Exception e2) { + e2.printStackTrace(); + } + } + return result; + } + + public static String sendGet(String url, Map<String, String> params, String authorization) { + String result = ""; + BufferedReader in = null; + try { + StringBuilder sb = new StringBuilder(); + sb.append(url); + if (!CollectionUtils.isEmpty(params)) { + sb.append("?"); + params.forEach((k, v) -> { + sb.append(k + "=" + v + "&"); + }); + sb.append("t=" + System.currentTimeMillis()); + } + String urlNameString = sb.toString(); + URL realUrl = new URL(urlNameString); + // 打开和URL之间的连接 + URLConnection connection = realUrl.openConnection(); + // 设置通用的请求属性 + connection.setRequestProperty("Authorization", authorization); + connection.setRequestProperty("accept", "*/*"); + connection.setRequestProperty("connection", "Keep-Alive"); + connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); + + // 建立实际的连接 + connection.connect(); + // 获取所有响应头字段 + Map<String, List<String>> map = connection.getHeaderFields(); + // 遍历所有的响应头字段 + for (String key : map.keySet()) { + System.out.println(key + "--->" + map.get(key)); + } + // 定义 BufferedReader输入流来读取URL的响应 + in = new BufferedReader(new InputStreamReader(connection.getInputStream())); + String line; + while ((line = in.readLine()) != null) { + result += line; + } + } catch (Exception e) { + System.out.println("发送GET请求出现异常!" + e); + e.printStackTrace(); + } + // 使用finally块来关闭输入流 + finally { + try { + if (in != null) { + in.close(); + } + } catch (Exception e2) { + e2.printStackTrace(); + } + } + return result; + } + + /** + * 向指定 URL 发送POST方法的请求 + * + * @param url + * @param json + * @return + */ + public static String sendPost(String url, String json) { + PrintWriter out = null; + BufferedReader in = null; + String result = ""; + try { + URL realUrl = new URL(url); + // 打开和URL之间的连接 + URLConnection conn = realUrl.openConnection(); + // 设置通用的请求属性 + conn.setRequestProperty("content-type", "application/json"); + conn.setRequestProperty("accept", "*/*"); + conn.setRequestProperty("connection", "Keep-Alive"); + conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); + + // 发送POST请求必须设置如下两行 + conn.setDoOutput(true); + conn.setDoInput(true); + // 获取URLConnection对象对应的输出流 + out = new PrintWriter(conn.getOutputStream()); + // 发送请求参数 + out.print(json); + // flush输出流的缓冲 + out.flush(); + // 定义BufferedReader输入流来读取URL的响应 + in = new BufferedReader(new InputStreamReader(conn.getInputStream())); + String line; + while ((line = in.readLine()) != null) { + result += line; + } + } catch (Exception e) { + System.out.println("发送 POST 请求出现异常!" + e); + e.printStackTrace(); + } + //使用finally块来关闭输出流、输入流 + finally { + try { + if (out != null) { + out.close(); + } + if (in != null) { + in.close(); + } + } catch (IOException ex) { + ex.printStackTrace(); + } + } + return result; + } + + /** + * 向指定 URL 发送POST方法的请求 + * + * @param url + * @param json + * @param authorization + * @return + */ + public static String sendPost(String url, String json, String authorization) { + PrintWriter out = null; + BufferedReader in = null; + String result = ""; + try { + URL realUrl = new URL(url); + // 打开和URL之间的连接 + URLConnection conn = realUrl.openConnection(); + // 设置通用的请求属性 + conn.setRequestProperty("Authorization", authorization); + conn.setRequestProperty("accept", "*/*"); + conn.setRequestProperty("connection", "Keep-Alive"); + conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); + + // 发送POST请求必须设置如下两行 + conn.setDoOutput(true); + conn.setDoInput(true); + // 获取URLConnection对象对应的输出流 + out = new PrintWriter(conn.getOutputStream()); + // 发送请求参数 + out.print(json); + // flush输出流的缓冲 + out.flush(); + // 定义BufferedReader输入流来读取URL的响应 + in = new BufferedReader(new InputStreamReader(conn.getInputStream())); + String line; + while ((line = in.readLine()) != null) { + result += line; + } + } catch (Exception e) { + System.out.println("发送 POST 请求出现异常!" + e); + e.printStackTrace(); + } + //使用finally块来关闭输出流、输入流 + finally { + try { + if (out != null) { + out.close(); + } + if (in != null) { + in.close(); + } + } catch (IOException ex) { + ex.printStackTrace(); + } + } + return result; + } + + +} diff --git a/shasteel-biz/src/main/java/com/iailab/module/shasteel/common/util/HttpsRequest.java b/shasteel-biz/src/main/java/com/iailab/module/shasteel/common/util/HttpsRequest.java new file mode 100644 index 0000000..9572904 --- /dev/null +++ b/shasteel-biz/src/main/java/com/iailab/module/shasteel/common/util/HttpsRequest.java @@ -0,0 +1,228 @@ +package com.iailab.module.shasteel.common.util; + +import lombok.extern.slf4j.Slf4j; +import org.apache.http.Header; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.util.EntityUtils; +import org.springframework.stereotype.Component; +import org.springframework.util.CollectionUtils; + +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.util.Map; + +/** + * @author PanZhibao + * @date 2021年06月03日 16:40 + */ +@Slf4j +@Component +public class HttpsRequest { + + /** + * doGet + * + * @param url + * @param map + * @param charset + * @param token + * @return + */ + public String doGet(String url, Map<String, String> map, String charset, String token) { + org.apache.http.client.HttpClient httpClient = null; + HttpGet httpGet = null; + String result = null; + try { + httpClient = new SSLClient(); + StringBuilder sb = new StringBuilder(); + sb.append(url); + if (!CollectionUtils.isEmpty(map)) { + if ((url.indexOf("?") == -1)) { + sb.append("?"); + } else { + sb.append("&"); + } + map.forEach((k, v) -> { + try { + sb.append(k + "=" + URLEncoder.encode(v, charset) + "&"); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + }); + sb.append("t=" + System.currentTimeMillis()); + } + log.info("doGet,url=" + sb.toString()); + httpGet = new HttpGet(sb.toString()); + //设置参数 + httpGet.addHeader("User-Agent", "PostmanRuntime/7.43.0"); + httpGet.addHeader("Accept", "*/*"); + httpGet.addHeader("Accept-Encoding", "gzip, deflate, br"); + httpGet.addHeader("Connection", "keep-alive"); + + HttpResponse response = httpClient.execute(httpGet); + if (response != null) { + HttpEntity resEntity = response.getEntity(); + if (resEntity != null) { + result = EntityUtils.toString(resEntity, charset); + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + return result; + } + + /** + * doPost + * + * @param url + * @param map + * @param json + * @param charset + * @param token + * @return + */ + public String doPost(String url, Map<String, String> map, String json, String charset, String token) { + org.apache.http.client.HttpClient httpClient = null; + HttpPost httpPost = null; + String result = null; + try { + httpClient = new SSLClient(); + StringBuilder sb = new StringBuilder(); + sb.append(url); + if (!CollectionUtils.isEmpty(map)) { + sb.append("?"); + map.forEach((k, v) -> { + try { + sb.append(k + "=" + URLEncoder.encode(v, charset) + "&"); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + }); + sb.append("t=" + System.currentTimeMillis()); + } + httpPost = new HttpPost(sb.toString()); + //设置参数 + httpPost.addHeader("Accept", "application/json"); + httpPost.addHeader("Content-Type", "application/json;charset=UTF-8"); + httpPost.addHeader("token", token); + StringEntity stringEntity = new StringEntity(json); + stringEntity.setContentEncoding("UTF-8"); + stringEntity.setContentType("application/json"); + httpPost.setEntity(stringEntity); + HttpResponse response = httpClient.execute(httpPost); + if (response != null) { + HttpEntity resEntity = response.getEntity(); + if (resEntity != null) { + result = EntityUtils.toString(resEntity, charset); + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + return result; + } + /** + * doPost + * + * @param url + * @param map + * @param json + * @param charset + * @param token + * @return + */ + public String doPostAuthorization(String url, Map<String, String> map, String json, String charset, String token) { + org.apache.http.client.HttpClient httpClient = null; + HttpPost httpPost = null; + String result = null; + try { + httpClient = new SSLClient(); + StringBuilder sb = new StringBuilder(); + sb.append(url); + if (!CollectionUtils.isEmpty(map)) { + sb.append("?"); + map.forEach((k, v) -> { + try { + sb.append(k + "=" + URLEncoder.encode(v, charset) + "&"); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + }); + sb.append("t=" + System.currentTimeMillis()); + } + httpPost = new HttpPost(sb.toString()); + //设置参数 + httpPost.addHeader("Accept", "application/json"); + httpPost.addHeader("Content-Type", "application/json;charset=UTF-8"); + httpPost.addHeader("Authorization", "Bearer{" + token + "}"); + StringEntity stringEntity = new StringEntity(json); + stringEntity.setContentEncoding("UTF-8"); + stringEntity.setContentType("application/json"); + httpPost.setEntity(stringEntity); + HttpResponse response = httpClient.execute(httpPost); + if (response != null) { + HttpEntity resEntity = response.getEntity(); + if (resEntity != null) { + result = EntityUtils.toString(resEntity, charset); + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + return result; + } + + /** + * doPost + * + * @param url + * @param map + * @param json + * @param charset + * @return + */ + public String doPostToken(String url, Map<String, String> map, String json, String charset) { + org.apache.http.client.HttpClient httpClient = null; + HttpPost httpPost = null; + String result = null; + try { + httpClient = new SSLClient(); + StringBuilder sb = new StringBuilder(); + sb.append(url); + if (!CollectionUtils.isEmpty(map)) { + sb.append("?"); + map.forEach((k, v) -> { + try { + sb.append(k + "=" + URLEncoder.encode(v, charset) + "&"); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + }); + sb.append("t=" + System.currentTimeMillis()); + } + httpPost = new HttpPost(sb.toString()); + //设置参数 + httpPost.addHeader("Accept", "application/json"); + httpPost.addHeader("Content-Type", "application/json;charset=UTF-8"); + StringEntity stringEntity = new StringEntity(json); + stringEntity.setContentEncoding("UTF-8"); + stringEntity.setContentType("application/json"); + httpPost.setEntity(stringEntity); + HttpResponse response = httpClient.execute(httpPost); + if (response != null) { + Header[] resHeader = response.getHeaders("X-Auth-Tkn"); + if (resHeader != null) { + result = resHeader[0].getValue(); + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + return result; + } +} diff --git a/shasteel-biz/src/main/java/com/iailab/module/shasteel/common/util/SSLClient.java b/shasteel-biz/src/main/java/com/iailab/module/shasteel/common/util/SSLClient.java new file mode 100644 index 0000000..fb17a36 --- /dev/null +++ b/shasteel-biz/src/main/java/com/iailab/module/shasteel/common/util/SSLClient.java @@ -0,0 +1,45 @@ +package com.iailab.module.shasteel.common.util; + + +import org.apache.http.conn.ClientConnectionManager; +import org.apache.http.conn.scheme.Scheme; +import org.apache.http.conn.scheme.SchemeRegistry; +import org.apache.http.conn.ssl.SSLSocketFactory; +import org.apache.http.impl.client.DefaultHttpClient; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; + +/** + * @author PanZhibao + * @date 2021年06月03日 15:35 + */ +public class SSLClient extends DefaultHttpClient { + public SSLClient() throws Exception { + super(); + //传输协议需要根据自己的判断 + SSLContext ctx = SSLContext.getInstance("TLS"); + X509TrustManager tm = new X509TrustManager() { + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + return null; + } + }; + ctx.init(null, new TrustManager[]{tm}, null); + SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); + ClientConnectionManager ccm = this.getConnectionManager(); + SchemeRegistry sr = ccm.getSchemeRegistry(); + sr.register(new Scheme("https", 443, ssf)); + } +} diff --git a/shasteel-biz/src/main/java/com/iailab/module/shasteel/job/task/RunScheduleOnaOptTask.java b/shasteel-biz/src/main/java/com/iailab/module/shasteel/job/task/RunScheduleOnaOptTask.java index da50f53..f33f03d 100644 --- a/shasteel-biz/src/main/java/com/iailab/module/shasteel/job/task/RunScheduleOnaOptTask.java +++ b/shasteel-biz/src/main/java/com/iailab/module/shasteel/job/task/RunScheduleOnaOptTask.java @@ -82,14 +82,13 @@ } schemeMap.clear(); Map<String, MdkScheduleRespDTO> resultMap = new HashMap<String, MdkScheduleRespDTO>(); - schemeList.forEach(item -> { - schemeMap.put(item.getCode(), item); - StScheduleSchemeDTO scheme = schemeList.get(0); + schemeList.forEach(scheme -> { + schemeMap.put(scheme.getCode(), scheme); MdkScheduleReqDTO dto = new MdkScheduleReqDTO(); dto.setScheduleTime(scheduleTime); dto.setScheduleCode(scheme.getCode()); MdkScheduleRespDTO mdkScheduleRespDTO = mdkApi.doSchedule(dto); - resultMap.put(item.getCode(), mdkScheduleRespDTO); + resultMap.put(scheme.getCode(), mdkScheduleRespDTO); }); if (CollectionUtils.isEmpty(resultMap)) { logger.info("resultMap为空"); diff --git a/shasteel-biz/src/main/java/com/iailab/module/shasteel/job/task/RunScheduleSteamTask.java b/shasteel-biz/src/main/java/com/iailab/module/shasteel/job/task/RunScheduleSteamTask.java index aca64a9..57d20aa 100644 --- a/shasteel-biz/src/main/java/com/iailab/module/shasteel/job/task/RunScheduleSteamTask.java +++ b/shasteel-biz/src/main/java/com/iailab/module/shasteel/job/task/RunScheduleSteamTask.java @@ -22,6 +22,8 @@ /** * 蒸汽调度 + * 定时触发 + * 30 0/2 * * * ? * * 参考点压力信号 pressure_flag * 锦丰调度建议 jinfengAdvice diff --git a/shasteel-biz/src/main/java/com/iailab/module/shasteel/job/task/SyncSegmentedDataTask.java b/shasteel-biz/src/main/java/com/iailab/module/shasteel/job/task/SyncSegmentedDataTask.java new file mode 100644 index 0000000..e88f129 --- /dev/null +++ b/shasteel-biz/src/main/java/com/iailab/module/shasteel/job/task/SyncSegmentedDataTask.java @@ -0,0 +1,135 @@ +package com.iailab.module.shasteel.job.task; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.iailab.framework.common.util.http.HttpUtils; +import com.iailab.module.model.api.mcs.McsApi; +import com.iailab.module.model.api.mcs.dto.ElectricityPriceSegmentedDTO; +import com.iailab.module.shasteel.job.vo.RequestAccessTokenVO; +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.stereotype.Component; + +import javax.crypto.Cipher; +import java.security.KeyFactory; +import java.security.PublicKey; +import java.security.spec.X509EncodedKeySpec; +import java.time.Instant; +import java.time.LocalDate; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.util.*; + +/** + * 同步分段数据定时任务 + * @author Jay + */ +@Component("syncSegmentedDataTask") +public class SyncSegmentedDataTask implements ITask { + private Logger logger = LoggerFactory.getLogger(getClass()); + + @Autowired + private McsApi mcsApi; + + @Autowired + private RabbitTemplate rabbitTemplate; + + private static final String PUBLIC_KEY_URL = "http://10.88.7.107:8081/api/api/services/Runtime/Authentication/GetLoginRSAPublicKeyAsync"; + + private static final String ACCESS_TOKEN_URL = "http://10.88.7.107:8081/EP.Web/account/ajaxLogin"; + + private static final String QUERY_SEGMENTED_DATA_URL = "http://10.88.7.107:8081/SG.Web/api/services/nYJK/DiagnosticsSg/QuerySegmentedDataAsync"; + + private static final String USERNAME = "Mx001@sgis"; + + private static final String PASSWORD = "123456"; + + @Override + public void run(String params) { + logger.info("syncSegmentedDataTask定时任务正在执行,参数为:{}", params); + try { + Calendar calendar = Calendar.getInstance(); + calendar.set(Calendar.SECOND, 0); + calendar.set(Calendar.MILLISECOND, 0); + //获取 公钥 + String publicKeyKey = getPublicKey(); + // 组合密码 + Instant instant = Instant.now(); // 获取当前时间的UTC时间 + ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, ZoneId.of("Z")); + DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME; + String isoString = zonedDateTime.format(formatter); + String password = isoString + "|" + PASSWORD; + RequestAccessTokenVO requestAccessToken = new RequestAccessTokenVO(); + requestAccessToken.setUserName(USERNAME); + // 使用公钥和组合后的密码进行密码加密 + String realPassword = encryptWithPublicKey(publicKeyKey, password); + logger.info("公钥和组合后的密码进行密码加密:" + realPassword); + requestAccessToken.setPassword(realPassword); + requestAccessToken.setSource(1); + //获取 token + String accessToken = "Bearer " + getAccessToken(requestAccessToken); + //获取保存后的数据 + List<ElectricityPriceSegmentedDTO> list = getElectricityPriceSegmentedList(accessToken); + logger.info("开始保存数据:" + JSON.toJSONString(list)); + mcsApi.createElectricityPrice(list); + logger.info("保存数据完成"); + } catch (Exception ex) { + logger.error("syncSegmentedDataTask运行异常:" + ex.getMessage()); + ex.printStackTrace(); + } + logger.info("syncSegmentedDataTask运行完成"); + } + + public String getPublicKey() { + String publicKeyString = ""; + String resp = HttpUtils.sendGet(PUBLIC_KEY_URL,null,""); + logger.info("获取公钥的返回值:" + resp); + JSONObject jsonObject = JSON.parseObject(resp); + if (jsonObject.get("status").equals(200)) { + publicKeyString = jsonObject.getJSONObject("data").getString("pemPublicKey"); + } + return publicKeyString.replace("-----BEGIN PUBLIC KEY-----", "") + .replace("-----END PUBLIC KEY-----", "") + .replaceAll("\\s", ""); + } + + public String getAccessToken(RequestAccessTokenVO requestAccessToken) { + String accessToken = ""; + logger.info("请求参数:" + JSON.toJSONString(requestAccessToken)); + String resp = HttpUtils.sendPost(ACCESS_TOKEN_URL, JSON.toJSONString(requestAccessToken)); + logger.info("获取token的返回值:" + resp); + JSONObject jsonObject = JSON.parseObject(resp); + if (jsonObject.get("status").equals(200)) { + String token = jsonObject.getJSONObject("data").getString("token"); + JSONObject tokenObject = JSON.parseObject(token); + accessToken = tokenObject.getString("accessToken"); + logger.info("获取到accessToken:" + accessToken); + } + return accessToken; + } + + public List<ElectricityPriceSegmentedDTO> getElectricityPriceSegmentedList(String accessToken){ + logger.info("accessToken: " + accessToken); + Map<String, String> paramsMap = new HashMap<>(); + LocalDate date = LocalDate.now(); // 获取当前日期的LocalDate实例 + String year = String.valueOf(date.getYear()); + paramsMap.put("clock", year); + logger.info("请求参数:" + JSON.toJSONString(paramsMap)); + String resp = HttpUtils.sendPost(QUERY_SEGMENTED_DATA_URL, JSON.toJSONString(paramsMap), accessToken); + logger.info("获取分段数据的返回值:" + resp); + JSONObject jsonObject = JSON.parseObject(resp); + List<ElectricityPriceSegmentedDTO> list = jsonObject.getJSONArray("data").toJavaList(ElectricityPriceSegmentedDTO.class); + list.forEach(item -> item.setYear(year)); + return list; + } + + public static String encryptWithPublicKey(String publicKeyString, String data) throws Exception { + PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyString))); + Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); + cipher.init(Cipher.ENCRYPT_MODE, publicKey); + return Base64.getEncoder().encodeToString(cipher.doFinal(data.getBytes())); + } +} diff --git a/shasteel-biz/src/main/java/com/iailab/module/shasteel/job/vo/RequestAccessTokenVO.java b/shasteel-biz/src/main/java/com/iailab/module/shasteel/job/vo/RequestAccessTokenVO.java new file mode 100644 index 0000000..5be904f --- /dev/null +++ b/shasteel-biz/src/main/java/com/iailab/module/shasteel/job/vo/RequestAccessTokenVO.java @@ -0,0 +1,23 @@ +package com.iailab.module.shasteel.job.vo; + +import lombok.Data; + +import java.io.Serializable; + +/** + * 查询token VO + * @author Jay + * @since 1.0.0 + */ +@Data +public class RequestAccessTokenVO implements Serializable { + + private static final long serialVersionUID = 1L; + + private String userName; + + private String password; + + private int source; + +} diff --git a/shasteel-biz/src/main/java/com/iailab/module/shasteel/mq/common/constant/CommonConstant.java b/shasteel-biz/src/main/java/com/iailab/module/shasteel/mq/common/constant/CommonConstant.java index 025a4de..ee3e176 100644 --- a/shasteel-biz/src/main/java/com/iailab/module/shasteel/mq/common/constant/CommonConstant.java +++ b/shasteel-biz/src/main/java/com/iailab/module/shasteel/mq/common/constant/CommonConstant.java @@ -1,8 +1,5 @@ package com.iailab.module.shasteel.mq.common.constant; - -import java.math.BigDecimal; - /** * @Description: 通用常量 */ @@ -20,12 +17,33 @@ //氧气系统优化调度决策方案code String OXYGEN_TWO_CODE = "oxygen02"; + //煤气调度code + String GAS_MODEL_CODE = "GAS01"; + //超上限 - String EXCEEDING_UPPER_LIMIT = "UpperLimit"; + String EXCEEDING_UPPER_LIMIT = "超上限"; //超下限 - String EXCEEDING_LOWER_LIMIT = "LowerLimit"; + String EXCEEDING_LOWER_LIMIT = "超下限"; //电力管网触发条件 String TRIGGER_CONDITION_ELEC = "NET_ELE"; + + String NET_COG = "NET_COG"; + + String NET_BFG = "NET_BFG"; + + String NET_ELE = "NET_ELE"; + + String NET_O2 = "NET_O2"; + + String NET_LDG = "NET_LDG"; + + String NET_STEAM = "NET_STEAM"; + + String NET_N2 = "NET_N2"; + + String NET_TEST = "NET_TEST"; + + String NET_GAS = "NET_GAS"; } diff --git a/shasteel-biz/src/main/java/com/iailab/module/shasteel/mq/consumer/ModelAlarmConsumer.java b/shasteel-biz/src/main/java/com/iailab/module/shasteel/mq/consumer/ModelAlarmConsumer.java index 846333f..f06f22b 100644 --- a/shasteel-biz/src/main/java/com/iailab/module/shasteel/mq/consumer/ModelAlarmConsumer.java +++ b/shasteel-biz/src/main/java/com/iailab/module/shasteel/mq/consumer/ModelAlarmConsumer.java @@ -1,5 +1,6 @@ package com.iailab.module.shasteel.mq.consumer; +import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.iailab.framework.common.util.date.DateUtils; import com.iailab.module.model.api.mcs.McsApi; @@ -13,16 +14,14 @@ import com.iailab.module.shasteel.mq.common.constant.CommonConstant; import com.iailab.module.shasteel.mq.config.QueueModelAlarmConfig; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; import org.springframework.amqp.core.Message; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; import javax.annotation.Resource; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; +import java.util.*; /** * 监听报警信息 @@ -41,10 +40,7 @@ @Resource private MdkApi mdkApi; - /** - * 事件标识 - */ - private final String EVENT_FLAG = "GasAlarm"; + private static String lastRunGasSchedule = ""; /** * 监听报警信息,执行调度 @@ -57,29 +53,56 @@ log.info("routingKey:" + routingKey); String messageBody = new String(message.getBody()); log.info("messageBody:" + messageBody); - JSONObject messageJson = JSONObject.parseObject(messageBody); + Map<String, Object> messageJson = JSONObject.parseObject(messageBody); if (CollectionUtils.isEmpty(messageJson)) { return; } + Date predictTime = DateUtils.parse(messageJson.get("predictTime").toString(), DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND); + if (new Date().getTime() - predictTime.getTime() > 1000 * 60 * 10) { + log.info("过滤旧消息"); + return; + } + // 查找需要执行的调度方案 List<StScheduleSchemeDTO> scheduleSchemeList = mcsApi.listScheduleScheme(ScheduleTriggerMethodEnum.EVENT.getCode(), routingKey); - for(StScheduleSchemeDTO stScheduleSchemeDTO : scheduleSchemeList){ + if (CollectionUtils.isEmpty(scheduleSchemeList)) { + log.info("routingKey:" + routingKey + ",调度方案为空。"); + return; + } + for (StScheduleSchemeDTO stScheduleSchemeDTO : scheduleSchemeList) { + String runKey = "GasSchedule_" + stScheduleSchemeDTO.getCode() + "_" + predictTime.getTime(); + log.info("runKey:" + runKey); + log.info("lastRunGasSchedule:" + lastRunGasSchedule); + if (lastRunGasSchedule.equals(runKey)) { + continue; + } + lastRunGasSchedule = runKey; MdkScheduleReqDTO mdkScheduleReqDTO = new MdkScheduleReqDTO(); mdkScheduleReqDTO.setScheduleCode(stScheduleSchemeDTO.getCode()); - mdkScheduleReqDTO.setScheduleTime(stScheduleSchemeDTO.getScheduleTime()); - MdkScheduleRespDTO mdkScheduleRespDTO = mdkApi.doSchedule(mdkScheduleReqDTO);//执行调度方案 - if(mdkScheduleRespDTO == null){ + mdkScheduleReqDTO.setScheduleTime(predictTime); + //执行调度方案 + MdkScheduleRespDTO mdkScheduleRespDTO = mdkApi.doSchedule(mdkScheduleReqDTO); + if (mdkScheduleRespDTO == null) { return; } - AlarmMessageRespDTO alarmRespDTO = (AlarmMessageRespDTO)messageJson.get("AlarmMessageRespDTO"); - alarmRespDTO.setId(UUID.randomUUID().toString()); - alarmRespDTO.setAlarmTime(DateUtils.parse(messageJson.get("predictTime").toString(), DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND)); - mcsApi.createAlarmMessage(alarmRespDTO); + Map<String, Object> result = mdkScheduleRespDTO.getResult(); switch (mdkScheduleRespDTO.getScheduleCode()) { - case CommonConstant.OXYGEN_ONE_CODE://氧气班平衡计划方案 - if(!result.containsKey("faAdvice") || !result.containsKey("yingDiAdvice") || !result.containsKey("yingZhongAdvice") - || !result.containsKey("hongAdvice") || !result.containsKey("RunAdvice")){ + case CommonConstant.GAS_MODEL_CODE: + // 结果写入测点 + mdkApi.scheduleModelOut(mdkScheduleRespDTO); + + // 保存调度建议 + String sch_obj_gas = "GAS"; + saveScheduleSuggest("adviceBFG", result.get("adviceBFG"), sch_obj_gas, predictTime); + saveScheduleSuggest("adviceCOG", result.get("adviceCOG"), sch_obj_gas, predictTime); + saveScheduleSuggest("adviceLDG13W", result.get("adviceLDG13W"), sch_obj_gas, predictTime); + saveScheduleSuggest("adviceLDG12W", result.get("adviceLDG12W"), sch_obj_gas, predictTime); + saveScheduleSuggest("adviceLDG12WT", result.get("adviceLDG12WT"), sch_obj_gas, predictTime); + break; + case CommonConstant.OXYGEN_ONE_CODE: + if (!result.containsKey("faAdvice") || !result.containsKey("yingDiAdvice") || !result.containsKey("yingZhongAdvice") + || !result.containsKey("hongAdvice") || !result.containsKey("RunAdvice")) { return; } for (String key : result.keySet()) { @@ -90,28 +113,28 @@ suggestRespDTO.setContent(result.get("faAdvice").toString());//法夜空建议送出量建议 suggestRespDTO.setSchemeId(stScheduleSchemeDTO.getId()); mcsApi.createScheduleSuggest(suggestRespDTO); - }else if ("yingDiAdvice".equals(key) && !"".equals(result.get("yingDiAdvice").toString())) { + } else if ("yingDiAdvice".equals(key) && !"".equals(result.get("yingDiAdvice").toString())) { ScheduleSuggestRespDTO suggestRespDTO = new ScheduleSuggestRespDTO(); suggestRespDTO.setId(UUID.randomUUID().toString()); suggestRespDTO.setScheduleObj(stScheduleSchemeDTO.getScheduleObj()); suggestRespDTO.setContent(result.get("yingDiAdvice").toString());//盈德低压建议送出量建议 suggestRespDTO.setSchemeId(stScheduleSchemeDTO.getId()); mcsApi.createScheduleSuggest(suggestRespDTO); - }else if ("yingZhongAdvice".equals(key) && !"".equals(result.get("yingZhongAdvice").toString())) { + } else if ("yingZhongAdvice".equals(key) && !"".equals(result.get("yingZhongAdvice").toString())) { ScheduleSuggestRespDTO suggestRespDTO = new ScheduleSuggestRespDTO(); suggestRespDTO.setId(UUID.randomUUID().toString()); suggestRespDTO.setScheduleObj(stScheduleSchemeDTO.getScheduleObj()); suggestRespDTO.setContent(result.get("yingZhongAdvice").toString());//盈德中压建议送出量建议 suggestRespDTO.setSchemeId(stScheduleSchemeDTO.getId()); mcsApi.createScheduleSuggest(suggestRespDTO); - }else if ("hongAdvice".equals(key) && !"".equals(result.get("hongAdvice").toString())) { + } else if ("hongAdvice".equals(key) && !"".equals(result.get("hongAdvice").toString())) { ScheduleSuggestRespDTO suggestRespDTO = new ScheduleSuggestRespDTO(); suggestRespDTO.setId(UUID.randomUUID().toString()); suggestRespDTO.setScheduleObj(stScheduleSchemeDTO.getScheduleObj()); suggestRespDTO.setContent(result.get("hongAdvice").toString());//宏昌建议送出量建议 suggestRespDTO.setSchemeId(stScheduleSchemeDTO.getId()); mcsApi.createScheduleSuggest(suggestRespDTO); - }else if ("RunAdvice".equals(key) && !"".equals(result.get("RunAdvice").toString())) { + } else if ("RunAdvice".equals(key) && !"".equals(result.get("RunAdvice").toString())) { ScheduleSuggestRespDTO suggestRespDTO = new ScheduleSuggestRespDTO(); suggestRespDTO.setId(UUID.randomUUID().toString()); suggestRespDTO.setScheduleObj(stScheduleSchemeDTO.getScheduleObj()); @@ -122,8 +145,8 @@ } break; case CommonConstant.OXYGEN_TWO_CODE://氧气系统优化调度决策方案 - if(!result.containsKey("yingdiAdvice") || !result.containsKey("faAdvice") || !result.containsKey("hongAdvice") - || !result.containsKey("RunAdvice")){ + if (!result.containsKey("yingdiAdvice") || !result.containsKey("faAdvice") || !result.containsKey("hongAdvice") + || !result.containsKey("RunAdvice")) { return; } for (String key : result.keySet()) { @@ -134,21 +157,21 @@ suggestRespDTO.setContent(result.get("yingdiAdvice").toString());//盈德中压建议调整量建议 suggestRespDTO.setSchemeId(stScheduleSchemeDTO.getId()); mcsApi.createScheduleSuggest(suggestRespDTO); - }else if ("faAdvice".equals(key) && !"".equals(result.get("faAdvice").toString())) { + } else if ("faAdvice".equals(key) && !"".equals(result.get("faAdvice").toString())) { ScheduleSuggestRespDTO suggestRespDTO = new ScheduleSuggestRespDTO(); suggestRespDTO.setId(UUID.randomUUID().toString()); suggestRespDTO.setScheduleObj(stScheduleSchemeDTO.getScheduleObj()); suggestRespDTO.setContent(result.get("faAdvice").toString());//法夜空建议调整量建议 suggestRespDTO.setSchemeId(stScheduleSchemeDTO.getId()); mcsApi.createScheduleSuggest(suggestRespDTO); - }else if ("hongAdvice".equals(key) && !"".equals(result.get("hongAdvice").toString())) { + } else if ("hongAdvice".equals(key) && !"".equals(result.get("hongAdvice").toString())) { ScheduleSuggestRespDTO suggestRespDTO = new ScheduleSuggestRespDTO(); suggestRespDTO.setId(UUID.randomUUID().toString()); suggestRespDTO.setScheduleObj(stScheduleSchemeDTO.getScheduleObj()); suggestRespDTO.setContent(result.get("hongAdvice").toString());//宏昌建议调整量建议 suggestRespDTO.setSchemeId(stScheduleSchemeDTO.getId()); mcsApi.createScheduleSuggest(suggestRespDTO); - }else if ("RunAdvice".equals(key) && !"".equals(result.get("RunAdvice").toString())) { + } else if ("RunAdvice".equals(key) && !"".equals(result.get("RunAdvice").toString())) { ScheduleSuggestRespDTO suggestRespDTO = new ScheduleSuggestRespDTO(); suggestRespDTO.setId(UUID.randomUUID().toString()); suggestRespDTO.setScheduleObj(stScheduleSchemeDTO.getScheduleObj()); @@ -163,4 +186,18 @@ } } } + + private void saveScheduleSuggest(String title, Object content, String scheduleObj, Date scheduleTime) { + if (content == null || StringUtils.isBlank(content.toString()) || "0".equals(content.toString())) { + log.info(title + "content为空"); + return; + } + ScheduleSuggestRespDTO suggest = new ScheduleSuggestRespDTO(); + suggest.setTitle(title); + suggest.setContent(content.toString()); + suggest.setScheduleObj(scheduleObj); + suggest.setScheduleTime(scheduleTime); + suggest.setSort(0); + mcsApi.createScheduleSuggest(suggest); + } } \ No newline at end of file diff --git a/shasteel-biz/src/main/java/com/iailab/module/shasteel/mq/consumer/ModelElecPredictFinishConsumer.java b/shasteel-biz/src/main/java/com/iailab/module/shasteel/mq/consumer/ModelElecPredictFinishConsumer.java index 43b8c5e..2faa438 100644 --- a/shasteel-biz/src/main/java/com/iailab/module/shasteel/mq/consumer/ModelElecPredictFinishConsumer.java +++ b/shasteel-biz/src/main/java/com/iailab/module/shasteel/mq/consumer/ModelElecPredictFinishConsumer.java @@ -1,21 +1,22 @@ package com.iailab.module.shasteel.mq.consumer; import com.iailab.module.model.api.mcs.McsApi; +import com.iailab.module.model.api.mcs.dto.ScheduleSuggestRespDTO; import com.iailab.module.model.api.mcs.dto.StScheduleSchemeDTO; import com.iailab.module.model.api.mdk.MdkApi; import com.iailab.module.model.api.mdk.dto.MdkScheduleReqDTO; +import com.iailab.module.model.api.mdk.dto.MdkScheduleRespDTO; import com.iailab.module.model.enums.ScheduleTriggerMethodEnum; import com.iailab.module.shasteel.mq.common.constant.CommonConstant; import com.iailab.module.shasteel.mq.config.QueuePredictFinishConfig; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; import org.springframework.amqp.core.Message; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; import javax.annotation.Resource; -import java.util.Calendar; -import java.util.Date; -import java.util.List; +import java.util.*; /** * @description: @@ -31,6 +32,17 @@ @Resource private MdkApi mdkApi; + + //功率因数调度 code + private static final List<String> elecScheduleCodes = new ArrayList<String>(){{ + add("rejuandiaodu"); + add("leyangdiaodu"); + add("lengzhadiaodu"); + add("hailidiaodu"); + add("dongqudiaodu"); + }}; + + private static final String adviceKey = "advice"; /** * 监听电力预测完成,执行电力调度 @@ -54,7 +66,26 @@ MdkScheduleReqDTO mdkScheduleReqDTO = new MdkScheduleReqDTO(); mdkScheduleReqDTO.setScheduleCode(stScheduleSchemeDTO.getCode()); mdkScheduleReqDTO.setScheduleTime(scheduleTime); - mdkApi.doSchedule(mdkScheduleReqDTO); + MdkScheduleRespDTO mdkScheduleRespDTO = mdkApi.doSchedule(mdkScheduleReqDTO); + + //功率因数调度 保存调度建议 + if (elecScheduleCodes.contains(stScheduleSchemeDTO.getCode())) { + Map<String, Object> result = mdkScheduleRespDTO.getResult(); + if (result.containsKey(adviceKey)) { + String advice = result.get(adviceKey).toString().trim(); + if (StringUtils.isNotBlank(advice)) { + ScheduleSuggestRespDTO suggest = new ScheduleSuggestRespDTO(); + suggest.setTitle("电力调度建议"); + suggest.setContent(advice); + suggest.setSchemeId(stScheduleSchemeDTO.getId()); + suggest.setScheduleObj(stScheduleSchemeDTO.getScheduleObj()); + suggest.setScheduleTime(scheduleTime); + suggest.setSort(0); + mcsApi.createScheduleSuggest(suggest); + } + } + } + } diff --git a/shasteel-biz/src/main/java/com/iailab/module/shasteel/mq/consumer/ModelPredictFinishConsumer.java b/shasteel-biz/src/main/java/com/iailab/module/shasteel/mq/consumer/ModelPredictFinishConsumer.java index 802d502..19ab2ac 100644 --- a/shasteel-biz/src/main/java/com/iailab/module/shasteel/mq/consumer/ModelPredictFinishConsumer.java +++ b/shasteel-biz/src/main/java/com/iailab/module/shasteel/mq/consumer/ModelPredictFinishConsumer.java @@ -18,13 +18,12 @@ import javax.annotation.Resource; import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; +import java.util.stream.Collectors; /** * 监听预测完成 + * 根据预警配置产生预警信息 * * @author PanZhibao * @Description @@ -39,6 +38,8 @@ @Resource private RabbitTemplate rabbitTemplate; + + private static String lastRunAlarm = ""; /** * 监听预测完成,产生预警消息 @@ -56,61 +57,118 @@ if (CollectionUtils.isEmpty(messageJson)) { return; } + // 预测时间 + Date predictTime = DateUtils.parse(messageJson.get("predictTime").toString(), DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND); + // 预测模块/预测管网 + String moduleType = messageJson.get("moduleType").toString(); + // 查询相关预警配置 List<AlarmConfigRespDTO> configList = mcsApi.listAlarmConfig(new HashMap<String, Object>()); if (CollectionUtils.isEmpty(configList)) { + log.info("AlarmConfigList is empty"); return; } - List<String> outputIdList = new ArrayList<>(); - configList.forEach(item -> { - outputIdList.add(item.getOutId()); - }); - configList.forEach(item -> { - PreDataJsonReqVO reqVO = new PreDataJsonReqVO(); - reqVO.setPredictTime(DateUtils.parse(messageJson.get("predictTime").toString(), DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND)); - reqVO.setOutputIdList(outputIdList); - Map<String, List<Object[]>> preData = mcsApi.getPreDataCur(reqVO); - if (CollectionUtils.isEmpty(preData)) { + List<String> outputIdList = configList.stream().map(item -> { + return item.getOutId(); + }).collect(Collectors.toList()); + List<AlarmMessageRespDTO> alarmList = new ArrayList<>(); + if (moduleType.equals(CommonConstant.NET_BFG) || moduleType.equals(CommonConstant.NET_COG) || + moduleType.equals(CommonConstant.NET_LDG)) { + String runKey = "GasAlarm_" + predictTime.getTime(); + log.info("runKey:" + runKey); + log.info("lastRunAlarm:" + lastRunAlarm); + if (lastRunAlarm.equals(runKey)) { return; } - List<Object[]> result = preData.get(item.getOutId()); - int toIndex = result.size(); - if (toIndex <= 0) { - return; - } - int fromIndex = result.size() - item.getCompLength(); - List<Object[]> predictList = result.subList(fromIndex, toIndex); - for (Object[] data : predictList) { - BigDecimal dataValue = new BigDecimal(Double.parseDouble(data[1].toString())).setScale(2, BigDecimal.ROUND_HALF_UP); - if (!(dataValue.compareTo(item.getLowerLimit()) >= 0 && dataValue.compareTo(item.getUpperLimit()) <= 0)) { - AlarmMessageRespDTO alarmMessage = new AlarmMessageRespDTO(); - alarmMessage.setConfigId(item.getId()); - if (dataValue.compareTo(item.getLowerLimit()) < 0) { - alarmMessage.setAlarmType(CommonConstant.EXCEEDING_LOWER_LIMIT);//超下限 - } else if (dataValue.compareTo(item.getUpperLimit()) > 0) { - alarmMessage.setAlarmType(CommonConstant.EXCEEDING_UPPER_LIMIT);//超上限 + lastRunAlarm = runKey; + for (AlarmConfigRespDTO configItem : configList) { + PreDataJsonReqVO reqVO = new PreDataJsonReqVO(); + reqVO.setPredictTime(predictTime); + reqVO.setOutputIdList(outputIdList); + Map<String, List<Object[]>> preData = mcsApi.getPreDataCur(reqVO); + if (CollectionUtils.isEmpty(preData)) { + return; + } + Map<String, BigDecimal> culData = new HashMap<>(); + preData.forEach((key, value) -> { + double nv = value.stream().map(v1 -> { + return Double.parseDouble(v1[1].toString()); + }).collect(Collectors.toList()).stream().mapToDouble(Double::doubleValue).sum(); + culData.put(key, new BigDecimal(nv)); + }); + + List<Object[]> result = preData.get(configItem.getOutId()); + if (CollectionUtils.isEmpty(result)) { + continue; + } + // 累计值 + BigDecimal culValue = new BigDecimal(result.stream().map(v1 -> { + return Double.parseDouble(v1[1].toString()); + }).collect(Collectors.toList()).stream().mapToDouble(Double::doubleValue).sum()); + log.info("culValue:" + culValue); + + // 生成预警信息 + AlarmMessageRespDTO alarmMessage = new AlarmMessageRespDTO(); + alarmMessage.setConfigId(configItem.getId()); + alarmMessage.setTitle(configItem.getTitle()); + alarmMessage.setAlarmObj(configItem.getAlarmObj()); + alarmMessage.setAlarmTime(predictTime); + log.info("对比累计值是否超限"); + StringBuilder content = new StringBuilder(); + if (configItem.getCulUpper() != null && culValue.compareTo(configItem.getCulUpper()) > 0) { + content.append("即将超出累计值上限"); + alarmMessage.setAlarmType(CommonConstant.EXCEEDING_UPPER_LIMIT); + alarmMessage.setContent(content.toString()); + mcsApi.createAlarmMessage(alarmMessage); + alarmList.add(alarmMessage); + continue; + } + if (configItem.getCulLower() != null && culValue.compareTo(configItem.getCulLower()) < 0) { + content.append("即将低于累计值下限"); + alarmMessage.setAlarmType(CommonConstant.EXCEEDING_LOWER_LIMIT); + alarmMessage.setContent(content.toString()); + mcsApi.createAlarmMessage(alarmMessage); + alarmList.add(alarmMessage); + continue; + } + + log.info("对比预测值是否超限"); + int toIndex = result.size(); + int fromIndex = result.size() - configItem.getCompLength(); + List<Object[]> predictList = result.subList(fromIndex, toIndex); + for (Object[] data : predictList) { + BigDecimal dataValue = new BigDecimal(Double.parseDouble(data[1].toString())).setScale(2, BigDecimal.ROUND_HALF_UP); + if (dataValue.compareTo(configItem.getLowerLimit()) >= 0 && dataValue.compareTo(configItem.getUpperLimit()) <= 0) { + log.info("预测值不超限"); + continue; } - alarmMessage.setAlarmTime(DateUtils.parse(data[0].toString(), DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND)); - StringBuffer sb = new StringBuffer(); - sb.append(data[0]); - sb.append(" "); - sb.append(item.getAlarmObj()); - if ("1".equals(alarmMessage.getAlarmType())) { - sb.append(CommonConstant.EXCEEDING_LOWER_LIMIT); - } else if ("2".equals(alarmMessage.getAlarmType())) { - sb.append(CommonConstant.EXCEEDING_UPPER_LIMIT); + alarmMessage.setOutTime(DateUtils.parse(data[0].toString(), DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND)); + content.append(DateUtils.format(alarmMessage.getOutTime(), DateUtils.FORMAT_SIMPLE_TIME)); + content.append(","); + content.append("即将"); + if (dataValue.compareTo(configItem.getLowerLimit()) < 0) { + content.append("低与下限"); + alarmMessage.setAlarmType(CommonConstant.EXCEEDING_LOWER_LIMIT); + + } else if (dataValue.compareTo(configItem.getUpperLimit()) > 0) { + content.append("超出上限"); + alarmMessage.setAlarmType(CommonConstant.EXCEEDING_UPPER_LIMIT); } - sb.append(dataValue); - sb.append(item.getUnit()); - alarmMessage.setContent(sb.toString()); - System.out.println("预警消息=" + alarmMessage); - rabbitTemplate.convertAndSend(RoutingConstant.EXCHANGE, RoutingConstant.Iailab_Model_Alarm, alarmMessage); + alarmMessage.setContent(content.toString()); + mcsApi.createAlarmMessage(alarmMessage); + alarmList.add(alarmMessage); break; } } - System.out.println(preData); - }); + } + if (!CollectionUtils.isEmpty(alarmList)) { + log.info("发送预警消息"); + Map<String, Object> msg = new HashMap<>(2); + msg.put("predictTime", DateUtils.format(predictTime, DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND)); + msg.put("alarmList", alarmList); + rabbitTemplate.convertAndSend(RoutingConstant.EXCHANGE, RoutingConstant.Iailab_Model_Alarm, msg); + } } catch (Exception e) { - return; + e.printStackTrace(); } } diff --git a/shasteel-biz/src/main/resources/application-dev.yaml b/shasteel-biz/src/main/resources/application-dev.yaml index 5415e33..080143f 100644 --- a/shasteel-biz/src/main/resources/application-dev.yaml +++ b/shasteel-biz/src/main/resources/application-dev.yaml @@ -35,7 +35,7 @@ primary: master datasource: master: - url: jdbc:mysql://127.0.0.1:3306/iailab_fast_tenant_shasteel?useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true # MySQL Connector/J 8.X 连接的示例 + url: jdbc:mysql://172.16.8.100:3306/iailab_fast_tenant_shasteel?useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true # MySQL Connector/J 8.X 连接的示例 username: root password: 123456 @@ -44,7 +44,17 @@ host: 127.0.0.1 # 地址 port: 6379 # 端口 database: 0 # 数据库索引 -# password: 123456 # 密码,建议生产环境开启 + password: 123456 # 密码,建议生产环境开启 + +--- #################### 监控相关配置 #################### + +# Actuator 监控端点的配置项 +management: + endpoints: + web: + base-path: /actuator # Actuator 提供的 API 接口的根目录。默认为 /actuator + exposure: + include: '*' # 需要开放的端点。默认值只打开 health 和 info 两个端点。通过设置 * ,可以开放所有端点。 --- #################### MQ 消息队列相关配置 #################### diff --git a/shasteel-biz/src/main/resources/application-prod.yaml b/shasteel-biz/src/main/resources/application-prod.yaml index 876dbec..bec697a 100644 --- a/shasteel-biz/src/main/resources/application-prod.yaml +++ b/shasteel-biz/src/main/resources/application-prod.yaml @@ -45,6 +45,16 @@ database: 8 password: 123456 +--- #################### 监控相关配置 #################### + +# Actuator 监控端点的配置项 +management: + endpoints: + web: + base-path: /actuator # Actuator 提供的 API 接口的根目录。默认为 /actuator + exposure: + include: '*' # 需要开放的端点。默认值只打开 health 和 info 两个端点。通过设置 * ,可以开放所有端点。 + --- #################### MQ #################### spring: diff --git a/shasteel-biz/src/main/resources/application-test.yaml b/shasteel-biz/src/main/resources/application-test.yaml index 1b8219d..9d651d4 100644 --- a/shasteel-biz/src/main/resources/application-test.yaml +++ b/shasteel-biz/src/main/resources/application-test.yaml @@ -60,6 +60,16 @@ database: 8 # 数据库索引 password: 123456 # 密码,建议生产环境开启 +--- #################### 监控相关配置 #################### + +# Actuator 监控端点的配置项 +management: + endpoints: + web: + base-path: /actuator # Actuator 提供的 API 接口的根目录。默认为 /actuator + exposure: + include: '*' # 需要开放的端点。默认值只打开 health 和 info 两个端点。通过设置 * ,可以开放所有端点。 + --- #################### 平台相关配置 #################### # 平台配置项,设置当前项目所有自定义的配置 -- Gitblit v1.9.3