• java项目运行时信息获取


    大体思路如下,想要获取启动时处理器数量、jvm 相关信息,操作系统信息、运行机器信息

    运行机器信息

    1. import org.slf4j.Logger;
    2. import org.slf4j.LoggerFactory;
    3. import java.lang.invoke.MethodHandles;
    4. /**
    5. * 机器工具类
    6. */
    7. public abstract class ServerUtils {
    8. private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
    9. /**
    10. * 获取可用处理器数量
    11. *
    12. * @return
    13. */
    14. public static int getAvailableProcessors() {
    15. return Runtime.getRuntime().availableProcessors();
    16. }
    17. public static void printAvailableProcessors() {
    18. logger.info("processors={}", Runtime.getRuntime().availableProcessors());
    19. }
    20. }

    系统信息

    1. import org.slf4j.Logger;
    2. import org.slf4j.LoggerFactory;
    3. import java.lang.invoke.MethodHandles;
    4. /**
    5. * 系统信息工具类
    6. *
    7. * @author Rike
    8. * @date 2023/6/28
    9. */
    10. public abstract class SystemUtils {
    11. private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
    12. public static String getOsName() {
    13. return System.getProperty("os.name");
    14. }
    15. public static void printOsName() {
    16. logger.info("os.name={}", System.getProperty("os.name"));
    17. }
    18. public static boolean isWindows() {
    19. return getOsName().startsWith("Windows");
    20. }
    21. public static boolean isLinux() {
    22. return getOsName().startsWith("Linux");
    23. }
    24. public static boolean isWindows(String osName) {
    25. return osName.startsWith("Windows");
    26. }
    27. public static boolean isLinux(String osName) {
    28. return osName.startsWith("Linux");
    29. }
    30. }

    通过 System.getProperty() 实现。

    jvm 信息

    1. import org.slf4j.Logger;
    2. import org.slf4j.LoggerFactory;
    3. import java.lang.invoke.MethodHandles;
    4. import java.lang.management.ManagementFactory;
    5. import java.lang.management.RuntimeMXBean;
    6. /**
    7. * jvm 信息工具类
    8. */
    9. public abstract class JvmUtils {
    10. private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
    11. /**
    12. * 打印 jvm 信息
    13. */
    14. public static void printJvmInfo() {
    15. RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    16. logger.info("jvm name={}", runtimeMXBean.getName());
    17. logger.info("class={}", runtimeMXBean.getClass());
    18. logger.info("java.class.path={}", runtimeMXBean.getClassPath());
    19. logger.info("java.library.path={}", runtimeMXBean.getLibraryPath());
    20. logger.info("bootClassPath={}", runtimeMXBean.getBootClassPath());
    21. logger.info("java.vm.vendor={}", runtimeMXBean.getVmVendor());
    22. logger.info("java.vm.name={}", runtimeMXBean.getVmName());
    23. logger.info("java.vm.version={}", runtimeMXBean.getVmVersion());
    24. logger.info("java.vm.specification.name={}", runtimeMXBean.getSpecName());
    25. logger.info("java.vm.specification.vendor={}", runtimeMXBean.getSpecVendor());
    26. logger.info("java.vm.specification.version={}", runtimeMXBean.getSpecVersion());
    27. logger.info("java.version={}", System.getProperty("java.version"));
    28. logger.info("java.runtime.version={}", System.getProperty("java.runtime.version"));
    29. logger.info("java.class.version={}", System.getProperty("java.class.version"));
    30. logger.info("inputArguments={}", runtimeMXBean.getInputArguments());
    31. logger.info("managementSpecVersion={}", runtimeMXBean.getManagementSpecVersion());
    32. logger.info("startTime={}", runtimeMXBean.getStartTime());
    33. logger.info("uptime={}", runtimeMXBean.getUptime());
    34. /*logger.info("+++++++++++++++++++++++++++++++++++++++");
    35. runtimeMXBean.getSystemProperties().entrySet().parallelStream().forEach(entry -> {
    36. System.out.println(entry.getKey() + "=" + entry.getValue());
    37. });
    38. logger.info("+++++++++++++++++++++++++++++++++++++++");*/
    39. }
    40. }

    通过 ManagementFactory 获取 RuntimeMXBean 对象获取相关信息。

    spring 环境信息

    1. import org.slf4j.Logger;
    2. import org.slf4j.LoggerFactory;
    3. import org.springframework.beans.BeansException;
    4. import org.springframework.context.ApplicationContext;
    5. import org.springframework.context.ApplicationContextAware;
    6. import org.springframework.context.ConfigurableApplicationContext;
    7. import org.springframework.core.env.ConfigurableEnvironment;
    8. import org.springframework.core.env.EnumerablePropertySource;
    9. import org.springframework.core.env.PropertySource;
    10. import org.springframework.stereotype.Component;
    11. import java.lang.invoke.MethodHandles;
    12. import java.util.List;
    13. import java.util.Map;
    14. import java.util.stream.Collectors;
    15. /**
    16. * spring Environment 信息获取工具类
    17. */
    18. @Component
    19. public class SpringEnvironmentUtils implements ApplicationContextAware {
    20. private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
    21. private static ConfigurableEnvironment environment = null;
    22. @Override
    23. public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    24. environment = (ConfigurableEnvironment) applicationContext.getBean(ConfigurableApplicationContext.ENVIRONMENT_BEAN_NAME);
    25. }
    26. public static void printPropertyValue(String property) {
    27. logger.info("[{}]={}", property, environment.getProperty(property));
    28. }
    29. public static String getPropertyValue(String property) {
    30. return environment.getProperty(property);
    31. }
    32. /**
    33. * 打印所有的 Environment 信息
    34. */
    35. public static void printAllEnvironmentInfo() {
    36. // printSystemEnvironment();
    37. // printSystemProperties();
    38. printPropertySources();
    39. printProfiles();
    40. }
    41. public static void printSystemEnvironment() {
    42. logger.info("+++++++++++++++++++++++++++++++++++++++");
    43. logger.info("print system environment begin");
    44. logger.info("+++++++++++++++++++++++++++++++++++++++");
    45. environment.getSystemEnvironment().entrySet().parallelStream().forEach(entry -> {
    46. // System.out.println(entry.getKey() + "=" + entry.getValue());
    47. logger.info("{}={}", entry.getKey(), entry.getValue());
    48. });
    49. logger.info("+++++++++++++++++++++++++++++++++++++++");
    50. logger.info("print system environment end");
    51. logger.info("+++++++++++++++++++++++++++++++++++++++");
    52. Map map = System.getenv();
    53. map.entrySet().stream().forEach(entry -> {
    54. // System.out.println(entry.getKey() + "=" + entry.getValue());
    55. logger.info("{}={}", entry.getKey(), entry.getValue());
    56. });
    57. }
    58. public static void printSystemProperties() {
    59. logger.info("+++++++++++++++++++++++++++++++++++++++");
    60. logger.info("print system properties begin");
    61. logger.info("+++++++++++++++++++++++++++++++++++++++");
    62. environment.getSystemProperties().entrySet().parallelStream().forEach(entry -> {
    63. // System.out.println(entry.getKey() + "=" + entry.getValue());
    64. logger.info("{}={}", entry.getKey(), entry.getValue());
    65. });
    66. logger.info("+++++++++++++++++++++++++++++++++++++++");
    67. logger.info("print system properties end");
    68. logger.info("+++++++++++++++++++++++++++++++++++++++");
    69. }
    70. public static void printPropertySources() {
    71. logger.info("+++++++++++++++++++++++++++++++++++++++");
    72. logger.info("print property sources begin");
    73. logger.info("+++++++++++++++++++++++++++++++++++++++");
    74. // 筛选继承 EnumerablePropertySource 的类和实现 Map 的类
    75. List> list = environment.getPropertySources().stream().filter(ps -> (ps instanceof EnumerablePropertySource && ps.getSource() instanceof Map)).collect(Collectors.toList());
    76. list.stream().forEach(ps -> {
    77. String name = ps.getName();
    78. logger.info("[{}] include property and value begin", name);
    79. Map source = (Map) ps.getSource();
    80. StringBuffer stringBuffer = new StringBuffer();
    81. int size = source.entrySet().size();
    82. // 记录当前下标
    83. int index = -1;
    84. for (Object entry : source.entrySet()) {
    85. index++;
    86. Map.Entry temp = (Map.Entry) entry;
    87. // System.out.println(temp.getKey() + "="+ temp.getValue());
    88. // logger.info("{}={}", temp.getKey(), temp.getValue());
    89. // 将参数进行拼接方便日志打印
    90. stringBuffer.append(temp.getKey()).append("=").append(temp.getValue());
    91. /**
    92. * 换行符打印的情况
    93. *
    94. * 总数量大于1
    95. *
    96. * 下标小于总数减1
    97. *
    98. */
    99. if (size > 1 && index < size -1) {
    100. stringBuffer.append("\n");
    101. }
    102. }
    103. // 拼接的字符串不为空时打印
    104. if (stringBuffer.length() > 0) {
    105. logger.info("{}", stringBuffer);
    106. }
    107. logger.info("[{}] include property and value end", name);
    108. });
    109. logger.info("+++++++++++++++++++++++++++++++++++++++");
    110. logger.info("print property sources end");
    111. logger.info("+++++++++++++++++++++++++++++++++++++++");
    112. }
    113. public static void printProfiles() {
    114. logger.info("+++++++++++++++++++++++++++++++++++++++");
    115. logger.info("print profiles begin");
    116. logger.info("+++++++++++++++++++++++++++++++++++++++");
    117. String[] defaultProfiles = environment.getDefaultProfiles();
    118. logger.info("defaultProfiles={}", defaultProfiles);
    119. String[] activeProfiles = environment.getActiveProfiles();
    120. logger.info("activeProfiles={}", activeProfiles);
    121. logger.info("+++++++++++++++++++++++++++++++++++++++");
    122. logger.info("print profiles end");
    123. logger.info("+++++++++++++++++++++++++++++++++++++++");
    124. }
    125. }

    借助于 ApplicationContext 获取 ConfigurableEnvironment 对象,进而获取 System.getProperty() 和 System.getenv() 相关信息。

    整合

    1. import org.springframework.beans.factory.InitializingBean;
    2. import org.springframework.core.Ordered;
    3. import org.springframework.stereotype.Component;
    4. /**
    5. * 启动信息
    6. */
    7. @Component
    8. public class StartInfo implements InitializingBean, Ordered {
    9. @Override
    10. public void afterPropertiesSet() throws Exception {
    11. SpringEnvironmentUtils.printPropertyValue("spring.cloud.nacos.server-addr");
    12. ServerUtils.printAvailableProcessors();
    13. SystemUtils.printOsName();
    14. JvmUtils.printJvmInfo();
    15. SpringEnvironmentUtils.printAllEnvironmentInfo();
    16. }
    17. @Override
    18. public int getOrder() {
    19. return LOWEST_PRECEDENCE;
    20. }
    21. }

    创建一个类实现 InitializingBean 接口,添加 @Component 注解,在 spring ioc 容器启动时执行其中的逻辑,对代码无侵入性,无需修改其他代码即可实现最终的功能。

    可以参照 zookeeper 中源码

    1. <dependency>
    2. <groupId>org.apache.zookeepergroupId>
    3. <artifactId>zookeeperartifactId>
    4. <version>3.9.1version>
    5. dependency>

    1. package org.apache.zookeeper;
    2. import java.net.InetAddress;
    3. import java.net.UnknownHostException;
    4. import java.util.ArrayList;
    5. import java.util.List;
    6. import org.slf4j.Logger;
    7. /**
    8. * Provide insight into the runtime environment.
    9. *
    10. */
    11. public class Environment {
    12. public static final String JAAS_CONF_KEY = "java.security.auth.login.config";
    13. public static class Entry {
    14. private String k;
    15. private String v;
    16. public Entry(String k, String v) {
    17. this.k = k;
    18. this.v = v;
    19. }
    20. public String getKey() {
    21. return k;
    22. }
    23. public String getValue() {
    24. return v;
    25. }
    26. @Override
    27. public String toString() {
    28. return k + "=" + v;
    29. }
    30. }
    31. private static void put(List l, String k, String v) {
    32. l.add(new Entry(k, v));
    33. }
    34. public static List list() {
    35. List l = new ArrayList<>();
    36. put(l, "zookeeper.version", Version.getFullVersion());
    37. try {
    38. put(l, "host.name", InetAddress.getLocalHost().getCanonicalHostName());
    39. } catch (UnknownHostException e) {
    40. put(l, "host.name", "");
    41. }
    42. put(l, "java.version", System.getProperty("java.version", ""));
    43. put(l, "java.vendor", System.getProperty("java.vendor", ""));
    44. put(l, "java.home", System.getProperty("java.home", ""));
    45. put(l, "java.class.path", System.getProperty("java.class.path", ""));
    46. put(l, "java.library.path", System.getProperty("java.library.path", ""));
    47. put(l, "java.io.tmpdir", System.getProperty("java.io.tmpdir", ""));
    48. put(l, "java.compiler", System.getProperty("java.compiler", ""));
    49. put(l, "os.name", System.getProperty("os.name", ""));
    50. put(l, "os.arch", System.getProperty("os.arch", ""));
    51. put(l, "os.version", System.getProperty("os.version", ""));
    52. put(l, "user.name", System.getProperty("user.name", ""));
    53. put(l, "user.home", System.getProperty("user.home", ""));
    54. put(l, "user.dir", System.getProperty("user.dir", ""));
    55. // Get memory information.
    56. Runtime runtime = Runtime.getRuntime();
    57. int mb = 1024 * 1024;
    58. put(l, "os.memory.free", runtime.freeMemory() / mb + "MB");
    59. put(l, "os.memory.max", runtime.maxMemory() / mb + "MB");
    60. put(l, "os.memory.total", runtime.totalMemory() / mb + "MB");
    61. return l;
    62. }
    63. public static void logEnv(String msg, Logger log) {
    64. List env = Environment.list();
    65. for (Entry e : env) {
    66. log.info(msg + e.toString());
    67. }
    68. }
    69. }

    参考链接

    https://blog.csdn.net/qq742143797/article/details/113553660

  • 相关阅读:
    ChatGPT AIGC 办公自动化拆分Excel工作表
    [附源码]java毕业设计基于的城镇住房公积金管理系统
    Docker笔记
    【MedusaSTears】正则表达式搜索心得
    019-第三代软件开发-Git提交规范
    归并排序详解
    nginx的安装(一)
    Nacos2.1.2源码修改支持高斯,postresql
    k8s强制删除一个 Pod
    C++ 多维数组
  • 原文地址:https://blog.csdn.net/zlpzlpzyd/article/details/133967701