Apache ShenYu监控系统搭建:InfluxDB数据采集与可视化
一、监控系统架构概述
Apache ShenYu(网关)的监控系统基于InfluxDB时序数据库实现流量数据采集与存储,通过MonitorDO实体类记录核心指标,结合InfluxDbService完成数据持久化。系统架构包含三个核心模块:
- 数据采集:由MonitorDO定义监控指标
- 存储服务:通过InfluxDbService实现数据写入
- 配置管理:InfluxDbConfiguration提供连接池与模板初始化
二、环境准备与依赖配置
2.1 必要依赖
在pom.xml中添加InfluxDB相关依赖(建议使用Maven中央仓库国内镜像):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-influxdb</artifactId>
</dependency>
2.2 配置参数
在application.yml中添加InfluxDB连接配置:
spring:
influxdb:
url: http://localhost:8086
username: admin
password: admin
database: shenyu_monitor
retention-policy: autogen
注:配置项需与InfluxDbConfiguration中的@ConditionalOnProperty注解匹配
三、核心实现原理
3.1 数据模型设计
MonitorDO定义了监控指标体系,包含以下核心字段: | 字段名 | 类型 | 说明 | |-----------|--------|-----------------------| | host | String | 网关服务器主机名 | | ip | String | 客户端IP地址 | | method | String | HTTP请求方法 | | module | String | 所属业务模块 | | rpcType | String | 远程调用类型(Dubbo/HTTP) | | count | Long | 请求计数 |
3.2 数据写入流程
InfluxDbService的writeData方法实现时序数据写入:
public void writeData(final MonitorDO monitorDO) {
final Point.Builder builder = Point.measurement("monitorDO")
.time(System.currentTimeMillis(), TimeUnit.MILLISECONDS);
builder.tag("host", monitorDO.getHost())
.tag("ip", monitorDO.getIp())
.tag("method", monitorDO.getMethod())
.addField("count", monitorDO.getCount());
influxDBTemplate.write(builder.build());
}
代码解析:通过Point.Builder构建InfluxDB数据点,使用毫秒级时间戳确保时序精度,标签(tag)用于数据过滤,字段(field)存储可度量值
四、可视化配置指南
4.1 Grafana面板配置
- 添加数据源:配置InfluxDB连接(URL填写
http://localhost:8086,数据库选择shenyu_monitor) - 导入仪表盘:推荐使用ID为
10000的InfluxDB默认仪表盘模板 - 自定义查询:示例查询语句:
SELECT mean("count") FROM "monitorDO" WHERE $timeFilter GROUP BY time($__interval), "module" fill(null)
4.2 关键监控指标
建议配置以下监控视图:
- 请求趋势图:按分钟聚合的请求总量曲线
- 模块流量占比:各业务模块的请求分布饼图
- 异常IP追踪:高频请求IP的热力图展示
五、性能优化建议
- 批处理优化:修改InfluxDbService实现批量写入:
public void batchWrite(List<MonitorDO> monitorDOS) {
List<Point> points = monitorDOS.stream().map(monitor ->
Point.measurement("monitorDO")
.time(System.currentTimeMillis(), TimeUnit.MILLISECONDS)
.tag("module", monitor.getModule())
.addField("count", monitor.getCount())
.build()
).collect(Collectors.toList());
influxDBTemplate.write(points);
}
- 数据保留策略:在InfluxDB中创建自定义保留策略:
CREATE RETENTION POLICY "7_days" ON "shenyu_monitor" DURATION 7d REPLICATION 1 DEFAULT
六、常见问题排查
6.1 连接失败
检查InfluxDbConfiguration的connectionFactory方法,确保:
- InfluxDB服务已启动
- 防火墙开放8086端口
- 配置文件中的用户名密码正确
6.2 数据写入延迟
通过JVM监控工具检查:
- InfluxDbService的
writeData方法执行耗时 - InfluxDB连接池状态(默认使用Spring Data的连接池配置)
七、扩展阅读
- 官方文档:README.md
- 测试用例:InfluxDbServiceTest
- 架构设计:script/image/soul架构图.png
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考



