首页 文章 精选 留言 我的

精选列表

搜索[Compose模式],共10000篇文章
优秀的个人博客,低调大师

【Prometheus·入门篇】PromQL 查询:语法、聚合运算与常用模式

## 前言 PromQL 是 Prometheus 的查询语言,也是整个监控系统的灵魂。写好 PromQL 是做监控告警和 Dashboard 设计的基础。本篇从语法到实战,覆盖 80% 日常查询场景。 --- ## 一、PromQL 基础语法 ### 即时查询(Instant Query) ```promql # 返回当前时刻的值 up # 结果:{instance="node1:9100", job="node"} 1 # {instance="node2:9100", job="node"} 1 # {instance="node3:9100", job="node"} 0 # 带标签过滤 up{job="node"} up{job="node", instance="node1:9100"} # 多值匹配 up{job=~"node|mysql|redis"} # 正则匹配 up{job!~"node.*"} # 正则不匹配 up{status!=""} # 不为空 ``` ### 范围查询(Range Query) ```promql # 返回过去 5 分钟所有数据点 up[5m] # 时间范围后缀 s - 秒 m - 分钟 h - 小时 d - 天 w - 周 y - 年 # 示例 rate(http_requests_total[10m]) # 过去 10 分钟速率 avg_over_time(cpu_usage[1h]) # 过去 1 小时平均 max_over_time(memory_usage[30m]) # 过去 30 分钟最大值 ``` ### 偏移查询(Offset) ```promql # 查询 1 小时前的值 up offset 1h # 与 1 小时前比较 http_requests_total - (http_requests_total offset 1h) # 当前总量 - 1小时前总量 = 过去1小时新增请求数 ``` ### @ 修饰符 ```promql # 查询指定时间点的数据 http_requests_total @ 1704067200 # Unix 时间戳 # 查询昨天此刻的数据 http_requests_total @ (time() - 86400) ``` --- ## 二、运算符 ### 算术运算 ```promql # 加减乘除 node_memory_MemTotal_bytes - node_memory_MemAvailable_bytes # 总内存 - 可用内存 = 已用内存 (node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes) * 100 # 可用内存百分比 rate(http_requests_total[5m]) * 1000 # 每秒请求数 × 1000 = 每毫秒请求数 ``` ### 比较运算 ```promql # 大于 node_memory_MemAvailable_bytes 100 # 过滤但不改变值(加 bool) http_requests_total > bool 100 # 返回 0 或 1 ``` ### 逻辑运算 ```promql # and(交集) node_cpu_seconds_total{mode="idle"} and node_cpu_seconds_total{mode="idle"} > 100 # or(并集) up{job="node"} or up{job="mysql"} # unless(差集) up unless up{instance="node1:9100"} # 所有 up 序列中排除 node1 ``` --- ## 三、聚合运算 ### 基本聚合 ```promql # sum —— 求和 sum(http_requests_total) # avg —— 平均 avg(node_cpu_seconds_total{mode="idle"}) # max / min max(node_memory_MemAvailable_bytes) min(node_filesystem_free_bytes) # count —— 序列计数 count(up) # topk / bottomk —— 取前N topk(3, rate(http_requests_total[5m])) # 请求数最高的3个 bottomk(3, node_memory_MemAvailable_bytes) # 内存最少的前3个 # quantile —— 分位数 quantile(0.99, http_request_duration_seconds) # P99 ``` ### by 分组 ```promql # 按方法分组求和 sum(rate(http_requests_total[5m])) by (method) # {method="GET"} 150.5 # {method="POST"} 45.2 # 按多个标签分组 sum(rate(http_requests_total[5m])) by (method, status) # {method="GET", status="200"} 120.3 # {method="GET", status="500"} 30.2 # {method="POST", status="201"} 45.2 # without —— 排除某些标签 sum(rate(http_requests_total[5m])) without (instance) # 按 instance 以外的所有标签分组 ``` ### 常用聚合组合 ```promql # 1. 每个实例的 CPU 使用率 100 - (avg(rate(node_cpu_seconds_total{mode="idle"}[5m])) by (instance) * 100) # 2. 每个服务每秒请求数 sum(rate(http_requests_total[5m])) by (service) # 3. 每个命名空间的内存使用 sum(container_memory_working_set_bytes{container!=""}) by (namespace) # 4. 全局错误率 sum(rate(http_requests_total{status=~"5.."}[5m])) / sum(rate(http_requests_total[5m])) * 100 ``` --- ## 四、rate / irate / increase ### rate —— 平均速率 ```promql # 过去 5 分钟平均每秒请求数 rate(http_requests_total[5m]) ``` ``` 原理: v5=100, v4=95, v3=90, v2=85, v1=80 rate = (v5 - v1) / (t5 - t1) = (100 - 80) / 300s = 0.067 req/s ``` **特点**:平滑、抗尖峰,适合绘制趋势图和告警。 ### irate —— 瞬时速率 ```promql # 最近两个数据点的速率 irate(http_requests_total[5m]) ``` ``` 原理: v5=100, v4=95 irate = (v5 - v4) / (t5 - t4) = (100 - 95) / 15s = 0.333 req/s ``` **特点**:敏感、反映瞬时变化,适合超精细趋势图,不适合告警。 ### increase —— 总增长量 ```promql # 过去 1 小时新增的请求数 increase(http_requests_total[1h]) ``` ``` 原理: increase = rate × 时间范围 = 0.067 × 3600 = 241.2 ``` **特点**:返回区间内总量,适合报表和计数。 ### 选择建议 | 函数 | 特点 | 适用场景 | |------|------|---------| | rate() | 平均、平滑 | 告警、趋势图 | | irate() | 瞬时、敏感 | 精细趋势图 | | increase() | 总量 | 报表、统计 | > ⚠️ **踩坑提示**:rate 会因 Counter 重置自动修正。如果应用重启导致 Counter 归零,rate 会用 `(current_value + previous_value) / interval` 补偿,不会产生负值。 --- ## 五、常用函数 ### 时间函数 ```promql # 时间相关 year() / month() / day() / hour() / minute() # 示例:只看工作时间告警 day_of_week() >= 1 and day_of_week() = 9 and hour() 1 表示流量增长 # 本周 vs 上周 sum(increase(http_requests_total[7d])) / (sum(increase(http_requests_total[7d])) offset 7d) * 100 ``` --- ## 七、子查询 ```promql # 计算过去 1 小时内每 5 分钟的最大 QPS max_over_time(rate(http_requests_total[5m])[1h:5m]) # [1h:5m] = 在过去 1 小时内,每 5 分钟计算一次 # 计算过去 1 小时内 CPU 使用率的峰值 max_over_time( (100 - avg(rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100) [1h:1m] ) ``` --- ## 要点回顾 | 查询类型 | 关键函数/语法 | 场景 | |---------|-------------|------| | 即时查询 | `metric{label="value"}` | 查看当前状态 | | 范围查询 | `metric[5m]` | 趋势图 | | 速率计算 | `rate() / irate() / increase()` | Counter 指标 | | 聚合 | `sum() / avg() / by()` | 分组统计 | | 分位数 | `histogram_quantile()` | 延迟分析 | | 比较 | `metric > threshold` | 阈值过滤 | | 预测 | `predict_linear()` | 容量规划 | | 子查询 | `[1h:5m]` | 二次计算 | - PromQL 是声明式查询语言,先选指标再加操作 - rate 适合告警(平滑),irate 适合图表(灵敏) - by 分组是核心,理解 by 后的聚合维度 - histogram_quantile 注意要按 le 聚合 - 子查询实现"对速率再取极值"等复杂需求 --- ## 下一篇预告 PromQL 掌握了,接下来该动手部署了。下一篇 **【Prometheus·部署篇】环境搭建:二进制部署与 Kubernetes 部署对比** 将手把手教你搭建 Prometheus 监控环境。

优秀的个人博客,低调大师

从 0 实现 React 18:手写并发模式与 Fiber 架构核心

# React 18 的并发渲染(Concurrent Rendering)是其最革命性的特性。它并非简单的新 API,而是一次**架构级的重写**——Fiber 架构赋予了 React 可中断、可恢复的渲染能力,使时间切片和优先级调度成为可能。本文将带你从零实现一个精简版 React 18,涵盖 **Fiber 数据结构**、**协调(Reconciliation)**、**并发调度**、**双缓冲(Double Buffering)** 和 **Hooks 工作原理**。 --- ## 1. Fiber 节点的数据结构 Fiber 是 React 18 中最小的工作单元,它是一个 JavaScript 对象,通过链表结构(child、sibling、return)描述组件树,使得更新工作可被拆分和中断。 ``` type FiberNode = { // 核心标识 tag: 'host_root' | 'host_component' | 'function_component' | 'host_text'; key: string | null; type: string | Function; // 'div' 或组件函数 // 状态与 props pendingProps: any; memoizedProps: any; memoizedState: any; // 对于 FC,存储 Hook 链表 // 链表结构 return: FiberNode | null; child: FiberNode | null; sibling: FiberNode | null; index: number; // 双缓冲与副作用 alternate: FiberNode | null; // 指向另一棵树的对应节点 flags: 'update' | 'delete' | 'placement' | 'layout_effect' | null; deletions: FiberNode[] | null; // 调度相关(React 18 核心) lanes: number; // 优先级位掩码 childLanes: number; }; ``` 每个 Fiber 节点通过 `alternate` 指针连接 current 树和 workInProgress 树,实现双缓冲渲染。 --- ## 2. 并发调度与时间切片 React 18 使用 `MessageChannel` 实现宏任务调度,在浏览器空闲时执行工作单元。以下实现 `workLoop`,它会在渲染超过 5ms 时主动让出主线程: ``` const DEADLINE = 5; // 毫秒 const channel = new MessageChannel(); let pendingCallback: (() => void) | null = null; channel.port2.onmessage = () => { const callback = pendingCallback; pendingCallback = null; if (callback) callback(); }; function scheduleCallback(callback: () => void) { pendingCallback = callback; channel.port1.postMessage(null); } let nextUnitOfWork: FiberNode | null = null; let workInProgressRoot: FiberNode | null = null; function performUnitOfWork(fiber: FiberNode): FiberNode | null { // 1. 协调(reconcile)子节点 reconcileChildren(fiber); // 2. 如果有子节点,返回子节点继续工作 if (fiber.child) return fiber.child; // 3. 否则找兄弟节点,或向上回溯 let next: FiberNode | null = fiber; while (next) { if (next.sibling) return next.sibling; next = next.return; } return null; } function workLoop(deadline: number) { let shouldYield = false; while (nextUnitOfWork && !shouldYield) { nextUnitOfWork = performUnitOfWork(nextUnitOfWork); shouldYield = performance.now() >= deadline; } if (nextUnitOfWork) { scheduleCallback(() => workLoop(performance.now() + DEADLINE)); } else { // 所有工作完成,提交到 DOM commitRoot(workInProgressRoot!); } } export function render(element: JSX.Element, container: HTMLElement) { // 创建 root Fiber const rootFiber: FiberNode = { tag: 'host_root', type: null, key: null, pendingProps: element, memoizedProps: null, memoizedState: null, return: null, child: null, sibling: null, index: 0, alternate: null, flags: null, deletions: null, lanes: 0, childLanes: 0, }; workInProgressRoot = rootFiber; nextUnitOfWork = rootFiber; scheduleCallback(() => workLoop(performance.now() + DEADLINE)); } ``` --- ## 3. 协调(Reconciliation)与 Diff 协调是 React 的灵魂。我们在 `reconcileChildren` 中比较新旧 Fiber 子节点,决定是复用、更新还是创建新节点。 ``` function reconcileChildren(workInProgress: FiberNode) { const children = workInProgress.pendingProps.children; // 简化版:仅处理单子节点 if (typeof children === 'string' || typeof children === 'number') { // 文本节点 const newFiber: FiberNode = { tag: 'host_text', type: null, key: null, pendingProps: children, memoizedProps: null, memoizedState: null, return: workInProgress, child: null, sibling: null, index: 0, alternate: null, flags: 'update', deletions: null, lanes: 0, childLanes: 0, }; workInProgress.child = newFiber; return; } // 处理元素节点 if (typeof children === 'object' && children !== null) { const newFiber: FiberNode = { tag: typeof children.type === 'function' ? 'function_component' : 'host_component', type: children.type, key: children.key ?? null, pendingProps: children.props, memoizedProps: null, memoizedState: null, return: workInProgress, child: null, sibling: null, index: 0, alternate: null, flags: 'placement', deletions: null, lanes: 0, childLanes: 0, }; workInProgress.child = newFiber; } } ``` --- ## 4. 函数组件与 Hooks 实现 React 18 的 Hook 调用顺序依赖 Fiber 节点上的 `memoizedState` 链表。以下是 `useState` 的精简实现: ``` type Hook = { memoizedState: any; queue: any[]; next: Hook | null; }; let currentlyRenderingFiber: FiberNode | null = null; let hookIndex = 0; function mountWorkInProgressHook(): Hook { const hook: Hook = { memoizedState: null, queue: [], next: null, }; const fiber = currentlyRenderingFiber!; if (!fiber.memoizedState) { fiber.memoizedState = hook; } else { // 遍历到链表末尾 let current = fiber.memoizedState; while (current.next) current = current.next; current.next = hook; } return hook; } export function useState(initial: T): [T, (action: T | ((prev: T) => T)) => void] { const fiber = currentlyRenderingFiber!; const hook = mountWorkInProgressHook(); // 读取 alternate 树中的历史状态 const alternate = fiber.alternate; let state: T = initial; if (alternate && alternate.memoizedState) { // 真实场景需遍历到对应索引的 Hook state = (alternate.memoizedState as Hook).memoizedState ?? initial; } hook.memoizedState = state; const setState = (action: T | ((prev: T) => T)) => { const newState = typeof action === 'function' ? (action as (prev: T) => T)(state) : action; // 触发更新(重新调度渲染) // 实际实现需要标记 fiber 并触发 workLoop scheduleUpdate(fiber, newState); }; return [state, setState]; } // 在执行函数组件时设置当前 fiber function renderFunctionComponent(fiber: FiberNode) { currentlyRenderingFiber = fiber; hookIndex = 0; const Component = fiber.type as Function; const props = fiber.pendingProps; const children = Component(props); fiber.memoizedProps = props; // 继续协调 children... } ``` --- ## 5. 提交(Commit)阶段 完成渲染后,将 workInProgress 树的变化应用到真实 DOM。React 18 支持 `useLayoutEffect` 和 `useEffect` 分别在提交前后执行。 ``` function commitRoot(root: FiberNode) { // 1. 递归遍历 fiber 树,执行 DOM 操作 commitWork(root.child); // 2. 将 workInProgress 树变为 current 树 root.alternate = root; // 3. 执行 useEffect(在浏览器绘制后异步执行) scheduleEffectCallbacks(root); } function commitWork(fiber: FiberNode | null) { if (!fiber) return; // 找到最近的 host_component 父节点 let parent = fiber.return; while (parent && parent.tag !== 'host_component') parent = parent.return; const domParent = (parent as any).domInstance; if (fiber.tag === 'host_component' || fiber.tag === 'host_text') { if (fiber.flags === 'placement') { // 创建 DOM 并插入 const dom = createDOM(fiber); domParent.appendChild(dom); } else if (fiber.flags === 'update') { updateDOM(fiber); } } commitWork(fiber.child); commitWork(fiber.sibling); } ``` --- ## 6. 总结 我们仅用数百行代码便重现了 React 18 的核心架构:**Fiber 链表**使渲染可中断,**MessageChannel + 时间切片**实现并发调度,**双缓冲树**与**alternate**指针保障状态一致性,**Hooks**通过链表顺序关联状态。 这个微型实现虽不包含事件合成、Suspense、并发优先级调度等完整功能,但它揭示了 React 18 最本质的设计哲学。建议读者运行代码,在浏览器 DevTools 的 Performance 面板中观察 `workLoop` 的切片效果,你会真正理解 React 如何做到“渲染不阻塞用户输入”。 React 18 的源码虽庞大,但核心思想高度凝练。掌握 Fiber 架构,你就掌握了现代前端框架设计的精髓。

资源下载

更多资源
优质分享App

优质分享App

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

用户登录
用户注册
修改密码
忘记密码