Spring Boot 实现应用监控和报警
Spring Boot 的应用监控方案比较多,Spring Boot+Prometheus+Grafana是目前比较常用的方案之一。它们三者之间的关系大概如下图:
01 开发 Spring Boot 应用
首先,创建一个SpringBoot项目,pom文件如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- https://mvnrepository.com/artifact/io.prometheus/simpleclient_spring_boot -->
<dependency>
<groupId>io.prometheus</groupId>
<artifactId>simpleclient_spring_boot</artifactId>
<version>0.8.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
注意: 这里的 Spring Boot 版本是 1.5.7.RELEASE,之所以不用最新的2.X是因为最新的 simpleclient_spring_boot 只支持1.5.X,不确定2.X版本的能否支持。
MonitorDemoApplication 启动类增加注解:
@EnablePrometheusEndpoint
@EnableSpringBootMetricsCollector
@SpringBootApplication
public class MonitorDemoApplication {
public static void main(String[] args) {
SpringApplication.run(MonitorDemoApplication.class, args);
}
}
server:
port: 8848
spring:
application:
name: monitor-demo
security:
user:
name: admin
password: 1234
basic:
enabled: true
# 安全路径列表,逗号分隔,此处只针对/admin路径进行认证
path: /admin
# actuator暴露接口的前缀
management:
context-path: /admin
# actuator暴露接口使用的端口,为了和api接口使用的端口进行分离
port: 8888
security:
enabled: true
roles: SUPERUSER
@RequestMapping("/heap/test")
@RestController
public class TestController {
public static final Map<String, Object> map = new ConcurrentHashMap<>();
@RequestMapping("")
public String testHeapUsed() {
for (int i = 0; i < 10000000; i++) {
map.put(i + "", new Object());
}
return "ok";
}
}
scrape_configs:
# The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
# - job_name: 'prometheus'
# metrics_path defaults to '/metrics'
# scheme defaults to 'http'.
# static_configs:
# - targets: ['localhost:9090']
- job_name: 'monitor-demo'
scrape_interval: 5s # 刮取的时间间隔
scrape_timeout: 5s
metrics_path: /admin/prometheus
scheme: http
basic_auth: #认证信息
username: admin
password: 1234
static_configs:
- targets:
- 127.0.0.1:8888 #此处填写 Spring Boot 应用的 IP + 端口号
4.选择图表样式
第二步: 邮箱配置
Grafana默认使用conf目录下defaults.ini作为配置文件运行,根据官方的建议我们不要更改defaults.ini而是在同级目录下新建一个配置文件custom.ini。
以腾讯企业邮箱为例,配置如下:
#################################### SMTP / Emailing #####################
[smtp]
enabled = true
host = smtp.exmail.qq.com:465
user = xxxx@ininin.com
# If the password contains # or ; you have to wrap it with triple quotes. Ex """#password;"""
password = XXX
cert_file =
key_file =
skip_verify = true
from_address = xxxx@ininin.com
from_name = Grafana
ehlo_identity = ininin.com
然后需要重启Grafana,命令grafana-server.exe -config=E:\file\grafana-6.3.3\conf\custom.ini
配置通知方式和信息
附上几个链接:
Prometheus官方文档:
推荐阅读:
评论