当微服务系统越来越庞大,各个服务间的调用关系也变得越来越复杂,需要一个工具来帮忙理清请求调用的服务链路。之前在《Spring Cloud Sleuth:分布式请求链路跟踪》一文中使用的是Sleuth+Zipkin的解决方案,最近发现应用性能监控(Application Performance Monitoring,APM)也可以很好地解决该问题。对比SkyWalking和Elastic APM之后,发现Elastic APM更胜一筹,今天我们来一波Elastic APM的使用实践!
Elastic APM是基于Elastic Stack构建的应用性能监控(APM)系统。它主要有如下用途:
Elastic APM 包括四大组件: APM Agent, APM Server, Elasticsearch, Kibana。
Elastic APM Agent 从其检测的应用程序中捕获不同类型的信息。这些操作被称为事件,可以是Span, Transaction, Error, or Metric。
学习了上面的基本概念之后,是时候来波实践了,接下来我们将使用Elastic APM来监控SpringBoot应用的性能信息。
安装Elastic APM之前,我们需要先安装好Elasticsearch和Kibana,具体参考《你居然还去服务器上捞日志,搭个日志收集系统难道不香么!》,注意使用7.6.2版本。
apm-server.yml
,修改下Elasticsearch的连接地址即可;output.elasticsearch:
hosts: ["localhost:9200"]
8200
端口运行;apm-sever -e
Java应用集成APM Agent的方式有三种,我们使用最简单的方式,直接在应用中集成。
pom.xml
中添加相关依赖;<!--Elastic Agent相关依赖-->
<dependency>
<groupId>co.elastic.apm</groupId>
<artifactId>apm-agent-attach</artifactId>
<version>1.17.0</version>
</dependency>
main
方法中添加Elastic APM的Attach API;@SpringBootApplication
public class MallTinyApplication {
public static void main(String[] args) {
ElasticApmAttacher.attach();
SpringApplication.run(MallTinyApplication.class, args);
}
}
resource
目录下添加Elastic APM的配置文件elasticapm.properties
;# 配置服务名称
service_name=mall-tiny-apm
# 配置应用所在基础包
application_packages=com.macro.mall.tiny
# 配置APM Server的访问地址
server_urls=http://localhost:8200
mall-tiny-apm
服务已经存在了;Transaction
查看详情,我们可以看到连SQL执行耗时信息都给我们统计好了;Span
查看详情,连SQL语句都给我们收集好了;/**
* 品牌管理Controller
* Created by macro on 2019/4/19.
*/
@Api(tags = "PmsBrandController", description = "商品品牌管理")
@Controller
@RequestMapping("/brand")
public class PmsBrandController {
@ApiOperation("远程调用获取所有品牌信息")
@RequestMapping(value = "/remoteListAll", method = RequestMethod.GET)
@ResponseBody
public CommonResult<List<PmsBrand>> remoteListAll() {
//模拟耗时操作
ThreadUtil.sleep(1, TimeUnit.SECONDS);
//远程调用获取数据
String response = HttpUtil.get("http://localhost:8088/brand/listAll");
JSONObject jsonObject = new JSONObject(response);
JSONArray data = jsonObject.getJSONArray("data");
List<PmsBrand> brandList = data.toList(PmsBrand.class);
return CommonResult.success(brandList);
}
}
springcloud-learning
中的微服务调用案例,也是可以进行请求链路跟踪的;int i=1/0;
即可,查看下收集到的异常信息;Elastic APM 完全可以取代Sleuth+Zipkin来做分布式请求链路追踪,并且提供了数据库及缓存调用时长的统计,很好很强大!不止于此,它还可以用来实时监控应用性能信息及度量指标,连错误日志也收集好了,是一款很好的应用性能监控工具!
https://github.com/macrozheng/mall-learning/tree/master/mall-tiny-apm
官方文档:https://www.elastic.co/guide/en/apm/index.html