分享基于Spring Boot Actuator
制作炫酷可视化系统监控,其中使用到了Prometheus
,Grafana
。
1. 概述
Spring Boot Actuator
是一个采集应用内部信息并暴露给外部的模块,它可以帮助我们监控和管理Spring Boot
应用。Prometheus
是由SoundCloud
开发的开源监控报警系统和时序列数据库,我们还可以选用其他工具如:AppOptics
,Atlas
,JMX
等,更多支持可查阅Spring Boot Actuator文档。Grafana
是一个跨平台的开源的度量分析和可视化工具,可以通过将采集的数据查询然后可视化的展示,并及时通知。
在下文中,我们将利用这三个工具制作炫酷可视化系统监控,查阅文档分别为:Spring Boot Actuator文档,Spring Boot Actuator数据文档,Prometheus引入文档,Prometheus安装文档,Grafana安装文档
2. Spring Boot Actuator
1. 引入
<!-- for maven -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
//for gradle
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-actuator'
}
2. 配置
//启用禁止
management.endpoint.shutdown.enabled=true
management.endpoints.enabled-by-default=false
//暴露接口
management.endpoint.info.enabled=true
management.endpoints.jmx.exposure.include=health,info
management.endpoints.web.exposure.include=*
management.endpoints.web.exposure.exclude=env,beans
//缓存时间
management.endpoint.beans.cache.time-to-live=10s
//CORS支持
management.endpoints.web.cors.allowed-origins=https://example.com
management.endpoints.web.cors.allowed-methods=GET,POST
设置数据接口权限
@Configuration(proxyBeanMethods = false)
public class ActuatorSecurity extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.requestMatcher(EndpointRequest.toAnyEndpoint()).authorizeRequests((requests) ->
requests.anyRequest().permitAll());
}
}
自定义数据接口
@ReadOperation
public CustomData getCustomData() {
return new CustomData("test", 5);
}
3. 通过HTTP
获取数据
Spring Boot Actuator
会自动配置所有启用的接口并通过HTTP
公开。默认使用id前缀为的端点的/Actuator
作为URL路径。例如,health
暴露为/Actuator/health
。他会使用Spring MVC
,Jackson
。
4. 指标数据内容
从HTTP
接口获取到为json
格式的数据。具体详细含义可查阅Spring Boot Actuator数据文档。
例如获取health
:
curl 'http://localhost:8080/Actuator/health' -i -X GET -H 'Accept: application/json'
{
"status" : "UP",
"components" : {
"broker" : {
"status" : "UP",
"components" : {
"us1" : {
"status" : "UP",
"details" : {
"version" : "1.0.2"
}
},
"us2" : {
"status" : "UP",
"details" : {
"version" : "1.0.4"
}
}
}
},
"db" : {
"status" : "UP",
"details" : {
"database" : "H2",
"validationQuery" : "isValid()"
}
},
"diskSpace" : {
"status" : "UP",
"details" : {
"total" : 194687758336,
"free" : 92457164800,
"threshold" : 10485760,
"exists" : true
}
}
}
}
3. Prometheus
1. 引入
maven
引入<!--for maven--> <dependency> <groupId>io.micrometer</groupId> <artifactId>micrometer-registry-prometheus</artifactId> <version>${micrometer.version}</version> </dependency>
暴露数据接口
management.endpoints.web.exposure.include=* management.metrics.tags.application=${spring.application.name}
2. 配置
在Spring Boot环境中下自动配置Prometheus接口。否则,可以使用任何基于JVM的HTTP服务器实现来将数据公开给Prometheus。
在Spring Boot中使用MeterRegistryCustomizer
自动注册配置:
@Bean
MeterRegistryCustomizer<MeterRegistry> metricsCommonTags() {
return registry -> registry.config().commonTags("application", "MYAPPNAME");
}
其他环境可参考下面示例:
//com.sun.net.httpserver.HttpServer
PrometheusMeterRegistry prometheusRegistry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT);
try {
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/prometheus", httpExchange -> {
String response = prometheusRegistry.scrape(); (1)
httpExchange.sendResponseHeaders(200, response.getBytes().length);
try (OutputStream os = httpExchange.getResponseBody()) {
os.write(response.getBytes());
}
});
new Thread(server::start).start();
} catch (IOException e) {
throw new RuntimeException(e);
}
更加详细的内容查阅Prometheus引入文档
3. 安装
下载最新的安装包。并安装
wget https://github.com/prometheus/prometheus/releases/download/v2.22.0/prometheus-2.22.0.linux-amd64.tar.gz tar xvfz prometheus-2.22.tar.gz cd prometheus-2.22
配置文件
prometheus.yml
。
注意GitLab
或者其他软件也使用到了Prometheus
,修改端口号解决问题。global: scrape_interval: 15s # By default, scrape targets every 15 seconds. # Attach these labels to any time series or alerts when communicating with # external systems (federation, remote storage, Alertmanager). external_labels: monitor: 'codelab-monitor' # A scrape configuration containing exactly one endpoint to scrape: # Here it's Prometheus itself. scrape_configs: # The job name is added as a label `job=<job_name>` to any timeseries scraped from this config. - job_name: 'prometheus' # Override the global default and scrape targets from this job every 5 seconds. scrape_interval: 5s static_configs: - targets: ['localhost:9090']
-job_name: 'Prometheus' #应用部署机器上的应用名 -targets: ['127.0.0.1:9090'] #应用运行机器上的本机端口号本机ip -job_name: 'SpringBoot_Prometheus' #SpringBoot的应用名 metrics_path: '/actuator/prometheus' #能获取节点信息的路径 -targets: ['192.168.159.1:8080'] #SpringBoot应用运行的机器的ip端口号
启动
# Start Prometheus. # By default, Prometheus stores its database in ./data (flag --storage.tsdb.path). ./prometheus --config.file=prometheus.yml
更加详细的内容查阅Prometheus安装文档
4. Grafana
1. 添加源/etc/yum.repos.d/grafana.repo
[grafana]
name=grafana
baseurl=https://packages.grafana.com/oss/rpm
repo_gpgcheck=1
enabled=1
gpgcheck=1
gpgkey=https://packages.grafana.com/gpg.key
sslverify=1
sslcacert=/etc/pki/tls/certs/ca-bundle.crt
2. 安装
sudo yum install grafana
更多版本和安装方法查阅Grafana安装文档
3. 启动
sudo systemctl daemon-reload
sudo systemctl start grafana-server
sudo systemctl status grafana-server
4. 自启动
sudo systemctl enable grafana-server
5. 登录
访问http//xxx:3000/
,输入用户名admin
和密码登录,第一次成功会提示更改密码。3000
为Grafana
的默认监听端口。
6. 绘制监控图
可以在Grafana
上设置数据源,自定义模板,导入模板等。这样就可以制作炫酷可视化系统监控了。