Files
sa-lessons/modules/module5/sections/02-prometheus-grafana.md
T
Alexander Abakumov 15e744da49 Initial commit: Complete Software Architecture course with 11 modules
- Added comprehensive course structure with 11 modules
- Included theoretical content, practical examples, and tasks
- Multi-language code examples (Java, Rust, Node.js, Python)
- Detailed analysis of architectural approaches and trade-offs
- Complete caching strategies documentation
- Architecture examples from real-world systems (Twitter, Netflix, Uber)
- Structured navigation and learning path
- Ready for educational use
2025-09-09 22:08:07 +03:00

156 lines
4.3 KiB
Markdown

# Prometheus и Grafana
## Навигация
- [🏠 Главная страница курса](../../../README.md)
- [📚 Модуль 5](../README.md)
---
## Prometheus
**Prometheus** — система мониторинга и база данных временных рядов.
### Архитектура Prometheus
```
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Application │ │ Application │ │ Application │
│ (Metrics) │ │ (Metrics) │ │ (Metrics) │
└─────────────────┘ └─────────────────┘ └─────────────────┘
│ │ │
└───────────────────────┼───────────────────────┘
│
┌─────────────────┐
│ Prometheus │
│ Server │
└─────────────────┘
│
┌─────────────────┐
│ Grafana │
│ (Dashboard) │
└─────────────────┘
```
### PromQL (Язык запросов Prometheus)
#### Основные запросы:
```promql
# Простая метрика
http_requests_total
# Метрика с фильтрами
http_requests_total{method="GET", status="200"}
# Агрегация
sum(http_requests_total) by (method)
# Rate (скорость изменения)
rate(http_requests_total[5m])
# Histogram quantiles
histogram_quantile(0.95, rate(http_request_duration_seconds_bucket[5m]))
```
#### Примеры запросов:
```promql
# Количество запросов в секунду
rate(http_requests_total[5m])
# Среднее время ответа
rate(http_request_duration_seconds_sum[5m]) / rate(http_request_duration_seconds_count[5m])
# 95-й перцентиль времени ответа
histogram_quantile(0.95, rate(http_request_duration_seconds_bucket[5m]))
# Ошибки в процентах
rate(http_requests_total{status=~"5.."}[5m]) / rate(http_requests_total[5m]) * 100
```
### Spring Boot + Prometheus
```java
@Configuration
public class PrometheusConfig {
@Bean
public MeterRegistry meterRegistry() {
return new PrometheusMeterRegistry(PrometheusConfig.DEFAULT);
}
}
@RestController
public class MetricsController {
private final MeterRegistry meterRegistry;
public MetricsController(MeterRegistry meterRegistry) {
this.meterRegistry = meterRegistry;
}
@GetMapping("/metrics")
public String metrics() {
return ((PrometheusMeterRegistry) meterRegistry).scrape();
}
}
```
## Grafana
**Grafana** — платформа для визуализации метрик и создания дашбордов.
### Создание дашборда
```json
{
"dashboard": {
"title": "Application Metrics",
"panels": [
{
"title": "Request Rate",
"type": "graph",
"targets": [
{
"expr": "rate(http_requests_total[5m])",
"legendFormat": "{{method}} {{endpoint}}"
}
]
},
{
"title": "Response Time",
"type": "graph",
"targets": [
{
"expr": "histogram_quantile(0.95, rate(http_request_duration_seconds_bucket[5m]))",
"legendFormat": "95th percentile"
}
]
}
]
}
}
```
### Алерты в Grafana
```json
{
"alert": {
"name": "High Error Rate",
"message": "Error rate is above 5%",
"conditions": [
{
"query": {
"params": ["A", "5m", "now"]
},
"reducer": {
"type": "last",
"params": []
},
"evaluator": {
"params": [0.05],
"type": "gt"
}
}
]
}
}
```