通过Micrometer+actuator暴露拉取metric的端点给Prometheus,通过grafana导入相关优秀模板进行jvm展示,业务方便在dashboard追加自定义panel展示,其中接口指标通过aop环绕通知上报指标,还有种方案通过nginx-vts-exporter实现。
org.springframework.boot
spring-boot-starter-actuator
io.micrometer
micrometer-registry-prometheus
暴露监控端点,查看是否有metric了http://localhost:8990/actuator/prometheus
management:
endpoints:
web:
exposure:
include: '*'
这样可以监控JVM了,grafana挑个模板如id 4701即可暂时
@Bean
MeterRegistryCustomizer configurer(@Value("${spring.application.name}") String applicationName){
return registry -> registry.config().commonTags("application",applicationName);
}
aop环绕,非接口监控或只监控指定的接口考虑使用自定义注解进行统一控制
@Aspect
@Slf4j
@Component
public class LogAspect {
@Autowired
MeterRegistry registry;
private Counter counter1; //counter类型:采集订单量总金额等业务数据,只增不减
private Counter counter2 ;
private List gaugeCollectionSize; //gauge类型,收集集合size,如果实时令牌数/实时事务数,可增可减
private Map gaugeMapSize;
private AtomicInteger intGauge;
private DistributionSummary summary;
@PostConstruct
private void init(){ //这些变量的变化会被监控
counter2=Counter.builder("test_new_coounter").description("测试counter").tag("env","test").register(registry);
counter1 = registry.counter("order_list_req_total","listCount","listCount");
gaugeCollectionSize =registry.gaugeCollectionSize("collectionSizeGauge", Lists.newArrayList(new ImmutableTag("env","test")),new CopyOnWriteArrayList());
gaugeMapSize =registry.gaugeMapSize("mapSizeGauge", Lists.newArrayList(new ImmutableTag("env","test")),new ConcurrentHashMap<>());
intGauge=registry.gauge("intRandomGauge", Lists.newArrayList(new ImmutableTag("env","test")),new AtomicInteger());
}
@Around("execution(public * com.construn.vehicle.*.controller.*.*(..))")
public Object arround(ProceedingJoinPoint pjp) throws Throwable {
long start= System.currentTimeMillis();
Object obj= pjp.proceed();
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest req = attributes.getRequest();
Tag tag1=new ImmutableTag("uri",req.getRequestURI());
Tag tag2=new ImmutableTag("ip",req.getHeader("x_forwarded_ip"));
Tag tag3=new ImmutableTag("method",req.getMethod());
Tag tag4=obj instanceof ResultEntity?new ImmutableTag("code",( (ResultEntity) obj).getCode()):new ImmutableTag("code", ErrorEnum.UNKNOWN_ERROR.getCode());
summary = registry.summary("api_summary",Lists.newArrayList(tag1,tag2,tag3,tag4)); //这里tag是变化的,不同于其它conter gauge指标类型可以在postConstrun方法初始化
summary.record(System.currentTimeMillis()-start);
return obj;
}
}
grafana没饼图,需要使用bin目录下的grafana-cli命令安装插件。。。,关键要掌握promQL,
参考https://yunlzheng.gitbook.io/prometheus-book/part-iii-prometheus-shi-zhan/readmd
请求耗时topk:topk(5,api_summary_max{job="springboot-payment"}) by (job)
异常状态码:api_summary_count{code!="0"} //添加报警
参考文章:https://blog.csdn.net/zhuyu19911016520/article/details/88383098