将包名com.nis修改为net.geedge
This commit is contained in:
25
src/main/java/net/geedge/CounterService.java
Normal file
25
src/main/java/net/geedge/CounterService.java
Normal file
@@ -0,0 +1,25 @@
|
||||
package net.geedge;
|
||||
|
||||
import com.google.common.util.concurrent.AtomicDouble;
|
||||
import io.micrometer.prometheus.PrometheusMeterRegistry;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
/**
|
||||
* created by bailong001 on 2019/07/16 14:49
|
||||
*/
|
||||
@Service
|
||||
public class CounterService {
|
||||
|
||||
@Resource
|
||||
private PrometheusMeterRegistry appleMeterRegistry;
|
||||
|
||||
public Object incrCount(String type, String value) {
|
||||
String name = "user.counter." + type;
|
||||
if ("Olp".equals(type)) {
|
||||
return appleMeterRegistry.gauge(name, new AtomicDouble(Double.parseDouble(value))).get();
|
||||
}
|
||||
return "null";
|
||||
}
|
||||
}
|
||||
18
src/main/java/net/geedge/OlpExporterApplication.java
Normal file
18
src/main/java/net/geedge/OlpExporterApplication.java
Normal file
@@ -0,0 +1,18 @@
|
||||
package net.geedge;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.actuate.autoconfigure.metrics.JvmMetricsAutoConfiguration;
|
||||
import org.springframework.boot.actuate.autoconfigure.metrics.LogbackMetricsAutoConfiguration;
|
||||
import org.springframework.boot.actuate.autoconfigure.metrics.SystemMetricsAutoConfiguration;
|
||||
import org.springframework.boot.actuate.autoconfigure.metrics.web.servlet.WebMvcMetricsAutoConfiguration;
|
||||
import org.springframework.boot.actuate.autoconfigure.metrics.web.tomcat.TomcatMetricsAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication(exclude = {JvmMetricsAutoConfiguration.class,SystemMetricsAutoConfiguration.class,TomcatMetricsAutoConfiguration.class,LogbackMetricsAutoConfiguration.class,WebMvcMetricsAutoConfiguration.class})
|
||||
public class OlpExporterApplication {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
SpringApplication.run(OlpExporterApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
23
src/main/java/net/geedge/config/MetricConfig.java
Normal file
23
src/main/java/net/geedge/config/MetricConfig.java
Normal file
@@ -0,0 +1,23 @@
|
||||
package net.geedge.config;
|
||||
//package net.geedge.config;
|
||||
//
|
||||
//import io.prometheus.client.CollectorRegistry;
|
||||
//import io.prometheus.client.Gauge;
|
||||
//import org.springframework.beans.factory.annotation.Autowired;
|
||||
//import org.springframework.context.annotation.Bean;
|
||||
//import org.springframework.context.annotation.Configuration;
|
||||
//
|
||||
//@Configuration
|
||||
//public class MetricConfig {
|
||||
//// @Autowired
|
||||
// public CollectorRegistry collectorRegistry = new CollectorRegistry();
|
||||
//
|
||||
// @Bean
|
||||
// Gauge processorNatGatewayMonitorSnat(){
|
||||
// return Gauge.build().name("processorNatGatewayMonitor_snat")
|
||||
// .labelNames("natgatewayid")
|
||||
// .help("processorNatGatewayMonitorSnat:record by gatewayid and nodeip")
|
||||
// .register(collectorRegistry);
|
||||
// }
|
||||
//
|
||||
//}
|
||||
@@ -0,0 +1,115 @@
|
||||
package net.geedge.controller;
|
||||
|
||||
import io.prometheus.client.CollectorRegistry;
|
||||
import io.prometheus.client.Gauge;
|
||||
import net.geedge.util.UdpUtils;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
@RestController
|
||||
public class OlpDataCollectController {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(OlpDataCollectController.class);
|
||||
|
||||
@Autowired
|
||||
private CollectorRegistry olpCollectorRegistry;
|
||||
|
||||
@GetMapping("/probe")
|
||||
public void endpointOlp(HttpServletRequest request,HttpServletResponse response,@RequestParam(required = true) String target,@RequestParam(required = true) Integer[] slot,@RequestParam(required = false) Integer timeout) throws IOException {
|
||||
if(timeout==null) {
|
||||
timeout = 5000;//默认5秒
|
||||
}
|
||||
logger.info(target);
|
||||
logger.info(Arrays.deepToString(slot));
|
||||
logger.info(timeout+"");
|
||||
|
||||
olpCollectorRegistry.clear();
|
||||
|
||||
Gauge labeledDurationSecondsGauge = Gauge.build().name("probe_duration_seconds")
|
||||
.labelNames("slot")
|
||||
.help("Check device status response time")
|
||||
.register(olpCollectorRegistry);
|
||||
|
||||
Gauge labeledBypassGauge = Gauge.build().name("probe_bypass")
|
||||
.labelNames("slot")
|
||||
.help("Return bypass status")
|
||||
.register(olpCollectorRegistry);
|
||||
|
||||
Gauge labeledSuccessGauge = Gauge.build().name("probe_success")
|
||||
.labelNames("slot")
|
||||
.help("Displays whether or not the probe was a success")
|
||||
.register(olpCollectorRegistry);
|
||||
|
||||
for(Integer oneSlot:slot) {
|
||||
double start = System.currentTimeMillis();
|
||||
String rlt = UdpUtils.send(target, oneSlot,timeout);
|
||||
double end = System.currentTimeMillis();
|
||||
double durationSeconds = (end-start)/1000;
|
||||
String slotStr = oneSlot+"";
|
||||
long bypass = rlt.endsWith("03")?0:(rlt.endsWith("0c")?1:-1);
|
||||
long success = (rlt.endsWith("03")||rlt.endsWith("0c"))?1:0;
|
||||
|
||||
labeledDurationSecondsGauge.labels(slotStr).set(durationSeconds);
|
||||
labeledBypassGauge.labels(slotStr).set(bypass);
|
||||
labeledSuccessGauge.labels(slotStr).set(success);
|
||||
|
||||
}
|
||||
|
||||
response.sendRedirect("/probePrometheus");
|
||||
|
||||
}
|
||||
|
||||
|
||||
// @GetMapping("/probe2")
|
||||
// public Object endpointOlp2(@RequestParam(required = true) String target,@RequestParam(required = true) Integer[] slot,@RequestParam(required = false) Integer timeout) {
|
||||
// if(timeout==null) {
|
||||
// timeout = 5000;//默认5秒
|
||||
// }
|
||||
// logger.info(target);
|
||||
// logger.info(Arrays.deepToString(slot));
|
||||
// logger.info(timeout+"");
|
||||
//
|
||||
// List<MetricFamilySamples> mfs = new ArrayList<MetricFamilySamples>();
|
||||
//
|
||||
// GaugeMetricFamily labeledDurationSecondsGauge = new GaugeMetricFamily("probe_duration_seconds", "Check device status response time", Arrays.asList("slot"));
|
||||
// mfs.add(labeledDurationSecondsGauge);
|
||||
//
|
||||
// GaugeMetricFamily labeledBypassGauge = new GaugeMetricFamily("probe_bypass", "Return bypass status", Arrays.asList("slot"));
|
||||
// mfs.add(labeledBypassGauge);
|
||||
//
|
||||
// GaugeMetricFamily labeledSuccessGauge = new GaugeMetricFamily("probe_success", "Displays whether or not the probe was a success", Arrays.asList("slot"));
|
||||
// mfs.add(labeledSuccessGauge);
|
||||
//
|
||||
// for(Integer oneSlot:slot) {
|
||||
// double start = System.currentTimeMillis();
|
||||
// String rlt = UdpUtils.send(target, oneSlot,timeout);
|
||||
// double end = System.currentTimeMillis();
|
||||
// double durationSeconds = (end-start)/1000;
|
||||
// String slotStr = oneSlot+"";
|
||||
// long bypass = rlt.endsWith("03")?0:(rlt.endsWith("0c")?1:-1);
|
||||
// long success = (rlt.endsWith("03")||rlt.endsWith("0c"))?1:0;
|
||||
//
|
||||
// labeledDurationSecondsGauge.addMetric(Arrays.asList(slotStr), durationSeconds);
|
||||
// labeledBypassGauge.addMetric(Arrays.asList(slotStr), bypass);
|
||||
// labeledSuccessGauge.addMetric(Arrays.asList(slotStr),success);
|
||||
// }
|
||||
//
|
||||
// Writer writer = new StringWriter();
|
||||
// TextFormatUtils.write004(writer, mfs);
|
||||
//
|
||||
//// return "<pre style=\"word-wrap: break-word; white-space: pre-wrap;\">"+writer.toString()+"</pre>";
|
||||
// return writer.toString();
|
||||
// }
|
||||
|
||||
}
|
||||
45
src/main/java/net/geedge/endpoint/OlpEndPoint.java
Normal file
45
src/main/java/net/geedge/endpoint/OlpEndPoint.java
Normal file
@@ -0,0 +1,45 @@
|
||||
package net.geedge.endpoint;
|
||||
|
||||
import io.prometheus.client.CollectorRegistry;
|
||||
import io.prometheus.client.Gauge;
|
||||
import io.prometheus.client.exporter.common.TextFormat;
|
||||
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
|
||||
import org.springframework.boot.actuate.endpoint.web.annotation.WebEndpoint;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.StringWriter;
|
||||
import java.io.Writer;
|
||||
|
||||
/**
|
||||
* created by bailong001 on 2019/08/12 16:47
|
||||
*/
|
||||
@WebEndpoint(id = "probePrometheus")
|
||||
public class OlpEndPoint {
|
||||
|
||||
private final CollectorRegistry collectorRegistry;
|
||||
|
||||
public OlpEndPoint(CollectorRegistry collectorRegistry) {
|
||||
this.collectorRegistry = collectorRegistry;
|
||||
// Gauge g = Gauge.build().name("gauge").help("blah").register();
|
||||
// g.set(1);
|
||||
// Gauge processorNatGatewayMonitorSnat =
|
||||
// processorNatGatewayMonitorSnat.labels("id-123145","192.168.1.1").set(123);
|
||||
// this.collectorRegistry.clear();
|
||||
}
|
||||
|
||||
@ReadOperation(produces = TextFormat.CONTENT_TYPE_004)
|
||||
public String scrape() {
|
||||
try {
|
||||
Writer writer = new StringWriter();
|
||||
TextFormat.write004(writer, this.collectorRegistry.metricFamilySamples());
|
||||
return writer.toString();
|
||||
} catch (IOException ex) {
|
||||
// This actually never happens since StringWriter::write() doesn't throw any
|
||||
// IOException
|
||||
throw new RuntimeException("Writing metrics failed", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package net.geedge.endpoint;
|
||||
|
||||
import io.micrometer.core.instrument.Clock;
|
||||
import io.micrometer.prometheus.PrometheusConfig;
|
||||
import io.micrometer.prometheus.PrometheusMeterRegistry;
|
||||
import io.prometheus.client.CollectorRegistry;
|
||||
import io.prometheus.client.Gauge;
|
||||
|
||||
//import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnEnabledEndpoint;
|
||||
import org.springframework.boot.actuate.autoconfigure.metrics.export.prometheus.PrometheusMetricsExportAutoConfiguration;
|
||||
import org.springframework.boot.actuate.autoconfigure.metrics.export.prometheus.PrometheusProperties;
|
||||
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
/**
|
||||
* created by bailong001 on 2019/08/12 16:30
|
||||
*/
|
||||
@Configuration
|
||||
@AutoConfigureAfter(value = {PrometheusMetricsExportAutoConfiguration.class})
|
||||
@ConditionalOnClass(value = {PrometheusMeterRegistry.class})
|
||||
@ConditionalOnProperty(prefix = "management.metrics.export.olp", name = "enabled", havingValue = "true",
|
||||
matchIfMissing = true)
|
||||
public class OlpPrometheusAutoConfiguration {
|
||||
|
||||
CollectorRegistry collectorRegistry = new CollectorRegistry();
|
||||
|
||||
@Bean(name = "olpPrometheusProperties")
|
||||
@ConfigurationProperties(prefix = "management.metrics.export.olp")
|
||||
public PrometheusProperties olpPrometheusProperties() {
|
||||
return new PrometheusProperties();
|
||||
}
|
||||
|
||||
@Bean(name = "olpPrometheusConfig")
|
||||
public PrometheusConfig olpPrometheusConfig() {
|
||||
return new OlpPropertiesConfigAdapter(olpPrometheusProperties());
|
||||
}
|
||||
|
||||
@Bean(name = "olpMeterRegistry")
|
||||
public PrometheusMeterRegistry olpMeterRegistry(Clock clock) {
|
||||
return new PrometheusMeterRegistry(olpPrometheusConfig(), olpCollectorRegistry(), clock);
|
||||
}
|
||||
|
||||
// @Bean(name = "labeledDurationSecondsGauge")
|
||||
// public Gauge labeledDurationSecondsGauge() {
|
||||
// return Gauge.build().name("probe_duration_seconds")
|
||||
// .labelNames("slot")
|
||||
// .help("Check device status response time")
|
||||
// .register(collectorRegistry);
|
||||
// }
|
||||
// @Bean(name = "labeledBypassGauge")
|
||||
// public Gauge labeledBypassGauge() {
|
||||
// return Gauge.build().name("probe_bypass")
|
||||
// .labelNames("slot")
|
||||
// .help("Return bypass status")
|
||||
// .register(collectorRegistry);
|
||||
// }
|
||||
// @Bean(name = "labeledSuccessGauge")
|
||||
// public Gauge labeledSuccessGauge() {
|
||||
// return Gauge.build().name("probe_success")
|
||||
// .labelNames("slot")
|
||||
// .help("Displays whether or not the probe was a success")
|
||||
// .register(collectorRegistry);
|
||||
// }
|
||||
|
||||
@Bean(name = "olpCollectorRegistry")
|
||||
public CollectorRegistry olpCollectorRegistry() {
|
||||
// CollectorRegistry collectorRegistry = new CollectorRegistry(true);
|
||||
// CollectorRegistry collectorRegistry = new CollectorRegistry();
|
||||
// collectorRegistry.clear();
|
||||
return collectorRegistry;
|
||||
}
|
||||
|
||||
@Configuration
|
||||
public static class TicketScrapeEndpointConfiguration {
|
||||
|
||||
@Resource
|
||||
private CollectorRegistry olpCollectorRegistry;
|
||||
|
||||
@Bean(name = "olpEndpoint")
|
||||
@ConditionalOnMissingBean
|
||||
public OlpEndPoint olpEndpoint() {
|
||||
return new OlpEndPoint(olpCollectorRegistry);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package net.geedge.endpoint;
|
||||
|
||||
import io.micrometer.prometheus.PrometheusConfig;
|
||||
import org.springframework.boot.actuate.autoconfigure.metrics.export.prometheus.PrometheusProperties;
|
||||
import org.springframework.boot.actuate.autoconfigure.metrics.export.properties.PropertiesConfigAdapter;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
/**
|
||||
* created by bailong001 on 2019/08/12 17:56
|
||||
*/
|
||||
public class OlpPropertiesConfigAdapter extends PropertiesConfigAdapter<PrometheusProperties>
|
||||
implements PrometheusConfig {
|
||||
|
||||
OlpPropertiesConfigAdapter(PrometheusProperties properties) {
|
||||
super(properties);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String get(String key) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean descriptions() {
|
||||
return get(PrometheusProperties::isDescriptions, PrometheusConfig.super::descriptions);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Duration step() {
|
||||
return get(PrometheusProperties::getStep, PrometheusConfig.super::step);
|
||||
}
|
||||
|
||||
}
|
||||
207
src/main/java/net/geedge/util/HexUtils.java
Normal file
207
src/main/java/net/geedge/util/HexUtils.java
Normal file
@@ -0,0 +1,207 @@
|
||||
package net.geedge.util;
|
||||
|
||||
public class HexUtils {
|
||||
|
||||
/**
|
||||
* 16进制表示的字符串转换为字节数组
|
||||
*
|
||||
* @param hexString 16进制表示的字符串
|
||||
* @return byte[] 字节数组
|
||||
*/
|
||||
public static byte[] hexStringToByteArray(String hexString) {
|
||||
hexString = hexString.replaceAll(" ", "");
|
||||
int len = hexString.length();
|
||||
byte[] bytes = new byte[len / 2];
|
||||
for (int i = 0; i < len; i += 2) {
|
||||
// 两位一组,表示一个字节,把这样表示的16进制字符串,还原成一个字节
|
||||
bytes[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character
|
||||
.digit(hexString.charAt(i + 1), 16));
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/**
|
||||
* 字节转十六进制字符串
|
||||
* @param b 需要进行转换的byte字节
|
||||
* @return 转换后的Hex字符串
|
||||
*/
|
||||
public static String byteToHex(byte b){
|
||||
String hex = Integer.toHexString(b & 0xFF);
|
||||
if(hex.length() < 2){
|
||||
hex = "0" + hex;
|
||||
}
|
||||
return hex;
|
||||
}
|
||||
|
||||
/**
|
||||
* byte[]数组转换为16进制的字符串
|
||||
*
|
||||
* @param bytes 要转换的字节数组
|
||||
* @return 转换后的结果
|
||||
*/
|
||||
public static String bytesToHexString(byte[] bytes) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int i = 0; i < bytes.length; i++) {
|
||||
String hex = Integer.toHexString(0xFF & bytes[i]);
|
||||
if (hex.length() == 1) {
|
||||
sb.append('0');
|
||||
}
|
||||
sb.append(hex);
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 合并字节数组:System.arraycopy()方法
|
||||
* @param bt1
|
||||
* @param bt2
|
||||
* @return
|
||||
*/
|
||||
public static byte[] byteMerger(byte[] bt1, byte[] bt2){
|
||||
byte[] bt3 = new byte[bt1.length+bt2.length];
|
||||
System.arraycopy(bt1, 0, bt3, 0, bt1.length);
|
||||
System.arraycopy(bt2, 0, bt3, bt1.length, bt2.length);
|
||||
return bt3;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 从一个byte[]数组中截取一部分
|
||||
* @param src
|
||||
* @param begin
|
||||
* @param count
|
||||
* @return
|
||||
*/
|
||||
public static byte[] subBytes(byte[] src, int begin, int count) {
|
||||
byte[] bs = new byte[count];
|
||||
for (int i=begin;i<begin+count; i++) {
|
||||
bs[i-begin] = src[i];
|
||||
}
|
||||
return bs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hex字符串转byte :需注意的是,Hex的字符串必须为十六进制的字符,否则会抛出异常。Hex的范围为0x00到0xFF。
|
||||
* @param inHex 待转换的Hex字符串 "55"
|
||||
* @return 转换后的byte 85
|
||||
*/
|
||||
public static byte hexToByte(String inHex){
|
||||
return (byte)Integer.parseInt(inHex,16);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将16进制字符串转换为10进制数
|
||||
* @param inHex
|
||||
* @return
|
||||
*/
|
||||
public static int hexToInt(String inHex){
|
||||
return Integer.parseInt(inHex, 16);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将10进制数转换为4个字节的16进制字符串
|
||||
* @param inHex
|
||||
* @return
|
||||
*/
|
||||
public static String intToHex(int inNum){
|
||||
return String.format("%08x", inNum);
|
||||
}
|
||||
|
||||
public static String intToHex(long inNum){
|
||||
return String.format("%08x", inNum);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
// String s = " ";
|
||||
// System.out.print(HexUtils.stringToHexString(s));
|
||||
|
||||
byte[] pzlxByte = new byte[2];
|
||||
String pzlx = new String(pzlxByte);//2byte
|
||||
// System.out.println(pzlx);
|
||||
// System.out.println(pzlx.getBytes().length);
|
||||
// System.out.println(HexUtils.stringToHexString(pzlx));
|
||||
|
||||
byte[] pzidByte = new byte[17];
|
||||
String pzid = new String(pzidByte);//17byte
|
||||
// System.out.println(pzid);
|
||||
// System.out.println(pzid.getBytes().length);
|
||||
// System.out.println(HexUtils.stringToHexString(pzid));
|
||||
|
||||
String rltHex = HexUtils.bytesToHexString(pzlx.getBytes());
|
||||
String rltHex2 = HexUtils.bytesToHexString(pzid.getBytes());
|
||||
System.out.println(rltHex);
|
||||
System.out.println(rltHex2);
|
||||
}
|
||||
|
||||
/**
|
||||
* 16进制字符串转换为字符串
|
||||
*
|
||||
* @param s
|
||||
* @return
|
||||
*/
|
||||
// public static String hexStringToString(String s) {
|
||||
// if (s == null || s.equals("")) {
|
||||
// return null;
|
||||
// }
|
||||
// s = s.replace(" ", "");
|
||||
// byte[] baKeyword = new byte[s.length() / 2];
|
||||
// for (int i = 0; i < baKeyword.length; i++) {
|
||||
// try {
|
||||
// baKeyword[i] = (byte) (0xff & Integer.parseInt(
|
||||
// s.substring(i * 2, i * 2 + 2), 16));
|
||||
// } catch (Exception e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
// }
|
||||
// try {
|
||||
// s = new String(baKeyword, "gbk");
|
||||
// new String();
|
||||
// } catch (Exception e1) {
|
||||
// e1.printStackTrace();
|
||||
// }
|
||||
// return s;
|
||||
// }
|
||||
|
||||
/**
|
||||
* hex字符串转byte数组:如果Hex超过0xFF,显然转换后结果不是一个byte,而是一个byte数组
|
||||
* @param inHex 待转换的Hex字符串
|
||||
* @return 转换后的byte数组结果
|
||||
*/
|
||||
public static byte[] hexToByteArray(String inHex){
|
||||
int hexlen = inHex.length();
|
||||
byte[] result;
|
||||
if (hexlen % 2 == 1){
|
||||
//奇数
|
||||
hexlen++;
|
||||
result = new byte[(hexlen/2)];
|
||||
inHex="0"+inHex;
|
||||
}else {
|
||||
//偶数
|
||||
result = new byte[(hexlen/2)];
|
||||
}
|
||||
int j=0;
|
||||
for (int i = 0; i < hexlen; i+=2){
|
||||
result[j]=hexToByte(inHex.substring(i,i+2));
|
||||
j++;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 一个十六进制数(Hex),正好为4个二进制位。一个字节(byte)为8个二进制位。因此,一个字节可表示为两个十六进制数字。
|
||||
* 字节数组转16进制
|
||||
* @param bytes 需要转换的byte数组
|
||||
* @return 转换后的Hex字符串
|
||||
*/
|
||||
public static String bytesToHex(byte[] bytes) {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
for(int i = 0; i < bytes.length; i++) {
|
||||
String hex = Integer.toHexString(bytes[i] & 0xFF);
|
||||
if(hex.length() < 2){
|
||||
sb.append(0);
|
||||
}
|
||||
sb.append(hex);
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
110
src/main/java/net/geedge/util/TextFormatUtils.java
Normal file
110
src/main/java/net/geedge/util/TextFormatUtils.java
Normal file
@@ -0,0 +1,110 @@
|
||||
package net.geedge.util;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.Writer;
|
||||
import java.util.List;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import io.prometheus.client.Collector;
|
||||
import io.prometheus.client.Collector.MetricFamilySamples;
|
||||
|
||||
public class TextFormatUtils {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(TextFormatUtils.class);
|
||||
|
||||
public static void write004(Writer writer, List<MetricFamilySamples> mfs) {
|
||||
try {
|
||||
String enter = "\n";
|
||||
for(MetricFamilySamples mfSample:mfs) {
|
||||
Collector.MetricFamilySamples metricFamilySamples = mfSample;
|
||||
writer.write("# HELP ");
|
||||
writer.write(metricFamilySamples.name);
|
||||
writer.write(' ');
|
||||
writeEscapedHelp(writer, metricFamilySamples.help);
|
||||
writer.write(enter);
|
||||
|
||||
writer.write("# TYPE ");
|
||||
writer.write(metricFamilySamples.name);
|
||||
writer.write(' ');
|
||||
writer.write(typeString(metricFamilySamples.type));
|
||||
writer.write(enter);
|
||||
|
||||
for (Collector.MetricFamilySamples.Sample sample: metricFamilySamples.samples) {
|
||||
writer.write(sample.name);
|
||||
if (sample.labelNames.size() > 0) {
|
||||
writer.write('{');
|
||||
for (int i = 0; i < sample.labelNames.size(); ++i) {
|
||||
writer.write(sample.labelNames.get(i));
|
||||
writer.write("=\"");
|
||||
writeEscapedLabelValue(writer, sample.labelValues.get(i));
|
||||
writer.write("\",");
|
||||
}
|
||||
writer.write('}');
|
||||
}
|
||||
writer.write(' ');
|
||||
writer.write(Collector.doubleToGoString(sample.value));
|
||||
if (sample.timestampMs != null){
|
||||
writer.write(' ');
|
||||
writer.write(sample.timestampMs.toString());
|
||||
}
|
||||
writer.write(enter);
|
||||
}
|
||||
}
|
||||
}catch (Exception e) {
|
||||
logger.error(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private static void writeEscapedHelp(Writer writer, String s) throws IOException {
|
||||
for (int i = 0; i < s.length(); i++) {
|
||||
char c = s.charAt(i);
|
||||
switch (c) {
|
||||
case '\\':
|
||||
writer.append("\\\\");
|
||||
break;
|
||||
case '\n':
|
||||
writer.append("\\n");
|
||||
break;
|
||||
default:
|
||||
writer.append(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String typeString(Collector.Type t) {
|
||||
switch (t) {
|
||||
case GAUGE:
|
||||
return "gauge";
|
||||
case COUNTER:
|
||||
return "counter";
|
||||
case SUMMARY:
|
||||
return "summary";
|
||||
case HISTOGRAM:
|
||||
return "histogram";
|
||||
default:
|
||||
return "untyped";
|
||||
}
|
||||
}
|
||||
|
||||
private static void writeEscapedLabelValue(Writer writer, String s) throws IOException {
|
||||
for (int i = 0; i < s.length(); i++) {
|
||||
char c = s.charAt(i);
|
||||
switch (c) {
|
||||
case '\\':
|
||||
writer.append("\\\\");
|
||||
break;
|
||||
case '\"':
|
||||
writer.append("\\\"");
|
||||
break;
|
||||
case '\n':
|
||||
writer.append("\\n");
|
||||
break;
|
||||
default:
|
||||
writer.append(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
48
src/main/java/net/geedge/util/UdpUtils.java
Normal file
48
src/main/java/net/geedge/util/UdpUtils.java
Normal file
@@ -0,0 +1,48 @@
|
||||
package net.geedge.util;
|
||||
|
||||
import java.net.DatagramPacket;
|
||||
import java.net.DatagramSocket;
|
||||
import java.net.InetAddress;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class UdpUtils {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(TextFormatUtils.class);
|
||||
|
||||
public static String send(String sendIp,Integer slot,int timeout) {
|
||||
String rlt = "";
|
||||
DatagramSocket ds = null;
|
||||
try {
|
||||
ds = new DatagramSocket();//通过DatagramSocket对象创建udp服务
|
||||
ds.setSoTimeout(timeout);
|
||||
// String line = "00 06 0502 00 00 68c2"; //发送的16进制字符串
|
||||
String slotStr = slot+"";
|
||||
if(slot<10) {
|
||||
slotStr = "0"+slotStr;
|
||||
}
|
||||
String line = "00 "+slotStr+" 0502 00 00"; //发送的16进制字符串
|
||||
byte[] buf = HexUtils.hexStringToByteArray(line);
|
||||
DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName(sendIp),6800);//发送至指定IP,指定端口
|
||||
ds.send(dp);//通过send方法将数据包发送出去
|
||||
//定义数据包,用于存储数据
|
||||
byte[] buf2 = new byte[8];
|
||||
DatagramPacket dp2 = new DatagramPacket(buf2,buf2.length);
|
||||
ds.receive(dp2);//通过服务的receive方法将收到数据存入数据包中,receive()为阻塞式方法
|
||||
//通过数据包的方法获取其中的数据
|
||||
String ip = dp2.getAddress().getHostAddress();
|
||||
|
||||
System.out.println(ip+"::"+HexUtils.bytesToHexString(buf2));
|
||||
|
||||
rlt = HexUtils.bytesToHexString(buf2);
|
||||
}catch (Exception e) {
|
||||
logger.error(sendIp+"::"+slot+">>"+e.getMessage());
|
||||
}finally {
|
||||
if(ds!=null) {
|
||||
ds.close();//关闭资源
|
||||
}
|
||||
}
|
||||
return rlt;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user