java-返回 traceID 与 本机ip
前言
如果您觉得有用的话,记得给博主点个赞,评论,收藏一键三连啊,写作不易啊^ _ ^。
而且听说点赞的人每天的运气都不会太差,实在白嫖的话,那欢迎常来啊!!!
java-返回 traceID 与 本机ip
1. pom依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-sleuth</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
2. 代码
2.1. 获取traceId逻辑
使用该依赖所加载的bean:
同时tracer.currentSpan().context().traceId()返回的traceId是十进制,最后只要转成十六进制就可以了。
package org.example.config;
import brave.Tracer;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.example.util.IpUtil;
import org.example.vo.LogTracerVo;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
/**
* @author 杨镇宇
* @date 2024/11/26 10:48
* @version 1.0
*/
@Component
@Slf4j
public class LogTracer {
@Resource
private Tracer tracer;
public LogTracerVo getTrace(){
String traceId = ObjectUtil.isNotNull(tracer.currentSpan()) ? Long.toHexString(tracer.currentSpan().context().traceId()) :"no traceId";
String hostAddress = IpUtil.getIp();
return LogTracerVo.builder().traceId(traceId).ip(hostAddress).build();
}
}
2.2. 对于获取本机ip逻辑
package org.example.util;
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
* Utility class for retrieving the local machine's IP address.
* Supports both Linux and Windows environments.
*
* @author 杨镇宇
* @date 2024/11/26 10:42
* @version 1.0
*/
public class IpUtil {
private static class SingleIpUtil {
private static String getIp() {
String ip = "";
try {
String os = System.getProperty("os.name").toLowerCase();
Process process;
boolean linuxFlag = os.contains("nix") || os.contains("nux") || os.contains("mac");
if (os.contains("win")) {
// Windows system: use ipconfig command
process = Runtime.getRuntime().exec("ipconfig");
} else if (linuxFlag) {
// Linux or macOS system: use hostname -I command
process = Runtime.getRuntime().exec("hostname -I");
} else {
return "Unsupported OS";
}
// Read the output with correct encoding (GBK for Windows)
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK"));
String line;
boolean found = false;
while ((line = reader.readLine()) != null) {
if (os.contains("win") && line.contains("IPv4")) {
// Extract the IPv4 address from the line containing "IPv4"
ip = line.split(":")[1].trim();
found = true;
break;
}
// On Linux/macOS, get the first non-empty line
if (linuxFlag && !line.trim().isEmpty()) {
ip = line.trim();
found = true;
break;
}
}
if (!found) {
return "IP address not found.";
}
System.out.println("Current IP Address: " + ip);
return ip;
} catch (Exception e) {
e.printStackTrace();
return "Error fetching IP";
}
}
}
private IpUtil() {
// Prevent instantiation
}
public static String getIp() {
return SingleIpUtil.getIp();
}
}
package org.example.vo;
import lombok.*;
/**
* @author 杨镇宇
* @date 2024/11/26 10:49
* @version 1.0
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class LogTracerVo {
private String traceId;
private String ip;
}
3. 测试
package org.example.controller;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.example.config.LogTracer;
import org.example.exception.ExceptionEnum;
import org.example.exception.ResultCode;
import org.example.exception.model.ResponseResult;
import org.example.exception.throwtype.RunException;
import org.example.service.ToolService;
import org.example.vo.KeyWordVo;
import org.example.vo.LogTracerVo;
import org.example.vo.ScanVo;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.List;
import java.util.Map;
/**
* @author 杨镇宇
* @date 2024/6/13 15:31
* @version 1.0
*/
@Api(value = "代码扫描", tags = {" 代码扫描"})
@Slf4j
@Validated
@RestController
@RequestMapping(value="api/tool")
public class ToolController {
@GetMapping("/traceId")
public Map<String,Object> testTraceId(){
Map<String,Object> map = Maps.newHashMap();
LogTracerVo trace = logTracer.getTrace();
log.info("测试 traceId 与 ip ============================");
log.info("traceID:"+trace.getTraceId());
log.info("ip:"+trace.getIp());
map.put("traceId",trace.getTraceId());
map.put("ip",trace.getIp());
return map;
}
}
idea 日志:
原文地址:https://blog.csdn.net/weixin_38316697/article/details/144057502
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!