Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

26.16. 自定义监控指标

		
package cn.netkiller.config;

import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.context.annotation.Configuration;

import java.util.*;

@Configuration
@Endpoint(id = "netkiller")
public class TestEndpoint {
    @ReadOperation
    public Map<String, Object> threadPoolsMetric() {
        Map<String, Object> metricMap = new HashMap<>();
        List<Map> threadPools = new ArrayList<>();
        Map<String, Object> poolInfo = new HashMap<>();
        poolInfo.put("thread.pool.name", "netkiller");
        poolInfo.put("thread.pool.core.size", 100);
        poolInfo.put("thread.pool.time", new Date());
        threadPools.add(poolInfo);
        metricMap.put("netkiller", threadPools);
        return metricMap;
    }
}		
		
		

验证

		
neo@MacBook-Pro-M2 ~> curl -s http://www.netkiller.cn:8080/actuator/netkiller | jq
{
  "netkiller": [
    {
      "thread.pool.time": "2023-04-24T09:08:14.407+00:00",
      "thread.pool.core.size": 100,
      "thread.pool.name": "netkiller"
    }
  ]
}		
		
		
		
import org.springframework.boot.actuate.endpoint.annotation.DeleteOperation;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.boot.actuate.endpoint.annotation.WriteOperation;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 自定义Actuator端点:/actuator/custom
 * @Endpoint注解的id为custom,对应访问路径是/actuator/custom
 */
@Component
@Endpoint(id = "custom")
public class CustomActuatorEndpoint {

    // 模拟存储一些自定义数据
    private final Map<String, String> data = new HashMap<>();

    public CustomActuatorEndpoint() {
        // 初始化数据
        data.put("key1", "value1");
        data.put("key2", "value2");
    }

    /**
     * GET请求:访问/actuator/custom,获取自定义数据
     * @ReadOperation对应HTTP GET
     */
    @ReadOperation
    public Map<String, Object> getCustomInfo() {
        Map<String, Object> result = new HashMap<>();
        result.put("message", "这是自定义Actuator端点的信息");
        result.put("data", data);
        result.put("status", "success");
        return result;
    }

    /**
     * POST请求:访问/actuator/custom,传入key和value,添加数据
     * @WriteOperation对应HTTP POST
     */
    @WriteOperation
    public String addCustomData(String key, String value) {
        data.put(key, value);
        return "添加成功:" + key + "=" + value;
    }

    /**
     * DELETE请求:访问/actuator/custom,传入key,删除数据
     * @DeleteOperation对应HTTP DELETE
     */
    @DeleteOperation
    public String deleteCustomData(String key) {
        data.remove(key);
        return "删除成功:" + key;
    }
}