<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet href="/scripts/pretty-feed-v3.xsl" type="text/xsl"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:h="http://www.w3.org/TR/html4/"><channel><title>七万号·数据平台实战手记</title><description>数据平台架构师｜受限环境数据平台实战 · 架构治理 · AI 哲学</description><link>https://realcpf.tech</link><item><title>存储与压缩：百万行秒出，DuckDB 的空间魔法</title><link>https://realcpf.tech/blog/duckdb-08</link><guid isPermaLink="true">https://realcpf.tech/blog/duckdb-08</guid><description>意义：分析查询吞吐翻倍 + 磁盘占用腰斩。受限环境/磁盘紧张时，DuckDB 是救星。</description><pubDate>Thu, 03 Sep 2026 14:00:00 GMT</pubDate><content:encoded>&lt;h2&gt;① 标题党&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;主标题&lt;/strong&gt;：&lt;code&gt;DuckDB 的文件怎么这么小？压缩也有方法论&lt;/code&gt;
&lt;strong&gt;备选A&lt;/strong&gt;：&lt;code&gt;数据没少，占用却少一大截，DuckDB 存盘有讲究&lt;/code&gt;
&lt;strong&gt;备选B（短视频）&lt;/strong&gt;：&lt;code&gt;小文件，装大智慧&lt;/code&gt;&lt;/p&gt;
&lt;h2&gt;② 开场钩子&lt;/h2&gt;
&lt;p&gt;我导了 100 万行数据进 DuckDB，存盘一看，文件小得不像话。数据没丢，却省了这么多——它压缩有一套。&lt;/p&gt;
&lt;h2&gt;③ 主角特性：压缩 / 列式存储收益&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;列式存储把&lt;strong&gt;同类型数据放一起&lt;/strong&gt; → 高重复度 → 压缩率极高。&lt;/li&gt;
&lt;li&gt;支持多种压缩（ZSTD 等），配合字典/游程编码，数字和枚举类列压缩尤其夸张。&lt;/li&gt;
&lt;li&gt;查询时对压缩数据尽量&quot;不解压就过滤&quot;，省 IO 又省 CPU。&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;意义&lt;/strong&gt;：分析查询吞吐翻倍 + 磁盘占用腰斩。受限环境/磁盘紧张时，DuckDB 是救星。&lt;/p&gt;
&lt;h2&gt;④ 最小可复现&lt;/h2&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;CREATE TABLE t AS SELECT i % 100 AS kind, i FROM range(1000000) t(i);
COPY t TO &apos;t.parquet&apos;;   -- 高重复列压缩惊人
-- 对比：同样数据行式存 vs 列式压缩后的大小
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;⑤ 结论&lt;/h2&gt;
&lt;blockquote&gt;
&lt;p&gt;DuckDB 文件小，不是偷数据，是把&quot;重复&quot;压缩到位。磁盘受限时，这种空间魔法尤其珍贵。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;⑥ 配图脚本&lt;/h2&gt;
&lt;p&gt;列式压缩示意 / 压缩前后大小对比 / 丢数据/原数据对比 / 结论卡&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;系列总览（全部完成）&lt;/h2&gt;
&lt;p&gt;| # | 标题党主题 | 细粒度特性 |
|:--:|----------|-----------|
| 01 | 快得离谱 | 列存 + 向量化 |
| 02 | 一个文件一个库 | 嵌入式 / 单文件 |
| 03 | 连 CPU 缓存都算计 | 缓存局部性 / 批处理 |
| 04 | 一张 SQL 查遍所有库 | 联邦查询 / attach |
| 05 | 脏乱差也能存 | VARIANT 半结构化 |
| 06 | 库不够用自己加轮子 | 扩展机制 / TableFunction |
| 07 | CONNECT 革别人命 | DuckDB as Server / Quack |
| 08 | 空间魔法 | 压缩 / 列式收益 |&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;每篇含：标题党(3版) + 30s 钩子 + 主角特性 + 最小可复现 SQL + 结论金句 + 5 帧配图脚本。
素材多来自你做 DuckDB 的真实经历（联邦查询、http-json 扩展、v2.0 畅想）——第 4/6/7 篇是你自己的实证。&lt;/p&gt;
&lt;/blockquote&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>CONNECT：DuckDB 2.0 在革&apos;服务器&apos;的命</title><link>https://realcpf.tech/blog/duckdb-07</link><guid isPermaLink="true">https://realcpf.tech/blog/duckdb-07</guid><description>意义：这是 v2.0（Cyanoptera）的头牌，把 DuckDB 从&apos;嵌入式分析引擎&apos;推向&apos;联邦查询服务器&apos;。</description><pubDate>Thu, 03 Sep 2026 13:00:00 GMT</pubDate><content:encoded>&lt;h2&gt;① 标题党&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;主标题&lt;/strong&gt;：&lt;code&gt;DuckDB 2.0 来了，CONNECT 这招在革谁的命？&lt;/code&gt;
&lt;strong&gt;备选A&lt;/strong&gt;：&lt;code&gt;从嵌入式到能联网，DuckDB 要当&quot;查询服务器&quot;了？&lt;/code&gt;
&lt;strong&gt;备选B（短视频）&lt;/strong&gt;：&lt;code&gt;小 Duck 长出翅膀&lt;/code&gt;&lt;/p&gt;
&lt;h2&gt;② 开场钩子&lt;/h2&gt;
&lt;p&gt;一直说 DuckDB 是&quot;嵌入式、单机&quot;,直到 2.0 的 CONNECT 出现——它居然能当服务、能远程查询别人。这不只是加功能，是要革掉&quot;服务器数据库&quot;的命。&lt;/p&gt;
&lt;h2&gt;③ 主角特性：DuckDB as a Server / CONNECT / Quack&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Quack + CONNECT&lt;/strong&gt;：任何 DuckDB 能 serve 库，任何 DuckDB 能 attach 远程库，&lt;code&gt;CONNECT&lt;/code&gt; 一条语句切换查询目标。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;remote pushdown&lt;/strong&gt;：SQL 直接下发给远程库（PostgreSQL/MySQL）执行，而非把表拉回来——联邦查询真正&quot;下推&quot;到源端。&lt;/li&gt;
&lt;li&gt;远程执行 + 结果回流，DuckDB 从&quot;进程内引擎&quot;升级为&quot;统一查询协议&quot;的节点。&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;意义&lt;/strong&gt;：这是 v2.0（Cyanoptera）的头牌，把 DuckDB 从&quot;嵌入式分析引擎&quot;推向&quot;联邦查询服务器&quot;。&lt;/p&gt;
&lt;h2&gt;④ 最小可复现（v2.0 构想语法）&lt;/h2&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;-- 服务端
CALL quack_serve(token=&apos;my_token&apos;);
-- 客户端
ATTACH &apos;quack:server.example.com&apos; AS qk (TOKEN &apos;my_token&apos;);
CONNECT qk;
SELECT count(*) FROM events;  -- 在服务端执行，结果回流
DISCONNECT;
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;⑤ 结论&lt;/h2&gt;
&lt;blockquote&gt;
&lt;p&gt;DuckDB 2.0 的 CONNECT，不是&quot;加了客户端/服务器模式&quot;这么简单——它把 DuckDB 变成联邦查询的有线协议。革的，是&quot;啥都得拉回来算&quot;的旧认知。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;⑥ 配图脚本&lt;/h2&gt;
&lt;p&gt;嵌入式 → 服务器演进 / CONNECT 链路 / remote pushdown 示意 / 结论卡&lt;/p&gt;
&lt;hr&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>扩展机制：给 DuckDB 写点东西其实很爽（也有坑）</title><link>https://realcpf.tech/blog/duckdb-06</link><guid isPermaLink="true">https://realcpf.tech/blog/duckdb-06</guid><description>坑：扩展 API 跨版本不稳，常要随 DuckDB 重编译；但因为是开源，能看到源码自己补。</description><pubDate>Thu, 03 Sep 2026 12:00:00 GMT</pubDate><content:encoded>&lt;h2&gt;① 标题党&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;主标题&lt;/strong&gt;：&lt;code&gt;DuckDB 还能装插件？给数据库加能力是种什么体验&lt;/code&gt;
&lt;strong&gt;备选A&lt;/strong&gt;：&lt;code&gt;从 http/json 到联邦，DuckDB 扩展让我自己造数据源&lt;/code&gt;
&lt;strong&gt;备选B（短视频）&lt;/strong&gt;：&lt;code&gt;库不够用？自己给它加个轮子&lt;/code&gt;&lt;/p&gt;
&lt;h2&gt;② 开场钩子&lt;/h2&gt;
&lt;p&gt;标准 DuckDB 已经很强，但当我想让它读一个&lt;strong&gt;自定义 HTTP 接口&lt;/strong&gt;时，发现它还能扩展。给数据库写插件，这个自由度让我停不下来。&lt;/p&gt;
&lt;h2&gt;③ 主角特性：扩展机制 / TableFunction / ParserExtension&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Extensions&lt;/strong&gt;：核心可裁剪可扩展，装 &lt;code&gt;httpfs&lt;/code&gt;/&lt;code&gt;postgres&lt;/code&gt;/&lt;code&gt;parquet&lt;/code&gt; 等按需加载。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;自定义 TableFunction&lt;/strong&gt;：你可以写一个表函数，把任意数据源暴露成 DuckDB 表（如自读 HTTP JSON）。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;ParserExtension&lt;/strong&gt;：甚至可以接管自定义 SQL 语法（&lt;code&gt;CREATE TABLE x USING http_json(...)&lt;/code&gt;），几乎重定义数据库语法。&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;坑&lt;/strong&gt;：扩展 API 跨版本不稳，常要随 DuckDB 重编译；但因为是开源，能看到源码自己补。&lt;/p&gt;
&lt;h2&gt;④ 最小可复现&lt;/h2&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;-- 装官方扩展
INSTALL httpfs;
LOAD httpfs;
-- 直接读 S3/HTTP 上的 parquet
SELECT * FROM read_parquet(&apos;s3://bucket/a.parquet&apos;);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;（自定义扩展：见「方案C」的 http-json 插件——把 REST 接口当表）&lt;/p&gt;
&lt;h2&gt;⑤ 结论&lt;/h2&gt;
&lt;blockquote&gt;
&lt;p&gt;DuckDB 的扩展机制，让&quot;数据库&quot;从封闭走向可编程。你能给它加轮子，甚至改语法——这是它区别于大多数库的自由。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;⑥ 配图脚本&lt;/h2&gt;
&lt;p&gt;扩展装载流程 / 自定义数据源暴露成表 / ParserExtension 语法接管 / 结论卡&lt;/p&gt;
&lt;hr&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>VARIANT：半结构化也能&apos;脏乱差&apos;地存</title><link>https://realcpf.tech/blog/duckdb-05</link><guid isPermaLink="true">https://realcpf.tech/blog/duckdb-05</guid><description>取舍：灵活牺牲了强类型保证；但换来&apos;先存进来再说，查询时才整形&apos;的从容。</description><pubDate>Thu, 03 Sep 2026 11:00:00 GMT</pubDate><content:encoded>&lt;h2&gt;① 标题党&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;主标题&lt;/strong&gt;：&lt;code&gt;DuckDB 也配叫&quot;小&quot;?VARIANT 半结构化玩出花&lt;/code&gt;
&lt;strong&gt;备选A&lt;/strong&gt;：&lt;code&gt;日志、JSON 一股脑，DuckDB 的 VARIANT 说：不用管 schema&lt;/code&gt;
&lt;strong&gt;备选B（短视频）&lt;/strong&gt;：&lt;code&gt;脏数据，DuckDB 也能优雅地接&lt;/code&gt;&lt;/p&gt;
&lt;h2&gt;② 开场钩子&lt;/h2&gt;
&lt;p&gt;做数据平台最烦的不是数据多，是&lt;strong&gt;数据乱&lt;/strong&gt;——这个字段有、那个字段没有，一天一个样。直到 DuckDB 的 VARIANT 出现，说：你不用管它长什么样。&lt;/p&gt;
&lt;h2&gt;③ 主角特性：VARIANT 类型（半结构化）&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;VARIANT&lt;/strong&gt;（v1.5+ 引入）：一个列里每行可以存&lt;strong&gt;不同结构&lt;/strong&gt;的 JSON 式数据，不用强约束 schema。&lt;/li&gt;
&lt;li&gt;自动&quot;撕碎&quot;（shred）公共结构 → 既能保持灵活，又能压缩好、执行快。&lt;/li&gt;
&lt;li&gt;天然适合&lt;strong&gt;实时日志 / 埋点 / 半结构化&lt;/strong&gt;摄取，不强制定义死 schema。&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;取舍&lt;/strong&gt;：灵活牺牲了强类型保证；但换来&quot;先存进来再说，查询时才整形&quot;的从容。&lt;/p&gt;
&lt;h2&gt;④ 最小可复现&lt;/h2&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;-- 一列里每行 JSON 结构不同，也能放进去
CREATE TABLE logs (v VARIANT);
INSERT INTO logs VALUES (&apos;{&quot;a&quot;:1}&apos;), (&apos;{&quot;b&quot;:&quot;x&quot;,&quot;c&quot;:[1,2]}&apos;), (&apos;{&quot;a&quot;:2,&quot;d&quot;:null}&apos;);

-- 灵活取用
SELECT v[&apos;a&apos;] FROM logs;
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;⑤ 结论&lt;/h2&gt;
&lt;blockquote&gt;
&lt;p&gt;VARIANT 让我敢把&quot;没想好 schema&quot;的数据先接进来。DuckDB 不只快，还学会了容忍世界的混乱。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;⑥ 配图脚本&lt;/h2&gt;
&lt;p&gt;乱结构 JSON 汇入 / MULTI-shape 示意 / 查询取字段 / 结论卡&lt;/p&gt;
&lt;hr&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>联邦查询：让 DuckDB 去读别人的库</title><link>https://realcpf.tech/blog/duckdb-04</link><guid isPermaLink="true">https://realcpf.tech/blog/duckdb-04</guid><description>取舍：联邦查询有关联开销，适合&apos;低频跨源分析&apos;，不适合高频热路径。</description><pubDate>Thu, 03 Sep 2026 10:00:00 GMT</pubDate><content:encoded>&lt;h2&gt;① 标题党&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;主标题&lt;/strong&gt;：&lt;code&gt;让 DuckDB 去读 MySQL、PostgreSQL、Parquet？一个 SQL 通吃&lt;/code&gt;
&lt;strong&gt;备选A&lt;/strong&gt;：&lt;code&gt;它的野心不是做数据库，是做&quot;统一查询入口&quot;&lt;/code&gt;
&lt;strong&gt;备选B（短视频）&lt;/strong&gt;：&lt;code&gt;一张 SQL，查遍所有库&lt;/code&gt;&lt;/p&gt;
&lt;h2&gt;② 开场钩子&lt;/h2&gt;
&lt;p&gt;数据散在 MySQL、PostgreSQL、Parquet、CSV……每个都有自己的引擎。直到我让 DuckDB 用一条 SQL，把它们全都查了——这就是联邦查询。&lt;/p&gt;
&lt;h2&gt;③ 主角特性：跨源查询 / 多数据源 attach&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;attach&lt;/strong&gt;：DuckDB 可以 attach 外部数据库（PostgreSQL/MySQL 等），像本地表一样查。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;跨源 JOIN&lt;/strong&gt;：一条 SQL 里 join MySQL 的表 + PostgreSQL 的表 + Parquet 文件，优化器统一调度。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;读多源文件&lt;/strong&gt;：parquet/csv/json/s3 原生支持，分析场景一个文件就是一个表。&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;取舍&lt;/strong&gt;：联邦查询有关联开销，适合&quot;低频跨源分析&quot;，不适合高频热路径。&lt;/p&gt;
&lt;h2&gt;④ 最小可复现&lt;/h2&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;-- 把 parquet 和 CSV 当表查
SELECT * FROM &apos;orders.parquet&apos;
JOIN &apos;customers.csv&apos; c ON o.cid = c.id;

-- attach 外部 PG（需扩展）
ATTACH &apos;postgres://host:5432/db&apos; AS pg;
SELECT * FROM pg.users;
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;⑤ 结论&lt;/h2&gt;
&lt;blockquote&gt;
&lt;p&gt;DuckDB 不只想做自己的库，它想把&quot;所有数据&quot;都纳入一张 SQL。联邦查询，是它当&quot;统一数据入口&quot;的第一步。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;⑥ 配图脚本&lt;/h2&gt;
&lt;p&gt;多数据源汇聚到 DuckDB / 跨源 join 链路 / parquet/csv 直查 / 结论卡&lt;/p&gt;
&lt;hr&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>缓存局部性：连 CPU 缓存它都算计好了</title><link>https://realcpf.tech/blog/duckdb-03</link><guid isPermaLink="true">https://realcpf.tech/blog/duckdb-03</guid><description>反常识：有时候不是数据集太大，而是你的查询把 CPU 缓存&apos;打爆&apos;了。DuckDB 尽量让每一次 CPU 循环都干实事。</description><pubDate>Thu, 03 Sep 2026 09:00:00 GMT</pubDate><content:encoded>&lt;h2&gt;① 标题党&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;主标题&lt;/strong&gt;：&lt;code&gt;DuckDB 快，是因为它连 CPU 缓存都算好了？&lt;/code&gt;
&lt;strong&gt;备选A&lt;/strong&gt;：&lt;code&gt;为什么同样的查询，DuckDB 的缓存命中率更高&lt;/code&gt;
&lt;strong&gt;备选B（短视频）&lt;/strong&gt;：&lt;code&gt;快，是一种精打细算&lt;/code&gt;&lt;/p&gt;
&lt;h2&gt;② 开场钩子&lt;/h2&gt;
&lt;p&gt;你可能觉得数据库快不快看算法、看索引。但 DuckDB 比我见过的库都更在乎一件事：&lt;strong&gt;CPU 缓存&lt;/strong&gt;。数据放不对地方，CPU 再好也白搭。&lt;/p&gt;
&lt;h2&gt;③ 主角特性：缓存局部性 / 批处理&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;缓存友好布局&lt;/strong&gt;：向量化一次处理一个 block，数据在内存里连续相邻 → 命中 CPU 高速缓存（L1/L2），避免频繁访内存。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;减少随机访问&lt;/strong&gt;：列存 + 批量处理让&quot;下一个数据&quot;大概率就在&quot;上一个数据&quot;旁边，预取命中率高。&lt;/li&gt;
&lt;li&gt;分析查询的&quot;顺序扫描 + 聚合&quot;模式，天然吃满缓存局部性。&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;反常识&lt;/strong&gt;：有时候不是数据集太大，而是你的查询把 CPU 缓存&quot;打爆&quot;了。DuckDB 尽量让每一次 CPU 循环都干实事。&lt;/p&gt;
&lt;h2&gt;④ 最小可复现&lt;/h2&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;-- 数据连续排布，批量 scan
SELECT count(*) FROM t WHERE a &gt; 100;
-- 观察内存带宽 vs 磁盘 IO（列存下大查询基本不吃 IO）
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;⑤ 结论&lt;/h2&gt;
&lt;blockquote&gt;
&lt;p&gt;快，是精打细算出来的。DuckDB 从存储布局到执行方式，每一步都在帮你哄着 CPU 缓存。硬件还是那块硬件，你却感觉它变快了。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;⑥ 配图脚本&lt;/h2&gt;
&lt;p&gt;缓存层级示意图 / 顺序扫描 vs 随机访问 / 带宽对比 / 结论卡&lt;/p&gt;
&lt;hr&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>一个文件就是一个库：嵌入式零依赖</title><link>https://realcpf.tech/blog/duckdb-02</link><guid isPermaLink="true">https://realcpf.tech/blog/duckdb-02</guid><description>取舍：单机嵌入式（无内置服务器、单写者）适合分析/开发/嵌入式产品，不适合高并发 OLTP——但它本就不打算干那个活。</description><pubDate>Thu, 03 Sep 2026 08:00:00 GMT</pubDate><content:encoded>&lt;h2&gt;① 标题党&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;主标题&lt;/strong&gt;：&lt;code&gt;DuckDB 把整个数据库塞进一个文件？还跑得飞快&lt;/code&gt;
&lt;strong&gt;备选A&lt;/strong&gt;：&lt;code&gt;没有服务器、没有端口，一个文件就是你的数据湖&lt;/code&gt;
&lt;strong&gt;备选B（短视频）&lt;/strong&gt;：&lt;code&gt;你的库，只有一个文件那么大&lt;/code&gt;&lt;/p&gt;
&lt;h2&gt;② 开场钩子&lt;/h2&gt;
&lt;p&gt;传统数据库要有服务、有端口、要安装客户端。DuckDB 却告诉我：&lt;strong&gt;你要的库，备份一下就是一个文件&lt;/strong&gt;。这背后是它&quot;嵌入式&quot;的野心。&lt;/p&gt;
&lt;h2&gt;③ 主角特性：嵌入式 / 单文件存储&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;嵌入式&lt;/strong&gt;：DuckDB 跑在你的进程里，不单独起服务，Python/Rust/Java 直接 import 调用，零部署。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;单文件&lt;/strong&gt;：整个库就是一个 &lt;code&gt;.duckdb&lt;/code&gt; 文件。拷走这个文件，你的数据就跟手走。&lt;/li&gt;
&lt;li&gt;支持内存模式（&lt;code&gt;:memory:&lt;/code&gt;）临时分析 + 磁盘模式持久化。&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;取舍&lt;/strong&gt;：单机嵌入式（无内置服务器、单写者）适合分析/开发/嵌入式产品，不适合高并发 OLTP——但它本就不打算干那个活。&lt;/p&gt;
&lt;h2&gt;④ 最小可复现&lt;/h2&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;# Python 里直接连一个文件库，不装服务
python3 -c &quot;import duckdb; duckdb.sql(&apos;create table t as select 42 as x&apos;); duckdb.sql(&apos;copy t to \&quot;db.parquet\&quot;&apos;)&quot;
# db.parquet 拷走，数据跟手走
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;⑤ 结论&lt;/h2&gt;
&lt;blockquote&gt;
&lt;p&gt;DuckDB 把&quot;数据库&quot;从&quot;要伺候的服务&quot;变成了&quot;一个随取随用的文件&quot;。嵌入式的爽，用过就回不去。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;⑥ 配图脚本&lt;/h2&gt;
&lt;p&gt;服务式 vs 嵌入式架构对比 / 单文件拖走示意 / 各语言 import / 结论卡&lt;/p&gt;
&lt;hr&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>列存 + 向量化：DuckDB 凭什么&apos;卷&apos;别人</title><link>https://realcpf.tech/blog/duckdb-01</link><guid isPermaLink="true">https://realcpf.tech/blog/duckdb-01</guid><description>反常识：行式 OLTP 库（MySQL/PostgreSQL）做分析慢，不是它笨，是&apos;摆数据的方式&apos;根本不对。DuckDB 从设计第一天就为分析而活。</description><pubDate>Thu, 03 Sep 2026 07:00:00 GMT</pubDate><content:encoded>&lt;h2&gt;① 标题党&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;主标题&lt;/strong&gt;：&lt;code&gt;同样是数据库，DuckDB 凭什么敢说自己&quot;快得离谱&quot;？&lt;/code&gt;
&lt;strong&gt;备选A&lt;/strong&gt;：&lt;code&gt;一个进程内的小库，跑分析为什么比得上大集群？&lt;/code&gt;
&lt;strong&gt;备选B（短视频）&lt;/strong&gt;：&lt;code&gt;DuckDB：卷，是一种美德&lt;/code&gt;&lt;/p&gt;
&lt;h2&gt;② 开场钩子（30 秒）&lt;/h2&gt;
&lt;p&gt;都说大数据要上 Spark、要上集群才够快。可我做 DuckDB 这些年，发现一个十几 MB 的库，单机就敢跟集群掰手腕。它凭什么？秘密就在它怎么&quot;摆数据、怎么算数&quot;。&lt;/p&gt;
&lt;h2&gt;③ 主角特性：列式存储 + 向量化执行&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;列式存储&lt;/strong&gt;：数据一列一列排，算 sum/avg/count 只碰需要的列，无关列一个不动。分析型查询天然切中列存。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;向量化执行&lt;/strong&gt;：DuckDB 不是一行一行算，而是&lt;strong&gt;一次算一整个 block&lt;/strong&gt;（一批行），把 CPU 的 SIMD 指令用到极致，吞吐量大几个量级。&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;反常识&lt;/strong&gt;：行式 OLTP 库（MySQL/PostgreSQL）做分析慢，不是它笨，是&quot;摆数据的方式&quot;根本不对。DuckDB 从设计第一天就为分析而活。&lt;/p&gt;
&lt;h2&gt;④ 最小可复现&lt;/h2&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;-- 100 万行，SELECT 只碰一列 —— 列存下几乎不读别的
CREATE TABLE t (id BIGINT, a BIGINT, b BIGINT, ...);
INSERT INTO t SELECT i, i*2, i*3 FROM range(1000000) t(i);

-- 向量化算 sum，单机毫秒级
SELECT sum(a), avg(b) FROM t;
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;⑤ 结论&lt;/h2&gt;
&lt;blockquote&gt;
&lt;p&gt;列存决定了&quot;读多少&quot;，向量化决定了&quot;算多快&quot;。DuckDB 把这两件事从设计第一天就做对了，所以它敢拿单机挑战集群。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;⑥ 配图脚本&lt;/h2&gt;
&lt;p&gt;行式 vs 列式对比 / SIMD 批量处理示意 / 单机 vs 集群比拼 / 结论卡&lt;/p&gt;
&lt;hr&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>外表与联邦：Doris 和 MySQL 的&apos;异地恋&apos;</title><link>https://realcpf.tech/blog/doris-10</link><guid isPermaLink="true">https://realcpf.tech/blog/doris-10</guid><description>取舍：外表查询有网络开销，性能低于库内表；适合&apos;低频跨源分析&apos;，不适合高频热路径。</description><pubDate>Tue, 01 Sep 2026 16:00:00 GMT</pubDate><content:encoded>&lt;h2&gt;① 标题党&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;主标题&lt;/strong&gt;：&lt;code&gt;Doris 和 MySQL 组 CP？外表 + Catalog 的联邦魔法&lt;/code&gt;
&lt;strong&gt;备选&lt;/strong&gt;：&lt;code&gt;一张 SQL 同时查 Doris 和 MySQL？Doris 的联邦查询揭底&lt;/code&gt;&lt;/p&gt;
&lt;h2&gt;② 开场钩子&lt;/h2&gt;
&lt;p&gt;业务数据散在 MySQL、Hive、Kafka……Doris 能&quot;一锅端&quot;吗？能。它用 Catalog + 外表，把别人的库当成自己的表来查。&lt;/p&gt;
&lt;h2&gt;③ 主角特性：Catalog / 外表 / 联邦查询&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Catalog&lt;/strong&gt;：注册外部数据源（Hive、Iceberg、MySQL、JDBC 等），一个命名空间接入。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;外表（External Table）&lt;/strong&gt;：Doris 不搬数据，直接&lt;strong&gt;映射/查询&lt;/strong&gt;外部表，支持跨源 JOIN。&lt;/li&gt;
&lt;li&gt;MySQL Catalog 下，Doris 能透明读 MySQL 表，做跨 Doris+MySQL 的联邦聚合。&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;取舍&lt;/strong&gt;：外表查询有网络开销，性能低于库内表；适合&quot;低频跨源分析&quot;，不适合高频热路径。&lt;/p&gt;
&lt;h2&gt;④ 最小可复现&lt;/h2&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;CREATE CATALOG mysql_cat PROPERTIES (
  &quot;type&quot; = &quot;jdbc&quot;,
  &quot;jdbc_url&quot; = &quot;jdbc:mysql://host:3306&quot;,
  &quot;username&quot; = &quot;u&quot;, &quot;password&quot; = &quot;p&quot;
);
-- 跨源 JOIN
SELECT d.city, m.name
FROM doris_tbl d
JOIN mysql_cat.db.tbl m ON d.id = m.id;
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;⑤ 结论&lt;/h2&gt;
&lt;blockquote&gt;
&lt;p&gt;Doris 用 Catalog + 外表把&quot;别人的库&quot;变&quot;自己的表&quot;，一张 SQL 通吃多源。联邦查询，从此不用跑来跑去搬数据。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;⑥ 配图脚本&lt;/h2&gt;
&lt;p&gt;Catalog 接入多个源 / 外表映射 / 跨源 JOIN 链路 / 性能取舍标注&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;系列总览（已全部完成）&lt;/h2&gt;
&lt;p&gt;| # | 标题党主题 | 细粒度特性 |
|:--:|----------|-----------|
| 01 | Count(*) 一秒算完 | 列式存储 + Rollup |
| 02 | 千亿行也能收纳 | 分区 + 分桶 |
| 03 | Rollup 预计算魔法 | Rollup / 物化索引 |
| 04 | 小文件保洁阿姨 | Compaction |
| 05 | 索引三兄弟 | 前缀/布隆/倒排 |
| 06 | 挂了也能活 | FE 选主 / BE 心跳+副本 |
| 07 | 导入高速通道 | Stream Load / Broker Load |
| 08 | 谁说只能 OLAP | 高并发点查 |
| 09 | 内存 OOM 也能活 | Spill / 内存管理 |
| 10 | 和 MySQL 组 CP | Catalog / 外表 / 联邦 |&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;每篇含：标题党(3版) + 30s 钩子 + 主角特性 + 最小可复现 SQL/命令 + 结论金句 + 5 帧配图脚本。
可用于掘金/公众号（文字版）+ B站/小红书（口播+配图脚本 OR html-video 成片）。&lt;/p&gt;
&lt;/blockquote&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>大查询内存告急？Doris 的 Spill 与节流</title><link>https://realcpf.tech/blog/doris-09</link><guid isPermaLink="true">https://realcpf.tech/blog/doris-09</guid><description>关键：spill 上限调太高=磁盘 IO 拖慢；太低=频繁溢写。要在&apos;内存省&apos;和&apos;磁盘 IO&apos;间平衡。</description><pubDate>Tue, 01 Sep 2026 15:00:00 GMT</pubDate><content:encoded>&lt;h2&gt;① 标题党&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;主标题&lt;/strong&gt;：&lt;code&gt;Doris 内存 OOM？它其实会&quot;把大象塞回冰箱&quot;&lt;/code&gt;
&lt;strong&gt;备选&lt;/strong&gt;：&lt;code&gt;大查询一跑就爆内存？Doris 的 spill 了解一下&lt;/code&gt;&lt;/p&gt;
&lt;h2&gt;② 开场钩子&lt;/h2&gt;
&lt;p&gt;一条超大 GROUP BY 或 JOIN 下去，内存直接打爆。Doris 是怎么活下来的？靠一个&quot;内存不够就往外吐&quot;的机制。&lt;/p&gt;
&lt;h2&gt;③ 主角特性：内存管理 / 溢写（Spill）&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Doris 有&lt;strong&gt;内存统计 + 限制&lt;/strong&gt;，BE 内存分块管理，防止单查询吃光整机。&lt;/li&gt;
&lt;li&gt;查询内存超阈值时，部分中间结果&lt;strong&gt;溢写（spill）到磁盘&lt;/strong&gt;，腾出内存继续算，而不是 OOM。&lt;/li&gt;
&lt;li&gt;用 &lt;code&gt;memory_limit&lt;/code&gt; 约束查询，避免&quot;一山不容二虎&quot;。&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;关键&lt;/strong&gt;：spill 上限调太高=磁盘 IO 拖慢；太低=频繁溢写。要在&quot;内存省&quot;和&quot;磁盘 IO&quot;间平衡。&lt;/p&gt;
&lt;h2&gt;④ 最小可复现&lt;/h2&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;-- 会话级限制查询内存
SET exec_mem_limit = 2147483648;  -- 2GB
-- 观察
SHOW PROCESSLIST;
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;⑤ 结论&lt;/h2&gt;
&lt;blockquote&gt;
&lt;p&gt;Doris 处理大查询不是硬扛，是&quot;该溢磁盘就溢磁盘&quot;。看懂它，你才敢放开跑大查询，而不是怕它崩。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;⑥ 配图脚本&lt;/h2&gt;
&lt;p&gt;内存水位线 / spill 到磁盘示意 / exec_mem_limit 调参 / 平衡曲线&lt;/p&gt;
&lt;hr&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>高并发点查：谁说 Doris 只能做 OLAP？</title><link>https://realcpf.tech/blog/doris-08</link><guid isPermaLink="true">https://realcpf.tech/blog/doris-08</guid><description>SELECT v FROM kv WHERE k = &apos;abc&apos;; -- 走前缀索引，短查询</description><pubDate>Tue, 01 Sep 2026 14:00:00 GMT</pubDate><content:encoded>&lt;h2&gt;① 标题党&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;主标题&lt;/strong&gt;：&lt;code&gt;Doris 只配跑报表？它的高并发点查打脸了多少人&lt;/code&gt;
&lt;strong&gt;备选&lt;/strong&gt;：&lt;code&gt;百万 QPS 点查，Doris 也能顶？这份优化你抄一下&lt;/code&gt;&lt;/p&gt;
&lt;h2&gt;② 开场钩子&lt;/h2&gt;
&lt;p&gt;都说 Doris 是 OLAP（分析型），做不了高并发在线查询。可部署得当，它单条主键查询也能扛住很高 QPS。秘密在&quot;点查怎么走最短路径&quot;。&lt;/p&gt;
&lt;h2&gt;③ 主角特性：点查优化（Unique/主键 + 前缀索引）&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;用 &lt;strong&gt;Unique 模型 / 主键模式&lt;/strong&gt;，按主键建排序键 → &lt;strong&gt;前缀索引直接定位&lt;/strong&gt;，不扫全表。&lt;/li&gt;
&lt;li&gt;高并发下走 &lt;strong&gt;短查询短路径&lt;/strong&gt;，命中索引直接返回。&lt;/li&gt;
&lt;li&gt;结合内存表/复制表提升点查并发。&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;④ 最小可复现&lt;/h2&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;CREATE TABLE kv (
  k VARCHAR(32), v VARCHAR(128)
) UNIQUE KEY(k) DISTRIBUTED BY HASH(k) BUCKETS 32;

SELECT v FROM kv WHERE k = &apos;abc&apos;;  -- 走前缀索引，短查询
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;⑤ 结论&lt;/h2&gt;
&lt;blockquote&gt;
&lt;p&gt;别低估 Doris：主键点查 + 前缀索引 + 短路径，它就是能扛并发。OLAP 和点查，Doris 都能给你。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;⑥ 配图脚本&lt;/h2&gt;
&lt;p&gt;主键定位 / 前缀索引直达 / QPS 对比 / 内存表提升并发&lt;/p&gt;
&lt;hr&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>Stream Load：大数据进 Doris 的&apos;高速通道&apos;</title><link>https://realcpf.tech/blog/doris-07</link><guid isPermaLink="true">https://realcpf.tech/blog/doris-07</guid><description>取舍：实时高频→Stream Load；超大离线 → Broker Load + 分区。</description><pubDate>Tue, 01 Sep 2026 13:00:00 GMT</pubDate><content:encoded>&lt;h2&gt;① 标题党&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;主标题&lt;/strong&gt;：&lt;code&gt;数据导入慢？Doris 的 Stream Load 是一道闪电&lt;/code&gt;
&lt;strong&gt;备选&lt;/strong&gt;：&lt;code&gt;同样导数据，为什么 Doris 能流水线式跑？&lt;/code&gt;&lt;/p&gt;
&lt;h2&gt;② 开场钩子&lt;/h2&gt;
&lt;p&gt;百万行数据要进 Doris，有人导到崩溃，有人秒入库。差的不是带宽，是你没用对导入通道。&lt;/p&gt;
&lt;h2&gt;③ 主角特性：Stream Load / Broker Load&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Stream Load&lt;/strong&gt;：HTTP 直连 BE，&lt;strong&gt;流式写入&lt;/strong&gt;，一条命令搞定小批量/实时（几十 MB 级秒导）。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Broker Load&lt;/strong&gt;：走 Broker（读外部文件系统 S3/HDFS），适合大批量离线。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;管道化写入&lt;/strong&gt;：数据边读边写，不落中间盘，减少滞留。&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;取舍&lt;/strong&gt;：实时高频→Stream Load；超大离线 → Broker Load + 分区。&lt;/p&gt;
&lt;h2&gt;④ 最小可复现&lt;/h2&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;curl --location-trusted -u root: \
  -H &quot;label:load_001&quot; -H &quot;column_separator:,&quot; \
  -T data.csv \
  http://&amp;#x3C;BE_HOST&gt;:8040/api/db/table/_stream_load
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;⑤ 结论&lt;/h2&gt;
&lt;blockquote&gt;
&lt;p&gt;Stream Load 是 Doris 的 HTTP 高速通道，边读边写、管道化。选对通道，导入从&quot;卡死&quot;变&quot;闪电&quot;。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;⑥ 配图脚本&lt;/h2&gt;
&lt;p&gt;HTTP 直连 BE / 管道流 / Broker 外部读 / 实时 vs 批量对比&lt;/p&gt;
&lt;hr&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>BE/FE 高可用：Doris 集群&apos;挂了也能活&apos;</title><link>https://realcpf.tech/blog/doris-06</link><guid isPermaLink="true">https://realcpf.tech/blog/doris-06</guid><description> ① 标题党 主标题：Doris 集群 FE 挂了怎么办？它其实早就想好退路 备选：单点故障最可怕，Doris 却用&apos;选主&apos;躲过去了</description><pubDate>Tue, 01 Sep 2026 12:00:00 GMT</pubDate><content:encoded>&lt;h2&gt;① 标题党&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;主标题&lt;/strong&gt;：&lt;code&gt;Doris 集群 FE 挂了怎么办？它其实早就想好退路&lt;/code&gt;
&lt;strong&gt;备选&lt;/strong&gt;：&lt;code&gt;单点故障最可怕，Doris 却用&quot;选主&quot;躲过去了&lt;/code&gt;&lt;/p&gt;
&lt;h2&gt;② 开场钩子&lt;/h2&gt;
&lt;p&gt;再稳的集群也有宕机。但 Doris 能在 FE 挂掉、BE 挂掉的时候&lt;strong&gt;继续服务&lt;/strong&gt;，不是因为命好，是它背后有一套存活机制。&lt;/p&gt;
&lt;h2&gt;③ 主角特性：FE 集群选主 + BE 心跳/副本均衡&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;FE（Frontend，元数据/查询入口）&lt;/strong&gt;：多个 FE 组成集群，通过 &lt;strong&gt;选举选主&lt;/strong&gt;（leader），主挂自动晋升 follower 继续对外。元数据靠 journal 同步。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;BE（Backend，数据节点）&lt;/strong&gt;：通过&lt;strong&gt;心跳&lt;/strong&gt;上报存活；数据靠&lt;strong&gt;多副本&lt;/strong&gt;（replication_num=3 默认）冗余。&lt;/li&gt;
&lt;li&gt;副本在 BE 之间&lt;strong&gt;自动均衡&lt;/strong&gt;，某台挂了，其他副本顶上。&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;④ 最小可复现&lt;/h2&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;-- 看 FE 集群状态
SHOW FRONTENDS;
-- 看 BE 健康/副本
SHOW BACKENDS;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;（生产建议：FE ≥ 3 个（奇数），BE ≥ 3 台，replication 3）&lt;/p&gt;
&lt;h2&gt;⑤ 结论&lt;/h2&gt;
&lt;blockquote&gt;
&lt;p&gt;Doris 的高可用不是玄学：FE 靠选主、BE 靠心跳+副本均衡。看懂这套，你才能放心把集群&quot;睡安稳&quot;。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;⑥ 配图脚本&lt;/h2&gt;
&lt;p&gt;FE 选主流程 / BE 心跳 / 副本冗余 / 均衡布局&lt;/p&gt;
&lt;hr&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>索引三兄弟：前缀索引、BloomFilter、倒排</title><link>https://realcpf.tech/blog/doris-05</link><guid isPermaLink="true">https://realcpf.tech/blog/doris-05</guid><description>- BloomFilter PROPERTIES (&apos;bloom_filter_columns&apos; = &apos;name&apos;);</description><pubDate>Tue, 01 Sep 2026 11:00:00 GMT</pubDate><content:encoded>&lt;h2&gt;① 标题党&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;主标题&lt;/strong&gt;：&lt;code&gt;Doris 查询慢？先看看它有没有&quot;小众索引&quot;&lt;/code&gt;
&lt;strong&gt;备选&lt;/strong&gt;：&lt;code&gt;前缀索引、布隆、倒排——Doris 的索引三兄弟谁最能打？&lt;/code&gt;&lt;/p&gt;
&lt;h2&gt;② 开场钩子&lt;/h2&gt;
&lt;p&gt;Doris 有三大&quot;隐形加速器&quot;，但很多人只会建表、不会用它们。用对了，查询快一个量级；用错了，白占空间。&lt;/p&gt;
&lt;h2&gt;③ 主角特性：三类索引&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;前缀索引（ShortKey Index）&lt;/strong&gt;：排序键的前缀自动生效，等值/范围查询直接定位，零成本。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;BloomFilter 索引&lt;/strong&gt;：对&quot;高基数、低命中率&quot;列加，先做存在性过滤，&lt;strong&gt;大比例剪枝&lt;/strong&gt;。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;倒排索引（Inverted Index）&lt;/strong&gt;：自 1.2 起支持，用于&lt;strong&gt;全文/子串/精确匹配&lt;/strong&gt;，如日志检索。&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;④ 最小可复现&lt;/h2&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;-- 排序键=前缀索引（建表时排序键顺序决定）
CREATE TABLE t (id, name, val) ORDER BY (id, name);

-- BloomFilter
PROPERTIES (&quot;bloom_filter_columns&quot; = &quot;name&quot;);

-- 倒排
CREATE INDEX idx_name ON t(name) USING INVERTED;
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;⑤ 结论&lt;/h2&gt;
&lt;blockquote&gt;
&lt;p&gt;前缀索引白送、布隆剪枝、倒排抓文本。把三者对症下药，Doris 的扫描成本能砍一个数量级。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;⑥ 配图脚本&lt;/h2&gt;
&lt;p&gt;三兄弟对比卡 / 前缀定位图谱 / 布隆剪枝示意 / 倒排查找文本&lt;/p&gt;
&lt;hr&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>Compaction：小文件太多的&apos;Doris 保洁阿姨&apos;</title><link>https://realcpf.tech/blog/doris-04</link><guid isPermaLink="true">https://realcpf.tech/blog/doris-04</guid><description>坑：写入速率远大于合并速率时，会出现&apos;合并跟不上&apos;，进入导入降级/拒绝 —— 这是生产里最常见的 Doris 事故之一。</description><pubDate>Tue, 01 Sep 2026 10:00:00 GMT</pubDate><content:encoded>&lt;h2&gt;① 标题党&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;主标题&lt;/strong&gt;：&lt;code&gt;Doris 小文件爆炸？Compaction 这个保洁阿姨你必须认识&lt;/code&gt;
&lt;strong&gt;备选&lt;/strong&gt;：&lt;code&gt;写了一天数据，Doris 卡了？它在偷偷&quot;合文件&quot;&lt;/code&gt;&lt;/p&gt;
&lt;h2&gt;② 开场钩子&lt;/h2&gt;
&lt;p&gt;数据是流式导进来的，越导文件越多、越碎。不收拾，查询会越来越慢。Doris 有一个&lt;strong&gt;后台保洁机制&lt;/strong&gt;在默默把碎文件合并成大块——它就是 Compaction。&lt;/p&gt;
&lt;h2&gt;③ 主角特性：Compaction 机制&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;LSM 式多版本&lt;/strong&gt;：每次导入生成一个小版本（memtable → 磁盘）&lt;/li&gt;
&lt;li&gt;Compaction 把多个小版本&lt;strong&gt;合并成一个大版本&lt;/strong&gt;，减少读取时的文件数、垃圾数据&lt;/li&gt;
&lt;li&gt;触发方式：累积量/时间/大小基数触发&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;坑&lt;/strong&gt;：写入速率远大于合并速率时，会出现&quot;合并跟不上&quot;，进入导入降级/拒绝 —— 这是生产里最常见的 Doris 事故之一。&lt;/p&gt;
&lt;h2&gt;④ 最小可复现&lt;/h2&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;SHOW TABLES FROM db;  -- 看 tablet 版本计数
-- 手动触发一次 compaction
CANCEL ALTER TABLE ...;  -- 误区
-- 正确：通过 BE 配置 / 等待后台合并
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;（核心是看懂 version count 与 compaction backlog）&lt;/p&gt;
&lt;h2&gt;⑤ 结论&lt;/h2&gt;
&lt;blockquote&gt;
&lt;p&gt;Compaction 是 Doris 的隐形保洁阿姨。它不干活，查询就开始吃灰。看懂它，你才能避开&quot;写太快把 Doris 写崩&quot;的坑。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;⑥ 配图脚本&lt;/h2&gt;
&lt;p&gt;LSM 版本时间线 / 合并示意 / version 计数监控 / 写放大 vs 读放大&lt;/p&gt;
&lt;hr&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>Rollup 与物化索引：Doris 的&apos;预计算魔法&apos;</title><link>https://realcpf.tech/blog/doris-03</link><guid isPermaLink="true">https://realcpf.tech/blog/doris-03</guid><description>多个 Rollup 对应不同聚合维度（城市级/每日级/用户级） - 查询优化器自动选择命中的 Rollup（最贴合的那个） - 与物化索引（Materialized Index）的取舍点</description><pubDate>Tue, 01 Sep 2026 09:00:00 GMT</pubDate><content:encoded>&lt;h2&gt;① 标题党&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;主标题&lt;/strong&gt;：&lt;code&gt;Rollup 是什么鬼？Doris 的&quot;预计算&quot;魔法一次讲透&lt;/code&gt;
&lt;strong&gt;备选&lt;/strong&gt;：&lt;code&gt;你的 Doris 查询慢？八成是没让 Rollup 把活干了&lt;/code&gt;&lt;/p&gt;
&lt;h2&gt;② 开场钩子&lt;/h2&gt;
&lt;p&gt;同样一条聚合查询，有人跑 3 秒，有人 3 毫秒。差的不是机器，是你没让 Doris 把结果&lt;strong&gt;提前算好&lt;/strong&gt;。&lt;/p&gt;
&lt;h2&gt;③ 主角特性：Rollup 表（物化视图）&lt;/h2&gt;
&lt;p&gt;Rollup 本质是&lt;strong&gt;预聚合的物化视图&lt;/strong&gt;：你在明细表上定义一个 Rollup，Doris 在你导入数据时，&lt;strong&gt;顺带把这张预聚合表算好&lt;/strong&gt;。查询如果命中 Rollup，直接读结果，不扫明细。&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;多个 Rollup 对应不同聚合维度（城市级/每日级/用户级）&lt;/li&gt;
&lt;li&gt;查询优化器自动&lt;strong&gt;选择命中的 Rollup&lt;/strong&gt;（最贴合的那个）&lt;/li&gt;
&lt;li&gt;与物化索引（Materialized Index）的取舍点&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;④ 最小可复现&lt;/h2&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;ALTER TABLE orders ADD ROLLUP r_cnt (city, count(*));
ALTER TABLE orders ADD ROLLUP r_amt (city, sum(amount));

-- 优化器命中 r_amt
SELECT city, sum(amount) FROM orders GROUP BY city;
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;⑤ 结论&lt;/h2&gt;
&lt;blockquote&gt;
&lt;p&gt;Rollup = 用&quot;写入时多一点成本&quot;换&quot;查询时快几个量级&quot;。Doris 的聪明，是帮你把重活提前干完。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;⑥ 配图脚本&lt;/h2&gt;
&lt;p&gt;预聚合时间轴 / 明细→Rollup 派生 / 查询命中示意 / 多 Rollup 选择&lt;/p&gt;
&lt;hr&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>分区分桶：超大表的&apos;强迫症收纳术&apos;</title><link>https://realcpf.tech/blog/doris-02</link><guid isPermaLink="true">https://realcpf.tech/blog/doris-02</guid><description>关键：分桶列选错，热点就会压垮单个 BE；选对，扫描天然并行。</description><pubDate>Tue, 01 Sep 2026 08:00:00 GMT</pubDate><content:encoded>&lt;h2&gt;① 标题党&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;主标题&lt;/strong&gt;：&lt;code&gt;一张表存千亿行？Doris 的分区分桶能让强迫症狂喜&lt;/code&gt;
&lt;strong&gt;备选&lt;/strong&gt;：&lt;code&gt;别人建表是写 SQL，你建表是给数据&quot;分房&quot;？&lt;/code&gt;&lt;/p&gt;
&lt;h2&gt;② 开场钩子&lt;/h2&gt;
&lt;p&gt;业务表动辄百亿行，可 Doris 查起来还是快。为什么呢？因为它建表时——不是把数据一股脑堆一块，而是&lt;strong&gt;先给你分了房、再排了队&lt;/strong&gt;。&lt;/p&gt;
&lt;h2&gt;③ 主角特性：Range 分区 + Hash 分桶&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Range 分区&lt;/strong&gt;：按时间/值域切大块（如按天/月），查询 &lt;code&gt;WHERE date=...&lt;/code&gt; 直接跳过无关分区（分区裁剪）。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Hash 分桶&lt;/strong&gt;：分区内部再按某列哈希切成固定桶，让数据均匀分布到多个 BE，配合分布式并行扫描。&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;关键&lt;/strong&gt;：分桶列选错，热点就会压垮单个 BE；选对，扫描天然并行。&lt;/p&gt;
&lt;h2&gt;④ 最小可复现&lt;/h2&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;CREATE TABLE events (
  id BIGINT, ts DATETIME, city VARCHAR(16), ...
)
PARTITION BY RANGE(ts) (...);       -- 按时间分区
DISTRIBUTED BY HASH(city) BUCKETS 16 -- 按城市分桶
PROPERTIES (&quot;replication_num&quot; = &quot;3&quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;⑤ 结论&lt;/h2&gt;
&lt;blockquote&gt;
&lt;p&gt;分区管&quot;跳过&quot;，分桶管&quot;并行&quot;。Doris 的建表，本质是让&lt;strong&gt;每一次查询天然走捷径&lt;/strong&gt;。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;⑥ 配图脚本&lt;/h2&gt;
&lt;p&gt;分区=切蛋糕 / 分桶=Hash 漏斗 / 分区裁剪示意 / 不均匀热点 vs 均匀对比&lt;/p&gt;
&lt;hr&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>Count(*) 一秒算完的秘密</title><link>https://realcpf.tech/blog/doris-01</link><guid isPermaLink="true">https://realcpf.tech/blog/doris-01</guid><description>反常识现象：MySQL 的 count() 要逐行扫整张表数一遍，一亿行 = 一亿次累加。</description><pubDate>Tue, 01 Sep 2026 07:00:00 GMT</pubDate><content:encoded>&lt;h2&gt;① 标题党&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;主标题&lt;/strong&gt;：&lt;code&gt;Doris 凭什么敢对 Count(*) 说：一秒给你算完？&lt;/code&gt;
&lt;strong&gt;备选A&lt;/strong&gt;：&lt;code&gt;同样是 Count(*)，为什么 Doris 快，MySQL 就歇菜？&lt;/code&gt;
&lt;strong&gt;备选B（短视频）&lt;/strong&gt;：&lt;code&gt;Doris：论查数，我不是针对谁&lt;/code&gt;&lt;/p&gt;
&lt;h2&gt;② 开场钩子（30 秒）&lt;/h2&gt;
&lt;p&gt;你有没有想过——同样是 &lt;code&gt;SELECT count(*) FROM 一张一亿行的表&lt;/code&gt;，MySQL 要跑几十秒，Doris 却一秒内搞定。它凭什么？是魔法，还是它查数时……偷偷干了什么？&lt;/p&gt;
&lt;h2&gt;③ 主角特性：列式存储 + Rollup 预聚合&lt;/h2&gt;
&lt;p&gt;今天只讲一个点：&lt;strong&gt;Doris 的 COUNT 为什么快——列式存储 + 前缀聚合。&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;反常识现象&lt;/strong&gt;：MySQL 的 &lt;code&gt;count(*)&lt;/code&gt; 要&lt;strong&gt;逐行扫&lt;/strong&gt;整张表数一遍，一亿行 = 一亿次累加。&lt;/p&gt;
&lt;p&gt;Doris 干了两件事：&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;列式存储&lt;/strong&gt;：数据一列一列排，&lt;code&gt;count(*)&lt;/code&gt; 只需知道&quot;有几行&quot;，&lt;strong&gt;不碰无关列&lt;/strong&gt;。MySQL 行式，整行挤一起，查个数也得读全行。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Rollup 预聚合（真·魔法）&lt;/strong&gt;：把 &lt;code&gt;count&lt;/code&gt; 结果&lt;strong&gt;提前算好存起来&lt;/strong&gt;。&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;④ 最小可复现&lt;/h2&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;-- 原表
CREATE TABLE orders (...);

-- 提前算好 count 的 Rollup
ALTER TABLE orders ADD ROLLUP r1 (city, count(*));

-- 查询命中 Rollup，直接取预聚合结果
SELECT city, count(*) FROM orders GROUP BY city;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;命中 Rollup 后，查询从&quot;扫全表&quot;变成&quot;读一行预聚合&quot;，几十到几百倍差距。&lt;/p&gt;
&lt;h2&gt;⑤ 结论&lt;/h2&gt;
&lt;blockquote&gt;
&lt;p&gt;Doris 的 Count 快，不是它算得快，是它&lt;strong&gt;早就算好了&lt;/strong&gt;——列存储省读取，Rollup 省重算。它把功夫下在你看不见的地方。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;⑥ 配图脚本&lt;/h2&gt;
&lt;p&gt;| 帧 | 画面 | 文案 |
|:--:|------|------|
| 1 | 黑底金字大标题 | Doris 凭啥 1 秒查完 Count? |
| 2 | 左右对比：逐行扫 vs 列式 | 行式 vs 列式 |
| 3 | Rollup 预聚合小卡片 | Rollup = 提前算好 |
| 4 | 代码特写 | ADD ROLLUP |
| 5 | 金句卡 | 功夫在你看不见的地方 |&lt;/p&gt;
&lt;hr&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>用 DeepSeek Harness 二开你自己的 WorkBuddy：Agent 运行时作为平台底座</title><link>https://realcpf.tech/blog/dsh-agent-runtime</link><guid isPermaLink="true">https://realcpf.tech/blog/dsh-agent-runtime</guid><description>适用场景 / 应用范围：本文面向「想基于开源 Agent 框架构建自有智能应用」的架构师与开发者。核心观点：Agent 框架的价值不止于「写插件给 agent 用」，更在于把整个 agent 运行时当成自己产品的底座——类比当年基于 Spring Boot 搭业务系统、基于低代码引擎搭表单应用。文章</description><pubDate>Sun, 16 Aug 2026 02:00:00 GMT</pubDate><content:encoded>&lt;blockquote&gt;
&lt;p&gt;适用场景 / 应用范围：本文面向「想基于开源 Agent 框架构建自有智能应用」的架构师与开发者。核心观点：Agent 框架的价值不止于「写插件给 agent 用」，更在于&lt;strong&gt;把整个 agent 运行时当成自己产品的底座&lt;/strong&gt;——类比当年基于 Spring Boot 搭业务系统、基于低代码引擎搭表单应用。文章以腾讯 WorkBuddy 为参照，逐模块拆解「用 dsh 做出一台差不多的 WorkBuddy」需要什么样的二开，最后给出「智能数据工作台」的个人实践与开源计划。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;一、问题：Agent 框架的二开，我们只解锁了 10%&lt;/h2&gt;
&lt;p&gt;2026 年的 Agent 生态有个显著现象：框架越来越多，教程越来越卷，但九成内容停留在同一个层次——&lt;strong&gt;教你怎么给某个框架写一个插件&lt;/strong&gt;。&lt;/p&gt;
&lt;p&gt;以 DeepSeek Harness（&lt;code&gt;dsh&lt;/code&gt;，v0.1.0-rc.5，基于 Cordis 的万物皆插件架构）为例：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;官方文档铺开就是「怎么写一个 tool 插件」「怎么写一个 provider 插件」「怎么声明一个 ctx.* 能力缝」&lt;/li&gt;
&lt;li&gt;社区讨论也集中在「给 agent 加个工具」「接个新数据源」&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;这当然有价值，但它只是&lt;strong&gt;框架使用者的视角&lt;/strong&gt;。很少有人从&lt;strong&gt;平台所有者的视角&lt;/strong&gt;问一个问题：&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;能不能不把 Agent 框架当成「一个 agent」，而是当成「一个可以承载我自己产品的运行时」？&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;类比一下：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;低代码时代&lt;/strong&gt;：低代码引擎不只是「做表单的工具」，它是「应用运行时底座」——你基于它二开，生成自己的行业应用。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;微服务时代&lt;/strong&gt;：Spring Boot 不只是「写接口的框架」，它是「业务系统底座」——你基于它二开，构建自己的业务平台。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Agent 时代&lt;/strong&gt;：dsh 这类框架，同样应该成为「智能应用底座」——你基于它二开，构建自己的智能工作台/智能枢纽/智能平台。&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;从传播度上看 &lt;strong&gt;WorkBuddy特别火&lt;/strong&gt;，本质上就是这条路线的商业验证：&lt;strong&gt;以 Agent 运行时为底座，挂载办公领域的业务能力&lt;/strong&gt;。本文将拆开它，看看用开源的 dsh 做出一台「差不多的 WorkBuddy」，到底需要什么样的二开。&lt;/p&gt;
&lt;h2&gt;二、约束：为什么这个想法现在才成立&lt;/h2&gt;
&lt;p&gt;在展开方案之前，先明确几个约束，它们决定了「以 agent 为底座」不是一句口号：&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;dsh 是 developer preview&lt;/strong&gt;。README 第一行就写着「THERE WILL BE COMPATIBILITY-BREAKING CHANGES」。把它当生产底座，必须接受「版本锁死 + 隔离升级」的策略，不能指望 API 稳定。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Agent 框架的能力边界在「编排」，不在「业务领域」&lt;/strong&gt;。它给你的是：agent 循环、工具注册表、会话事件日志、审批/沙箱、定时与工作流、SDK 驱动。它不给你：办公语义、企业知识库、连接器生态、业务前端。这些必须自研。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;智能平台的核心资产是「可审计、可追溯」&lt;/strong&gt;。好在这个约束 dsh 天然满足——它的 Session 是 append-only 事件日志，LLM 消息历史都是从日志派生的，这恰好是操作审计与业务溯源想要的底座。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;受限环境部署&lt;/strong&gt;。我们所在的环境强调内网/资源受限/全离线，这意味着运行时必须可静态分发、可离线运行——dsh 的 headless 模式无服务器无端口，SDK 通过 stdio JSON-RPC 驱动，天生适合。&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;三、架构级描绘：运行时底座到底提供什么&lt;/h2&gt;
&lt;p&gt;把 Agent 框架当底座，首先要看清它作为「运行时」提供了哪些可依赖的契约。以 dsh 为例，从架构级别拆解：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;┌─────────────────────────────────────────────────────┐
│              你的业务应用（领域层）                    │
│   办公能力 / 数据能力 / 生产模型 / 业务前端（自研）     │
├─────────────────────────────────────────────────────┤
│             Agent 运行时底座（dsh）                   │
│  ┌─────────┬──────────┬──────────┬───────────────┐  │
│  │ 规范契约  │ 集成能力  │ 扩展机制  │ 运维与安全      │  │
│  │ Service │ SDK驱动  │ 插件挂载  │ 会话事件日志     │  │
│  │ 声明式   │ JSON-RPC │ 工具注册  │ 审批/权限/沙箱   │  │
│  │ inject  │ headless │ provider │ 定时/工作流      │  │
│  └─────────┴──────────┴──────────┴───────────────┘  │
├─────────────────────────────────────────────────────┤
│        模型适配层（DeepSeek 系 / 可替换）              │
└─────────────────────────────────────────────────────┘
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;3.1 规范契约：不是 API 是「协议」&lt;/h3&gt;
&lt;p&gt;运行时底座和普通 SDK 的本质区别，是它给出的不是「函数调用」，而是&lt;strong&gt;可组合的规范&lt;/strong&gt;：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Service 声明式依赖（inject）&lt;/strong&gt;：插件声明 &lt;code&gt;inject: [&apos;tools&apos;, &apos;sessions&apos;]&lt;/code&gt;，运行时按依赖关系装配——你的业务模块可以声明「我需要 agent 循环」，而不是手动拼装。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;事件协议（Event）&lt;/strong&gt;：emit / waterfall / parallel / serial 四种派发模式，业务可以「观察」agent 的行为（审计）、「包装」agent 的结果（增强）、「拦截」agent 的请求（策略）。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;可逆效果（Effect）&lt;/strong&gt;：所有注册都是可回滚的——业务模块卸载时，它注册的工具、监听器、prompt 段自动消失，不会污染运行时。&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;这套规范意味着：&lt;strong&gt;你的业务逻辑可以「长」在运行时上，而不是「绑」在运行时里&lt;/strong&gt;。&lt;/p&gt;
&lt;h3&gt;3.2 集成能力：三种嵌入姿势&lt;/h3&gt;
&lt;p&gt;| 姿势 | 方式 | 适用场景 |
|-|-|-|
| &lt;strong&gt;A. 工具注入&lt;/strong&gt; | 业务能力注册为 &lt;code&gt;ctx.tools&lt;/code&gt; 的工具 | 给 agent 加「手」——让 agent 能调你的查询引擎、能操作你的业务系统 |
| &lt;strong&gt;B. Provider 扩展&lt;/strong&gt; | 业务实现能力缝的 provider | 给 agent 换「传感器」——新的数据源、新的模型、新的搜索后端 |
| &lt;strong&gt;C. SDK 驱动&lt;/strong&gt; | 外部进程通过 JSON-RPC/stdio 驱动 headless 运行时 | 你的产品是主框架，agent 是「大脑」——最推荐的二开姿势 |&lt;/p&gt;
&lt;h3&gt;3.3 扩展机制：能力缝（Seam）&lt;/h3&gt;
&lt;p&gt;dsh 的插件系统把「可扩展点」显式化为一组能力缝：&lt;code&gt;ctx.tools&lt;/code&gt;（工具）、&lt;code&gt;ctx.llm&lt;/code&gt;（模型）、&lt;code&gt;ctx.web&lt;/code&gt;（搜索/抓取）、&lt;code&gt;ctx.shell&lt;/code&gt;（命令）、&lt;code&gt;ctx.sessions&lt;/code&gt;（会话）、&lt;code&gt;ctx.subagents&lt;/code&gt;（子代理）、&lt;code&gt;ctx.schedule&lt;/code&gt;（定时）……每个缝都是&lt;strong&gt;注册表 + 选择器&lt;/strong&gt;：注册多个 provider，运行时按配置挑选。&lt;/p&gt;
&lt;p&gt;这是「底座」的典型特征：&lt;strong&gt;核心稳定、边界清晰、扩展点显式化&lt;/strong&gt;——和 Spring 的 Bean 容器、低代码引擎的组件库是同一个思想。&lt;/p&gt;
&lt;h2&gt;四、用 dsh 二开一台「差不多的 WorkBuddy」&lt;/h2&gt;
&lt;h3&gt;4.1 WorkBuddy 是什么&lt;/h3&gt;
&lt;p&gt;腾讯 WorkBuddy是企业级 AI 智能工作平台，核心能力五大模块：&lt;/p&gt;
&lt;p&gt;| 模块 | 能力 |
|-|-|
| &lt;strong&gt;自然语言交互&lt;/strong&gt; | 对话式指令操作办公软件（创建文档、安排日程、查询数据） |
| &lt;strong&gt;AI Agent 编排&lt;/strong&gt; | 创建自定义 Agent，串联多步任务（收集周报→汇总表格→发送邮件） |
| &lt;strong&gt;企业知识库&lt;/strong&gt; | 对接内部文档/CRM/ERP，私有数据问答与生成 |
| &lt;strong&gt;跨应用自动化&lt;/strong&gt; | 连接腾讯文档/企业微信/会议，审批、提醒、流程触发 |
| &lt;strong&gt;多终端适配&lt;/strong&gt; | PC + 移动端，与企业微信深度集成 |&lt;/p&gt;
&lt;p&gt;它的本质：&lt;strong&gt;以 Agent 运行时为底座 + 办公领域能力挂载&lt;/strong&gt;。下面逐模块看 dsh 怎么二开实现。&lt;/p&gt;
&lt;h3&gt;4.2 逐模块二开对照：dsh 版 WorkBuddy&lt;/h3&gt;
&lt;p&gt;| WorkBuddy 模块 | dsh 实现方式 | 二开工作量 |
|-|-|-|
| &lt;strong&gt;自然语言交互&lt;/strong&gt; | dsh 的 agent 循环天然支持多轮对话；&lt;code&gt;ask_user_question&lt;/code&gt; 工具做澄清；前端自建聊天 UI，通过 SDK 连 headless 运行时 | ⭐ 小（底座已有） |
| &lt;strong&gt;AI Agent 编排&lt;/strong&gt; | &lt;code&gt;ctx.subagents&lt;/code&gt; 子代理 + &lt;code&gt;workflow&lt;/code&gt; 插件编排多步任务；&lt;code&gt;todo&lt;/code&gt; 工具做任务管理；agent 循环自动处理「收集→汇总→发送」的串联 | ⭐ 小（底座已有） |
| &lt;strong&gt;企业知识库&lt;/strong&gt; | 自研 &lt;code&gt;knowledge&lt;/code&gt; 插件：文档解析 → 向量化 → 存向量库；注册 &lt;code&gt;retrieve&lt;/code&gt; 工具让 agent 能 RAG 检索；知识权限对接你的认证体系 | ⭐⭐⭐（领域自研） |
| &lt;strong&gt;跨应用自动化&lt;/strong&gt; | &lt;code&gt;schedule&lt;/code&gt; 插件做定时触发；&lt;code&gt;workflow&lt;/code&gt; 做流程编排；&lt;strong&gt;业务连接器写成工具插件&lt;/strong&gt;（如 &lt;code&gt;send_wecom&lt;/code&gt;、&lt;code&gt;create_doc&lt;/code&gt;、&lt;code&gt;query_crm&lt;/code&gt;）——这正是「工具注入」姿势 | ⭐⭐（写连接器） |
| &lt;strong&gt;审批节点&lt;/strong&gt; | dsh 自带 &lt;code&gt;interaction/approval&lt;/code&gt; 能力 + &lt;code&gt;user-questions&lt;/code&gt; 缝——agent 到审批节点暂停，等人确认再继续 | ⭐ 小（底座已有） |
| &lt;strong&gt;多终端&lt;/strong&gt; | headless + SDK 无 UI 依赖：Web/移动端/CLI 都通过 JSON-RPC 驱动同一个运行时 | ⭐ 小 |
| &lt;strong&gt;审计与安全&lt;/strong&gt; | Session 事件日志天然记录全部操作；权限预设（read-only / workspace-write / danger-full-access）做分级控制 | ⭐ 免费获得 |&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;核心结论：WorkBuddy 的「Agent 部分」几乎全是 dsh 底座现成的，你要二开的是「业务连接器」和「知识库」两个领域模块。&lt;/strong&gt;&lt;/p&gt;
&lt;h3&gt;4.3 最小可跑示例：一个「会查数据的 WorkBuddy」&lt;/h3&gt;
&lt;p&gt;用 SDK 驱动一个 headless agent，注册一个查询工具，就是 WorkBuddy 的最小雏形：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;from deepseek_harness import DeepSeekHarness

with DeepSeekHarness(
    model=&quot;deepseek-v4-flash&quot;,
    cwd=&quot;/workspace&quot;,
    cordis=&quot;examples/jsonrpc-agent/minimal.cordis.yml&quot;,
    runtime_bin=&quot;/path/to/packaged-bin.js&quot;,
) as harness:
    result = harness.run(&quot;查一下上周的销售数据，汇总成表格&quot;)
print(result.final_response)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;工具插件（把业务能力挂到 agent 上）：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;import { defineTool } from &apos;@deepseek-ai/dsh-tools&apos;

export const name = &apos;tool-sales-query&apos;
export const inject = [&apos;tools&apos;]

export function apply(ctx: Context): void {
  ctx.tools.register(defineTool({
    name: &apos;query_sales&apos;,
    description: &apos;查询销售数据（时间范围、区域）&apos;,
    parameters: {
      from: { type: &apos;string&apos;, required: true },
      region: { type: &apos;string&apos; }
    },
    async execute(args) {
      return await querySalesDB(args.from, args.region)  // 你的业务查询
    }
  }))
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;agent 接到「查销售数据」→ 调 &lt;code&gt;query_sales&lt;/code&gt; 工具 → 拿到结果 → 组织成表格回答。&lt;strong&gt;这就是 WorkBuddy 的对话式数据查询，半小时能跑通。&lt;/strong&gt;&lt;/p&gt;
&lt;h3&gt;4.4 同一底座，不同领域&lt;/h3&gt;
&lt;p&gt;WorkBuddy 是「办公」，同样的 dsh 底座可以挂：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;企业生产经营智能枢纽&lt;/strong&gt;：生产数据（设备 IoT、MES、能耗）→ 智能体实时分析 → 异常自动报警 → 生成处置建议 → 审批后下发执行。领域侧提供设备/产线/工单模型，agent 侧复用同一套循环。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;供应链智能枢纽&lt;/strong&gt;：库存/订单/物流 → 智能体推演 → 补货建议 → 联动 ERP。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;智能数据工作台&lt;/strong&gt;（个人案例，见下节）。&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;底座不变，变的是「挂载的领域模块」——这正是运行时底座最大的价值。&lt;/p&gt;
&lt;h2&gt;五、个人案例：智能数据工作台（即将开源）&lt;/h2&gt;
&lt;p&gt;以我自己的实践为例，说明这条二开路径的具体落地。目标是构建&lt;strong&gt;智能数据工作台&lt;/strong&gt;：数据源管理、实体管理、数据血缘、任务管理、智能查询、ChatBI。&lt;/p&gt;
&lt;h3&gt;架构：产品为核 + dsh 为 Agent 引擎&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;┌─────────────────────────────────────┐
│  智能数据工作台（我的产品）            │
│  ├─ 数据源 / 实体 / 血缘 / 任务（自研）│
│  ├─ 前端 UI                          │
│  └─ Agent 网关 ──JSON-RPC/SDK── dsh  │
│      （智能查询 / ChatBI 由 dsh agent 处理）│
└─────────────────────────────────────┘
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;工作台通过 dsh 的 Python SDK / JSON-RPC（stdio）起一个 headless agent 运行时，把「自然语言 → 规划 → 工具调用 → 回答」的整段智能逻辑托管给 dsh，业务侧只负责数据与界面。&lt;/p&gt;
&lt;h3&gt;为什么选「产品为核」而非「dsh 为核」&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;领域边界干净&lt;/strong&gt;。数据源管理、血缘、调度是数据工程问题，塞进 dsh 插件系统只会让两边都变复杂。业务归业务，agent 归 agent。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;隔离升级风险&lt;/strong&gt;。dsh 是 preview，产品为核下升级 dsh 只影响 Agent 网关；dsh 为核下升级等于重写产品。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;复用最值钱的能力&lt;/strong&gt;。要的不是 dsh 的表单和按钮，而是它的 agent 循环、工具执行管道、事件溯源日志、审批沙箱——这些恰好都是通过 SDK 暴露的。&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;核心壁垒：业务工具接入&lt;/h3&gt;
&lt;p&gt;工作台自己实现「多源联邦查询引擎」（DuckDB 插件化联邦：postgres_scanner / mysql_scanner / httpfs + 自研 HTTP API 表函数），然后把它&lt;strong&gt;注册成 dsh 的 tool 插件&lt;/strong&gt;：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;import { defineTool } from &apos;@deepseek-ai/dsh-tools&apos;

export const name = &apos;tool-duckquery&apos;
export const inject = [&apos;tools&apos;]

export function apply(ctx: Context): void {
  ctx.tools.register(defineTool({
    name: &apos;duckquery&apos;,
    description: &apos;对多数据源执行 SQL 查询（http/file/s3/jdbc），返回结果集&apos;,
    parameters: { sql: { type: &apos;string&apos;, required: true } },
    async execute(args) {
      return await runDuckQuery(args.sql)
    }
  }))
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;这一层就是「智能数据工作台」和普通 agent 的分水岭：&lt;strong&gt;agent 的大脑是通用的，工具是数据专属的&lt;/strong&gt;。&lt;/p&gt;
&lt;h3&gt;免费获得的审计与血缘&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;用户提问 &quot;上月华东区销售额&quot;
  → dsh agent 规划
  → 调 duckquery 工具执行 SQL
  → 引擎返回结果集
  → agent 组织自然语言回答
  → 整个过程写入 append-only SessionEvent 日志
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;每次 NL→SQL→结果→决策的链路天然留痕，后续做「查询级血缘」和操作审计时不需要额外埋点——dsh 的事件日志就是现成的数据源。&lt;/p&gt;
&lt;h3&gt;开源计划&lt;/h3&gt;
&lt;p&gt;这个项目我会在近期&lt;strong&gt;开源&lt;/strong&gt;：以 dsh 为 Agent 引擎 + 自研多源联邦查询层 + 事件日志血缘底座，三件套拼成一个「会思考、可追溯、能调度」的数据平台雏形。开源后欢迎大家在此基础上挂载自己的领域模块——这本身就是「运行时底座」理念的实践：&lt;strong&gt;核心稳定、边界清晰、扩展点开放&lt;/strong&gt;。&lt;/p&gt;
&lt;h2&gt;六、踩坑记录&lt;/h2&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;SDK runtime 找不到&lt;/strong&gt;：&lt;code&gt;Unable to locate the bundled DeepSeek Harness SDK runtime&lt;/code&gt;——SDK 默认要「捆绑运行时」，源码构建必须显式传 &lt;code&gt;runtime_bin&lt;/code&gt; 或 &lt;code&gt;launch_args_override&lt;/code&gt;。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;后台 shell 没有 pnpm/node&lt;/strong&gt;：fnm 管理的 node 在 multishell 路径里，cron/后台进程继承不到，必须显式 &lt;code&gt;export PATH=.../fnm/node-versions/v22.23.1/installation/bin:$PATH&lt;/code&gt;。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;沙箱默认拦截 bash&lt;/strong&gt;：headless 无审批通道，&lt;code&gt;workspace-write&lt;/code&gt; 模式下 bash 直接被拒（提示装 bubblewrap/Landlock）；二开跑真实任务要显式 &lt;code&gt;DSH_PERMISSION_MODE=danger-full-access&lt;/code&gt;，但这意味着把沙箱责任交还给产品层，&lt;strong&gt;必须自行补权限控制&lt;/strong&gt;。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;插件类名大小写是硬约束&lt;/strong&gt;：扩展生成器把扩展名 &lt;code&gt;linuxinfo&lt;/code&gt; 转成 &lt;code&gt;LinuxinfoExtension&lt;/code&gt;，类名写 &lt;code&gt;LinuxInfoExtension&lt;/code&gt; 会静态链接失败——生成器与源码的命名必须逐字符一致。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;preview 版本升级成本&lt;/strong&gt;：0.1.0-rc.x 之间 API 会变（SDK 的 runtime 契约、插件的 inject 签名），二开一定要锁版本、锁源码、留升级窗口。&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;七、总结&lt;/h2&gt;
&lt;p&gt;Agent 框架的二开价值，不在「多写几个插件」，而在「能不能把一个 agent 运行时，像数据库、像消息队列、像低代码引擎一样，当成平台的组成部分」。&lt;/p&gt;
&lt;p&gt;腾讯 WorkBuddy 已经证明了这个方向——「AI Agent 办公新范式」的本质，就是&lt;strong&gt;以 agent 运行时为底座，挂载办公领域的业务能力&lt;/strong&gt;。而本文的核心在于：&lt;strong&gt;用开源的 dsh，你也能二开出一台差不多的 WorkBuddy&lt;/strong&gt;——它的自然语言交互、Agent 编排、审批、审计全是底座现成的，你要写的只是「业务连接器」和「知识库」两个领域模块。&lt;/p&gt;
&lt;p&gt;同样的底座可以挂办公（WorkBuddy）、挂 CRM（Agentforce）、挂运维（ServiceNow）、挂生产经营（智能枢纽）、挂数据（我的工作台）。底座不变，变的是「挂载的领域模块」。&lt;/p&gt;
&lt;p&gt;dsh 在这件事上有几个难复制的底子：&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;万物皆插件&lt;/strong&gt;——业务工具、数据源 provider、审批策略都是可替换的挂载点；&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;事件溯源 Session&lt;/strong&gt;——agent 的每一次思考与工具调用都是 append-only 日志，天然满足审计与溯源；&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;headless + SDK&lt;/strong&gt;——无服务器、stdio 驱动，受限环境下可以像调用本地库一样把 agent 嵌进自己的产品。&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;技术会迭代，dsh 的 API 会变，但「以 agent 运行时为平台底座」这个思路，会是未来几年智能应用构建的主流姿势之一。早一步踩坑，就早一步拥有把 agent 变成基础设施的能力。&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;&lt;em&gt;明朗北街七万号·数研工坊 ｜ 扎根雄安新区中关村科技园，专注受限环境下软件搭建与数据平台落地&lt;/em&gt;&lt;/p&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>Grafana 监控大盘搭建与告警配置——让数据「看见」问题</title><link>https://realcpf.tech/blog/airgapped-grafana</link><guid isPermaLink="true">https://realcpf.tech/blog/airgapped-grafana</guid><description>明朗北街七万号·数研工坊｜扎根雄安新区中关村科技园，专注受限环境下软件搭建与数据平台落地</description><pubDate>Sat, 01 Aug 2026 03:30:00 GMT</pubDate><content:encoded>&lt;blockquote&gt;
&lt;p&gt;明朗北街七万号·数研工坊｜扎根雄安新区中关村科技园，专注受限环境下软件搭建与数据平台落地&lt;/p&gt;
&lt;/blockquote&gt;
&lt;hr&gt;
&lt;h2&gt;适用场景&lt;/h2&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;如果你属于以下任一种情况，这篇对你有用：&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;指标数据已经存到 VictoriaMetrics，但还停留在「命令行查」的阶段&lt;/li&gt;
&lt;li&gt;想一眼看清整个平台的健康状态（而不是一个个指标 curl）&lt;/li&gt;
&lt;li&gt;需要把监控数据可视化展示给团队或领导&lt;/li&gt;
&lt;li&gt;想让系统出问题时自动通知你（而不是你发现时已经炸了）&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;
&lt;p&gt;&lt;strong&gt;应用范围：&lt;/strong&gt; 监控体系的&lt;strong&gt;展示与告警层&lt;/strong&gt;。架构里的最后一环：Categraf（采集）→ VictoriaMetrics（存储）→ &lt;strong&gt;Grafana（展示+告警）&lt;/strong&gt;。本篇完成后，一套完整的 Metrics 可观测链路就通了。&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;架构定位（完整链路）&lt;/h2&gt;
&lt;pre&gt;&lt;code&gt;  Categraf ──► VictoriaMetrics ──► Grafana ──► 人
  (第9篇采集)   (第10篇存储)        (本篇展示)
                                     │
                                     ▼
                                   告警通知
                              (飞书/钉钉/邮件)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;到这里，监控体系的三件套就齐了。&lt;/strong&gt;&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;一、问题&lt;/h2&gt;
&lt;p&gt;数据在 VictoriaMetrics 里存着，你可以用 curl 查：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;curl &apos;http://127.0.0.1:8428/api/v1/query?query=cpu_usage_active&apos;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;但这不叫监控——这叫考古。你需要的是：&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;可视化&lt;/strong&gt;：把指标画成图，一眼看出趋势&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;大盘&lt;/strong&gt;：一台机器一个面板，所有关键指标一屏看全&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;告警&lt;/strong&gt;：CPU 超了、磁盘满了、服务挂了——自动通知你&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;这就是 Grafana 的工作。&lt;/p&gt;
&lt;h2&gt;二、约束&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;无公网，需离线部署&lt;/li&gt;
&lt;li&gt;数据源是 VictoriaMetrics（不是 Prometheus 本体）&lt;/li&gt;
&lt;li&gt;告警通知要能发到飞书/钉钉（内网环境常见 IM）&lt;/li&gt;
&lt;li&gt;资源受限，Grafana 本身要轻量运行&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;三、部署 Grafana&lt;/h2&gt;
&lt;h3&gt;3.1 方式一：Docker 部署（第 6 篇的 Docker 用起来）&lt;/h3&gt;
&lt;p&gt;如果已经搭好了第 6 篇的 Docker 环境：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# 从内部 Registry 拉取（或先在外网 pull 再 load）
docker run -d --name grafana \
    -p 3000:3000 \
    -v /data/grafana:/var/lib/grafana \
    --restart always \
    192.168.1.100:5000/grafana/grafana:latest
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;3.2 方式二：二进制部署（无 Docker 场景）&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;# 外网下载
wget https://dl.grafana.com/oss/release/grafana-11.1.0.linux-amd64.tar.gz

# 内网解压
tar xzf grafana-11.1.0.linux-amd64.tar.gz
mv grafana-v11.1.0 /usr/local/grafana

# 启动
nohup /usr/local/grafana/bin/grafana server \
    --homepath=/usr/local/grafana \
    &gt; /var/log/grafana.log 2&gt;&amp;#x26;1 &amp;#x26;
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;3.3 验证&lt;/h3&gt;
&lt;p&gt;浏览器访问 &lt;code&gt;http://&amp;#x3C;服务器IP&gt;:3000&lt;/code&gt;，默认账号密码 &lt;code&gt;admin/admin&lt;/code&gt;，首次登录会要求改密码。&lt;/p&gt;
&lt;h2&gt;四、接入 VictoriaMetrics 数据源&lt;/h2&gt;
&lt;h3&gt;4.1 添加数据源&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;登录 Grafana → 左侧菜单「Connections → Data sources」&lt;/li&gt;
&lt;li&gt;点击「Add data source」&lt;/li&gt;
&lt;li&gt;搜索选择 &lt;strong&gt;Prometheus&lt;/strong&gt;（VictoriaMetrics 兼容 Prometheus 协议，用 Prometheus 类型接入）&lt;/li&gt;
&lt;li&gt;URL 填：&lt;code&gt;http://&amp;#x3C;VM的IP&gt;:8428&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;点击「Save &amp;#x26; test」，提示成功即接通&lt;/li&gt;
&lt;/ol&gt;
&lt;blockquote&gt;
&lt;p&gt;为什么用 Prometheus 类型接 VM？因为 VM 完全兼容 Prometheus 的查询协议（PromQL），Grafana 用 Prometheus 数据源类型就能直接查 VM 的数据。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;五、搭建监控大盘&lt;/h2&gt;
&lt;h3&gt;5.1 新建 Dashboard&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;左侧菜单「Dashboards → New → New Dashboard」&lt;/li&gt;
&lt;li&gt;添加 Panel，选择数据源 Prometheus&lt;/li&gt;
&lt;li&gt;在查询框输入 PromQL&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;5.2 常用 PromQL（直接抄）&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;CPU 使用率：&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;100 - (avg by (instance) (rate(cpu_usage_total{...}[5m])))
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;内存使用率：&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;mem_used_percent
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;磁盘使用率：&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;disk_used_percent
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;服务存活（up）：&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;up
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;5.3 推荐的大盘结构&lt;/h3&gt;
&lt;p&gt;| 区块 | 指标 | 说明 |
|:----:|------|------|
| 概览 | up、CPU、内存、磁盘 | 一眼看全 |
| 每台机器 | 细分 CPU/内存/磁盘/网络 | 机器级排障 |
| 中间件 | MySQL 连接数、Redis 命中率 | 组件健康 |
| 应用 | QPS、延迟、错误率 | 服务维度 |&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;也可以直接导入官方 Dashboard 模板（Grafana 官网 Dashboards 页面下载 JSON，导入时选 VictoriaMetrics 数据源），省去手写 PromQL 的功夫。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;六、告警配置（重点）&lt;/h2&gt;
&lt;p&gt;监控的最终目的是告警——问题发生时第一时间知道。&lt;/p&gt;
&lt;h3&gt;6.1 创建告警规则&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;进入某个 Panel →「Edit」→「Alert」&lt;/li&gt;
&lt;li&gt;配置规则：
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;条件&lt;/strong&gt;：如 &lt;code&gt;cpu_usage_active &gt; 90&lt;/code&gt; 持续 5 分钟&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;评估间隔&lt;/strong&gt;：每 1 分钟评估一次&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;通知策略&lt;/strong&gt;：选择通知渠道&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;6.2 配置飞书/钉钉通知（内网场景）&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;方式：Webhook 通知。&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;飞书群机器人 Webhook：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;1. 在飞书群添加「自定义机器人」
2. 获取 Webhook URL（形如 https://open.feishu.cn/open-apis/bot/v2/hook/xxx）
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Grafana 配置：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# 在 Grafana 的 Contact points 里添加：
# 类型：Webhook
# URL：飞书机器人地址
# 消息体：自定义 JSON（飞书机器人要求特定格式）
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;告警内容模板示例（飞书消息）：&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-json&quot;&gt;{
  &quot;msg_type&quot;: &quot;text&quot;,
  &quot;content&quot;: {
    &quot;text&quot;: &quot;⚠️ 告警：{{ .CommonLabels.alertname }}\n实例：{{ .CommonLabels.instance }}\n描述：{{ .CommonAnnotations.summary }}&quot;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;6.3 告警分级&lt;/h3&gt;
&lt;p&gt;| 级别 | 示例 | 通知方式 |
|:----:|------|---------|
| 警告 | CPU &gt; 80% 持续 10 分钟 | 飞书普通通知 |
| 严重 | 服务 down / 磁盘 &gt; 95% | 飞书 @人 |
| 紧急 | 数据库挂掉 / 主节点失联 | 飞书 + 电话（如可行） |&lt;/p&gt;
&lt;h2&gt;七、常见坑&lt;/h2&gt;
&lt;p&gt;| 坑 | 症状 | 解决 |
|:--:|------|------|
| 数据源连不上 | Save &amp;#x26; test 失败 | VM 的 8428 端口是否被防火墙挡（第 2 篇） |
| 图是空的 | Panel 无数据 | 时间范围选对没？PromQL 写法对不对？ |
| 告警不触发 | 规则已建无通知 | 检查评估间隔、通知策略是否绑定 |
| 飞书收不到 | Webhook 配置了没消息 | 确认机器人没被飞书风控、消息格式对不对 |
| 磁盘暴涨 | Grafana 数据库变大 | Grafana 自身数据在 /var/lib/grafana，定期备份清理 |&lt;/p&gt;
&lt;h2&gt;八、总结——监控体系收官&lt;/h2&gt;
&lt;p&gt;到这里，三篇监控文章完成了。回顾整条链路：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;采集（Categraf）→ 存储（VictoriaMetrics）→ 展示告警（Grafana）
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;| 层 | 组件 | 端口 | 资源占用 |
|:--:|------|:----:|:--------:|
| 采集 | Categraf | 无（主动推送） | ~30MB |
| 存储 | VictoriaMetrics | 8428 | 受 allowedPercent 限制 |
| 展示 | Grafana | 3000 | ~200MB |&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;一套 3 个组件，总内存占用控制在 1G 以内&lt;/strong&gt;，就得到了完整的监控能力——这就是受限环境下「够用就好」的典范。&lt;/p&gt;
&lt;p&gt;从此你的平台不再是黑盒：机器负载、服务状态、中间件健康——一屏看全，出事自动通知。&lt;/p&gt;
&lt;hr&gt;
&lt;blockquote&gt;
&lt;p&gt;本文首发于掘金 · 作者：七万号
扎根雄安新区中关村科技园，专注受限环境下软件搭建与数据平台落地&lt;/p&gt;
&lt;/blockquote&gt;
&lt;blockquote&gt;
&lt;p&gt;下一篇预告：进入数据平台核心——Flink 集群部署&lt;/p&gt;
&lt;/blockquote&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>VictoriaMetrics 部署——比 Prometheus 更省资源的时序数据库</title><link>https://realcpf.tech/blog/airgapped-victoriametrics</link><guid isPermaLink="true">https://realcpf.tech/blog/airgapped-victoriametrics</guid><description>明朗北街七万号·数研工坊｜扎根雄安新区中关村科技园，专注受限环境下软件搭建与数据平台落地</description><pubDate>Sat, 01 Aug 2026 03:10:00 GMT</pubDate><content:encoded>&lt;blockquote&gt;
&lt;p&gt;明朗北街七万号·数研工坊｜扎根雄安新区中关村科技园，专注受限环境下软件搭建与数据平台落地&lt;/p&gt;
&lt;/blockquote&gt;
&lt;hr&gt;
&lt;h2&gt;适用场景&lt;/h2&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;如果你属于以下任一种情况，这篇对你有用：&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;想用 Prometheus 体系做监控，但机器资源紧张（Prometheus 本体吃内存）&lt;/li&gt;
&lt;li&gt;数据平台已经搭起来，需要一个地方存指标数据&lt;/li&gt;
&lt;li&gt;监控数据量大了之后，Prometheus 频繁 OOM 或磁盘暴涨&lt;/li&gt;
&lt;li&gt;想用一套兼容 PromQL 的方案，但比 Prometheus 更省资源&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;
&lt;p&gt;&lt;strong&gt;应用范围：&lt;/strong&gt; 监控体系的&lt;strong&gt;存储层&lt;/strong&gt;。在第 9 篇的架构图里，Categraf（采集）→ VictoriaMetrics（存储）→ Grafana（展示）。本篇解决「采集到的数据放哪、怎么存、怎么查」。&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;一、问题&lt;/h2&gt;
&lt;p&gt;采集器（Categraf）已经把数据送上来了，但送上来之后呢？&lt;/p&gt;
&lt;p&gt;需要一个「大仓库」把指标数据存起来，而且要能随时查询。行业标准是 Prometheus，但它在资源受限环境下有一个痛点——&lt;strong&gt;内存占用大&lt;/strong&gt;。&lt;/p&gt;
&lt;p&gt;Prometheus 的架构决定了它为了查询速度会把大量数据缓存在内存里。一台 4G 内存的机器，Prometheus 跑起来能吃掉 1.5-2G，这在资源受限的环境里非常肉疼。&lt;/p&gt;
&lt;h2&gt;二、约束&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;无公网，需离线部署&lt;/li&gt;
&lt;li&gt;机器资源紧张，存储引擎必须省内存&lt;/li&gt;
&lt;li&gt;需要兼容 Prometheus 协议（采集端、查询端都要兼容）&lt;/li&gt;
&lt;li&gt;数据要长期保留（至少 30 天以上）&lt;/li&gt;
&lt;li&gt;磁盘空间有限，存储要高效压缩&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;三、为什么选 VictoriaMetrics&lt;/h2&gt;
&lt;p&gt;| 维度 | Prometheus | VictoriaMetrics |
|:----:|:----------:|:---------------:|
| 内存占用 | 高（大量缓存） | &lt;strong&gt;低（约 1/3~1/2）&lt;/strong&gt; |
| 磁盘占用 | 高 | &lt;strong&gt;低（压缩率高）&lt;/strong&gt; |
| 查询语言 | PromQL | &lt;strong&gt;完全兼容 PromQL&lt;/strong&gt; |
| 数据写入 | Pull 为主 | &lt;strong&gt;Push/Pull 都支持&lt;/strong&gt; |
| 部署 | 一套组件 | &lt;strong&gt;单二进制&lt;/strong&gt; |
| 集群扩展 | 需要额外组件 | 单机足够，可扩展 |&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;一句话：同样的功能，VictoriaMetrics 用更少的资源。&lt;/strong&gt; 这正是受限环境最需要的。&lt;/p&gt;
&lt;h2&gt;四、部署&lt;/h2&gt;
&lt;h3&gt;4.1 获取安装包&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;# 外网下载单二进制
wget https://github.com/VictoriaMetrics/VictoriaMetrics/releases/download/v1.101.0/victoria-metrics-linux-amd64-v1.101.0.tar.gz

# ARM 架构
wget https://github.com/VictoriaMetrics/VictoriaMetrics/releases/download/v1.101.0/victoria-metrics-linux-arm64-v1.101.0.tar.gz
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;4.2 解压部署&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;tar xzf victoria-metrics-linux-amd64-v1.101.0.tar.gz
mv victoria-metrics-prod /usr/local/bin/victoria-metrics
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;4.3 启动&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;# 单机模式，数据目录 /data/vm，监听 8428 端口
nohup /usr/local/bin/victoria-metrics \
    -storageDataPath /data/vm \
    -retentionPeriod 90d \
    -memory.allowedPercent 40 \
    &gt; /var/log/victoria-metrics.log 2&gt;&amp;#x26;1 &amp;#x26;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;参数说明：&lt;/p&gt;
&lt;p&gt;| 参数 | 作用 | 建议 |
|------|------|:----:|
| &lt;code&gt;-storageDataPath&lt;/code&gt; | 数据目录 | 放磁盘大的分区 |
| &lt;code&gt;-retentionPeriod&lt;/code&gt; | 数据保留时间 | 90d（监控数据 90 天够用） |
| &lt;code&gt;-memory.allowedPercent&lt;/code&gt; | 内存上限百分比 | &lt;strong&gt;40（关键！防止吃满内存）&lt;/strong&gt; |
| &lt;code&gt;-httpListenAddr&lt;/code&gt; | 监听地址 | 默认 8428，内网可绑定 0.0.0.0 |&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;⚠️ &lt;code&gt;-memory.allowedPercent 40&lt;/code&gt; 一定要设。VictoriaMetrics 默认会用尽可用内存做缓存，多库共存时它会抢内存。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;4.4 systemd 管理&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;cat &gt; /etc/systemd/system/victoria-metrics.service &amp;#x3C;&amp;#x3C; &apos;EOF&apos;
[Unit]
Description=VictoriaMetrics
After=network.target

[Service]
ExecStart=/usr/local/bin/victoria-metrics \
    -storageDataPath /data/vm \
    -retentionPeriod 90d \
    -memory.allowedPercent 40
Restart=always

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable --now victoria-metrics
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;4.5 验证&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;# 健康检查
curl http://127.0.0.1:8428/health
# OK

# 查询接口
curl &apos;http://127.0.0.1:8428/api/v1/query?query=up&apos;
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;五、对接 Categraf（第 9 篇）&lt;/h2&gt;
&lt;p&gt;在第 9 篇里我们配置了 Categraf 的 &lt;code&gt;writers&lt;/code&gt; 指向 VM。现在 VM 起来了，确认数据进来了：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# 查询主机指标（Categraf 默认采集的）
curl &apos;http://127.0.0.1:8428/api/v1/query?query=cpu_usage_active&apos;

# 查询所有指标名
curl &apos;http://127.0.0.1:8428/api/v1/label/__name__/values&apos; | python3 -m json.tool
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;能看到 &lt;code&gt;cpu_*&lt;/code&gt;、&lt;code&gt;mem_*&lt;/code&gt;、&lt;code&gt;disk_*&lt;/code&gt; 等指标，说明链路已经打通。&lt;/p&gt;
&lt;h2&gt;六、数据管理&lt;/h2&gt;
&lt;h3&gt;6.1 数据保留策略&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;-retentionPeriod&lt;/code&gt; 控制保留时间。数据超出保留期会自动删除，无需手动清理。&lt;/p&gt;
&lt;h3&gt;6.2 磁盘空间估算&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;数据量 ≈ 每秒写入点数 × 指标大小

# 简单估算：1000 个指标 × 15s 间隔 × 90 天 ≈ 30-50GB
# 如果指标多，提前规划磁盘
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;6.3 查询性能优化&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;减少 &lt;code&gt;query&lt;/code&gt; 跨度过大的聚合（尽量缩小时间范围）&lt;/li&gt;
&lt;li&gt;用 &lt;code&gt;instant&lt;/code&gt; 查询代替 &lt;code&gt;range&lt;/code&gt; 查询（如果只需要当前值）&lt;/li&gt;
&lt;li&gt;避免在查询中做大量正则匹配&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;七、常见坑&lt;/h2&gt;
&lt;p&gt;| 坑 | 症状 | 解决 |
|:--:|------|------|
| 内存吃满 | 机器卡死 | &lt;code&gt;-memory.allowedPercent&lt;/code&gt; 调低 |
| 写入失败 | Categraf 日志 4xx | 确认 writers URL 是 &lt;code&gt;/prometheus/api/v1/write&lt;/code&gt; |
| 数据查不到 | 有指标但查询为空 | 检查时间范围、label 名写对没 |
| 端口冲突 | 8428 被占 | &lt;code&gt;ss -tlnp&lt;/code&gt; 查占用 |
| 时间不对 | 数据错位 | 配 NTP 同步时钟 |&lt;/p&gt;
&lt;h2&gt;八、总结&lt;/h2&gt;
&lt;p&gt;| 环节 | 关键动作 | 一句话 |
|:----:|---------|--------|
| 选型 | VictoriaMetrics 替代 Prometheus | 同功能，少一半资源 |
| 部署 | 单二进制 + 参数启动 | 一行命令的事 |
| 内存 | &lt;code&gt;-memory.allowedPercent 40&lt;/code&gt; | 必须设，防抢内存 |
| 保留 | &lt;code&gt;-retentionPeriod 90d&lt;/code&gt; | 90 天够用 |
| 对接 | Categraf writers 指向 8428 | 链路打通 |&lt;/p&gt;
&lt;p&gt;数据有了存储，下一步把它「画」出来给人看。下一篇部署 Grafana——监控体系的最后一环。&lt;/p&gt;
&lt;hr&gt;
&lt;blockquote&gt;
&lt;p&gt;本文首发于掘金 · 作者：七万号
扎根雄安新区中关村科技园，专注受限环境下软件搭建与数据平台落地&lt;/p&gt;
&lt;/blockquote&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>Categraf 部署实战——国产开源采集器的内网落地</title><link>https://realcpf.tech/blog/airgapped-categraf</link><guid isPermaLink="true">https://realcpf.tech/blog/airgapped-categraf</guid><description>明朗北街七万号·数研工坊｜扎根雄安新区中关村科技园，专注受限环境下软件搭建与数据平台落地</description><pubDate>Sat, 01 Aug 2026 03:00:00 GMT</pubDate><content:encoded>&lt;blockquote&gt;
&lt;p&gt;明朗北街七万号·数研工坊｜扎根雄安新区中关村科技园，专注受限环境下软件搭建与数据平台落地&lt;/p&gt;
&lt;/blockquote&gt;
&lt;hr&gt;
&lt;h2&gt;为什么必须重视监控与可观测&lt;/h2&gt;
&lt;p&gt;在讲具体怎么部署之前，我想先花点篇幅讲清楚一件事：&lt;strong&gt;为什么数据平台一定要有监控？&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;你搭好了数据库、Nginx、数据引擎，一切正常。但问题是——&lt;strong&gt;你永远不知道它什么时候会不正常。&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;一次内存泄漏、一次磁盘写满、一次网络抖动，都可能让平台在凌晨三点悄无声息地挂掉。没有监控，你发现问题的顺序永远是：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;用户报障 → 你被叫醒 → 远程登录 → 翻日志 → 定位 → 修复
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;这中间用户已经忍受了数小时的服务不可用。&lt;/p&gt;
&lt;p&gt;有监控之后，顺序变成：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;监控告警 → 你被通知 → 远程登录 → 修复
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;问题在用户感知之前就被发现了。&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;监控的价值，一句话：把「事后救火」变成「事前预警」。&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;而「可观测性」是监控的升级版。监控回答「系统现在还活着吗」，可观测性回答「系统为什么变成这样」。一个完整的可观测体系包含三根支柱：&lt;/p&gt;
&lt;p&gt;| 支柱 | 回答的问题 | 典型工具 |
|:----:|-----------|---------|
| &lt;strong&gt;Metrics（指标）&lt;/strong&gt; | 系统健康吗？ | Prometheus、VictoriaMetrics |
| &lt;strong&gt;Logs（日志）&lt;/strong&gt; | 发生了什么？ | ELK、Loki |
| &lt;strong&gt;Traces（链路）&lt;/strong&gt; | 为什么变慢？ | Jaeger、SkyWalking |&lt;/p&gt;
&lt;p&gt;本系列三篇，先搭最核心的 &lt;strong&gt;Metrics 链路&lt;/strong&gt;：采集（Categraf）→ 存储（VictoriaMetrics）→ 展示（Grafana）。&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;适用场景&lt;/h2&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;如果你属于以下任一种情况，这篇对你有用：&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;平台搭起来了，但「黑盒运行」——不知道机器负载、不知道磁盘剩多少、不知道服务还活着没&lt;/li&gt;
&lt;li&gt;想用 Prometheus 体系但资源紧张（Prometheus 本体占内存不小）&lt;/li&gt;
&lt;li&gt;需要采集主机指标（CPU/内存/磁盘/网络）和自定义应用指标&lt;/li&gt;
&lt;li&gt;想给夜莺（Nightingale）或其他监控平台做数据采集&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;
&lt;p&gt;&lt;strong&gt;应用范围：&lt;/strong&gt; 监控体系的数据采集层。在架构里，Categraf 是「眼睛」——它负责到处看，把看到的数据送给 VictoriaMetrics（第 10 篇）存储，再由 Grafana（第 11 篇）展示。&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;架构定位&lt;/h2&gt;
&lt;pre&gt;&lt;code&gt;   ┌────────────┐    ┌────────────┐    ┌────────────┐
   │  主机指标    │    │  MySQL指标  │    │ 应用自定义  │
   └──────┬─────┘    └──────┬─────┘    └──────┬─────┘
          └────────┬────────┘                │
                   ▼                         │
           ┌──────────────┐                  │
           │  Categraf    │◄─────────────────┘  本篇主角：采集
           │  (采集器)     │
           └──────┬───────┘
                  ▼
           ┌──────────────┐
           │VictoriaMetrics│  第 10 篇：存储
           └──────┬───────┘
                  ▼
           ┌──────────────┐
           │   Grafana    │  第 11 篇：展示
           └──────────────┘
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h2&gt;一、问题&lt;/h2&gt;
&lt;p&gt;平台上的每台服务器都是一个「黑盒」：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;磁盘还剩多少？不知道&lt;/li&gt;
&lt;li&gt;CPU 是不是被打满了？不知道&lt;/li&gt;
&lt;li&gt;MySQL 的慢查询多不多？不知道&lt;/li&gt;
&lt;li&gt;某个服务是不是悄悄挂了？不知道&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;你需要的是一套「眼睛」——到处盯着，把数据报回来。这就是采集器的工作。&lt;/p&gt;
&lt;h2&gt;二、约束&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;无公网，需离线部署&lt;/li&gt;
&lt;li&gt;资源受限，采集器本身要轻量（不能比被监控的服务还占资源）&lt;/li&gt;
&lt;li&gt;需要同时采集主机、中间件、自定义应用指标&lt;/li&gt;
&lt;li&gt;后续可能对接多种监控后端（Prometheus、VictoriaMetrics、Nightingale）&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;三、为什么选 Categraf&lt;/h2&gt;
&lt;p&gt;| 采集器 | 特点 | 资源占用 |
|:------:|------|:--------:|
| node_exporter | 只能采主机指标，采集中间件要装一堆 exporter | 低但碎片化 |
| Telegraf | 插件丰富，但 Go 二进制 + 配置文件复杂 | 中 |
| &lt;strong&gt;Categraf&lt;/strong&gt; | &lt;strong&gt;国产开源，一个二进制搞定主机+中间件+自定义&lt;/strong&gt; | &lt;strong&gt;低（单二进制）&lt;/strong&gt; |&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Categraf 的核心优势：&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;单二进制文件，一个程序解决所有采集需求（替代 N 个 exporter）&lt;/li&gt;
&lt;li&gt;原生支持 Prometheus 协议，数据直接推送到 VictoriaMetrics/Prometheus&lt;/li&gt;
&lt;li&gt;支持夜莺（Nightingale）生态，国产监控平台友好&lt;/li&gt;
&lt;li&gt;轻量，内存占用约 20-50MB&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;四、部署&lt;/h2&gt;
&lt;h3&gt;4.1 获取安装包&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;# 外网下载（GitHub Releases 或国内镜像）
wget https://github.com/flashcatcloud/categraf/releases/download/v0.3.76/categraf-v0.3.76-linux-amd64.tar.gz

# ARM 架构
wget https://github.com/flashcatcloud/categraf/releases/download/v0.3.76/categraf-v0.3.76-linux-arm64.tar.gz
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;4.2 解压部署&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;tar xzf categraf-v0.3.76-linux-amd64.tar.gz
mv categraf-v0.3.76-linux-amd64 /usr/local/categraf
cd /usr/local/categraf

# 目录结构
# ├── categraf          主程序
# ├── conf/             配置目录
# │   ├── config.toml   主配置（上报地址等）
# │   └── input.*/      各采集插件配置
# └── ...
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;4.3 配置主文件&lt;/h3&gt;
&lt;p&gt;编辑 &lt;code&gt;conf/config.toml&lt;/code&gt;，配置数据上报地址（指向 VictoriaMetrics）：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[global]
  hostname = &quot;node-01&quot;
  interval = 15s          # 采集间隔

[writers]
  urls = [&quot;http://192.168.1.100:8428/prometheus/api/v1/write&quot;]
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;code&gt;8428&lt;/code&gt; 是 VictoriaMetrics 的写入端口，&lt;code&gt;/prometheus/api/v1/write&lt;/code&gt; 是兼容 Prometheus 的写入路径。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;4.4 启用采集插件&lt;/h3&gt;
&lt;p&gt;Categraf 的插件按目录管理，默认只启用主机采集（&lt;code&gt;input.system&lt;/code&gt; 等）。常用的：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# 主机基础指标（默认启用）
conf/input.system/
conf/input.cpu/
conf/input.mem/
conf/input.disk/
conf/input.net/

# 中间件指标（按需启用）
conf/input.mysql/
conf/input.redis/
conf/input.nginx/
conf/input.kafka/

# 自定义应用指标
conf/input.prometheus/
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;启用某个插件：编辑对应目录下的 &lt;code&gt;conf.toml&lt;/code&gt;，去掉注释或填入配置。&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;例如 MySQL 采集：&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# conf/input.mysql/conf.toml
[[instances]]
  address = &quot;127.0.0.1:3306&quot;
  username = &quot;monitor&quot;
  password = &quot;MonitorPass!2026&quot;
  labels = { instance = &quot;mysql-master&quot; }
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;4.5 启动&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;# 前台测试（确认配置无错）
./categraf --test

# 后台运行
nohup ./categraf &gt; /var/log/categraf.log 2&gt;&amp;#x26;1 &amp;#x26;

# 或用 systemd 管理
cat &gt; /etc/systemd/system/categraf.service &amp;#x3C;&amp;#x3C; &apos;EOF&apos;
[Unit]
Description=Categraf Agent
After=network.target

[Service]
ExecStart=/usr/local/categraf/categraf
Restart=always

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable --now categraf
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;4.6 验证采集是否成功&lt;/h3&gt;
&lt;p&gt;数据有没有送到 VictoriaMetrics，直接在 VM 上查：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# 在 VictoriaMetrics 机器上（第 10 篇部署后）
curl &apos;http://127.0.0.1:8428/api/v1/query?query=cpu_usage_active&apos;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;有数据返回，说明采集链路通了。&lt;/p&gt;
&lt;h2&gt;五、自定义应用指标采集&lt;/h2&gt;
&lt;p&gt;这是 Categraf 相对 node_exporter 最大的优势——应用自己暴露指标，Categraf 直接抓。&lt;/p&gt;
&lt;h3&gt;5.1 应用侧暴露指标&lt;/h3&gt;
&lt;p&gt;Java 应用引入 Micrometer + Prometheus registry，或者任何 Prometheus SDK，在 &lt;code&gt;/metrics&lt;/code&gt; 端点暴露指标。Spring Boot：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-yaml&quot;&gt;# application.yml
management:
  endpoints:
    web:
      exposure:
        include: prometheus
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;5.2 Categraf 抓取&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;# conf/input.prometheus/conf.toml
[[instances]]
  urls = [&quot;http://127.0.0.1:8080/actuator/prometheus&quot;]
  labels = { app = &quot;user-service&quot; }
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;重启 Categraf 后，应用的指标就进入了监控体系。&lt;/p&gt;
&lt;h2&gt;六、常见坑&lt;/h2&gt;
&lt;p&gt;| 坑 | 症状 | 解决 |
|:--:|------|------|
| 数据没上报 | 查询无数据 | 先 &lt;code&gt;./categraf --test&lt;/code&gt; 本地测试 |
| 写入失败 | 日志有 4xx | 确认 writers 的 URL 路径写对 |
| 时间戳错乱 | 图上数据忽前忽后 | 确认服务器时钟同步（内网要配 NTP） |
| MySQL 采集失败 | 无 mysql 指标 | 确认 monitor 账号权限：&lt;code&gt;GRANT PROCESS, REPLICATION CLIENT ON *.* TO &apos;monitor&apos;&lt;/code&gt; |
| 磁盘采集重复 | 挂载点重复 | input.disk 里配置 mount_point 过滤 |&lt;/p&gt;
&lt;h2&gt;七、总结&lt;/h2&gt;
&lt;p&gt;| 环节 | 关键动作 | 一句话 |
|:----:|---------|--------|
| 选型 | Categraf 单二进制 | 一个采集器替代一堆 exporter |
| 部署 | 解压即用 | 注意架构 x64/aarch64 |
| 配置 | writers 指到 VM | 上报地址是关键 |
| 插件 | 按需启用目录 | MySQL/Redis/自定义各就各位 |
| 验证 | &lt;code&gt;--test&lt;/code&gt; + VM 查数据 | 链路通了才算部署完 |&lt;/p&gt;
&lt;p&gt;数据采回来只是第一步——得有个地方存。下一篇部署 VictoriaMetrics，把数据接住。&lt;/p&gt;
&lt;hr&gt;
&lt;blockquote&gt;
&lt;p&gt;本文首发于掘金 · 作者：七万号
扎根雄安新区中关村科技园，专注受限环境下软件搭建与数据平台落地&lt;/p&gt;
&lt;/blockquote&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>Nginx 内网部署与配置实战——平台唯一的请求入口</title><link>https://realcpf.tech/blog/airgapped-nginx</link><guid isPermaLink="true">https://realcpf.tech/blog/airgapped-nginx</guid><description>明朗北街七万号·数研工坊｜扎根雄安新区中关村科技园，专注受限环境下软件搭建与数据平台落地</description><pubDate>Sat, 01 Aug 2026 02:50:00 GMT</pubDate><content:encoded>&lt;blockquote&gt;
&lt;p&gt;明朗北街七万号·数研工坊｜扎根雄安新区中关村科技园，专注受限环境下软件搭建与数据平台落地&lt;/p&gt;
&lt;/blockquote&gt;
&lt;hr&gt;
&lt;h2&gt;适用场景&lt;/h2&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;如果你属于以下任一种情况，这篇对你有用：&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;内网平台多个服务想统一从 80 端口访问，而不是一堆随机端口&lt;/li&gt;
&lt;li&gt;需要反向代理、负载均衡、静态资源服务&lt;/li&gt;
&lt;li&gt;内网想启用 HTTPS（自签证书），避免明文传输&lt;/li&gt;
&lt;li&gt;想搞清楚 Nginx 的配置体系（server/location/upstream）&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;
&lt;p&gt;&lt;strong&gt;应用范围：&lt;/strong&gt; 平台架构的&lt;strong&gt;统一入口&lt;/strong&gt;。第 7 篇解决了「数据怎么存住」，本篇解决「请求怎么进来」。在整体架构里，Nginx 是所有 HTTP 请求的第一站，下面挂着应用服务、监控面板、数据平台各组件。&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;架构定位&lt;/h2&gt;
&lt;pre&gt;&lt;code&gt;                    ┌─────────────┐
   用户请求  ──────► │   Nginx     │  ← 本篇主角：唯一入口
                    └──────┬──────┘
                    ┌──────┴──────┐
                    ▼             ▼
           ┌──────────────┐ ┌──────────────┐
           │ 应用服务:8080 │ │ 监控面板:3000│  ← 下游各服务
           └──────────────┘ └──────────────┘
                    │
                    ▼
            ┌──────────────┐
            │  存储底座      │  ← 第 7 篇：MySQL/PG/Redis
            └──────────────┘
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;| Nginx 角色 | 说明 | 典型配置 |
|:----------:|------|---------|
| &lt;strong&gt;反向代理&lt;/strong&gt; | 统一入口，转发到下游服务 | &lt;code&gt;proxy_pass&lt;/code&gt; |
| &lt;strong&gt;负载均衡&lt;/strong&gt; | 多个后端实例分担请求 | &lt;code&gt;upstream&lt;/code&gt; |
| &lt;strong&gt;静态服务&lt;/strong&gt; | 前端页面、静态资源 | &lt;code&gt;root&lt;/code&gt; + &lt;code&gt;index&lt;/code&gt; |
| &lt;strong&gt;SSL 终结&lt;/strong&gt; | HTTPS 证书卸载 | &lt;code&gt;ssl_certificate&lt;/code&gt; |&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;一、问题&lt;/h2&gt;
&lt;p&gt;平台跑起来了：应用服务 8080、监控面板 3000、接口服务 9090……用户要记一堆端口，还不安全。&lt;/p&gt;
&lt;p&gt;而且内网环境没有现成的负载均衡器（没有云 SLB），所有请求需要一个统一入口。&lt;/p&gt;
&lt;h2&gt;二、约束&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;无公网，Nginx 需编译安装或离线安装&lt;/li&gt;
&lt;li&gt;需要自签证书做 HTTPS（没有正规 CA 证书）&lt;/li&gt;
&lt;li&gt;下游服务数量多、端口各异&lt;/li&gt;
&lt;li&gt;ARM 机器也需要对应版本&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;三、安装 Nginx&lt;/h2&gt;
&lt;h3&gt;3.1 方案 A：离线编译（推荐，可定制）&lt;/h3&gt;
&lt;p&gt;依赖第 4 篇编译好的 GCC，以及几个基础依赖包：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# 外网下载
wget http://nginx.org/download/nginx-1.24.0.tar.gz

# 内网编译
tar xzf nginx-1.24.0.tar.gz
cd nginx-1.24.0

./configure \
    --prefix=/usr/local/nginx \
    --with-http_ssl_module \
    --with-http_stub_status_module \
    --with-http_gzip_static_module

make -j$(nproc) &amp;#x26;&amp;#x26; make install
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;如果 configure 报缺依赖（pcre/zlib），用第 3 篇的 yum 源装：&lt;code&gt;yum install -y pcre-devel zlib-devel openssl-devel&lt;/code&gt;。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;3.2 方案 B：yum 安装（省事，版本旧）&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;yum install -y nginx   # 前提：第 3 篇的本地源已配置
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;3.3 启动&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;# 编译安装的
/usr/local/nginx/sbin/nginx

# yum 安装的
systemctl start nginx
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;验证：&lt;code&gt;curl -I http://127.0.0.1&lt;/code&gt; 返回 200 即成功。&lt;/p&gt;
&lt;h2&gt;四、核心配置体系&lt;/h2&gt;
&lt;p&gt;Nginx 配置的核心是三个块，层层嵌套：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;http {                          # 全局：worker、日志、gzip
    upstream backend {          # 上游组：负载均衡的后端列表
        server 192.168.1.11:8080 weight=1;
        server 192.168.1.12:8080 weight=1;
    }

    server {                    # 虚拟主机：监听端口+域名
        listen 80;
        server_name example.com;

        location / {            # 路径规则：路由到哪
            proxy_pass http://backend;
        }

        location /static/ {     # 静态资源直接返回文件
            root /data/www;
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;理解优先级：&lt;code&gt;http&lt;/code&gt; &gt; &lt;code&gt;server&lt;/code&gt; &gt; &lt;code&gt;location&lt;/code&gt;。&lt;/strong&gt;&lt;/p&gt;
&lt;h2&gt;五、反向代理配置&lt;/h2&gt;
&lt;h3&gt;5.1 最简反向代理&lt;/h3&gt;
&lt;p&gt;把所有请求转发到一个后端：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;server {
    listen 80;
    server_name _;

    location / {
        proxy_pass http://192.168.1.11:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;5.2 按路径分发到不同服务（平台场景）&lt;/h3&gt;
&lt;p&gt;一套平台多个服务，用路径区分：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;server {
    listen 80;
    server_name _;

    # 应用 API
    location /api/ {
        proxy_pass http://192.168.1.11:8080;
    }

    # 监控面板
    location /grafana/ {
        proxy_pass http://192.168.1.12:3000;
    }

    # 前端静态页面
    location / {
        root /data/frontend;
        index index.html;
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;这样用户只需要记一个地址 &lt;code&gt;http://平台IP/&lt;/code&gt;，后面跟路径就能访问不同服务。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;5.3 负载均衡&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;upstream app_backend {
    server 192.168.1.11:8080;
    server 192.168.1.12:8080;
    server 192.168.1.13:8080;
}

server {
    listen 80;
    location / {
        proxy_pass http://app_backend;
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;默认轮询。其他策略：&lt;/p&gt;
&lt;p&gt;| 策略 | 配置 | 场景 |
|:----:|------|------|
| 轮询 | 默认 | 无状态服务 |
| 权重 | &lt;code&gt;server x weight=3;&lt;/code&gt; | 机器性能不均 |
| IP 哈希 | &lt;code&gt;ip_hash;&lt;/code&gt; | 需要会话保持 |&lt;/p&gt;
&lt;h2&gt;六、HTTPS 与自签证书&lt;/h2&gt;
&lt;h3&gt;6.1 生成自签证书&lt;/h3&gt;
&lt;p&gt;内网没有 CA，用 openssl 生成自签证书：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# 生成私钥
openssl genrsa -out server.key 2048

# 生成自签证书（有效期 10 年）
openssl req -new -x509 -key server.key -out server.crt -days 3650 \
    -subj &quot;/C=CN/ST=Hebei/L=Xiong&apos;an/O=Internal/CN=192.168.1.100&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;code&gt;CN&lt;/code&gt; 可以填 IP 或域名。填 IP 的话，浏览器访问时用 IP 就不会报「域名不匹配」（还是会报「不受信任」，因为自签）。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;6.2 配置 HTTPS&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;server {
    listen 443 ssl;
    server_name _;

    ssl_certificate     /usr/local/nginx/conf/server.crt;
    ssl_certificate_key /usr/local/nginx/conf/server.key;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;

    location / {
        proxy_pass http://192.168.1.11:8080;
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;6.3 HTTP 跳转 HTTPS（可选）&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;server {
    listen 80;
    return 301 https://$host$request_uri;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;七、常见坑&lt;/h2&gt;
&lt;p&gt;| 坑 | 症状 | 解决 |
|:--:|------|------|
| 端口被占 | bind() to 0.0.0.0:80 failed | &lt;code&gt;ss -tlnp&lt;/code&gt; 找占用进程 |
| 配置不生效 | 改了没反应 | &lt;code&gt;nginx -s reload&lt;/code&gt;（不是 restart） |
| 静态资源 404 | location 路径不对 | 确认 &lt;code&gt;root&lt;/code&gt; + URI 拼接后的真实路径 |
| 后端 502 | 后端没起来 | &lt;code&gt;curl&lt;/code&gt; 直接测后端端口 |
| 日志没输出 | 排障无头绪 | &lt;code&gt;error_log logs/error.log debug;&lt;/code&gt; |
| 上传大文件超时 | 413 / 504 | &lt;code&gt;client_max_body_size 100m;&lt;/code&gt; + &lt;code&gt;proxy_read_timeout 300s;&lt;/code&gt; |&lt;/p&gt;
&lt;h2&gt;八、总结&lt;/h2&gt;
&lt;p&gt;Nginx 在内网平台里的角色一句话：&lt;strong&gt;一个入口，转发一切。&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;| 环节 | 核心配置 | 一句话 |
|:----:|---------|--------|
| 安装 | 编译加 &lt;code&gt;--with-http_ssl_module&lt;/code&gt; | 记得带 SSL 模块 |
| 反向代理 | &lt;code&gt;proxy_pass&lt;/code&gt; | 记住加 X-Forwarded 头 |
| 多服务 | 按 &lt;code&gt;location&lt;/code&gt; 路径分发 | 一个端口访问整个平台 |
| 负载均衡 | &lt;code&gt;upstream&lt;/code&gt; + &lt;code&gt;ip_hash&lt;/code&gt; | 无状态轮询，有状态哈希 |
| HTTPS | 自签证书 + 443 server | 内网也建议上 TLS |&lt;/p&gt;
&lt;p&gt;到这里，&lt;strong&gt;「请求入口 + 存储底座」&lt;/strong&gt; 两层已经就位。下一批文章开始往上走——监控体系（Categraf → VictoriaMetrics → Grafana），然后是数据引擎（Flink → Spark → SeaTunnel → Calcite → DuckDB）。&lt;/p&gt;
&lt;hr&gt;
&lt;blockquote&gt;
&lt;p&gt;本文首发于掘金 · 作者：七万号
扎根雄安新区中关村科技园，专注受限环境下软件搭建与数据平台落地&lt;/p&gt;
&lt;/blockquote&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>Redis / MySQL / PostgreSQL 内网部署实录——存储底座的三根柱子</title><link>https://realcpf.tech/blog/airgapped-db-trio</link><guid isPermaLink="true">https://realcpf.tech/blog/airgapped-db-trio</guid><description>明朗北街七万号·数研工坊｜扎根雄安新区中关村科技园，专注受限环境下软件搭建与数据平台落地</description><pubDate>Sat, 01 Aug 2026 02:30:00 GMT</pubDate><content:encoded>&lt;blockquote&gt;
&lt;p&gt;明朗北街七万号·数研工坊｜扎根雄安新区中关村科技园，专注受限环境下软件搭建与数据平台落地&lt;/p&gt;
&lt;/blockquote&gt;
&lt;hr&gt;
&lt;h2&gt;适用场景&lt;/h2&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;如果你属于以下任一种情况，这篇对你有用：&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;内网环境需要部署数据平台的核心存储（关系型 + 缓存）&lt;/li&gt;
&lt;li&gt;一台机器上要同时跑 MySQL、PostgreSQL、Redis，内存分配纠结&lt;/li&gt;
&lt;li&gt;想搞清楚「业务库用 MySQL 还是 PG」「缓存什么时候上 Redis」&lt;/li&gt;
&lt;li&gt;部署完数据库被连接不上、权限不对、内存不足折磨&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;
&lt;p&gt;&lt;strong&gt;应用范围：&lt;/strong&gt; 数据平台的&lt;strong&gt;存储底座&lt;/strong&gt;。在整体架构里，这一层在 Nginx（请求入口）之下、数据引擎（Flink/Spark）之下，是所有应用的数据最终落脚点。第 8 篇的 Nginx 负责「请求怎么进来」，本篇负责「数据怎么存住」。&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;架构定位&lt;/h2&gt;
&lt;p&gt;先看这张图，理解这三者在一套平台里的分工：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;                    ┌─────────────┐
   用户请求  ──────► │   Nginx     │  ← 请求入口（第 8 篇）
                    └──────┬──────┘
                           ▼
                 ┌───────────────────┐
                 │   应用服务(微服务)  │
                 └───────┬───────────┘
                         │
          ┌──────────────┼──────────────┐
          ▼              ▼              ▼
   ┌──────────┐   ┌──────────┐   ┌──────────┐
   │  MySQL   │   │    PG    │   │  Redis   │
   │ 核心业务  │   │  复杂业务  │   │ 缓存/会话 │
   └──────────┘   └──────────┘   └──────────┘
     ← 存储底座：三根柱子 →
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;| 组件 | 定位 | 典型数据 |
|:----:|------|---------|
| &lt;strong&gt;MySQL&lt;/strong&gt; | 核心业务库 | 用户、订单、配置等结构化数据 |
| &lt;strong&gt;PostgreSQL&lt;/strong&gt; | 复杂业务/JSON/地理数据 | 需要高级类型、复杂查询的场景 |
| &lt;strong&gt;Redis&lt;/strong&gt; | 缓存/会话/队列 | 热数据、登录态、计数器、发布订阅 |&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;一、问题&lt;/h2&gt;
&lt;p&gt;数据平台跑起来，第一件事就是要有地方存数据。但内网环境装数据库，比想象中坑多：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;mysql -h 127.0.0.1 -uroot -p
# ERROR 2002: Can&apos;t connect to local MySQL server
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;或者是——&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;systemctl start mysqld
# 启动失败：Initialization of mysqld failed
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;更常见的是——装是装上了，三四个数据库挤在一台机器上，内存互相抢，跑几天就开始卡。&lt;/p&gt;
&lt;h2&gt;二、约束&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;无公网，不能用包管理器在线装（openEuler 源里有部分，但不全）&lt;/li&gt;
&lt;li&gt;资源受限，可能多库共享一台机器&lt;/li&gt;
&lt;li&gt;需要满足安全合规（密码策略、最小权限、审计）&lt;/li&gt;
&lt;li&gt;ARM 架构机器需要对应版本的安装包&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;三、先规划：内存怎么分&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;多库共存的第一原则：先分内存，再装库。&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;假设一台 8G 内存的机器，要跑 MySQL + PG + Redis：&lt;/p&gt;
&lt;p&gt;| 组件 | 建议分配 | 配置项 |
|:----:|:--------:|--------|
| MySQL | 3G | &lt;code&gt;innodb_buffer_pool_size=2G&lt;/code&gt; + &lt;code&gt;sort_buffer_size=32M&lt;/code&gt; |
| PostgreSQL | 2G | &lt;code&gt;shared_buffers=1G&lt;/code&gt; + &lt;code&gt;work_mem=64M&lt;/code&gt; |
| Redis | 1G | &lt;code&gt;maxmemory 1gb&lt;/code&gt; |
| 系统余量 | 2G | — |&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;⚠️ 不设上限的后果：PG 的 &lt;code&gt;work_mem&lt;/code&gt; 默认 4MB 但会被每个连接放大，MySQL 的 buffer pool 默认占内存 75%。&lt;strong&gt;多库共存，必须显式设置内存参数。&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;四、MySQL 部署&lt;/h2&gt;
&lt;h3&gt;4.1 安装&lt;/h3&gt;
&lt;p&gt;内网环境下，推荐用 tar.gz 二进制包（不依赖系统包管理器，多版本可控）：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# 外网下载（以 8.0.36 为例）
wget https://mirrors.tuna.tsinghua.edu.cn/mysql/downloads/MySQL-8.0/mysql-8.0.36-linux-glibc2.12-x86_64.tar.xz

# 内网解压
mkdir -p /usr/local/mysql
tar xJf mysql-8.0.36-linux-glibc2.12-x86_64.tar.xz -C /usr/local/mysql --strip-components=1
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;4.2 初始化&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;# 创建数据目录和用户
mkdir -p /data/mysql
useradd -r mysql

# 初始化数据目录
/usr/local/mysql/bin/mysqld --initialize-insecure \
    --basedir=/usr/local/mysql --datadir=/data/mysql \
    --user=mysql

# 启动
/usr/local/mysql/bin/mysqld --daemonize \
    --basedir=/usr/local/mysql --datadir=/data/mysql \
    --user=mysql
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;4.3 初始化后必做三件事&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;① 改 root 密码：&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;mysql -uroot
ALTER USER &apos;root&apos;@&apos;localhost&apos; IDENTIFIED BY &apos;StrongPass!2026&apos;;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;② 建业务账号（最小权限）：&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;CREATE USER &apos;app&apos;@&apos;%&apos; IDENTIFIED BY &apos;AppPass!2026&apos;;
GRANT SELECT,INSERT,UPDATE,DELETE ON biz_db.* TO &apos;app&apos;@&apos;%&apos;;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;③ 配置 my.cnf（内存上限是关键）：&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# /etc/my.cnf
[mysqld]
port=3306
datadir=/data/mysql
innodb_buffer_pool_size=2G        # 上限，别超过物理内存 60%
max_connections=500
character-set-server=utf8mb4
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;4.4 验证&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;mysql -uapp -p -h 127.0.0.1 -P 3306 -e &quot;SELECT 1&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;五、PostgreSQL 部署&lt;/h2&gt;
&lt;h3&gt;5.1 安装&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;# 外网下载二进制包
wget https://mirrors.tuna.tsinghua.edu.cn/postgresql/source/v16.2/postgresql-16.2.tar.gz

# 内网编译（PG 编译比较简单，依赖少）
tar xzf postgresql-16.2.tar.gz
cd postgresql-16.2
./configure --prefix=/usr/local/pgsql
make -j$(nproc) &amp;#x26;&amp;#x26; make install
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;如果嫌编译慢，也可以直接用系统源 &lt;code&gt;yum install postgresql-server&lt;/code&gt;（openEuler 源里有），但版本可能较旧。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;5.2 初始化&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;# PG 不允许 root 运行，必须切用户
useradd -r postgres
mkdir -p /data/pgsql
chown postgres:postgres /data/pgsql

su - postgres
/usr/local/pgsql/bin/initdb -D /data/pgsql
/usr/local/pgsql/bin/pg_ctl -D /data/pgsql -l /data/pgsql/log start
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;5.3 配置 pg_hba.conf（连接权限）&lt;/h3&gt;
&lt;p&gt;PG 的连接控制在这个文件里，内网环境常见配置：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# /data/pgsql/pg_hba.conf
# 本机
local   all   all                     trust
# 内网网段
host    all   all   192.168.1.0/24    md5
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;改完重启生效：&lt;code&gt;pg_ctl -D /data/pgsql reload&lt;/code&gt;&lt;/p&gt;
&lt;h3&gt;5.4 配置内存上限&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;# /data/pgsql/postgresql.conf
shared_buffers = 1G
work_mem = 64MB
maintenance_work_mem = 256MB
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;5.5 验证&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;su - postgres -c &quot;/usr/local/pgsql/bin/psql -c &apos;SELECT version();&apos;&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;六、Redis 部署&lt;/h2&gt;
&lt;h3&gt;6.1 安装&lt;/h3&gt;
&lt;p&gt;Redis 编译极快（纯 C，几十秒），推荐源码编译：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;wget https://download.redis.io/releases/redis-7.2.4.tar.gz
tar xzf redis-7.2.4.tar.gz
cd redis-7.2.4
make -j$(nproc)
# 可选 make test（要几分钟）
make install
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;6.2 配置&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;# /etc/redis.conf
bind 0.0.0.0                    # 内网环境监听所有网卡
port 6379
daemonize yes
requirepass RedisPass!2026      # 必设密码！
maxmemory 1gb                   # 上限
maxmemory-policy allkeys-lru    # 淘汰策略
appendonly yes                  # AOF 持久化
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;6.3 启动与验证&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;redis-server /etc/redis.conf
redis-cli -a RedisPass!2026 ping
# PONG
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;⚠️ &lt;strong&gt;内网 Redis 也必须设密码。&lt;/strong&gt; 曾见过内网 Redis 裸奔被挖矿的案例——内网不是绝对安全，扫描器无处不在。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;七、三库对比与选型&lt;/h2&gt;
&lt;p&gt;| 维度 | MySQL | PostgreSQL | Redis |
|:----:|:-----:|:----------:|:-----:|
| 定位 | 通用关系库 | 高级关系库 | 内存缓存 |
| JSON | 支持（8.0 后） | 优秀（jsonb） | — |
| 复杂查询 | 一般 | 强（CTE/窗口函数） | — |
| 地理数据 | 弱 | 强（PostGIS） | — |
| 并发写 | 一般 | 较强 | 极强 |
| 适合场景 | 常规业务 | 复杂业务/分析 | 热点/会话/队列 |&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;选型口诀：&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;常规业务 → MySQL&lt;/li&gt;
&lt;li&gt;复杂查询/JSON/地理 → PostgreSQL&lt;/li&gt;
&lt;li&gt;热点数据/登录态/计数器 → Redis&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;不要为了「潮流」换库，内网环境稳定性 &gt; 技术新鲜度&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;八、常见坑&lt;/h2&gt;
&lt;p&gt;| 坑 | 症状 | 解决 |
|:--:|------|------|
| MySQL 连不上 | ERROR 2002 | 确认服务启动了，&lt;code&gt;ss -tlnp&lt;/code&gt; 看端口 |
| 连接被拒 | ERROR 1130 | 账号 host 是 localhost，改 &lt;code&gt;&apos;app&apos;@&apos;%&apos;&lt;/code&gt; |
| PG 无法登录 | password authentication failed | pg_hba.conf 的 md5 密码不匹配，重设 |
| Redis 连上没权限 | NOAUTH | 客户端加密码参数 |
| 内存被吃光 | 三库互相挤 | 显式设置各自内存上限（第三节） |
| 中文乱码 | 数据存进去乱 | MySQL 统一 utf8mb4 |&lt;/p&gt;
&lt;h2&gt;九、总结&lt;/h2&gt;
&lt;p&gt;存储底座部署的核心，其实就三个字：&lt;strong&gt;先规划。&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;先规划内存分配 → 再逐个安装 → 后设置上限与权限
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;| 组件 | 核心配置 | 必做 |
|:----:|---------|:----:|
| MySQL | innodb_buffer_pool_size | 改密码 + 建最小权限账号 |
| PG | shared_buffers + pg_hba.conf | 非 root 运行 + 网段放行 |
| Redis | maxmemory + requirepass | 设密码 + 持久化 |&lt;/p&gt;
&lt;p&gt;存住数据之后，下一步是给整个平台开一个统一的入口——Nginx。下一篇讲请求入口的部署与配置。&lt;/p&gt;
&lt;hr&gt;
&lt;blockquote&gt;
&lt;p&gt;本文首发于掘金 · 作者：七万号
扎根雄安新区中关村科技园，专注受限环境下软件搭建与数据平台落地&lt;/p&gt;
&lt;/blockquote&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>离线部署 Docker 并导入镜像——资源受限环境的容器化实践</title><link>https://realcpf.tech/blog/airgapped-docker-offline</link><guid isPermaLink="true">https://realcpf.tech/blog/airgapped-docker-offline</guid><description>明朗北街七万号·数研工坊｜扎根雄安新区中关村科技园，专注受限环境下软件搭建与数据平台落地</description><pubDate>Sat, 01 Aug 2026 01:30:00 GMT</pubDate><content:encoded>&lt;blockquote&gt;
&lt;p&gt;明朗北街七万号·数研工坊｜扎根雄安新区中关村科技园，专注受限环境下软件搭建与数据平台落地&lt;/p&gt;
&lt;/blockquote&gt;
&lt;hr&gt;
&lt;h2&gt;适用场景&lt;/h2&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;如果你属于以下任一种情况，这篇对你有用：&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;内网环境想用 Docker 部署组件（监控、数据库、中间件），但没有 Docker Hub&lt;/li&gt;
&lt;li&gt;需要在多台服务器上快速部署同样的容器环境&lt;/li&gt;
&lt;li&gt;想自建一个内部的镜像仓库，让内网机器都能拉取镜像&lt;/li&gt;
&lt;li&gt;被 &lt;code&gt;docker pull&lt;/code&gt; 卡死、镜像拉不下来困扰&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;
&lt;p&gt;&lt;strong&gt;应用范围：&lt;/strong&gt; 内网容器化部署的基础能力。后续的监控体系（VictoriaMetrics、Grafana）、数据库、大数据组件都可能用 Docker 部署。第 3 篇（镜像源）的 Nginx 暴露思路，在这里升级为完整的镜像仓库。&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;一、问题&lt;/h2&gt;
&lt;p&gt;在内网环境想用 Docker，第一反应是：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;docker pull mysql:8.0
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;然后……卡住了。没有外网，Docker Hub 根本连不上。&lt;/p&gt;
&lt;p&gt;即便你通过某种方式拿到了 docker 安装包，装完之后 &lt;code&gt;docker pull&lt;/code&gt; 依然是废的。&lt;strong&gt;没有镜像，Docker 就是空壳。&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;所以内网环境的容器化，核心不是「装 Docker」，而是「搞到镜像」。&lt;/p&gt;
&lt;h2&gt;二、约束&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;无公网，无法 &lt;code&gt;docker pull&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;多台服务器需要相同的容器镜像&lt;/li&gt;
&lt;li&gt;部分机器 ARM 架构（鲲鹏、飞腾），需要对应架构的镜像&lt;/li&gt;
&lt;li&gt;镜像文件通常较大（几百 MB 到几个 GB），传输和存储都要规划&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;三、第一步：离线安装 Docker&lt;/h2&gt;
&lt;h3&gt;3.1 方案 A：rpm 包安装（推荐）&lt;/h3&gt;
&lt;p&gt;在有外网的机器上，用 &lt;code&gt;yumdownloader&lt;/code&gt; 把 docker 相关的 rpm 包全部拉下来：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# 在有外网的 CentOS/openEuler 机器上
yum install -y yum-utils
yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo

# 创建下载目录
mkdir -p docker-rpms &amp;#x26;&amp;#x26; cd docker-rpms

# 下载 docker 及依赖（不带 --resolve 会漏依赖，带的话会拉全）
yumdownloader docker-ce docker-ce-cli containerd.io docker-compose-plugin --resolve
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;把 &lt;code&gt;docker-rpms&lt;/code&gt; 目录整体打包传到内网，然后：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# 内网机器上安装（注意用 rpm -Uvh 处理依赖顺序）
rpm -Uvh *.rpm
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;3.2 方案 B：静态二进制（无依赖安装）&lt;/h3&gt;
&lt;p&gt;Docker 官方提供静态二进制包，解压即用，不依赖 rpm：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# 外网下载
wget https://download.docker.com/linux/static/stable/x86_64/docker-24.0.7.tgz

# 内网解压
tar xzf docker-24.0.7.tgz
cp docker/* /usr/bin/

# 启动
dockerd &amp;#x26;
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;ARM 机器把 URL 中的 &lt;code&gt;x86_64&lt;/code&gt; 换成 &lt;code&gt;aarch64&lt;/code&gt;。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;3.3 验证&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;docker version
docker run hello-world   # 如果能跑，说明 daemon 正常（本地有镜像才行）
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;四、第二步：搞到镜像（核心！）&lt;/h2&gt;
&lt;p&gt;装好 Docker 之后的重头戏：怎么把镜像搞到内网。&lt;/p&gt;
&lt;h3&gt;4.1 方案 A：在有外网的机器上 pull 再导出&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;在有外网的机器上：&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# pull 需要的镜像
docker pull mysql:8.0
docker pull grafana/grafana:latest
docker pull victoriametrics/victoria-metrics:latest

# 导出为 tar 文件
docker save -o images.tar mysql:8.0 grafana/grafana victoriametrics/victoria-metrics
# 或者导出单个
docker save mysql:8.0 -o mysql-8.0.tar
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;在内网机器上导入：&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;docker load -i images.tar
# 验证
docker images
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;这是最直接、最常用的方式。缺点：如果镜像版本更新，要重新导出导入。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;4.2 方案 B：自建内部 Registry（多机共享）&lt;/h3&gt;
&lt;p&gt;如果多台服务器都要用同一批镜像，每台都 load 一遍 tar 包很蠢。自建 Registry：&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step 1：在一台机器上跑 Registry&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;docker run -d --name registry -p 5000:5000 -v /data/registry:/var/lib/registry registry:2
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Step 2：有外网机器拉镜像 → tag 成内部仓库地址 → push&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;docker pull mysql:8.0
docker tag mysql:8.0 192.168.1.100:5000/mysql:8.0
docker push 192.168.1.100:5000/mysql:8.0
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Step 3：内网其他机器配置 insecure registry 后直接 pull&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;编辑 &lt;code&gt;/etc/docker/daemon.json&lt;/code&gt;：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
  &quot;insecure-registries&quot;: [&quot;192.168.1.100:5000&quot;]
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;systemctl restart docker
docker pull 192.168.1.100:5000/mysql:8.0
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;内网没有 HTTPS 证书，必须加 &lt;code&gt;insecure-registries&lt;/code&gt;，否则 docker 拒绝用 HTTP 协议访问。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;4.3 方案 C：Harbor（企业级，后续可升级）&lt;/h3&gt;
&lt;p&gt;如果镜像数量多、需要权限管理、审计，可以上 Harbor。但 Harbor 本身安装较重，内网小规模场景 Registry 够用。&lt;strong&gt;先跑起来，规模大了再升级。&lt;/strong&gt;&lt;/p&gt;
&lt;h3&gt;4.4 架构问题：x86 镜像 vs ARM 镜像&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;镜像有架构之分。&lt;/strong&gt; 在内网混部环境（x86 + ARM）经常踩坑：&lt;/p&gt;
&lt;p&gt;| 机器架构 | 需要镜像架构 | 验证方式 |
|:--------:|:-----------:|---------|
| x86_64 | amd64 | &lt;code&gt;docker image inspect xxx --format &apos;{{.Architecture}}&apos;&lt;/code&gt; |
| ARM64 | arm64 | 同上 |&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;镜像必须和 CPU 架构匹配。ARM 机器上跑 x86 镜像会直接报 &lt;code&gt;exec format error&lt;/code&gt;。
有外网机器上导出镜像时，要在&lt;strong&gt;同架构&lt;/strong&gt;的机器上 pull（或者用 &lt;code&gt;docker pull --platform arm64&lt;/code&gt; 指定）。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;五、docker-compose 离线部署&lt;/h2&gt;
&lt;p&gt;内网环境强烈建议装 docker-compose（现在叫 docker compose plugin），后面部署监控、数据库都会用到。&lt;/p&gt;
&lt;h3&gt;5.1 安装&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;# 外网下载二进制（注意架构）
wget https://github.com/docker/compose/releases/download/v2.24.0/docker-compose-linux-x86_64

# 内网安装
mv docker-compose-linux-x86_64 /usr/local/bin/docker-compose
chmod +x /usr/local/bin/docker-compose
docker-compose version
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;5.2 使用示例&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;# 创建 docker-compose.yml
cat &gt; docker-compose.yml &amp;#x3C;&amp;#x3C; &apos;EOF&apos;
version: &apos;3&apos;
services:
  mysql:
    image: 192.168.1.100:5000/mysql:8.0
    container_name: mysql8
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: yourpass
    ports:
      - &quot;3306:3306&quot;
    volumes:
      - /data/mysql:/var/lib/mysql
EOF

docker-compose up -d
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;六、常见坑&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;坑 1：&lt;code&gt;docker pull&lt;/code&gt; 卡死/超时&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;内网没配镜像源，直接默认连 Docker Hub。解决：走 4.2 的自建 Registry 方案，或配置代理（如果有）。&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;坑 2：&lt;code&gt;exec format error&lt;/code&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;架构不匹配。ARM 机器用了 x86 镜像。用 4.4 的方式确认架构，重新拉取正确架构镜像。&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;坑 3：&lt;code&gt;Error response from daemon: Get https://...: http: server gave HTTP response to HTTPS client&lt;/code&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Registry 用的是 HTTP 没配 HTTPS。解决：&lt;code&gt;/etc/docker/daemon.json&lt;/code&gt; 加 &lt;code&gt;insecure-registries&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;坑 4：&lt;code&gt;Cannot connect to the Docker daemon&lt;/code&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;daemon 没启动。&lt;code&gt;systemctl status docker&lt;/code&gt; 检查，或 &lt;code&gt;dockerd &amp;#x26;&lt;/code&gt; 手动启动。也可能是 socket 权限问题：把用户加入 docker 组 &lt;code&gt;usermod -aG docker youruser&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;坑 5：磁盘空间不够&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;镜像很占空间。Docker 默认数据目录在 &lt;code&gt;/var/lib/docker&lt;/code&gt;。如果系统盘小，把数据目录挪到大盘：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# /etc/docker/daemon.json
{
  &quot;data-root&quot;: &quot;/data/docker&quot;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;七、总结&lt;/h2&gt;
&lt;p&gt;内网 Docker 的核心思路，一句话：&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;安装是小事，镜像才是大事。&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;| 环节 | 关键动作 | 一句话 |
|:----:|---------|--------|
| 装 Docker | rpm 包或静态二进制 | 一次装好，多机复用 |
| 搞镜像 | 外网 pull → save → 内网 load | 最直接的方式 |
| 多机共享 | 自建 Registry + insecure-registries | 一台 push，全网 pull |
| 架构 | x86/ARM 镜像必须匹配 | &lt;code&gt;exec format error&lt;/code&gt; 就是它 |
| 编排 | docker-compose 二进制 | 部署监控/数据库必备 |&lt;/p&gt;
&lt;p&gt;下一篇进入监控体系前，先把 Docker 用起来——后面的 VictoriaMetrics、Grafana 都会用它部署。&lt;/p&gt;
&lt;hr&gt;
&lt;blockquote&gt;
&lt;p&gt;本文首发于掘金 · 作者：七万号
扎根雄安新区中关村科技园，专注受限环境下软件搭建与数据平台落地&lt;/p&gt;
&lt;/blockquote&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>JDK 安装与环境变量配置——每个数据平台的起点</title><link>https://realcpf.tech/blog/airgapped-jdk-env</link><guid isPermaLink="true">https://realcpf.tech/blog/airgapped-jdk-env</guid><description>明朗北街七万号·数研工坊｜扎根雄安新区中关村科技园，专注受限环境下软件搭建与数据平台落地</description><pubDate>Sat, 01 Aug 2026 01:00:00 GMT</pubDate><content:encoded>&lt;blockquote&gt;
&lt;p&gt;明朗北街七万号·数研工坊｜扎根雄安新区中关村科技园，专注受限环境下软件搭建与数据平台落地&lt;/p&gt;
&lt;/blockquote&gt;
&lt;hr&gt;
&lt;h2&gt;适用场景&lt;/h2&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;如果你属于以下任一种情况，这篇对你有用：&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;内网环境要装任何 Java 系组件（Flink、Spark、SeaTunnel、Doris、各类微服务）&lt;/li&gt;
&lt;li&gt;服务器上需要同时存在多个 JDK 版本（不同组件对版本要求不同）&lt;/li&gt;
&lt;li&gt;刚装完系统，准备开始搭建数据平台（第 4 篇 GCC 之后）&lt;/li&gt;
&lt;li&gt;遇到 &lt;code&gt;java: command not found&lt;/code&gt; 或 &lt;code&gt;UnsupportedClassVersionError&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;
&lt;p&gt;&lt;strong&gt;应用范围：&lt;/strong&gt; 几乎所有大数据组件都运行在 JVM 上。JDK 装不对、环境变量配不好，后面 Flink/Spark/SeaTunnel 全部启动不起来。这是数据平台的第零号前置。&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;一、问题&lt;/h2&gt;
&lt;p&gt;装好了系统，编译好了 GCC，接下来要装 Java 系组件。但：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;java -version
# bash: java: command not found
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;JDK 从哪来？怎么装？装哪个版本？配哪些环境变量？——在内网环境，每一步都有讲究。&lt;/p&gt;
&lt;h2&gt;二、约束&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;无公网，无法用 &lt;code&gt;apt install openjdk&lt;/code&gt; 或从 Oracle 官网下载&lt;/li&gt;
&lt;li&gt;不同组件对 JDK 版本要求不同（Flink 1.14 要 Java 8/11，SeaTunnel 2.x 要 Java 8+，Doris 用 Java 8）&lt;/li&gt;
&lt;li&gt;内网环境通常要长期维护，JDK 不能随意升级&lt;/li&gt;
&lt;li&gt;ARM 架构机器需要对应版本的 JDK&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;三、JDK 版本选择&lt;/h2&gt;
&lt;h3&gt;3.1 版本选哪个？&lt;/h3&gt;
&lt;p&gt;| 组件 | 推荐 JDK |
|------|:--------:|
| Flink 1.14+ | Java 8 / 11 |
| Spark 3.x | Java 8 / 11 / 17 |
| SeaTunnel 2.x | Java 8+ |
| Doris | Java 8（JDK 8 最稳） |
| Elasticsearch 7.x | Java 8 / 11 |
| Kafka 3.x | Java 8 / 11 |
| 自研 Spring Boot 服务 | Java 8 / 17 / 21 |&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;内网环境建议：优先 JDK 8，兼容性最好。&lt;/strong&gt; 大数据组件对 Java 8 的支持最成熟。如果你有明确的新版本需求（如 Spring Boot 3 强制 Java 17+），再单独装 17。&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;版本选择逻辑：先看组件要求，再定 JDK，而不是先装最新 JDK。&lt;/strong&gt;&lt;/p&gt;
&lt;h3&gt;3.2 下载哪个发行版？&lt;/h3&gt;
&lt;p&gt;内网环境建议用 &lt;strong&gt;Eclipse Temurin（Adoptium）&lt;/strong&gt; 或 &lt;strong&gt;OpenJDK&lt;/strong&gt;：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# Temurin JDK 8 (x86_64)
wget https://mirrors.tuna.tsinghua.edu.cn/Adoptium/8/jdk/x64/linux/OpenJDK8U-jdk_x64_linux_hotspot_8u412b08.tar.gz

# Temurin JDK 11 (x86_64)
wget https://mirrors.tuna.tsinghua.edu.cn/Adoptium/11/jdk/x64/linux/OpenJDK11U-jdk_x64_linux_hotspot_11.0.23_9.tar.gz

# ARM64 (aarch64) 版本：把路径中的 x64 换成 aarch64
wget https://mirrors.tuna.tsinghua.edu.cn/Adoptium/8/jdk/aarch64/linux/OpenJDK8U-jdk_aarch64_linux_hotspot_8u412b08.tar.gz
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;清华 TUNA 有 Adoptium 的完整镜像，路径规律：&lt;code&gt;/Adoptium/&amp;#x3C;版本&gt;/jdk/&amp;#x3C;架构&gt;/linux/&amp;#x3C;文件名&gt;&lt;/code&gt;。
记住：&lt;strong&gt;架构后缀（x64 / aarch64）必须和服务器 CPU 匹配&lt;/strong&gt;，否则启动直接报错。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;四、离线安装 JDK&lt;/h2&gt;
&lt;h3&gt;4.1 推荐方式：tar.gz 解压（不用 rpm）&lt;/h3&gt;
&lt;p&gt;rpm 安装的 JDK 会把文件散落到系统目录，不易管理。tar.gz 解压到统一目录，多版本共存更清晰：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# 创建统一目录
mkdir -p /usr/local/java

# 解压
tar xzf OpenJDK8U-jdk_x64_linux_hotspot_8u412b08.tar.gz -C /usr/local/java/

# 查看解压结果
ls /usr/local/java/
# jdk8u412-b08
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;4.2 规范：使用软链接固定版本&lt;/h3&gt;
&lt;p&gt;实际使用中经常要切换版本，用软链接把「当前版本」指到固定名字：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;ln -sf /usr/local/java/jdk8u412-b08 /usr/local/java/current
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;之后配置环境变量指向 &lt;code&gt;current&lt;/code&gt;，以后升级 JDK 只需要换软链接。&lt;/p&gt;
&lt;h2&gt;五、环境变量配置&lt;/h2&gt;
&lt;h3&gt;5.1 三个必须配置的变量&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;export JAVA_HOME=/usr/local/java/current
export PATH=$JAVA_HOME/bin:$PATH
export CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;JAVA_HOME&lt;/strong&gt;：Java 安装根目录。很多组件（Flink、Spark、Maven）通过它找 JDK&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;PATH&lt;/strong&gt;：让 &lt;code&gt;java&lt;/code&gt;、&lt;code&gt;javac&lt;/code&gt; 命令可用&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;CLASSPATH&lt;/strong&gt;：类搜索路径。现代 Java 一般不需要手动配，但老组件可能依赖&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;5.2 写入全局配置（推荐）&lt;/h3&gt;
&lt;p&gt;创建 &lt;code&gt;/etc/profile.d/java.sh&lt;/code&gt;：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;cat &gt; /etc/profile.d/java.sh &amp;#x3C;&amp;#x3C; &apos;EOF&apos;
export JAVA_HOME=/usr/local/java/current
export PATH=$JAVA_HOME/bin:$PATH
EOF
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;这样所有用户登录都会自动加载：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;source /etc/profile
java -version
# openjdk version &quot;1.8.0_412&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;5.3 系统级 vs 用户级&lt;/h3&gt;
&lt;p&gt;| 位置 | 生效范围 | 适用场景 |
|------|---------|---------|
| &lt;code&gt;/etc/profile.d/*.sh&lt;/code&gt; | 所有用户 | &lt;strong&gt;内网服务器推荐&lt;/strong&gt; |
| &lt;code&gt;/etc/profile&lt;/code&gt; | 所有用户（登录 shell） | 传统方式 |
| &lt;code&gt;~/.bashrc&lt;/code&gt; | 单个用户 | 个人开发机 |
| &lt;code&gt;~/.bash_profile&lt;/code&gt; | 单个用户（登录 shell） | macOS 习惯 |&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;内网多台机器&lt;/strong&gt;建议统一用 &lt;code&gt;/etc/profile.d/java.sh&lt;/code&gt;，这样所有机器配置一致，脚本化部署也方便。&lt;/p&gt;
&lt;h2&gt;六、多版本 JDK 共存&lt;/h2&gt;
&lt;h3&gt;6.1 场景&lt;/h3&gt;
&lt;p&gt;Flink 要 Java 8，新的 Spring Boot 3 要 Java 17。共存方案：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# 两个 JDK 都解压到 /usr/local/java/
/usr/local/java/jdk8u412-b08
/usr/local/java/jdk-17.0.11

# 各自独立，通过软链接切换
ln -sf /usr/local/java/jdk8u412-b08 /usr/local/java/current   # 切到 8
ln -sf /usr/local/java/jdk-17.0.11 /usr/local/java/current    # 切到 17
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;6.2 组件级指定（更精细）&lt;/h3&gt;
&lt;p&gt;很多组件支持在启动脚本里指定 JAVA_HOME，不依赖全局变量：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# 以 Flink 为例，编辑 conf/flink-env.sh
export JAVA_HOME=/usr/local/java/jdk8u412-b08

# Spark 同理，spark-env.sh
export JAVA_HOME=/usr/local/java/jdk8u412-b08
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;多版本共存的正确姿势：全局一个默认版本，组件各自指定所需版本。&lt;/strong&gt;&lt;/p&gt;
&lt;h2&gt;七、验证与排障&lt;/h2&gt;
&lt;h3&gt;7.1 验证安装&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;java -version
javac -version
echo $JAVA_HOME
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;7.2 常见坑&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;坑 1：&lt;code&gt;java: command not found&lt;/code&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;PATH 没配好。&lt;code&gt;source /etc/profile&lt;/code&gt; 后再试。如果还是不行，确认 &lt;code&gt;/etc/profile.d/java.sh&lt;/code&gt; 是否被执行（&lt;code&gt;ls /etc/profile.d/&lt;/code&gt; 检查文件权限，需要可读）。&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;坑 2：&lt;code&gt;UnsupportedClassVersionError&lt;/code&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;JDK 版本太低。编译用的 JDK 版本高于运行环境。解决：升级 JDK 或降级编译目标（&lt;code&gt;-source 1.8 -target 1.8&lt;/code&gt;）。&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;坑 3：&lt;code&gt;Error: Could not create the Java Virtual Machine&lt;/code&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;内存不够。JVM 启动时申请的内存超过机器可用内存，调小 &lt;code&gt;-Xmx&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;坑 4：启动报 &lt;code&gt;libjli.so: cannot open shared object file&lt;/code&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;少见但内网环境会遇到：JDK 解压到某个路径后目录被移动。重新解压到最终路径，或检查 &lt;code&gt;$JAVA_HOME&lt;/code&gt; 路径是否真的存在。&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;坑 5：&lt;code&gt;Unable to locate a Java Runtime&lt;/code&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;组件脚本找不到 JAVA_HOME。在组件配置里显式指定（6.2 节的做法）。&lt;/p&gt;
&lt;h2&gt;八、总结&lt;/h2&gt;
&lt;p&gt;| 环节 | 关键动作 | 一句话 |
|:----:|---------|--------|
| 选版本 | 看组件要求，别追新 | 大数据组件默认 Java 8 |
| 下载 | Temurin，注意架构 x64/aarch64 | 架构错=装不上 |
| 安装 | tar.gz 解压到 /usr/local/java | 统一目录好管理 |
| 配置 | /etc/profile.d/java.sh | 全机器统一 |
| 多版本 | 软链接 current + 组件单独指定 | 全局一个默认 |&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;数据平台的第零号前置，就是把这五个字搞定：JAVA_HOME 对。&lt;/strong&gt;&lt;/p&gt;
&lt;hr&gt;
&lt;blockquote&gt;
&lt;p&gt;本文首发于掘金 · 作者：七万号
扎根雄安新区中关村科技园，专注受限环境下软件搭建与数据平台落地&lt;/p&gt;
&lt;/blockquote&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>离线编译 GCC——一个看似简单实则劝退的操作</title><link>https://realcpf.tech/blog/airgapped-gcc-build</link><guid isPermaLink="true">https://realcpf.tech/blog/airgapped-gcc-build</guid><description>明朗北街七万号·数研工坊｜扎根雄安新区中关村科技园，专注受限环境下软件搭建与数据平台落地</description><pubDate>Sat, 01 Aug 2026 00:30:00 GMT</pubDate><content:encoded>&lt;blockquote&gt;
&lt;p&gt;明朗北街七万号·数研工坊｜扎根雄安新区中关村科技园，专注受限环境下软件搭建与数据平台落地&lt;/p&gt;
&lt;/blockquote&gt;
&lt;hr&gt;
&lt;h2&gt;适用场景&lt;/h2&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;如果你属于以下任一种情况，这篇对你有用：&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;内网环境需要编译 C/C++ 源码，但系统自带的 gcc 版本太低&lt;/li&gt;
&lt;li&gt;需要在新版本编译器下编译大数据组件（如 ClickHouse、DuckDB、部分机器学习库）&lt;/li&gt;
&lt;li&gt;系统自带的 yum 源里找不到新版 gcc（第 3 篇镜像源里只有基础包）&lt;/li&gt;
&lt;li&gt;需要交叉编译 ARM 架构的软件（飞腾、鲲鹏平台）&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;
&lt;p&gt;&lt;strong&gt;应用范围：&lt;/strong&gt; 一切需要从源码编译的场景。很多开源软件的官方文档要求 &lt;code&gt;gcc 9+&lt;/code&gt;，而内网系统自带的多是 gcc 4.8（CentOS 7 经典问题）或 gcc 8.x（openEuler）。编译新版 GCC 是绕不开的一步。&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;一、问题&lt;/h2&gt;
&lt;p&gt;内网环境，需要编译一个依赖新特性的 C++ 库，但：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;gcc --version
# gcc (GCC) 4.8.5  ← CentOS 7 标配
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;代码一编译就报错：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;error: &apos;std::filesystem&apos; has not been declared
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;需要 gcc 9+。yum 源里没有（第 3 篇说过，ISO 里的包是固定的）。怎么办？——从源码编译 GCC。&lt;/p&gt;
&lt;h2&gt;二、约束&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;无公网，无法直接下载&lt;/li&gt;
&lt;li&gt;编译 GCC 需要&lt;strong&gt;前置依赖&lt;/strong&gt;（GMP、MPFR、MPC 三个库），它们不在 ISO 里&lt;/li&gt;
&lt;li&gt;编译 GCC 耗时较长（1-3 小时，取决于机器性能）&lt;/li&gt;
&lt;li&gt;编译失败排查难度大&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;三、准备工作：在联网机器上打包依赖&lt;/h2&gt;
&lt;h3&gt;3.1 获取源码包&lt;/h3&gt;
&lt;p&gt;在&lt;strong&gt;有外网的机器&lt;/strong&gt;上下载以下源码包：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# GCC 源码（以 9.3.0 为例）
wget https://mirrors.aliyun.com/gnu/gcc/gcc-9.3.0/gcc-9.3.0.tar.gz

# GCC 依赖的三个库（GMP、MPFR、MPC）
wget https://mirrors.aliyun.com/gnu/gmp/gmp-6.1.2.tar.bz2
wget https://mirrors.aliyun.com/gnu/mpfr/mpfr-4.0.2.tar.bz2
wget https://mirrors.aliyun.com/gnu/mpc/mpc-1.1.0.tar.gz
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;3.2 国内镜像源&lt;/h3&gt;
&lt;p&gt;上面用的是阿里云镜像。其他选择：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;清华 TUNA：&lt;code&gt;https://mirrors.tuna.tsinghua.edu.cn/gnu/gcc/&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;中科大 USTC：&lt;code&gt;https://mirrors.ustc.edu.cn/gnu/gcc/&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;3.3 打包上传&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;tar czf gcc-offline.tar.gz gcc-9.3.0.tar.gz gmp-6.1.2.tar.bz2 mpfr-4.0.2.tar.bz2 mpc-1.1.0.tar.gz
# 传到内网服务器（用第 2 篇的 rsync/scp）
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;四、内网编译&lt;/h2&gt;
&lt;h3&gt;4.1 解压&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;tar xzf gcc-offline.tar.gz
cd gcc-9.3.0
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;4.2 一键下载依赖？——不行&lt;/h3&gt;
&lt;p&gt;GCC 源码目录里有个 &lt;code&gt;contrib/download_prerequisites&lt;/code&gt; 脚本，它会自动下载 GMP/MPFR/MPC。&lt;strong&gt;但在内网环境用不了&lt;/strong&gt;（它从外网下载）。&lt;/p&gt;
&lt;p&gt;替代方案：手动把三个依赖包放进源码目录，让编译系统自动识别：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# 把三个依赖包复制到 gcc 源码目录
cp ../gmp-6.1.2.tar.bz2 ./
cp ../mpfr-4.0.2.tar.bz2 ./
cp ../mpc-1.1.0.tar.gz ./

# 解压并创建软链接（GCC 编译脚本会按名字找）
tar xjf gmp-6.1.2.tar.bz2
tar xjf mpfr-4.0.2.tar.bz2
tar xzf mpc-1.1.0.tar.gz

ln -sf gmp-6.1.2 gmp
ln -sf mpfr-4.0.2 mpfr
ln -sf mpc-1.1.0 mpc
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;关键点：GCC 源码根目录下的 build 脚本会检测 &lt;code&gt;gmp/&lt;/code&gt;、&lt;code&gt;mpfr/&lt;/code&gt;、&lt;code&gt;mpc/&lt;/code&gt; 这三个软链接目录，存在就跳过下载。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;4.3 创建独立编译目录&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;不要直接在源码目录里 make&lt;/strong&gt;，这是 GCC 编译的经典规范：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;mkdir build &amp;#x26;&amp;#x26; cd build
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;4.4 配置编译参数&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;../configure \
    --prefix=/usr/local/gcc-9.3.0 \
    --enable-languages=c,c++ \
    --disable-multilib \
    --disable-bootstrap
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;参数说明：&lt;/p&gt;
&lt;p&gt;| 参数 | 作用 | 建议 |
|------|------|:----:|
| &lt;code&gt;--prefix&lt;/code&gt; | 安装路径 | 装到独立目录，方便多版本共存 |
| &lt;code&gt;--enable-languages=c,c++&lt;/code&gt; | 只要 C/C++ | 数据平台场景够用，别全开 |
| &lt;code&gt;--disable-multilib&lt;/code&gt; | 不编译多架构库 | 省一半编译时间 |
| &lt;code&gt;--disable-bootstrap&lt;/code&gt; | 不用三步自举编译 | 大幅缩短编译时间（首次编译没必要） |&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;⚠️ 如果嫌编译慢，&lt;code&gt;--disable-bootstrap&lt;/code&gt; 是最大的省时开关。三步 bootstrap 会让编译时间翻倍甚至三倍，首次编译完全没必要。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;4.5 编译安装&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;make -j$(nproc)
# -j 用满所有核，nproc 返回 CPU 核数
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;编译耗时取决于机器：8 核机器大约 40-60 分钟，4 核要 1.5-2 小时。&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;make install
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;4.6 验证&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;/usr/local/gcc-9.3.0/bin/gcc --version
# gcc (GCC) 9.3.0
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;写个简单的 C++17 测试：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;cat &gt; test.cpp &amp;#x3C;&amp;#x3C; &apos;EOF&apos;
#include &amp;#x3C;iostream&gt;
#include &amp;#x3C;filesystem&gt;
int main() {
    std::cout &amp;#x3C;&amp;#x3C; &quot;GCC OK: &quot; &amp;#x3C;&amp;#x3C; std::filesystem::current_path() &amp;#x3C;&amp;#x3C; std::endl;
    return 0;
}
EOF

/usr/local/gcc-9.3.0/bin/g++ -std=c++17 test.cpp -o test &amp;#x26;&amp;#x26; ./test
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;能输出路径就说明 &lt;code&gt;std::filesystem&lt;/code&gt; 可用，编译成功。&lt;/p&gt;
&lt;h2&gt;五、让系统默认使用新 GCC&lt;/h2&gt;
&lt;p&gt;编译完只是第一步，要让后续编译命令默认用新版：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# 加入 PATH（写入 /etc/profile.d/gcc.sh）
cat &gt; /etc/profile.d/gcc.sh &amp;#x3C;&amp;#x3C; &apos;EOF&apos;
export PATH=/usr/local/gcc-9.3.0/bin:$PATH
export LD_LIBRARY_PATH=/usr/local/gcc-9.3.0/lib64:$LD_LIBRARY_PATH
EOF

source /etc/profile.d/gcc.sh
gcc --version
# 现在默认就是 9.3.0
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;六、踩坑记录&lt;/h2&gt;
&lt;h3&gt;坑 1：编译报 &lt;code&gt;cannot find -lgmp&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;依赖库没被识别。确认 &lt;code&gt;gmp/&lt;/code&gt;、&lt;code&gt;mpfr/&lt;/code&gt;、&lt;code&gt;mpc/&lt;/code&gt; 软链接在 GCC 源码根目录下，且在 &lt;code&gt;build&lt;/code&gt; 目录配置前建立。&lt;/p&gt;
&lt;h3&gt;坑 2：&lt;code&gt;make&lt;/code&gt; 卡在某一步特别久&lt;/h3&gt;
&lt;p&gt;GCC 编译 libstdc++ 时会有一次比较久的过程，属正常。如果超过 30 分钟无输出，检查 &lt;code&gt;make -j&lt;/code&gt; 的核数是不是超过了实际核数导致内存溢出（&lt;code&gt;-j$(nproc)&lt;/code&gt; 一般没问题，但如果是虚拟机建议 &lt;code&gt;-j2&lt;/code&gt;）。&lt;/p&gt;
&lt;h3&gt;坑 3：编译期内存不足&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;make -j8&lt;/code&gt; 在 4G 内存的机器上容易 OOM。降核数：&lt;code&gt;make -j2&lt;/code&gt;。或者配置时加 &lt;code&gt;--disable-libsanitizer&lt;/code&gt; 减少内存占用。&lt;/p&gt;
&lt;h3&gt;坑 4：装完 gcc 却找不到 g++&lt;/h3&gt;
&lt;p&gt;检查 configure 是否带了 &lt;code&gt;--enable-languages=c,c++&lt;/code&gt;。只写 &lt;code&gt;c&lt;/code&gt; 就不会编 g++。&lt;/p&gt;
&lt;h3&gt;坑 5：磁盘空间不足&lt;/h3&gt;
&lt;p&gt;GCC 源码 + build 目录 + 安装结果，总共需要约 6-8GB。提前 &lt;code&gt;df -h&lt;/code&gt; 确认。&lt;/p&gt;
&lt;h2&gt;七、总结&lt;/h2&gt;
&lt;p&gt;离线编译 GCC 的完整流程：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;外网下载源码+依赖 → 打包 → 上传内网
→ 解压+软链接依赖 → 建 build 目录 → configure → make → make install
→ 配置 PATH → 验证编译
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;核心就三个字：&lt;strong&gt;依赖全、别图快、验证过。&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;| 环节 | 关键动作 |
|:----:|---------|
| 依赖 | GMP/MPFR/MPC 必须手动放进源码目录并建软链接 |
| 编译 | 独立 build 目录 + &lt;code&gt;--disable-bootstrap&lt;/code&gt; 省时间 |
| 安装 | 独立 prefix，方便多版本共存 |
| 验证 | 编译一个实际用的 C++17 程序，别只看 gcc --version |&lt;/p&gt;
&lt;hr&gt;
&lt;blockquote&gt;
&lt;p&gt;本文首发于掘金 · 作者：七万号
扎根雄安新区中关村科技园，专注受限环境下软件搭建与数据平台落地&lt;/p&gt;
&lt;/blockquote&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>打通第一公里：内网 SSH、SCP 与防火墙策略</title><link>https://realcpf.tech/blog/airgapped-ssh-scp-firewall</link><guid isPermaLink="true">https://realcpf.tech/blog/airgapped-ssh-scp-firewall</guid><description>明朗北街七万号·数研工坊｜扎根雄安新区中关村科技园，专注受限环境下软件搭建与数据平台落地</description><pubDate>Sat, 01 Aug 2026 00:00:00 GMT</pubDate><content:encoded>&lt;blockquote&gt;
&lt;p&gt;明朗北街七万号·数研工坊｜扎根雄安新区中关村科技园，专注受限环境下软件搭建与数据平台落地&lt;/p&gt;
&lt;/blockquote&gt;
&lt;hr&gt;
&lt;h2&gt;适用场景&lt;/h2&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;如果你属于以下任一种情况，这篇对你有用：&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;刚装好操作系统，需要远程管理服务器（第 1 篇的后续）&lt;/li&gt;
&lt;li&gt;内网环境多台服务器之间需要互相传文件&lt;/li&gt;
&lt;li&gt;部署中间件时发现端口连不上，排查半天发现是防火墙&lt;/li&gt;
&lt;li&gt;数据平台集群搭建前，需要先打通机器之间的网络&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;
&lt;p&gt;&lt;strong&gt;应用范围：&lt;/strong&gt; 所有内网 Linux 服务器管理、文件传输、服务端口放行。这是搭建任何数据平台的前置技能——第 3 篇（镜像源）、第 6 篇（Docker）都会依赖它。&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;一、问题&lt;/h2&gt;
&lt;p&gt;服务器装好了系统，但你不能整天坐在机房操作。你需要远程登录、传文件、开端口。但内网环境没有云控制台给你点按钮，一切都要命令行搞定。&lt;/p&gt;
&lt;p&gt;而且内网环境有个特点：&lt;strong&gt;机器多、网络复杂、安全要求高&lt;/strong&gt;。SSH 配置不好会连不上，防火墙开太大又过不了安全审计。&lt;/p&gt;
&lt;h2&gt;二、约束&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;无公网 IP，全部走内网 IP&lt;/li&gt;
&lt;li&gt;多台服务器之间需要互相访问&lt;/li&gt;
&lt;li&gt;数据平台组件需要开放大量端口&lt;/li&gt;
&lt;li&gt;安全要求：不能直接 &lt;code&gt;systemctl stop firewalld&lt;/code&gt; 一关了事（有些环境过不了审）&lt;/li&gt;
&lt;li&gt;部分服务器无显示器，只能远程操作&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;三、SSH：远程管理的基石&lt;/h2&gt;
&lt;h3&gt;3.1 基本配置&lt;/h3&gt;
&lt;p&gt;SSH 服务端默认端口 22。装完系统后先确认服务在跑：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;systemctl status sshd
# 没装的话
yum install -y openssh-server
systemctl enable --now sshd
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;客户端连接：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;ssh root@192.168.1.100
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;3.2 密钥登录：内网运维的正确姿势&lt;/h3&gt;
&lt;p&gt;密码登录在内网环境有两大痛点：一是每次都要输密码，二是多台机器密码管理混乱。密钥登录是标准做法。&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;生成密钥对（在本地机器上）：&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;ssh-keygen -t ed25519 -C &quot;deploy@internal&quot;
# 一路回车，会在 ~/.ssh/ 下生成 id_ed25519（私钥）和 id_ed25519.pub（公钥）
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;复制公钥到目标服务器：&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;ssh-copy-id root@192.168.1.100
# 首次会要求输入密码，之后就可以免密登录
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;验证：&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;ssh root@192.168.1.100
# 不再要求密码，直接登录成功
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;禁用密码登录（安全加固）：&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;编辑 &lt;code&gt;/etc/ssh/sshd_config&lt;/code&gt;：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;PasswordAuthentication no
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;然后重启 SSH：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;systemctl restart sshd
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;⚠️ 禁用密码登录前，务必确认密钥已经能正常登录。否则你会把自己锁在门外。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;3.3 内网 SSH 的两个坑&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;坑 1：连接特别慢&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;症状：输入 ssh 命令后要等 5-10 秒才提示输密码。
原因：DNS 反向解析超时。&lt;/p&gt;
&lt;p&gt;解决：编辑 &lt;code&gt;/etc/ssh/sshd_config&lt;/code&gt;，加一行：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;UseDNS no
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;坑 2：局域网内多台机器 IP 难记&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;在本地 &lt;code&gt;~/.ssh/config&lt;/code&gt; 里配置别名：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Host node1
    HostName 192.168.1.100
    User root
    Port 22

Host node2
    HostName 192.168.1.101
    User root
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;之后直接 &lt;code&gt;ssh node1&lt;/code&gt; 就行。&lt;/p&gt;
&lt;h2&gt;四、SCP：内网传文件&lt;/h2&gt;
&lt;p&gt;scp 基于 SSH，无需额外配置，装好 SSH 就能用。&lt;/p&gt;
&lt;h3&gt;4.1 基本用法&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;# 本地上传到服务器
scp ./app.tar.gz root@192.168.1.100:/opt/

# 服务器下载到本地
scp root@192.168.1.100:/opt/backup.sql ./

# 传目录加 -r
scp -r ./configs/ root@192.168.1.100:/etc/

# 指定端口
scp -P 22022 ./app.tar.gz root@192.168.1.100:/opt/
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;4.2 大文件传输的坑&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;坑：传大文件（几个 G 的 ISO、镜像包）断断续续&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;scp 不支持断点续传。传一半断了只能重来。解决方式：&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;方案 A：用 rsync（推荐）&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;rsync -avP ./big-file.iso root@192.168.1.100:/opt/
# -P = --partial + --progress，支持断点续传
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;方案 B：分卷压缩再传&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# 本地分卷
tar czf - ./data/ | split -b 2G - part-
# 传所有分卷
scp part-* root@192.168.1.100:/opt/
# 远端合并解压
cat part-* | tar xzf -
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;4.3 内网传输加速技巧&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;内网带宽通常足够，瓶颈常在磁盘 IO。用 &lt;code&gt;rsync -z&lt;/code&gt; 压缩传输能显著加速（针对文本类文件）&lt;/li&gt;
&lt;li&gt;多文件并行传输：&lt;code&gt;rsync&lt;/code&gt; 加 &lt;code&gt;-P&lt;/code&gt; 后多开几个终端窗口分别传不同目录&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;五、防火墙：放行还是不开？&lt;/h2&gt;
&lt;h3&gt;5.1 先搞清楚你面对的是哪一套&lt;/h3&gt;
&lt;p&gt;CentOS/RHEL 系 7+ 用 firewalld，6 及以下用 iptables。openEuler、KylinOS 默认都是 firewalld。先看：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;systemctl status firewalld
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;5.2 firewalld 基本操作&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;# 查看当前放行规则
firewall-cmd --list-all

# 放行一个端口
firewall-cmd --permanent --add-port=8080/tcp
firewall-cmd --reload

# 放行一个服务（如果内置了）
firewall-cmd --permanent --add-service=http
firewall-cmd --reload

# 移除端口
firewall-cmd --permanent --remove-port=8080/tcp
firewall-cmd --reload
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;⚠️ 记得 &lt;code&gt;--permanent&lt;/code&gt; 后一定要 &lt;code&gt;--reload&lt;/code&gt;，否则重启后失效。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;5.3 数据平台常见端口清单（速查）&lt;/h3&gt;
&lt;p&gt;| 组件 | 端口 | 协议 | 放行说明 |
|------|:----:|:----:|---------|
| SSH | 22 | TCP | 必须放行 |
| MySQL | 3306 | TCP | 应用服务器 → 数据库 |
| PostgreSQL | 5432 | TCP | 应用服务器 → 数据库 |
| Redis | 6379 | TCP | 应用服务器 → 缓存 |
| Kafka | 9092 | TCP | 生产者/消费者 |
| Nginx | 80/443 | TCP | 对外服务 |
| Flink WebUI | 8081 | TCP | 运维访问 |
| Spark UI | 4040 | TCP | 运维访问 |
| Doris FE | 8030/9030 | TCP | FE 管理口/查询口 |
| Grafana | 3000 | TCP | 运维访问 |
| Prometheus/VM | 9090/8428 | TCP | 监控采集 |
| 节点间通信 | 全开 | TCP | 集群内部 |&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;内网集群内部通信端口&lt;/strong&gt;：如果安全要求允许，集群节点之间建议直接放行整个网段：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;firewall-cmd --permanent --add-rich-rule=&apos;rule family=&quot;ipv4&quot; source address=&quot;192.168.1.0/24&quot; accept&apos;
firewall-cmd --reload
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;5.4 什么时候可以关防火墙&lt;/h3&gt;
&lt;p&gt;内网数据平台环境，如果集群规模小、无外部访问、安全审计不严，调试阶段直接关掉省心：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;systemctl stop firewalld
systemctl disable firewalld
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;但如果你要过等保/安全审计，就用上面的按需放行方式，并保留完整的端口清单文档——审计时直接给清单，比「我关了防火墙」体面得多。&lt;/p&gt;
&lt;h2&gt;六、总结&lt;/h2&gt;
&lt;p&gt;| 技能 | 核心命令 | 记住一点 |
|------|---------|---------|
| SSH 登录 | &lt;code&gt;ssh-keygen&lt;/code&gt; + &lt;code&gt;ssh-copy-id&lt;/code&gt; | 密钥登录，禁用密码 |
| SSH 调优 | &lt;code&gt;UseDNS no&lt;/code&gt; | 解决连接慢 |
| 文件传输 | &lt;code&gt;rsync -avP&lt;/code&gt; | 断点续传，比 scp 可靠 |
| 防火墙放行 | &lt;code&gt;firewall-cmd --permanent --add-port=xxx/tcp&lt;/code&gt; | 加 &lt;code&gt;--reload&lt;/code&gt; |
| 集群互通 | 放行整个内网网段 | 省心且可审计 |&lt;/p&gt;
&lt;p&gt;内网环境下的第一公里打通，就是这三件事：&lt;strong&gt;SSH 能登、文件能传、端口能通。&lt;/strong&gt; 搞定这三样，后面搭镜像源、装 Docker、部署数据平台才有基础。&lt;/p&gt;
&lt;hr&gt;
&lt;blockquote&gt;
&lt;p&gt;本文首发于掘金 · 作者：七万号
扎根雄安新区中关村科技园，专注受限环境下软件搭建与数据平台落地&lt;/p&gt;
&lt;/blockquote&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>Spring Boot 在有限资源下的部署策略——一次 Tomcat 合并部署的真实实验</title><link>https://realcpf.tech/blog/springboot-tomcat-deploy</link><guid isPermaLink="true">https://realcpf.tech/blog/springboot-tomcat-deploy</guid><description>明朗北街七万号·数研工坊｜扎根雄安新区中关村科技园，专注受限环境下软件搭建与数据平台落地</description><pubDate>Fri, 31 Jul 2026 01:30:00 GMT</pubDate><content:encoded>&lt;blockquote&gt;
&lt;p&gt;明朗北街七万号·数研工坊｜扎根雄安新区中关村科技园，专注受限环境下软件搭建与数据平台落地&lt;/p&gt;
&lt;/blockquote&gt;
&lt;hr&gt;
&lt;h2&gt;一、问题&lt;/h2&gt;
&lt;p&gt;假设我们有 20 多个服务的微服务集群，但甲方要降本增效，服务器资源直接砍半。&lt;/p&gt;
&lt;p&gt;我们怎么办？&lt;/p&gt;
&lt;p&gt;当然，如果从架构设计当初就考虑好了，支持服务按模块方式聚合，当然就不是问题了。但我们大多时候考虑的都是如何支持更大体量的业务、更高的并发、扩容分布式多实例——很少考虑资源缩小的问题。&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;二、可选方案&lt;/h2&gt;
&lt;p&gt;面对资源砍半的约束，我列举了以下几种可行的方向：&lt;/p&gt;
&lt;p&gt;| # | 方案 | 说明 | 改造成本 |
|:-:|------|------|:--------:|
| 1 | JVM 调优 | 对每个服务监控分析，调节 JVM 参数 | 低 |
| 2 | &lt;strong&gt;Tomcat 合并部署&lt;/strong&gt; | 改造为 war 包，多个服务部署到同一 Tomcat | &lt;strong&gt;中&lt;/strong&gt; |
| 3 | 代码融合 | 直接做代码整合，缩减服务数量 | 高 |
| 4 | Spring Modulith | Spring Boot 官方模块化方案 | 中高 |
| 5 | Koupleless / SOFAArk | 动态加载的热部署模式，快速聚合 | 中 |&lt;/p&gt;
&lt;p&gt;方案 4 算是比较均衡的，但需要较强的架构思维和业务梳理能力。方案 5 适合快速验证。方案 1 和 3 不做展开。&lt;/p&gt;
&lt;p&gt;我对&lt;strong&gt;方案 2 进行改造和验证&lt;/strong&gt;——将多个 Spring Boot 服务改造为 war 包，统一部署到一个 Tomcat 中。&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;三、实验过程&lt;/h2&gt;
&lt;h3&gt;测试环境&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;拉取开源项目 SpringBlade 的代码&lt;/li&gt;
&lt;li&gt;启动 6 个核心服务：blade-develop、blade-admin、blade-auth、blade-report、blade-resource、blade-system&lt;/li&gt;
&lt;li&gt;JVM 参数统一设置为 -Xmx 768m&lt;/li&gt;
&lt;li&gt;对比两轮：独立 jar 启动 vs 合并 war 部署到 Tomcat 11&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;独立 JAR 模式&lt;/h3&gt;
&lt;p&gt;六个服务分别以 java -jar 启动，在 Nacos 中注册为独立实例。&lt;/p&gt;
&lt;h3&gt;Tomcat 合并模式&lt;/h3&gt;
&lt;p&gt;简单改造启动类后，将六个服务的 war 包放入 Tomcat 11 的 webapps 目录，通过健康接口确认全部正常启动。&lt;/p&gt;
&lt;h3&gt;资源占用对比&lt;/h3&gt;
&lt;p&gt;| 模式 | PID | RES | MEM% |
|:----:|:---:|:---:|:----:|
| &lt;strong&gt;Tomcat 合并&lt;/strong&gt; | 147478 | &lt;strong&gt;3.4g&lt;/strong&gt; | &lt;strong&gt;11.2%&lt;/strong&gt; |
| blade-develop | 160608 | 987.2m | 3.1% |
| blade-admin | 160049 | 1.4g | 4.6% |
| blade-auth | 160417 | 989.5m | 3.1% |
| blade-report | 160178 | 1.1g | 3.7% |
| blade-resource | 160739 | 986.5m | 3.1% |
| blade-system | 160262 | 1.0g | 3.2% |
| &lt;strong&gt;JAR 合计&lt;/strong&gt; | 6 个进程 | &lt;strong&gt;~6.4g&lt;/strong&gt; | &lt;strong&gt;~20.8%&lt;/strong&gt; |&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;四、结果分析&lt;/h2&gt;
&lt;h3&gt;预期与现实的差距&lt;/h3&gt;
&lt;p&gt;说实话，在做这个实验之前，我的预期是 Tomcat 部署多个服务会比独立 JAR 有明显的资源节省。但实际数据告诉我——差距不是想象中那种数量级的差异。&lt;/p&gt;
&lt;p&gt;6 个独立 JAR 总占用约 6.4g，合并到 Tomcat 后约 3.4g。省了将近一半，但如果仔细看数据会发现，Tomcat 自身就占用了不小的固定开销。在 Tomcat 中跑 6 个服务和跑 1 个服务对比，边际资源增长是有限的——这才是节流的本质：共享了基础运行时的成本。&lt;/p&gt;
&lt;h3&gt;那合并部署的意义在哪？&lt;/h3&gt;
&lt;p&gt;内存不是唯一的维度。换个角度看收益：&lt;/p&gt;
&lt;p&gt;| 维度 | 独立 JAR 部署 | Tomcat 合并部署 | 变化 |
|------|:------------:|:---------------:|:----:|
| 进程数 | 6 | 1 + Tomcat 管理进程 | -83% |
| 端口占用 | 6 | 1 | -83% |
| 内存总占用 | ~6.4g | ~3.4g | -47% |
| 启动时间 | 6 x 各自启动 | 1 次 Tomcat 启动 | 大幅缩短 |
| 运维管理 | 6 个进程分别管理 | 1 个容器统一管理 | 显著简化 |&lt;/p&gt;
&lt;p&gt;真正的收益不在内存绝对值，而在管理成本和进程数量的降低。尤其是在资源受限的内网环境，少一个进程就意味着少一分运维负担。&lt;/p&gt;
&lt;h3&gt;什么场景适合这个方案&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;服务器资源紧张，短期内无法扩容&lt;/li&gt;
&lt;li&gt;服务数量多但单个服务负载不高&lt;/li&gt;
&lt;li&gt;运维人力有限，需要降低管理复杂度&lt;/li&gt;
&lt;li&gt;改造预算有限，不能做代码层面的重构&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;什么场景不适合&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;单个服务负载本身就很高（需要独立扩缩容）&lt;/li&gt;
&lt;li&gt;服务间隔离要求严格（故障隔离、安全域）&lt;/li&gt;
&lt;li&gt;已经上了 K8s 容器编排（没必要倒退回 Tomcat）&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h2&gt;五、总结&lt;/h2&gt;
&lt;p&gt;这次实验给我最大的启发是：架构决策不是在完美方案之间做选择，而是在当前约束下找最优解。&lt;/p&gt;
&lt;p&gt;Tomcat 合并部署不是一个漂亮的方案，但在服务器资源砍半、又不能重构代码的约束下，它是能最快落地、风险最低的选择。省下的是实实在在的管理成本和进程开销。&lt;/p&gt;
&lt;p&gt;后面我还会继续测试方案 4（Spring Modulith）和方案 5（Koupleless），看看在资源受限场景下，还有哪些被低估的妥协式方案。欢迎持续关注。&lt;/p&gt;
&lt;hr&gt;
&lt;blockquote&gt;
&lt;p&gt;本文首发于掘金 | 作者：七万号
扎根雄安新区中关村科技园，专注受限环境下软件搭建与数据平台落地&lt;/p&gt;
&lt;/blockquote&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>没有外网，代码怎么装？自建内网 Yum 镜像源实战</title><link>https://realcpf.tech/blog/airgapped-yum-mirror</link><guid isPermaLink="true">https://realcpf.tech/blog/airgapped-yum-mirror</guid><description>明朗北街七万号·数研工坊｜扎根雄安新区中关村科技园，专注受限环境下软件搭建与数据平台落地</description><pubDate>Fri, 31 Jul 2026 01:00:00 GMT</pubDate><content:encoded>&lt;blockquote&gt;
&lt;p&gt;明朗北街七万号·数研工坊｜扎根雄安新区中关村科技园，专注受限环境下软件搭建与数据平台落地&lt;/p&gt;
&lt;/blockquote&gt;
&lt;hr&gt;
&lt;h2&gt;一、问题&lt;/h2&gt;
&lt;p&gt;服务器装好了操作系统，没有外网。&lt;code&gt;yum install&lt;/code&gt; 全部报错。怎么装软件？&lt;/p&gt;
&lt;p&gt;有人说去配互联网镜像源——但内网连不通外网，配了也没用。&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;二、约束&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;服务器无法访问外网&lt;/li&gt;
&lt;li&gt;需要安装 GCC、Nginx 等基础软件&lt;/li&gt;
&lt;li&gt;同一局域网内有多个服务器需要同样配置&lt;/li&gt;
&lt;li&gt;不能使用互联网镜像源&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h2&gt;三、方案：ISO 挂载 + Nginx 暴露为 HTTP 源&lt;/h2&gt;
&lt;p&gt;我的做法是用操作系统 ISO 镜像作为基础源，结合 Nginx 暴露为 HTTP 协议的内网 Yum 源。步骤如下：&lt;/p&gt;
&lt;h3&gt;第 1 步：上传 OS ISO 到服务器&lt;/h3&gt;
&lt;p&gt;将操作系统 ISO 镜像文件上传到服务器，例如上传到 &lt;code&gt;/root/&lt;/code&gt; 目录。&lt;/p&gt;
&lt;h3&gt;第 2 步：挂载 ISO 到目录&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;mkdir -p /mnt/cdrom
mount -o loop /root/CentOS-7-x86_64-DVD-2009.iso /mnt/cdrom
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;ISO 挂载后，里面自带的 Packages 目录就是完整的 RPM 包仓库。&lt;/p&gt;
&lt;h3&gt;第 3 步：修改 repo 指向本地 ISO 路径&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;cd /etc/yum.repos.d/
mkdir backup
mv *.repo backup/

cat &gt; local.repo &amp;#x3C;&amp;#x3C; &apos;EOF&apos;
[local-base]
name=Local ISO Base
baseurl=file:///mnt/cdrom
enabled=1
gpgcheck=0
EOF
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;此时已经可以用 &lt;code&gt;yum install&lt;/code&gt; 安装 ISO 自带的包了。&lt;/p&gt;
&lt;h3&gt;第 4 步：安装 GCC 和 Nginx 依赖&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;yum install -y gcc gcc-c++ make pcre-devel zlib-devel openssl-devel
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;这些基础包 ISO 里基本都有。&lt;/p&gt;
&lt;h3&gt;第 5 步：编译安装 Nginx&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;tar -xzf nginx-1.24.0.tar.gz
cd nginx-1.24.0

./configure --prefix=/usr/local/nginx \
  --with-http_stub_status_module \
  --with-http_ssl_module

make &amp;#x26;&amp;#x26; make install
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;第 6 步：拷贝 RPM 包到独立目录&lt;/h3&gt;
&lt;p&gt;将 ISO 挂载目录下的所有 RPM 包拷贝到一个独立的目录，用于 Nginx 对外暴露：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;mkdir -p /data/yum-repo
cp -r /mnt/cdrom/Packages /data/yum-repo/
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;第 7 步：配置 Nginx 暴露为 HTTP 源&lt;/h3&gt;
&lt;p&gt;编辑 Nginx 配置：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;server {
    listen       80;
    server_name  _;

    location / {
        root   /data/yum-repo;
        autoindex on;
        autoindex_exact_size off;
        autoindex_localtime on;
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;启动 Nginx：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;/usr/local/nginx/sbin/nginx
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;第 8 步：同一局域网的其他服务器修改 repo 地址&lt;/h3&gt;
&lt;p&gt;其他服务器只需将 repo 配置改成 Nginx 的 HTTP 地址：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[nginx-base]
name=Nginx Yum Repo
baseurl=http://&amp;#x3C;你的服务器IP&gt;/
enabled=1
gpgcheck=0
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;然后就能愉快地 &lt;code&gt;yum install&lt;/code&gt; 了。&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;四、补充：如果只需要几个特定的 RPM 包&lt;/h2&gt;
&lt;p&gt;上面说的是搭一个完整的源给整个局域网用。但有些场景你不需要搭源——比如只需要在两台机器上装一个包，不想搞全套 Nginx 暴露。&lt;/p&gt;
&lt;p&gt;这时候可以用 &lt;code&gt;dnf&lt;/code&gt; 的 &lt;code&gt;download&lt;/code&gt; 插件，在外网机器上把某个包和它的依赖一次性拉下来，打包传到内网装：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# 在外网机器上（有网的环境）
dnf install -y dnf-plugins-core
dnf download --resolve --alldeps nginx
# 这会下载 nginx 及其所有依赖的 RPM 包到当前目录
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;然后把下载下来的一堆 &lt;code&gt;.rpm&lt;/code&gt; 打包上传到内网服务器：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# 在内网服务器上
rpm -ivh *.rpm
# 或
yum localinstall *.rpm
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;这比搭 Nginx 源轻量得多，适合快速解决小范围的包依赖问题。缺点是每台机器都得传一次，机器多了还是老老实实搭源。&lt;/p&gt;
&lt;h2&gt;五、总结&lt;/h2&gt;
&lt;p&gt;整个过程用到的工具全部来自 ISO 自身，形成一个自洽的闭环：&lt;/p&gt;
&lt;p&gt;| 步骤 | 工具 | 来源 |
|:----:|------|:----:|
| 挂载 ISO | mount | 系统自带 |
| 安装 GCC / Nginx 依赖 | yum | ISO 内的 RPM |
| 编译 Nginx | gcc + make | 上一步 yum 安装 |
| 暴露 HTTP 源 | Nginx | 上一步编译安装 |
| 局域网安装 | yum | 指向 Nginx HTTP 源 |&lt;/p&gt;
&lt;p&gt;有同学可能会问：为什么不直接用 &lt;code&gt;file://&lt;/code&gt; 的 repo，还要多此一举搭 Nginx？&lt;/p&gt;
&lt;p&gt;因为 &lt;code&gt;file://&lt;/code&gt; 只能本机用。同一局域网的其他服务器没法挂载你的本地路径。Nginx 一转成 HTTP 源，整个局域网都能共用，才叫真正的「内网镜像源」。&lt;/p&gt;
&lt;hr&gt;
&lt;blockquote&gt;
&lt;p&gt;本文首发于掘金 | 作者：七万号
扎根雄安新区中关村科技园，专注受限环境下软件搭建与数据平台落地&lt;/p&gt;
&lt;/blockquote&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>从裸机开始：内网环境下的操作系统安装全流程</title><link>https://realcpf.tech/blog/airgapped-os-install</link><guid isPermaLink="true">https://realcpf.tech/blog/airgapped-os-install</guid><description>明朗北街七万号·数研工坊｜扎根雄安新区中关村科技园，专注受限环境下软件搭建与数据平台落地</description><pubDate>Fri, 31 Jul 2026 00:30:00 GMT</pubDate><content:encoded>&lt;blockquote&gt;
&lt;p&gt;明朗北街七万号·数研工坊｜扎根雄安新区中关村科技园，专注受限环境下软件搭建与数据平台落地&lt;/p&gt;
&lt;/blockquote&gt;
&lt;hr&gt;
&lt;h2&gt;一、问题&lt;/h2&gt;
&lt;p&gt;新到了一批服务器，要装操作系统。&lt;/p&gt;
&lt;p&gt;公网是没有的，PXE 装机也是没有的。唯一有的是一台可以接显示器的测试机和一摞光盘镜像。&lt;/p&gt;
&lt;p&gt;怎么装？&lt;/p&gt;
&lt;p&gt;大多数互联网公司的同事可能已经很久没有亲手装过操作系统了——云平台上一键选镜像、点创建，十分钟搞定。&lt;/p&gt;
&lt;p&gt;但在内网环境，你得从把 ISO 镜像搞到服务器上开始。&lt;/p&gt;
&lt;h2&gt;二、约束&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;服务器无法访问公网&lt;/li&gt;
&lt;li&gt;无 PXE / 无人值守装机环境&lt;/li&gt;
&lt;li&gt;芯片架构不统一（x86_64 + ARM64 混部）&lt;/li&gt;
&lt;li&gt;部分机器没有显示器接口（只能无界面安装）&lt;/li&gt;
&lt;li&gt;需要同时支持欧拉（openEuler）和麒麟（KylinOS）&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;三、第一步：根据芯片架构选择正确的镜像&lt;/h2&gt;
&lt;p&gt;这是最容易翻车的一步。&lt;/p&gt;
&lt;p&gt;同一个操作系统版本，针对不同芯片架构的镜像完全不同。装错了连启动都启动不了。&lt;/p&gt;
&lt;h3&gt;常见架构对应关系&lt;/h3&gt;
&lt;p&gt;| CPU 架构 | 常见 CPU | 对应镜像后缀 |
|----------|---------|:-----------:|
| x86_64 | Intel Xeon / AMD EPYC | &lt;code&gt;x86_64&lt;/code&gt; / &lt;code&gt;amd64&lt;/code&gt; |
| ARM64 | 鲲鹏 920 / 飞腾 S2500 | &lt;code&gt;aarch64&lt;/code&gt; / &lt;code&gt;arm64&lt;/code&gt; |&lt;/p&gt;
&lt;h3&gt;镜像选择实战&lt;/h3&gt;
&lt;h4&gt;openEuler&lt;/h4&gt;
&lt;pre&gt;&lt;code&gt;# x86_64 架构
openEuler-22.03-LTS-x86_64-dvd.iso

# ARM64 架构
openEuler-22.03-LTS-aarch64-dvd.iso
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;下载建议：&lt;/strong&gt; openEuler 的镜像可以在有网的机器上提前下载。&lt;/p&gt;
&lt;h4&gt;KylinOS（麒麟）&lt;/h4&gt;
&lt;p&gt;麒麟分为服务器版（V10）和桌面版，服务器部署通常用 V10。&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# x86_64 架构
Kylin-Server-V10-SP3-x86_64.iso

# ARM64 架构
Kylin-Server-V10-SP3-aarch64.iso
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;注意：&lt;/strong&gt; 麒麟的 ISO 文件名中通常包含 &lt;code&gt;x86&lt;/code&gt; 或 &lt;code&gt;aarch&lt;/code&gt; 标识，下载前务必确认。&lt;/p&gt;
&lt;h3&gt;小技巧&lt;/h3&gt;
&lt;p&gt;拿到一台新机器，不知道 CPU 架构？开机进 BIOS 或者在系统启动时看自检信息。如果已经有一台能用的机器，直接跑：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# 查看 CPU 架构
uname -m

# 输出示例
# x86_64 → Intel/AMD
# aarch64 → ARM（鲲鹏、飞腾）
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;一个很常见的坑：&lt;/strong&gt; 下载了 x86_64 的镜像想装在 ARM 机器上，或者反过来。看着 ISO 名只差一个后缀，但启动时直接报 &lt;code&gt;Invalid image&lt;/code&gt;。所以下载镜像之前，第一件事是先确认芯片型号。&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;四、从 ISO 制作启动介质&lt;/h2&gt;
&lt;p&gt;内网环境通常没有 U 盘量产工具，最简单的方式是用 &lt;code&gt;dd&lt;/code&gt; 命令把 ISO 写入 U 盘：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# 查看 U 盘设备名（通常是 /dev/sdb 或 /dev/sdc）
lsblk

# 写入 ISO 到 U 盘（注意：这个操作会清空 U 盘所有数据）
sudo dd if=./openEuler-22.03-LTS-x86_64-dvd.iso of=/dev/sdb bs=4M status=progress

# 同步缓存
sync
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;写入完成后，U 盘就可以作为启动介质了。&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;提示：&lt;/strong&gt; &lt;code&gt;dd&lt;/code&gt; 命令没有进度条，加 &lt;code&gt;status=progress&lt;/code&gt; 可以实时查看写入进度。如果系统比较老不支持这个参数，就耐心等几分钟再用 &lt;code&gt;sync&lt;/code&gt;。&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;五、界面安装&lt;/h2&gt;
&lt;p&gt;把 U 盘插上服务器，开机进入 BIOS 设置从 U 盘启动。&lt;/p&gt;
&lt;h3&gt;5.1 通用步骤&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;选择安装语言&lt;/strong&gt;——默认 English，内网部署建议选中文&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;安装目的地&lt;/strong&gt;——选择要安装系统的硬盘
&lt;ul&gt;
&lt;li&gt;如果有多块硬盘，建议 SSD 装系统，HDD 做数据盘&lt;/li&gt;
&lt;li&gt;分区方案：自动分区够用，手动分区更可控&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;网络配置&lt;/strong&gt;——配置静态 IP（内网环境很少有 DHCP）
&lt;ul&gt;
&lt;li&gt;IP 地址、子网掩码、网关、DNS 每个字段都可能卡住&lt;/li&gt;
&lt;li&gt;建议提前整理好 IP 规划表&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;软件选择&lt;/strong&gt;——最小化安装，后续按需装
&lt;ul&gt;
&lt;li&gt;数据平台场景推荐选「基础设施服务器」或「虚拟化主机」&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Root 密码&lt;/strong&gt;——设置一个你能记住的密码&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;开始安装&lt;/strong&gt;——等进度条跑完&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;5.2 openEuler 安装注意&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;默认的防火墙规则比较严格，安装完成后第一件事是检查 iptables/firewalld&lt;/li&gt;
&lt;li&gt;如果选择最小化安装，&lt;code&gt;tar&lt;/code&gt;、&lt;code&gt;wget&lt;/code&gt; 这些基础工具可能没有，手动 &lt;code&gt;yum install&lt;/code&gt; 一下&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;5.3 KylinOS 安装注意&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;麒麟 V10 的安装界面和 CentOS/RHEL 非常接近，照上面步骤走&lt;/li&gt;
&lt;li&gt;安装完成后默认 SELinux 是 enforcing，对于数据平台场景建议先设为 permissive（后续再根据需要开启）&lt;/li&gt;
&lt;li&gt;麒麟的 yum 源默认指向官方仓库（需要联网），内网环境尽快切为本地源（下一篇文章会讲）&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h2&gt;六、无界面安装（PXE 都没有？用 U 盘 Kickstart）&lt;/h2&gt;
&lt;p&gt;有些服务器没有接显示器的接口，或者机房太远不方便接显示器。这时候需要用无界面安装的方式。&lt;/p&gt;
&lt;h3&gt;6.1 方案：U 盘 + Kickstart 配置文件&lt;/h3&gt;
&lt;p&gt;操作很简单：在 U 盘的 ISO 写入完成后，修改启动参数，让它自动读取一个预先写好的 Kickstart 配置文件。&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step 1：准备 kickstart 文件&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;创建 &lt;code&gt;ks.cfg&lt;/code&gt;（以下是一个最简配置）：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# Minimal Kickstart Config
text
install
cdrom
lang zh_CN.UTF-8
keyboard us
rootpw your-password-here
timezone Asia/Shanghai
network --bootproto static --ip 192.168.1.100 --netmask 255.255.255.0 --gateway 192.168.1.1 --nameserver 192.168.1.1
zerombr
clearpart --all --initlabel
autopart
reboot

%packages
@base
tar
wget
vim
%end
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Step 2：放入 U 盘&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;把 &lt;code&gt;ks.cfg&lt;/code&gt; 复制到 U 盘的根目录。&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step 3：启动时指定 kickstart 文件&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;开机进入安装介质的引导菜单，在选完安装选项后，按 &lt;code&gt;e&lt;/code&gt; 键编辑启动参数，在 &lt;code&gt;linux&lt;/code&gt; 开头的行末尾加上：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;inst.ks=/dev/sdb1:/ks.cfg
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;然后按 &lt;code&gt;Ctrl+X&lt;/code&gt; 启动，系统会自动读取配置文件进行无人值守安装。&lt;/p&gt;
&lt;p&gt;如果设备名不确定（可能是 &lt;code&gt;/dev/sdc1&lt;/code&gt; 或 &lt;code&gt;/dev/sda1&lt;/code&gt;），可以在启动前先插 U 盘进一个临时系统确认。&lt;/p&gt;
&lt;h3&gt;6.2 什么是 Kickstart&lt;/h3&gt;
&lt;p&gt;Kickstart 是 RedHat 系（包括 openEuler 和 KylinOS）的自动化安装方案。用配置文件代替手工点选界面，支持磁盘分区、网络配置、用户密码、预装软件包等所有安装选项。&lt;/p&gt;
&lt;p&gt;对于需要批量部署多台服务器的场景，你可以把 &lt;code&gt;ks.cfg&lt;/code&gt; 放在一个共享目录里，所有机器指向同一个配置文件，实现标准化安装。&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;如果多台机器配置不同（比如 IP 不一样）&lt;/strong&gt;，可以用 Shell 脚本生成不同的 &lt;code&gt;ks.cfg&lt;/code&gt;，然后逐台安装。&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;七、安装后的第一件事&lt;/h2&gt;
&lt;p&gt;装完系统，重启之后，第一件事不是装应用，而是：&lt;/p&gt;
&lt;h3&gt;7.1 检查网络通畅&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;# 检查 IP
ip addr

# 检查是否能 ping 通网关
ping -c 3 192.168.1.1

# 检查 DNS 是否生效
ping -c 3 your-internal-dns-server
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;7.2 关闭防火墙（或放行必要端口）&lt;/h3&gt;
&lt;p&gt;对于内网数据平台环境，如果对安全性要求不是极致严格，建议在调试阶段：&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# 查看防火墙状态
systemctl status firewalld

# 临时关闭（重启后失效）
systemctl stop firewalld

# 永久关闭
systemctl disable firewalld

# 或者只放行需要的端口，比如 SSH
firewall-cmd --permanent --add-port=22/tcp
firewall-cmd --reload
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;7.3 检查磁盘挂载&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;# 查看磁盘信息
lsblk
df -h

# 如果有未挂载的数据盘
fdisk -l
# 然后格式化并挂载到 /data 目录
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;7.4 配置本地 yum 源&lt;/h3&gt;
&lt;p&gt;这是内网环境下最关键的一步——没有这一步，啥也装不了。下一篇文章专门讲这个。&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;八、总结&lt;/h2&gt;
&lt;p&gt;从拿到一台新服务器到装好操作系统，看起来是最基础的活儿，但在内网环境里每一步都有坑。总结成一句话：&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;镜像选对架构，安装记录配置，装完先测网络和磁盘。&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;| 环节 | 要点 | 常见坑 |
|:----:|------|:------:|
| 选镜像 | x86_64 vs aarch64 必须对应 CPU | 镜像和 CPU 架构不匹配 |
| 做启动盘 | dd 命令写入 U 盘 | 误写错设备名导致数据丢失 |
| 界面安装 | 网络配置、分区、root 密码 | DHCP 用不了，静态 IP 配错 |
| 无界面安装 | U 盘 + ks.cfg | ks.cfg 设备名不对 |
| 装后检查 | 网络、防火墙、磁盘、yum 源 | 防火墙没关导致后续所有服务连不上 |&lt;/p&gt;
&lt;hr&gt;
&lt;blockquote&gt;
&lt;p&gt;本文首发于掘金 · 作者：七万号&lt;/p&gt;
&lt;/blockquote&gt;
&lt;blockquote&gt;
&lt;p&gt;下篇预告：《没有外网，代码怎么装？自建内网镜像源实战》&lt;/p&gt;
&lt;/blockquote&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>五年，三个认知——一个数据平台开发者的成长自白</title><link>https://realcpf.tech/blog/my-five-years</link><guid isPermaLink="true">https://realcpf.tech/blog/my-five-years</guid><description>五年前，我以为做技术的终点是「什么都能做」。</description><pubDate>Fri, 31 Jul 2026 00:00:00 GMT</pubDate><content:encoded>&lt;blockquote&gt;
&lt;p&gt;明朗北街七万号·数研工坊&lt;/p&gt;
&lt;/blockquote&gt;
&lt;hr&gt;
&lt;h2&gt;引子&lt;/h2&gt;
&lt;p&gt;五年前，我以为做技术的终点是「什么都能做」。&lt;/p&gt;
&lt;p&gt;五年后我才明白，真正的分水岭是——&lt;strong&gt;在什么都不能做的时候，你还能做什么。&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;我从华为云出来，辗转了几家公司，最后落地在雄安。这些年我待过的环境，有一个共同特点：&lt;strong&gt;没有公网。&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;你能想象吗？一台刚装好的服务器摆在面前，没有 yum 源，没有 pip 源，没有 Docker Hub。你会的所有框架、所有工具，全停在联网这一步。&lt;/p&gt;
&lt;p&gt;一开始我很崩溃。后来我发现，这恰恰是我最值钱的经验。&lt;/p&gt;
&lt;p&gt;这些年下来，我总结了三个认知。&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;认知一：技术越深，越要学会「不做什么」&lt;/h2&gt;
&lt;p&gt;我刚入行的时候有个毛病——追求技术上的「全栈」。&lt;/p&gt;
&lt;p&gt;看到 Flink 火了就去学 Flink，看到 K8s 火了就去搭 K8s。那时候我的电脑里存了几十个目录，每个都是「入门到精通」的学习笔记。&lt;/p&gt;
&lt;p&gt;直到有一次，我在内网搭一个数据平台。&lt;/p&gt;
&lt;p&gt;按照我当时的思维，第一反应是上 K8s——微服务、容器编排、弹性伸缩，一步到位。方案写得很漂亮，架构图画得也很好看。&lt;/p&gt;
&lt;p&gt;然后我发现，集群一共就三台服务器。K8s 的控制平面一装，资源已经吃掉了三分之一。&lt;/p&gt;
&lt;p&gt;更致命的是——Docker 镜像拉不下来。&lt;/p&gt;
&lt;p&gt;你学了一身屠龙技，结果发现龙根本不在这个房间里。&lt;/p&gt;
&lt;p&gt;那是我第一次意识到：&lt;strong&gt;「会做什么」不是你的上限，「能在什么条件下做」才是你的壁垒。&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;从那以后，我不再追求技术广度，而是开始深耕一个问题：&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;在没有条件的时候，怎么把事情做成。&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;我开始学怎么从源码编译、怎么搭本地镜像源、怎么把十个微服务塞进一个 Tomcat。这些活儿说出去不高级，但它们有一个共同的特点——&lt;strong&gt;离开公网，全得靠这些。&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;你会的框架再多，装不上就是零。&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;认知二：架构的本质是妥协&lt;/h2&gt;
&lt;p&gt;我在上篇文章里讲过，我把六个 Spring Boot 服务塞进了一个 Tomcat。&lt;/p&gt;
&lt;p&gt;有人问：为什么不用 K8s？为什么不做微服务？为什么不搞容器化？&lt;/p&gt;
&lt;p&gt;因为做不到。&lt;/p&gt;
&lt;p&gt;不是因为技术不行，是因为&lt;strong&gt;资源的约束摆在那里。&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;三台机器，二十几个服务，不可能每个服务一个独立进程。没有完美的方案，只有在当前约束下的最优解。这就是我要说的第二个认知——&lt;strong&gt;架构的本质不是设计，是妥协。&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;没有条件的架构，和你从教科书上学到的架构，完全是两回事。&lt;/p&gt;
&lt;p&gt;教科书教你：服务要拆分、数据库要读写分离、缓存要集群。&lt;/p&gt;
&lt;p&gt;现实告诉你：就一台 4G 内存的机器，你看着办。&lt;/p&gt;
&lt;p&gt;在现实的约束下，我开始做一些「不优雅」的决定。&lt;/p&gt;
&lt;p&gt;把多个服务合并部署到同一个容器里。用同一个数据库实例承载多个业务模块。放弃 K8s，用 Shell 脚本加 SSH 完成自动化部署。&lt;/p&gt;
&lt;p&gt;每一件事单独拿出来，放在技术社区里都会被骂。但组合在一起，它们构成了一个在三台机器上稳定运行了两年多、服务了两千多人的数据平台。&lt;/p&gt;
&lt;p&gt;后来我总结了一句话，写在了我的笔记本首页：&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;没有完美的方案，只有当前约束下的最优解。&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;这不是妥协。这是认清现实后的理性选择。&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;认知三：真正值钱的不是技术，是解决「不能」的能力&lt;/h2&gt;
&lt;p&gt;几年前，一个朋友问我：你觉得在这个行业里，什么能力最值钱？&lt;/p&gt;
&lt;p&gt;我当时回答：算法、架构、业务理解。&lt;/p&gt;
&lt;p&gt;现在我会说：&lt;strong&gt;解决「不能」的能力。&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;什么是解决「不能」的能力？&lt;/p&gt;
&lt;p&gt;是不能联网的时候，你用 ISO 挂载搭起了 yum 源。&lt;/p&gt;
&lt;p&gt;是不能下载的时候，你用外网机器把依赖一个个打包回来，传到内网。&lt;/p&gt;
&lt;p&gt;是没有 GPU 的时候，你在 CPU 上跑通了模型推理。&lt;/p&gt;
&lt;p&gt;是国产操作系统不支持 HDP 的时候，你一行一行改源码完成了适配。&lt;/p&gt;
&lt;p&gt;这些事情的技术含量真的高吗？不高。GCC 编译、挂载 ISO、写 Shell 脚本——这些都是基础功。&lt;/p&gt;
&lt;p&gt;但为什么别人做不到？&lt;/p&gt;
&lt;p&gt;因为大多数人在能联网、能下载、能随便装包的环境下工作。他们从来没有被逼着去解决「不能」的问题。而当他们真的面对一个不能联网的环境时，他们连第一步都迈不出去。&lt;/p&gt;
&lt;p&gt;而你已经迈了几百步了。&lt;/p&gt;
&lt;p&gt;这些年在内网环境下，我沉淀了一套自己的工具链和流程：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;从裸机到可用平台的部署流程&lt;/li&gt;
&lt;li&gt;离线环境下的镜像源搭建方案&lt;/li&gt;
&lt;li&gt;资源受限时的架构决策框架&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;这些经验很大可能永远也上不了那些热门的技术大会。但在那些真正需要的人眼里——比如同在受限环境下工作的工程师们——这些东西比任何新技术都值钱。&lt;/p&gt;
&lt;p&gt;因为你在帮他们解决一个很多人解决不了的问题：&lt;strong&gt;在没有条件的时候，把事情做成。&lt;/strong&gt;&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;尾声：为什么我开始输出&lt;/h2&gt;
&lt;p&gt;说实话，做了五年技术，我从来没想过写文章。&lt;/p&gt;
&lt;p&gt;促使我动笔的原因很简单：我翻自己的博客，发现自己这些年踩过的坑、总结的经验，很多已经开始模糊了。&lt;/p&gt;
&lt;p&gt;写下来不是为了让别人看，最开始是为了让自己记住。&lt;/p&gt;
&lt;p&gt;但写着写着，我发现这些内容对别人也可能有用。在这个行业里，大多数人走的是「宽路」——海量的资源、成熟的工具链、完善的基础设施。少部分人走的是「窄路」——有限的资源、自给自足、从零到一。&lt;/p&gt;
&lt;p&gt;我走的是窄路。而且很幸运，我走通了。&lt;/p&gt;
&lt;p&gt;所以我想把这些年的记录整理出来，形成一系列文章。聊受限环境下的数据平台实战，聊资源紧张时的架构选择，聊那些「不优雅但有用」的方案。&lt;/p&gt;
&lt;p&gt;下一篇开始，我会从最基础的环境搭建讲起——内网环境下的操作系统安装、镜像源搭建、离线编译。&lt;/p&gt;
&lt;p&gt;希望我的弯路，能成为你的捷径。&lt;/p&gt;
&lt;hr&gt;
&lt;blockquote&gt;
&lt;p&gt;本文首发于掘金 · 作者：七万号
扎根雄安新区中关村科技园，专注受限环境下软件搭建与数据平台落地&lt;/p&gt;
&lt;/blockquote&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>observability 之 LoongCollector</title><link>https://realcpf.tech/blog/observability-1</link><guid isPermaLink="true">https://realcpf.tech/blog/observability-1</guid><description>LoongCollector</description><pubDate>Thu, 08 Jan 2026 18:16:00 GMT</pubDate><content:encoded>&lt;h2&gt;loongcollector&lt;/h2&gt;
&lt;p&gt;LoongCollector 是一个开源的分布式日志采集系统，基于 Fluentd 构建，支持多语言，多平台，多协议，多数据源，多数据目的。&lt;/p&gt;
&lt;h3&gt;eBPF + 采集&lt;/h3&gt;
&lt;blockquote&gt;
&lt;p&gt;需要自行编译，github的release有问题，coolbpf的分支错误，需要将其切换到loongcollector-base&lt;/p&gt;
&lt;/blockquote&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;# 编译镜像 sls-opensource-registry.cn-shanghai.cr.aliyuncs.com/loongcollector-community-edition/loongcollector-build-linux:2.1.13
# 更新core/_third_party/
# 其中coolbpf要是loongcollector-base分支编译出的eBPF才能用

# under /core/build
cmake ..
make -sj$(nproc)

&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;简单示例&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-yaml&quot;&gt;enable: true
inputs:
  - Type: input_network_observer
    ProbeConfig:
      L7Config:
        Enable: true
        SampleRate: 1.0
        EnableLog: true
        EnableMetric: true
        EnableSpan: true
      L4Config:
        Enable: true
      ApmConfig:
        Workspace: prod
        AppName: test
        AppId: xx@test
        ServiceId: ss@test
        Language: java
      EnableLog: true
      EnableMetric: true
      EnableSpan: true
      EnableProtocols:
        - &quot;http&quot;
      DisableConnStats: false
      EnableConnTrackerDump: true
flushers:
  - Type: flusher_file
    FilePath: input_network_observer.log
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;输出拆分metric、trace\log&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-yaml&quot;&gt;enable: true
inputs:
  - Type: input_network_observer
    ProbeConfig:
      L7Config:
        Enable: true
        SampleRate: 1.0
        EnableLog: true
        EnableMetric: true
        EnableSpan: true
      L4Config:
        Enable: true
      ApmConfig:
        Workspace: prod
        AppName: test
        AppId: xx@test
        ServiceId: ss@test
        Language: java
      EnableLog: true
      EnableMetric: true
      EnableSpan: true
      EnableProtocols:
        - &quot;http&quot;
      DisableConnStats: false
      EnableConnTrackerDump: true

# 多路输出
flushers:
  - Type: flusher_file
    FilePath: input_network_observer_metric.log
    Match:
      Type: event_type
      Value: metric
  - Type: flusher_file
    FilePath: input_network_observer_trace.log
    Match:
      Type: event_type
      Value: trace
  - Type: flusher_file
    FilePath: input_network_observer_log.log
    Match:
      Type: event_type
      Value: log
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;metric&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-json&quot;&gt;{
  &quot;__host_ip__&quot;: &quot;192.168.124.50&quot;,
  &quot;__hostname__&quot;: &quot;localhost.localdomain&quot;,
  &quot;__machine_uuid__&quot;: &quot;0FAC399A-EC91-11F0-A1B4-3D6692D60605&quot;,
  &quot;__source__&quot;: &quot;192.168.124.50&quot;,
  &quot;acs_arms_service_id&quot;: &quot;ss@test&quot;,
  &quot;acs_cms_workspace&quot;: &quot;prod&quot;,
  &quot;data_type&quot;: &quot;metric&quot;,
  &quot;host&quot;: &quot;&quot;,
  &quot;language&quot;: &quot;java&quot;,
  &quot;pid&quot;: &quot;xx@test&quot;,
  &quot;serverIp&quot;: &quot;192.168.124.50&quot;,
  &quot;service&quot;: &quot;test&quot;,
  &quot;source&quot;: &quot;apm&quot;,
  &quot;technology&quot;: &quot;ebpf&quot;,
  &quot;__time__&quot;: 1767877042,
  &quot;__labels__&quot;: {
    &quot;status&quot;: &quot;2xx&quot;,
    &quot;workloadName&quot;: &quot;&quot;,
    &quot;workloadKind&quot;: &quot;&quot;,
    &quot;namespace&quot;: &quot;&quot;,
    &quot;rpc&quot;: &quot;/conf/&quot;,
    &quot;rpcType&quot;: &quot;0&quot;,
    &quot;callType&quot;: &quot;http&quot;,
    &quot;callKind&quot;: &quot;http&quot;,
    &quot;endpoint&quot;: &quot;/conf/&quot;,
    &quot;destId&quot;: &quot;192.168.124.1&quot;
  },
  &quot;__name__&quot;: &quot;arms_rpc_requests_by_status_count&quot;,
  &quot;__value__&quot;: 1.0
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;trace&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-json&quot;&gt;{
  &quot;__host_ip__&quot;: &quot;192.168.124.50&quot;,
  &quot;__hostname__&quot;: &quot;localhost.localdomain&quot;,
  &quot;__machine_uuid__&quot;: &quot;0FAC399A-EC91-11F0-A1B4-3D6692D60605&quot;,
  &quot;__source__&quot;: &quot;192.168.124.50&quot;,
  &quot;acs.arms.service.id&quot;: &quot;ss@test&quot;,
  &quot;acs.cms.workspace&quot;: &quot;prod&quot;,
  &quot;app&quot;: &quot;&quot;,
  &quot;arms.app.type&quot;: &quot;apm&quot;,
  &quot;arms.appId&quot;: &quot;xx@test&quot;,
  &quot;data_type&quot;: &quot;trace&quot;,
  &quot;host.ip&quot;: &quot;192.168.124.50&quot;,
  &quot;host.name&quot;: &quot;&quot;,
  &quot;language&quot;: &quot;java&quot;,
  &quot;service.name&quot;: &quot;test&quot;,
  &quot;technology&quot;: &quot;ebpf&quot;,
  &quot;__time__&quot;: 1767877035,
  &quot;traceId&quot;: &quot;f2d3a99bb387e089a5d223ee96ec44fa79bc7130c7af716c65e6658e1cd6f6c0&quot;,
  &quot;spanId&quot;: &quot;8eff0a1008f9bfddada56cf0d2ac9f0e&quot;,
  &quot;parentSpanId&quot;: &quot;&quot;,
  &quot;spanName&quot;: &quot;/conf/continuous_pipeline_config/common_v2/&quot;,
  &quot;startTime&quot;: 1767877035774786053,
  &quot;endTime&quot;: 1767877035775402006,
  &quot;duration&quot;: 615953,
  &quot;attributes&quot;: {
    &quot;host&quot;: &quot;192.168.124.50&quot;,
    &quot;host.name&quot;: &quot;&quot;,
    &quot;k8s.pod.name&quot;: &quot;&quot;,
    &quot;k8s.pod.ip&quot;: &quot;&quot;,
    &quot;k8s.namespace&quot;: &quot;&quot;,
    &quot;k8s.workload.kind&quot;: &quot;&quot;,
    &quot;k8s.workload.name&quot;: &quot;&quot;,
    &quot;k8s.peer.pod.name&quot;: &quot;external&quot;,
    &quot;k8s.peer.pod.ip&quot;: &quot;external&quot;,
    &quot;k8s.peer.namespace&quot;: &quot;external&quot;,
    &quot;k8s.peer.workload.kind&quot;: &quot;external&quot;,
    &quot;peerWorkloadName&quot;: &quot;external&quot;,
    &quot;k8s.peer.service.name&quot;: &quot;external&quot;,
    &quot;protocol&quot;: &quot;ProtoHTTP&quot;,
    &quot;local.addr&quot;: &quot;192.168.124.50:16415&quot;,
    &quot;remote.addr&quot;: &quot;192.168.124.1:30352&quot;,
    &quot;remote.port&quot;: &quot;30352&quot;,
    &quot;rpcType&quot;: &quot;0&quot;,
    &quot;call.kind&quot;: &quot;http&quot;,
    &quot;call.type&quot;: &quot;http&quot;,
    &quot;destId&quot;: &quot;192.168.124.1&quot;,
    &quot;endpoint&quot;: &quot;&quot;,
    &quot;fd&quot;: &quot;4&quot;,
    &quot;process.pid&quot;: &quot;9733&quot;,
    &quot;container.id&quot;: &quot;&quot;,
    &quot;trace.role&quot;: &quot;IsServer&quot;,
    &quot;ip&quot;: &quot;192.168.124.50&quot;,
    &quot;remote.ip&quot;: &quot;192.168.124.1&quot;,
    &quot;net.namespace&quot;: &quot;-268435304&quot;,
    &quot;family&quot;: &quot;AF_INET&quot;,
    &quot;startTsNs&quot;: &quot;3218715424237&quot;,
    &quot;rpc&quot;: &quot;/conf/continuous_pipeline_config/common_v2/&quot;,
    &quot;req.body&quot;: &quot;&quot;,
    &quot;resp.body&quot;: &quot;&quot;,
    &quot;http.req.body.size&quot;: &quot;0&quot;,
    &quot;http.resp.body.size&quot;: &quot;0&quot;,
    &quot;version&quot;: &quot;http1.1&quot;
  },
  &quot;scope&quot;: {}
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;log&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-json&quot;&gt;{
  &quot;__host_ip__&quot;: &quot;192.168.124.50&quot;,
  &quot;__hostname__&quot;: &quot;localhost.localdomain&quot;,
  &quot;__machine_uuid__&quot;: &quot;0FAC399A-EC91-11F0-A1B4-3D6692D60605&quot;,
  &quot;__source__&quot;: &quot;192.168.124.50&quot;,
  &quot;data_type&quot;: &quot;log&quot;,
  &quot;__time__&quot;: 1767877035,
  &quot;k8s.peer.pod.name&quot;: &quot;external&quot;,
  &quot;k8s.peer.pod.ip&quot;: &quot;external&quot;,
  &quot;k8s.peer.namespace&quot;: &quot;external&quot;,
  &quot;k8s.peer.workload.kind&quot;: &quot;external&quot;,
  &quot;k8s.peer.workload.name&quot;: &quot;external&quot;,
  &quot;k8s.peer.service.name&quot;: &quot;external&quot;,
  &quot;protocol&quot;: &quot;ProtoHTTP&quot;,
  &quot;local.addr&quot;: &quot;192.168.124.50:16415&quot;,
  &quot;remote.addr&quot;: &quot;192.168.124.1:30352&quot;,
  &quot;remote.port&quot;: &quot;30352&quot;,
  &quot;rpc_type&quot;: &quot;0&quot;,
  &quot;arms.call.kind&quot;: &quot;http&quot;,
  &quot;arms.call.type&quot;: &quot;http&quot;,
  &quot;dest.id&quot;: &quot;192.168.124.1&quot;,
  &quot;fd&quot;: &quot;4&quot;,
  &quot;pid&quot;: &quot;9733&quot;,
  &quot;trace.role&quot;: &quot;IsServer&quot;,
  &quot;ip&quot;: &quot;192.168.124.50&quot;,
  &quot;remote.ip&quot;: &quot;192.168.124.1&quot;,
  &quot;netns&quot;: &quot;-268435304&quot;,
  &quot;family&quot;: &quot;AF_INET&quot;,
  &quot;start_time_nsec&quot;: &quot;3218715424237&quot;,
  &quot;latency&quot;: &quot;615953.000000&quot;,
  &quot;http.method&quot;: &quot;GET&quot;,
  &quot;http.path&quot;: &quot;/conf/continuous_pipeline_config/common_v2/&quot;,
  &quot;http.version&quot;: &quot;http1.1&quot;,
  &quot;http.status.code&quot;: &quot;200&quot;,
  &quot;http.req.body&quot;: &quot;&quot;,
  &quot;http.resp.body&quot;: &quot;&quot;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;ebpf =&gt; VictoriaMetrics&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-yaml&quot;&gt;enable: true
inputs:
  - Type: input_file
    FilePaths:
      - input_network_observer_log.log
flushers:
  - Type: flusher_loki
    URL: http://192.168.124.50:9428/insert/loki/api/v1/push
    MaxMessageWait: 100000000
    MaxMessageBytes: 16
    Timeout: 1000000000000
    MinBackoff: 100000000000
    MaxBackoff: 1000000000000
    MaxRetries: 10
    StaticLabels:
      source: ilogtail
&lt;/code&gt;&lt;/pre&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>rainbond 离线安装</title><link>https://realcpf.tech/blog/rainbond</link><guid isPermaLink="true">https://realcpf.tech/blog/rainbond</guid><description>rainbond 离线安装</description><pubDate>Tue, 12 Aug 2025 18:16:00 GMT</pubDate><content:encoded>&lt;h2&gt;rainbond 离线安装&lt;/h2&gt;
&lt;h3&gt;安装k3s&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;# 先创建配置文件 在安装
# 创建目录
mkdir -p /etc/rancher/k3s

# 创建 K3s 配置文件，禁用 traefik 和 local-storage
cat &amp;#x3C;&amp;#x3C;EOF &gt; /etc/rancher/k3s/config.yaml
disable:
  - traefik
  - local-storage
system-default-registry: registry.cn-hangzhou.aliyuncs.com
EOF

cat &amp;#x3C;&amp;#x3C;EOF &gt; /etc/rancher/k3s/registries.yaml
configs:
  &quot;goodrain.me&quot;:
    auth:
      username: admin
      password: admin1234
    tls:
      insecure_skip_verify: true
EOF


mkdir -p /var/lib/rancher/k3s/agent/images/
cp k3s-airgap-images-amd64.tar /var/lib/rancher/k3s/agent/images/


cp k3s /usr/local/bin/

# 必须指定 K3S_NODE_NAME 后面values里要填写节点名称

INSTALL_K3S_SKIP_DOWNLOAD=true K3S_NODE_NAME=192.168.124.201 ./k3s-install.sh


# 后面helm需要
mkdir ~/.kube
cp /etc/rancher/k3s/k3s.yaml ~/.kube/config



# agent 节点
INSTALL_K3S_SKIP_DOWNLOAD=true K3S_URL=https://myserver:6443 K3S_TOKEN=mynodetoken ./install.sh




# 卸载
/usr/local/bin/k3s-uninstall.sh
/usr/local/bin/k3s-agent-uninstall.sh

&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;安装rainbond&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;# 环境里有这几个 k3s kubectl(用k3s的） nerdctl helm

# 导入离线镜像
nerdctl -a &quot;/run/k3s/containerd/containerd.sock&quot;  -n k8s.io load -i rainbond-offline-images.tar

# 离线安装
helm install rainbond ./rainbond-chart --create-namespace -n rbd-system -f values.yaml

# 如果values要改 可用用更新方式
helm upgrade --install rainbond ./rainbond-chart --create-namespace -n rbd-system -f values.yaml

# 看
watch kubectl get pod -n rbd-system

&lt;/code&gt;&lt;/pre&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>Biz Lake</title><link>https://realcpf.tech/blog/biz-lake</link><guid isPermaLink="true">https://realcpf.tech/blog/biz-lake</guid><description>个人项目 Biz Lake 介绍</description><pubDate>Wed, 04 Jun 2025 18:16:00 GMT</pubDate><content:encoded>&lt;h3&gt;Biz Lake&lt;/h3&gt;
&lt;blockquote&gt;
&lt;p&gt;业务湖：轻快好省、开箱即用的数据湖，集汇聚、治理、分析一体的内嵌数据湖&lt;/p&gt;
&lt;/blockquote&gt;
&lt;hr&gt;
&lt;blockquote&gt;
&lt;p&gt;Business Lake: A lightweight, cost-effective, and out of the box data lake that integrates aggregation, governance, and analysis into an embedded data lake Resources&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h4&gt;2025.06&lt;/h4&gt;
&lt;h4&gt;feature&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;[ ] Batch Data Convergence
&lt;ul&gt;
&lt;li&gt;[ ] Mq&lt;/li&gt;
&lt;li&gt;[ ] Http&lt;/li&gt;
&lt;li&gt;[x] ADBC&lt;/li&gt;
&lt;li&gt;[ ] File&lt;/li&gt;
&lt;li&gt;[ ] S3&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;[x] Catalog system&lt;/li&gt;
&lt;li&gt;[ ] Easy to use indicator system&lt;/li&gt;
&lt;li&gt;[ ] Flexible and powerful BI reports&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;img src=&quot;/biz-lake-1.png&quot; alt=&quot;biz-lake&quot;&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/realcpf/biz-lake&quot;&gt;Github-BizLake&lt;/a&gt;

&lt;a href=&quot;https://gitee.com/realcpf_0/biz-lake&quot;&gt;Gitee-BizLake&lt;/a&gt;

&lt;a href=&quot;https://atomgit.com/realcpf/biz-lake&quot;&gt;AtomGit-BizLake&lt;/a&gt;&lt;/p&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>关于大模型调用服务里不得不说的那些事</title><link>https://realcpf.tech/blog/the-ai-call-service</link><guid isPermaLink="true">https://realcpf.tech/blog/the-ai-call-service</guid><description>关于大模型调用服务里不得不说的那些事</description><pubDate>Sat, 01 Feb 2025 09:16:00 GMT</pubDate><content:encoded>&lt;p&gt;下面这段1、2、3是通过DeekSeek总结的，代码部分人工作了调整，为了保证可以运行：&lt;/p&gt;
&lt;hr&gt;
&lt;h3&gt;&lt;strong&gt;1. 智能Web服务的趋势&lt;/strong&gt;&lt;/h3&gt;
&lt;h4&gt;&lt;strong&gt;从功能型到认知型的演进&lt;/strong&gt;&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;传统Web服务&lt;/strong&gt;：以数据查询、表单提交为主（如电商下单、信息展示）。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;智能Web服务&lt;/strong&gt;：借助大模型实现自然语言交互、个性化推荐、动态内容生成。
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;核心能力&lt;/strong&gt;：
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;语义理解&lt;/strong&gt;：用户意图识别（如模糊搜索、情感分析）。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;内容生成&lt;/strong&gt;：自动生成文本、代码、图片（如客服机器人、设计助手）。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;决策支持&lt;/strong&gt;：基于数据分析的智能决策（如金融风控、医疗诊断建议）。&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h4&gt;&lt;strong&gt;典型场景&lt;/strong&gt;&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;自动化流程&lt;/strong&gt;：合同审核、报告生成。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;多模态交互&lt;/strong&gt;：语音输入、图像识别与文本联动。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;实时个性化&lt;/strong&gt;：根据用户历史行为动态调整服务逻辑。&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h3&gt;&lt;strong&gt;2. 大模型服务生态性&lt;/strong&gt;&lt;/h3&gt;
&lt;h4&gt;&lt;strong&gt;生态分层&lt;/strong&gt;&lt;/h4&gt;
&lt;p&gt;| 层级           | 代表服务/工具               | 作用                   |
| -------------- | --------------------------- | ---------------------- |
| &lt;strong&gt;基础设施层&lt;/strong&gt; | OpenAI API、Claude、Llama 2 | 提供基础模型能力       |
| &lt;strong&gt;框架工具层&lt;/strong&gt; | LangChain、Hugging Face     | 简化模型调用与流程编排 |
| &lt;strong&gt;应用集成层&lt;/strong&gt; | Spring AI、FastAPI插件      | 与现有开发框架深度整合 |&lt;/p&gt;
&lt;h4&gt;&lt;strong&gt;开发者友好性&lt;/strong&gt;&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;标准化接口&lt;/strong&gt;：RESTful API、SDK封装（如OpenAI Java库）。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;本地化部署&lt;/strong&gt;：Ollama支持本地运行大模型，降低数据泄露风险。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;成本分级&lt;/strong&gt;：按需选择云API（按Token计费）或私有化部署。&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h3&gt;&lt;strong&gt;3. Java开发：Spring Boot的AI Starter调用大模型&lt;/strong&gt;&lt;/h3&gt;
&lt;h4&gt;&lt;strong&gt;Spring-ai项目简介&lt;/strong&gt;&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;定位&lt;/strong&gt;：Spring官方推出的AI集成框架，统一不同模型服务的调用方式。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;核心功能&lt;/strong&gt;：
&lt;ul&gt;
&lt;li&gt;支持OpenAI、Ollama、Hugging Face等主流服务商。&lt;/li&gt;
&lt;li&gt;提供模板化接口（如&lt;code&gt;ChatClient&lt;/code&gt;、&lt;code&gt;EmbeddingClient&lt;/code&gt;）。&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h4&gt;&lt;strong&gt;开发步骤&lt;/strong&gt;&lt;/h4&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;添加依赖&lt;/strong&gt;：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-xml&quot;&gt;&amp;#x3C;!-- 主要是AI部分的
        &amp;#x3C;dependency&gt;
         &amp;#x3C;groupId&gt;org.springframework.ai&amp;#x3C;/groupId&gt;
         &amp;#x3C;artifactId&gt;spring-ai-ollama-spring-boot-starter&amp;#x3C;/artifactId&gt;
     &amp;#x3C;/dependency&gt; --&gt;
&amp;#x3C;!-- pom.xml --&gt;
 &amp;#x3C;modelVersion&gt;4.0.0&amp;#x3C;/modelVersion&gt;
 &amp;#x3C;parent&gt;
     &amp;#x3C;groupId&gt;org.springframework.boot&amp;#x3C;/groupId&gt;
     &amp;#x3C;artifactId&gt;spring-boot-starter-parent&amp;#x3C;/artifactId&gt;
     &amp;#x3C;version&gt;3.4.2&amp;#x3C;/version&gt;
     &amp;#x3C;relativePath/&gt;
 &amp;#x3C;/parent&gt;
 &amp;#x3C;groupId&gt;tech.realcpf&amp;#x3C;/groupId&gt;
 &amp;#x3C;artifactId&gt;jc-ai-services&amp;#x3C;/artifactId&gt;
 &amp;#x3C;version&gt;1.0-SNAPSHOT&amp;#x3C;/version&gt;

 &amp;#x3C;properties&gt;
     &amp;#x3C;java.version&gt;17&amp;#x3C;/java.version&gt;
     &amp;#x3C;spring-ai.version&gt;1.0.0-M5&amp;#x3C;/spring-ai.version&gt;
 &amp;#x3C;/properties&gt;
 &amp;#x3C;dependencies&gt;
 &amp;#x3C;!-- ai部分的库 --&gt;
     &amp;#x3C;dependency&gt;
         &amp;#x3C;groupId&gt;org.springframework.ai&amp;#x3C;/groupId&gt;
         &amp;#x3C;artifactId&gt;spring-ai-ollama-spring-boot-starter&amp;#x3C;/artifactId&gt;
     &amp;#x3C;/dependency&gt;
     &amp;#x3C;dependency&gt;
         &amp;#x3C;groupId&gt;org.springframework.boot&amp;#x3C;/groupId&gt;
         &amp;#x3C;artifactId&gt;spring-boot-starter-web&amp;#x3C;/artifactId&gt;
     &amp;#x3C;/dependency&gt;
 &amp;#x3C;/dependencies&gt;


 &amp;#x3C;dependencyManagement&gt;
     &amp;#x3C;dependencies&gt;
         &amp;#x3C;dependency&gt;
             &amp;#x3C;groupId&gt;org.springframework.ai&amp;#x3C;/groupId&gt;
             &amp;#x3C;artifactId&gt;spring-ai-bom&amp;#x3C;/artifactId&gt;
             &amp;#x3C;version&gt;${spring-ai.version}&amp;#x3C;/version&gt;
             &amp;#x3C;type&gt;pom&amp;#x3C;/type&gt;
             &amp;#x3C;scope&gt;import&amp;#x3C;/scope&gt;
         &amp;#x3C;/dependency&gt;
     &amp;#x3C;/dependencies&gt;
 &amp;#x3C;/dependencyManagement&gt;

&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;配置模型参数&lt;/strong&gt;：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-yaml&quot;&gt;# application.properties
spring.ai.ollama.base-url=http://localhost:11434
spring.ai.ollama.chat.model=deepseek-r1:8b
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;调用模型服务&lt;/strong&gt;：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;@RestController
public class TranslationController {
    @Autowired
    private OllamaChatModel ollamaChatModel;

    @PostMapping(&quot;/translate&quot;)
    public String translate(@RequestParam String text,
                            @RequestParam String targetLang) {
        String prompt = &quot;将以下文本翻译为&quot; + targetLang + &quot;:\n&quot; + text;
        return ollamaChatModel.call(prompt);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;hr&gt;
&lt;h3&gt;&lt;strong&gt;4. 翻译Demo完整示例&lt;/strong&gt;&lt;/h3&gt;
&lt;h4&gt;&lt;strong&gt;环境准备&lt;/strong&gt;&lt;/h4&gt;
&lt;ol&gt;
&lt;li&gt;安装Ollama（本地模型服务）：
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;curl -fsSL https://ollama.com/install.sh | sh
ollama pull deepseek-r1:8b  # 下载模型
ollama serve        # 启动服务
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;h4&gt;&lt;strong&gt;代码实现&lt;/strong&gt;&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;// 启动类
@SpringBootApplication
public class AiDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(AiDemoApplication.class, args);
    }
}

// 翻译接口
@RestController
@RequestMapping(&quot;/api&quot;)
public class TranslationController {

    private final OllamaChatModel ollamaChatModel;

    public TranslationController(OllamaChatModel ollamaChatModel) {
        this.ollamaChatModel = ollamaChatModel;
    }

    @PostMapping(&quot;/translate&quot;)
    public ResponseEntity&amp;#x3C;String&gt; translateText(
            @RequestParam String text,
            @RequestParam(defaultValue = &quot;法语&quot;) String language) {

        String systemPrompt = &quot;你是一名专业翻译，保持术语准确，输出结果不带注释。&quot;;
        String userPrompt = String.format(&quot;将以下内容翻译为%s：%s&quot;, language, text);

        String fullPrompt = systemPrompt + &quot;\n\n&quot; + userPrompt;
        String result = ollamaChatModel.call(fullPrompt);

        return ResponseEntity.ok(result);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;&lt;strong&gt;测试结果&lt;/strong&gt;&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;# 请求示例
curl -X POST http://localhost:8080/api/translate \
  -d &quot;text=Spring AI极大地简化了大模型集成&quot; \
  -d &quot;language=英语&quot;

# 响应输出
&quot;Spring AI significantly simplifies the integration of large language models.&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;&lt;strong&gt;技术扩展建议&lt;/strong&gt;&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;流式响应&lt;/strong&gt;：使用&lt;code&gt;StreamingChatClient&lt;/code&gt;实现逐词输出。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;上下文管理&lt;/strong&gt;：通过&lt;code&gt;ChatMemory&lt;/code&gt;维护对话历史。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;异常处理&lt;/strong&gt;：重试机制、Fallback降级策略。&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>关于spring那些不得不说的故事</title><link>https://realcpf.tech/blog/the-spring</link><guid isPermaLink="true">https://realcpf.tech/blog/the-spring</guid><description>关于spring那些不得不说的故事</description><pubDate>Fri, 12 Jul 2024 18:16:00 GMT</pubDate><content:encoded>&lt;h3&gt;Spring Security (6.2.x) Custom Usage&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;AuthenticationProvider&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
@Component
public class AkSkAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {
    // 进行实际的用户信息校验
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        System.out.println(authentication.getName());
        List&amp;#x3C;String&gt; perms = new ArrayList&amp;#x3C;&gt;(3);
        perms.add(&quot;operator&quot;);
        perms.add(&quot;viewer&quot;);
        perms.add(&quot;admin&quot;);
        List&amp;#x3C;SimpleGrantedAuthority&gt; authorities = new ArrayList&amp;#x3C;&gt;(perms.size());
        for (String perm:perms) {
            authorities.add(new SimpleGrantedAuthority(perm));
        }
        return new MyToken(&quot;ak&quot;,&quot;sk&quot;,authorities);
    }
    // 判断当前Authentication 是否会用该Provider校验
    @Override
    public boolean supports(Class&amp;#x3C;?&gt; authentication) {
        return MyToken.class.isAssignableFrom(authentication);
    }
}

&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;AbstractAuthenticationProcessingFilter&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class AkSkAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
    public AkSkAuthenticationFilter(String defaultFilterProcessesUrl, AuthenticationManager authenticationManager) {
        super(new AntPathRequestMatcher(defaultFilterProcessesUrl, &quot;GET&quot;));
        this.setAuthenticationManager(authenticationManager);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        String ak = request.getHeader(&quot;ak&quot;);
        String sk = request.getHeader(&quot;sk&quot;);
        if (&quot;ak&quot;.equals(ak) &amp;#x26;&amp;#x26; &quot;sk&quot;.equals(sk)) {
            List&amp;#x3C;String&gt; perms = new ArrayList&amp;#x3C;&gt;(3);
            perms.add(&quot;operator&quot;);
            perms.add(&quot;viewer&quot;);
            perms.add(&quot;admin&quot;);
            List&amp;#x3C;SimpleGrantedAuthority&gt; authorities = new ArrayList&amp;#x3C;&gt;(perms.size());
            for (String perm:perms) {
                authorities.add(new SimpleGrantedAuthority(perm));
            }
            // 调用Provider校验
            return this.getAuthenticationManager().authenticate(new MyToken(ak,sk,authorities));
        }

        return null;
    }

    // 成功
    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        System.out.println(&quot;success&quot;);
        final String xId = UUID.randomUUID().toString();
        response.getWriter().write(xId);
    }

    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
                                              AuthenticationException failed)
            throws IOException, ServletException {
        System.out.println(&quot;fail&quot;);
        super.unsuccessfulAuthentication(request, response, failed);
    }
}

&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;Configuration&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;
import com.example.demo.sec.AkSkFilter;
import com.example.demo.sec.AkSkAuthenticationProvider;
import com.example.demo.sec.AkSkAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.csrf.CsrfFilter;

import static org.springframework.security.config.http.SessionCreationPolicy.STATELESS;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration {

    @Autowired
    private AkSkFilter akSkFilter;

    // AbstractAuthenticationProcessingFilter
    @Bean
    public AkSkAuthenticationFilter theAuthFilter() {
        return new AkSkAuthenticationFilter(&quot;/v1/token&quot;,authenticationManager());
    }

    // 包装 AuthenticationProvider
    @Bean
    public AuthenticationManager authenticationManager(){
        ProviderManager authenticationManager = new ProviderManager(authenticationProvider());
        authenticationManager.setEraseCredentialsAfterAuthentication(true);
        return authenticationManager;
    }
    // AuthenticationProvider
    @Bean
    public AuthenticationProvider authenticationProvider() {
        return new AkSkAuthenticationProvider();
    }



    @Bean
    public SecurityFilterChain authorizeRequestsFilterChain(HttpSecurity http) throws Exception {
        http.csrf(AbstractHttpConfigurer::disable)
                .authorizeHttpRequests(req -&gt;
                        req.requestMatchers(&quot;/v1/token&quot;)
                                .permitAll()
                                .anyRequest().authenticated()

                )
                 // 设置authenticationManager
                .authenticationManager(authenticationManager())
                .sessionManagement(session -&gt; session.sessionCreationPolicy(STATELESS))
                //  设置自定义的校验
                .addFilterAfter(theAuthFilter(), CsrfFilter.class)
                .addFilterBefore(akSkFilter, AkSkAuthenticationFilter.class);

        return http.build();
    }

&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Spring IoC and Bean&lt;/h3&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;a href=&quot;https://docs.spring.io/spring-framework/reference/core/beans/introduction.html&quot;&gt;The org.springframework.beans and org.springframework.context packages are the basis for Spring Framework’s IoC container.&lt;/a&gt; The BeanFactory interface provides an advanced configuration mechanism capable of managing any type of object. ApplicationContext is a sub-interface of BeanFactory. It adds:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Easier integration with Spring’s AOP features&lt;/li&gt;
&lt;li&gt;Message resource handling (for use in internationalization)&lt;/li&gt;
&lt;li&gt;Event publication&lt;/li&gt;
&lt;li&gt;Application-layer specific contexts such as the WebApplicationContext for use in web applications.&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;
&lt;p&gt;&lt;img src=&quot;/article-img/container-magic.png&quot; alt=&quot;The Spring IoC container&quot;&gt;&lt;/p&gt;
&lt;h4&gt;Create Config Get Beans&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;ApplicationContext context1 = new ClassPathXmlApplicationContex(&quot;services.xml&quot;);
ApplicationContext context2 = new GenericGroovyApplicationContext(&quot;services.groovy&quot;);
ApplicationContext context3 = FileSystemXmlApplicationContext(&quot;&quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;ApplicationContext context = new ClassPathXmlApplicationContext(&quot;services.xml&quot;);

// getBean
DemoEntity entity1 = context.getBean(&quot;entity1&quot;, DemoEntity.class);

System.out.println(entity1);

DemoEntity entityAlias = context.getBean(&quot;entityAlias&quot;,DemoEntity.class);
System.out.println(entityAlias);
assert entity1 == entityAlias;


&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;XML config attrs&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-xml&quot;&gt;&amp;#x3C;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&amp;#x3C;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
       xmlns:p=&quot;http://www.springframework.org/schema/p&quot;
       xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
		https://www.springframework.org/schema/beans/spring-beans.xsd&quot;&gt;

        &amp;#x3C;!-- factory-method -&gt; public static factory method  --&gt;
    &amp;#x3C;bean id=&quot;entity2&quot; class=&quot;tech.realcpf.spring.dto.DemoEntity&quot; factory-method=&quot;createInstance&quot;&gt;
        &amp;#x3C;property name=&quot;name&quot; value=&quot;jiacheng.liu&quot;/&gt;
        &amp;#x3C;property name=&quot;age&quot; value=&quot;25&quot;/&gt;
    &amp;#x3C;/bean&gt;


    &amp;#x3C;!-- use    xmlns:p=&quot;http://www.springframework.org/schema/p&quot;--&gt;
    &amp;#x3C;bean id=&quot;entity3&quot; class=&quot;tech.realcpf.spring.dto.DemoEntity&quot;
        destroy-method=&quot;destroy&quot;
        p:name=&quot;jc.liu&quot;
        p:age=&quot;89&quot;&gt;
        &amp;#x3C;!-- additional collaborators and configuration for this bean go here --&gt;
    &amp;#x3C;/bean&gt;

    &amp;#x3C;!-- constructor-arg --&gt;
    &amp;#x3C;bean id=&quot;entity1&quot; class=&quot;tech.realcpf.spring.dto.DemoEntity&quot;&gt;
        &amp;#x3C;constructor-arg type=&quot;java.lang.String&quot; value=&quot;by constructor&quot; name=&quot;name&quot; index=&quot;0&quot;&gt;&amp;#x3C;/constructor-arg&gt;
        &amp;#x3C;constructor-arg type=&quot;java.lang.Integer&quot; value=&quot;123&quot; name=&quot;age&quot; index=&quot;1&quot;&gt;&amp;#x3C;/constructor-arg&gt;
    &amp;#x3C;/bean&gt;

    &amp;#x3C;alias name=&quot;entity1&quot; alias=&quot;entityAlias&quot;&gt;&amp;#x3C;/alias&gt;

    &amp;#x3C;!-- depends-on  other beans --&gt;
   &amp;#x3C;bean id=&quot;beanOne&quot; class=&quot;ExampleBean&quot; depends-on=&quot;manager&quot;/&gt;
&amp;#x3C;!--    &amp;#x3C;bean id=&quot;manager&quot; class=&quot;ManagerBean&quot; /&gt;--&gt;

    &amp;#x3C;!-- lazy-init  --&gt;
   &amp;#x3C;bean id=&quot;lazy&quot; class=&quot;com.something.ExpensiveToCreateBean&quot; lazy-init=&quot;true&quot;/&gt;
&amp;#x3C;!--    &amp;#x3C;bean name=&quot;not.lazy&quot; class=&quot;com.something.AnotherBean&quot;/&gt;--&gt;

    &amp;#x3C;!-- init method --&gt;
   &amp;#x3C;bean id=&quot;exampleInitBean&quot; class=&quot;examples.ExampleBean&quot; init-method=&quot;init&quot;/&gt;
   &amp;#x3C;!-- scope --&gt;
   &amp;#x3C;bean id=&quot;exampleInitBean&quot; class=&quot;examples.ExampleBean&quot; scope=&quot;prototype&quot;/&gt;
&amp;#x3C;/beans&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;/article-img/prototype.png&quot; alt=&quot;prototype&quot;&gt;&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;&lt;img src=&quot;/article-img/singleton.png&quot; alt=&quot;singleton&quot;&gt;&lt;/p&gt;
&lt;h4&gt;BeanPostProcessor&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;
private static final BeanPostProcessor beanPostProcessor = new BeanPostProcessor() {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println(&quot;Bean &apos;&quot; + beanName + &quot;&apos; created : &quot; + bean.toString());
        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }
};

// PropertyOverrideConfigurer
// PropertySourcesPlaceholderConfigurer

private static final BeanFactoryPostProcessor beanFactoryPostProcessor = new BeanFactoryPostProcessor() {
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

    }
};


&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Spring SPI&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-plaintext&quot;&gt;
通过 resources/META-INF/spring.factories 作为SPI的配置文件
内容如下：
org.springframework.context.ApplicationContextInitializer=\
tech.realcpf.spring.DemoApplicationContextInitializer
org.springframework.context.ApplicationListener=\
tech.realcpf.spring.DemoApplicationListener


如果用spring-boot，再spring-boot3之后配置文件改成
 resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports 作为SPI的配置文件
内容则是一个类一行

其中 org.springframework.boot.autoconfigure.AutoConfiguration 是Interface名

&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Spring Aop&lt;/h3&gt;
&lt;blockquote&gt;
&lt;p&gt;https://docs.spring.io/spring-framework/reference/core/aop-api/pointcuts.html&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h4&gt;Proxy - ProxyFactoryBean&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;ApplicationContext context =
        new ClassPathXmlApplicationContext(&quot;aopdemo.xml&quot;);
IDemoModel model = (IDemoModel) context.getBean(&quot;demoModelProxy&quot;);

System.out.println(model.hello(&quot;jc.liu&quot;));
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-xml&quot;&gt;
&amp;#x3C;bean id=&quot;demoModelProxy&quot;
   class=&quot;org.springframework.aop.framework.ProxyFactoryBean&quot;&gt;
       &amp;#x3C;property name=&quot;proxyInterfaces&quot;&gt;
           &amp;#x3C;list&gt;
               &amp;#x3C;value&gt;tech.realcpf.spring.aop.IDemoModel&amp;#x3C;/value&gt;
           &amp;#x3C;/list&gt;
       &amp;#x3C;/property&gt;

       &amp;#x3C;property name=&quot;target&quot; ref=&quot;demoModelImpl&quot;&gt;

       &amp;#x3C;/property&gt;

       &amp;#x3C;property name=&quot;interceptorNames&quot;&gt;
           &amp;#x3C;list&gt;
                &amp;#x3C;value&gt;demoModelArgs&amp;#x3C;/value&gt; &amp;#x3C;!-- impl MethodBeforeAdvice --&gt;
               &amp;#x3C;value&gt;demoModelReturn&amp;#x3C;/value&gt; &amp;#x3C;!-- impl AfterReturningAdvice --&gt;
           &amp;#x3C;/list&gt;
       &amp;#x3C;/property&gt;
   &amp;#x3C;/bean&gt;

&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Auto Proxy - BeanNameAutoProxyCreator&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;ApplicationContext context =
                new ClassPathXmlApplicationContext(&quot;aopdemo.xml&quot;);
IDemoModel demoModel = context.getBean(IDemoModel.class);
System.out.println(demoModel.hello(&quot;jc.liu&quot;));

&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-xml&quot;&gt;
 &amp;#x3C;bean class=&quot;org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator&quot;&gt;
                &amp;#x3C;property name=&quot;interceptorNames&quot;&gt;
                    &amp;#x3C;list&gt;
                        &amp;#x3C;value&gt;demoModelArgs&amp;#x3C;/value&gt;
                        &amp;#x3C;value&gt;demoModelReturn&amp;#x3C;/value&gt;
                    &amp;#x3C;/list&gt;
                &amp;#x3C;/property&gt;

        &amp;#x3C;!--        for auto match--&gt;
        &amp;#x3C;property name=&quot;beanNames&quot; value=&quot;*Model&quot;&gt;&amp;#x3C;/property&gt;
    &amp;#x3C;/bean&gt;

&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Aspectj&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;
// call before
@Before(&quot;tech.realcpf.spring.aop.aj.SystemArchitecture.service()&quot;)
public void callBefore(JoinPoint joinPoint) {
    System.out.println(&quot;Before : &quot; + Arrays.toString(joinPoint.getArgs()));
}


// call after
@AfterReturning(pointcut = &quot;tech.realcpf.spring.aop.aj.SystemArchitecture.service()&quot;,
        returning = &quot;result&quot;)
public void logResult(Object result) {
    System.out.println(&quot;after :&quot; + result);
}

@Pointcut(&quot;execution(* tech.realcpf.spring.aop.aj..*(..))&quot;)
public void service() {}

&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-xml&quot;&gt;
    &amp;#x3C;!-- enable aspectj --&gt;
    &amp;#x3C;aop:aspectj-autoproxy/&gt;

&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;#Spring EL&lt;/h2&gt;
&lt;blockquote&gt;
&lt;p&gt;https://docs.spring.io/spring-framework/reference/core/expressions/evaluation.html&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h4&gt;&lt;a href=&quot;https://docs.spring.io/spring-framework/reference/core/expressions/language-ref.html&quot;&gt;更多的语法语义&lt;/a&gt;&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;static class Simple {
    public List&amp;#x3C;Boolean&gt; booleans = new ArrayList&amp;#x3C;&gt;();
}

ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression(&quot;&apos;Hello World&apos;.concat(&apos;!&apos;)&quot;);
String message = (String) exp.getValue();
System.out.println(message);
System.out.println(
    parser.parseExpression(&quot;&apos;hello&apos;.bytes.length&quot;).getValue()
);

Simple simple = new Simple();
simple.booleans.add(false);
EvaluationContext context = SimpleEvaluationContext.forReadOnlyDataBinding().build();

parser.parseExpression(&quot;booleans[0]&quot;)
        .setValue(context,simple,&quot;true&quot;);
assert simple.booleans.get(0);


&lt;/code&gt;&lt;/pre&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>argo 在数据任务编排执行中的应用</title><link>https://realcpf.tech/blog/argo-for-data-job</link><guid isPermaLink="true">https://realcpf.tech/blog/argo-for-data-job</guid><description>通过argo 使得数据ETL任务on cloud</description><pubDate>Sat, 01 Jun 2024 18:16:00 GMT</pubDate><content:encoded>&lt;h3&gt;argo golang client&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;带参数提交hello world&lt;/li&gt;
&lt;/ol&gt;
&lt;pre&gt;&lt;code class=&quot;language-go&quot;&gt;var helloWorldWorkflow = wfv1.Workflow{
	ObjectMeta: metav1.ObjectMeta{
		GenerateName: &quot;hello-world-with-param-&quot;,
	},
	Spec: wfv1.WorkflowSpec{
		Entrypoint: &quot;whalesay&quot;,
		Templates: []wfv1.Template{
			{
				Name: &quot;whalesay&quot;,
				Container: &amp;#x26;corev1.Container{
					Image:   &quot;docker/whalesay:latest&quot;,
					Command: []string{&quot;cowsay&quot;},
                    // 参数模板
					Args:    []string{&quot;{{inputs.parameters.message}}&quot;},
				},
				Inputs: wfv1.Inputs{
                    // 参数值 此处是固定值，还可以是 configMapKeyRef http等
					Parameters: []wfv1.Parameter{
						{
							Name:        &quot;message&quot;,
							Value:       wfv1.AnyStringPtr(&quot;从golang传入的参数&quot;),
							Description: wfv1.AnyStringPtr(&quot;这是描述&quot;),
						},
					},
				},
			},
		},
	},
}
&lt;/code&gt;&lt;/pre&gt;
&lt;ol start=&quot;2&quot;&gt;
&lt;li&gt;访问外部服务的提交(先在argo下建立对应外部endpoint的service)&lt;/li&gt;
&lt;/ol&gt;
&lt;pre&gt;&lt;code class=&quot;language-yaml&quot;&gt;kind: Endpoints
apiVersion: v1
metadata:
  name: outer-ip
subsets:
  - addresses:
      - ip: 192.168.124.23
    ports:
      - port: 2015
        name: tcp
---
apiVersion: v1
kind: Service
metadata:
  name: outer-ip
spec:
  ports:
    - protocol: TCP
      port: 2015
      name: tcp
      targetPort: 2015
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;这样就可以打通数据任务的网络连接&lt;/p&gt;
&lt;/blockquote&gt;
&lt;pre&gt;&lt;code class=&quot;language-go&quot;&gt;var curlExtServiceWorkflow = wfv1.Workflow{
	ObjectMeta: metav1.ObjectMeta{
		GenerateName: &quot;demo-ext-service-curl-&quot;,
	},
	Spec: wfv1.WorkflowSpec{
		Entrypoint: &quot;curl&quot;,
		Templates: []wfv1.Template{
			{
				Name: &quot;curl&quot;,
				Container: &amp;#x26;corev1.Container{
					Image:   &quot;docker.io/curlimages/curl&quot;,
					Command: []string{&quot;curl&quot;},
					Args:    []string{&quot;{{inputs.parameters.addr}}&quot;},
				},
				Inputs: wfv1.Inputs{
					Parameters: []wfv1.Parameter{
						{
							Name:        &quot;addr&quot;,
							Value:       wfv1.AnyStringPtr(&quot;192.168.124.23:2015&quot;),
							Description: wfv1.AnyStringPtr(&quot;这是描述&quot;),
						},
					},
				},
			},
		},
	},
}

&lt;/code&gt;&lt;/pre&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>Building dynamic routing forwarding based on pingora</title><link>https://realcpf.tech/blog/pingora-simple</link><guid isPermaLink="true">https://realcpf.tech/blog/pingora-simple</guid><description>基于pingora的http代理服务探索</description><pubDate>Tue, 28 May 2024 18:16:00 GMT</pubDate><content:encoded>&lt;h3&gt;生命周期简介&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;# 使用httpbin 验证转发 以及header修改
podman run -p 8080:80 docker.io/kong/httpbin:latest

RUST_LOG=INFO cargo run

# 该请求会转发到8080 并体系header修改
curl localhost:18081/get -v
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;#[async_trait]
impl ProxyHttp for SimpleGateway{
    type CTX = ();
    fn new_ctx(&amp;#x26;self) -&gt; Self::CTX {}

    ///
    /// 转发
    async fn upstream_peer(&amp;#x26;self, session: &amp;#x26;mut Session, ctx: &amp;#x26;mut Self::CTX) -&gt; pingora_error::Result&amp;#x3C;Box&amp;#x3C;HttpPeer&gt;&gt; {
        log_summary(session,&quot;upstream_peer&quot;);

        let peer = Box::new(HttpPeer::new((&quot;127.0.0.1&quot;, 8080), false, &quot;1.1.1.1&quot;.to_string()));
        Ok(peer)
    }

    ///
    /// 首先处理请求
    /// 解析、验证、速率限制
    /// 注意 返回true意味着请求退出 false 继续
    async fn request_filter(&amp;#x26;self, _session: &amp;#x26;mut Session, _ctx: &amp;#x26;mut Self::CTX) -&gt; pingora_error::Result&amp;#x3C;bool&gt; where Self::CTX: Send + Sync {
        log_summary(_session,&quot;request_filter&quot;);
        Ok(false)
    }

    ///
    /// 决定是否继续请求
    async fn proxy_upstream_filter(&amp;#x26;self, _session: &amp;#x26;mut Session, _ctx: &amp;#x26;mut Self::CTX) -&gt; pingora_error::Result&amp;#x3C;bool&gt; where Self::CTX: Send + Sync {
        log_summary(_session,&quot;proxy_upstream_filter&quot;);
        Ok(true)
    }

    ///
    /// 请求发到上游前修改请求
    async fn upstream_request_filter(&amp;#x26;self, _session: &amp;#x26;mut Session, _upstream_request: &amp;#x26;mut RequestHeader, _ctx: &amp;#x26;mut Self::CTX) -&gt; pingora_error::Result&amp;#x3C;()&gt; where Self::CTX: Send + Sync {
        log_summary(_session,&quot;upstream_request_filter&quot;);
        _upstream_request.insert_header(&quot;service-name&quot;,&amp;#x26;self.name)
    }

    ///
    /// 在返回下游前修改响应
    async fn response_filter(&amp;#x26;self, _session: &amp;#x26;mut Session, _upstream_response: &amp;#x26;mut ResponseHeader, _ctx: &amp;#x26;mut Self::CTX) -&gt; pingora_error::Result&amp;#x3C;()&gt; where Self::CTX: Send + Sync {
        log_summary(_session,&quot;response_filter&quot;);
        _upstream_response.insert_header(&quot;server-resp&quot;,&amp;#x26;self.name)
    }

    ///
    /// 针对响应正文
    fn response_body_filter(&amp;#x26;self, _session: &amp;#x26;mut Session, _body: &amp;#x26;mut Option&amp;#x3C;Bytes&gt;, _end_of_stream: bool, _ctx: &amp;#x26;mut Self::CTX) -&gt; pingora_error::Result&amp;#x3C;Option&amp;#x3C;Duration&gt;&gt; where Self::CTX: Send + Sync {
        log_summary(_session,&quot;response_body_filter&quot;);
        Ok(Some(Duration::from_secs(0)))
    }


    ///
    /// session日志
    async fn logging(&amp;#x26;self, _session: &amp;#x26;mut Session, _e: Option&amp;#x3C;&amp;#x26;Error&gt;, _ctx: &amp;#x26;mut Self::CTX) where Self::CTX: Send + Sync {
        let res_code = _session.response_written()
            .map_or(0,|resp|resp.status.as_u16());
        info!(&quot;{} response code: {res_code}&quot;,self.request_summary(_session,_ctx));
    }

    ///
    /// 刚刚连接
    async fn connected_to_upstream(&amp;#x26;self, _session: &amp;#x26;mut Session, _reused: bool, _peer: &amp;#x26;HttpPeer, _fd: RawFd, _digest: Option&amp;#x3C;&amp;#x26;Digest&gt;, _ctx: &amp;#x26;mut Self::CTX) -&gt; pingora_error::Result&amp;#x3C;()&gt; where Self::CTX: Send + Sync {
        log_summary(_session,&quot;connected_to_upstream&quot;);
        Ok(())
    }
}

fn log_summary(session: &amp;#x26;mut Session,func_name:&amp;#x26;str) {
    let summary = session.request_summary();
    info!(&quot;==&gt;{func_name:?} {summary:?}&quot;)
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;静态路由代理&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;
#[async_trait]
impl ProxyHttp for SimpleProxy{
    type CTX = CurrentRoute;

    fn new_ctx(&amp;#x26;self) -&gt; Self::CTX {
        CurrentRoute{
            // 一级路由用于判断转发到何处
            inner_route:&quot;&quot;.to_string(),
            // 去掉一级路由后的部分
            goto_route:&quot;&quot;.to_string(),
        }
    }

    async fn request_filter(&amp;#x26;self, _session: &amp;#x26;mut Session, _ctx: &amp;#x26;mut Self::CTX) -&gt; pingora_error::Result&amp;#x3C;bool&gt; where Self::CTX: Send + Sync {
        log_summary(_session,&quot;request_filter&quot;);
        // 获取一级路由
        let path = _session.req_header().uri.path_and_query().unwrap().to_string();
        let path_arr = path.strip_prefix(&quot;/&quot;).unwrap().split_once(&quot;/&quot;).unwrap();
        // 如果没有就返回不再继续
        if !self.where_go_to.contains_key(path_arr.0) {
            return Ok(true)
        }
        // 如果又就存入上下文
        _ctx.inner_route = path_arr.0.to_string();
        _ctx.goto_route = path_arr.1.to_string();
        Ok(false)
    }

    async fn upstream_peer(&amp;#x26;self, session: &amp;#x26;mut Session, ctx: &amp;#x26;mut Self::CTX) -&gt; pingora_error::Result&amp;#x3C;Box&amp;#x3C;HttpPeer&gt;&gt; {
        log_summary(session,&quot;upstream_peer&quot;);
        // 从map中获取转发目标
        let peer = self.where_go_to.get(&amp;#x26;ctx.inner_route).unwrap();
        let peer_addr = &amp;#x26;peer.0;
        let peer_port = peer.1;
        // 构建peer
        let bp = Box::new(HttpPeer::new((String::from(peer_addr),peer_port),false,&quot;1.1.1.1&quot;.to_string()));
        Ok(bp)
    }

    async fn upstream_request_filter(&amp;#x26;self, _session: &amp;#x26;mut Session, _upstream_request: &amp;#x26;mut RequestHeader, _ctx: &amp;#x26;mut Self::CTX) -&gt; pingora_error::Result&amp;#x3C;()&gt; where Self::CTX: Send + Sync {

        // 把转发路径改为去掉一级路由的部分
        let path = &amp;#x26;_ctx.goto_route;
        let v = PathAndQuery::from_str(&amp;#x26;path).unwrap();
        _upstream_request.set_uri(Uri::from(v));
        Ok(())

    }

    async fn response_filter(&amp;#x26;self, _session: &amp;#x26;mut Session, _upstream_response: &amp;#x26;mut ResponseHeader, _ctx: &amp;#x26;mut Self::CTX) -&gt; pingora_error::Result&amp;#x3C;()&gt; where Self::CTX: Send + Sync {
        Ok(())
    }

    async fn logging(&amp;#x26;self, _session: &amp;#x26;mut Session, _e: Option&amp;#x3C;&amp;#x26;Error&gt;, _ctx: &amp;#x26;mut Self::CTX) where Self::CTX: Send + Sync {
        log_summary(_session,&quot;logging&quot;);
        // 如果为空就是从request_filter 404跳过来的
        if _ctx.goto_route.is_empty() {
            // 准备ResponseHeader
            let mut req_h = ResponseHeader::build(404,Some(6)).unwrap();
            // 返回数据
            let b = Bytes::from(&quot;can not find proxy path&quot;);
            req_h.append_header(&quot;Content-Length&quot;,b.len()).unwrap();
            // 一定要write_response_header 写准备ResponseHeader 才能把后面的body写入响应
            _session.write_response_header(Box::new(req_h)).await.unwrap();

            _session.write_response_body(b).await.unwrap();
            _session.set_keepalive(None);

            info!(&quot;==&gt;is write{:?}&quot;,_session.response_written());

            _session.finish_body().await.unwrap();
        }

    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;动态路由转发&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;# 实现效果
# 1.check route exits ?
curl --request POST --url &apos;http://127.0.0.1:18081/a/post?a=3&apos; --header &apos;Accept: *&apos; --header &apos;Content-Type: *&apos;
# 2. add route
 curl --request GET \
   --url http://127.0.0.1:8989/ \
   --header &apos;Content-Type: application/json&apos; \
   --header &apos;User-Agent: insomnia/2023.5.8&apos; \
   --data &apos;{
 	&quot;route&quot;:&quot;a&quot;,
 	&quot;addr&quot;:&quot;127.0.0.1&quot;,
 	&quot;port&quot;:8080
 }&apos;
# 3. check again
curl --request POST --url &apos;http://127.0.0.1:18081/a/post?a=3&apos; --header &apos;Accept: *&apos; --header &apos;Content-Type: *&apos;

&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;
pub struct MutRouteProxy {
    // 因为所有权问题以及并发等问题 使用了moka的sync cache
    where_go_to:Cache&amp;#x3C;String,PeerAddr&gt;,
}

// http proxy 部分没有改变

// 添加了一个admin app 用于添加路由


#[async_trait]
impl ServeHttp for AdminApp {
    async fn response(&amp;#x26;self, http_session: &amp;#x26;mut ServerSession) -&gt; Response&amp;#x3C;Vec&amp;#x3C;u8&gt;&gt; {
        let read_timeout = 2000;
        let body = match timeout(
            Duration::from_millis(read_timeout),
            http_session.read_request_body(),
        )
            .await
        {
            Ok(res) =&gt; res.unwrap().unwrap_or_else(|| Bytes::from(&quot;no body!&quot;)),
            Err(_) =&gt; {
                panic!(&quot;Timed out after {:?}ms&quot;, read_timeout);
            }
        };

        let v:NewRoute= serde_json::from_slice(body.to_vec().as_slice()).unwrap();
        let route = v.route;
        let addr = v.addr;
        let port = v.port;
        info!(&quot;new route ==={route} &gt; {addr}:{port}&quot;);
        self.map.insert(route,PeerAddr(addr,port));

        let ret = Bytes::from(&quot;ok&quot;);
        Response::builder()
            .status(StatusCode::OK)
            .header(http::header::CONTENT_TYPE, &quot;text/html&quot;)
            .header(http::header::CONTENT_LENGTH, ret.len())
            .body(ret.to_vec())
            .unwrap()
    }
}

&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;代码仓库&lt;/h3&gt;
&lt;blockquote&gt;
&lt;p&gt;GITHUB&lt;a href=&quot;https://github.com/real-cpf/po-hproxy&quot;&gt;po-hproxy&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;blockquote&gt;
&lt;p&gt;ATOM&lt;a href=&quot;https://atomgit.com/realcpf/po-hproxy&quot;&gt;po-hproxy&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>Programming Rust 2nd Edition-2021</title><link>https://realcpf.tech/blog/programming-rust-2nd-edition-2021</link><guid isPermaLink="true">https://realcpf.tech/blog/programming-rust-2nd-edition-2021</guid><description>Programming Rust 2nd Edition-2021</description><pubDate>Wed, 28 Feb 2024 19:22:00 GMT</pubDate><content:encoded>&lt;h3&gt;Fundamental-Types&lt;/h3&gt;
&lt;blockquote&gt;
&lt;p&gt;There are many, many types of books in the world, which makes good sense, because there are many, many types of people, and everybody wants to read something different.
—Lemony Snicke
&lt;img src=&quot;/jupyter-img/7272218c-e7b9-4a3c-841c-8e70158e6cd8.png&quot; alt=&quot;image.png&quot;&gt; &gt; &lt;img src=&quot;/jupyter-img/273479eb-91ca-450a-b065-dcddb54493eb.png&quot; alt=&quot;image.png&quot;&gt; &gt; &lt;img src=&quot;/jupyter-img/9d18a5b2-dd1c-4912-8c26-82192ff707e9.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h4&gt;Fixed-Width Numeric Types&lt;/h4&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/fde9c118-8af2-4e88-babc-e9e74eccffe2.png&quot; alt=&quot;image.png&quot;&gt;
&lt;img src=&quot;/jupyter-img/338ecab3-09c6-457e-a7e3-77a3551c3813.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;// 10_u8.checked_mul(10).expect(&quot;数值溢出&quot;);
// 100_u8.checked_add(200).expect(&quot;&quot;);
// let x = 100_u8;
// let y = 100_u8;
// // Do the addition; panic if it overflows.
// let sum = x.checked_add(y).unwrap();
// 超出不报错
500_u16.wrapping_mul(500);  // 53392
500_i16.wrapping_mul(500); // -12144
// In bitwise shift operations, the shift distance
// is wrapped to fall within the size of the value.
// So a shift of 17 bits in a 16-bit type is a shift
// of 1.
// assert_eq!(5_i16.wrapping_shl(17), 10);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/c16a8623-53aa-4bce-a299-07032df98262.png&quot; alt=&quot;image.png&quot;&gt;
&lt;img src=&quot;/jupyter-img/16a70a25-fa52-42a9-b9c0-6cd40ae276c2.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;h4&gt;Characters&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;assert_eq!(&apos;*&apos; as i32, 42);
assert_eq!(&apos;ಠ&apos; as u16, 0xca0);
assert_eq!(&apos;ಠ&apos; as i8, -0x60); // U+0CA0 truncated to eight bits, signed
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;assert_eq!(&apos;*&apos;.is_alphabetic(), false);
assert_eq!(&apos;β&apos;.is_alphabetic(), true);
assert_eq!(&apos;8&apos;.to_digit(10), Some(8));
assert_eq!(&apos;ಠ&apos;.len_utf8(), 3);
assert_eq!(std::char::from_digit(2, 10), Some(&apos;2&apos;));
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Tuples&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let text = &quot;I see the eigenvalue in thine eye&quot;;
let (head, tail) = text.split_at(21);
assert_eq!(head, &quot;I see the eigenvalue &quot;);
assert_eq!(tail, &quot;in thine eye&quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let text = &quot;I see the eigenvalue in thine eye&quot;;
let temp = text.split_at(21);
let head = temp.0;
let tail = temp.1;
assert_eq!(head, &quot;I see the eigenvalue &quot;);
assert_eq!(tail, &quot;in thine eye&quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Slices&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let v: Vec&amp;#x3C;f64&gt; = vec![0.0, 0.707, 1.0, 0.707];
let a: [f64; 4] = [0.0, -0.707, -1.0, -0.707];
let sv: &amp;#x26;[f64] = &amp;#x26;v;
let sa: &amp;#x26;[f64] = &amp;#x26;a;
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;Error: The variable `sv` contains a reference with a non-static lifetime so
can&apos;t be persisted. You can prevent this error by making sure that the
variable goes out of scope - i.e. wrapping the code in {}.
[E0597] Error: `a` does not live long enough
   ╭─[command_23:1:1]
   │
 2 │ let a: [f64; 4] = [0.0, -0.707, -1.0, -0.707];
   │     ┬
   │     ╰── binding `a` declared here
   │
 4 │ let sa: &amp;#x26;[f64] = &amp;#x26;a;
   │                  ─┬
   │                   ╰── borrowed value does not live long enough
   │                   │
   │                   ╰── cast requires that `a` is borrowed for `&apos;static`
───╯
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/52556aaf-7d7f-4d8a-b235-ca5d3b192482.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;h4&gt;String Literals&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;println!(&quot;In the room the women come and go,
Singing of Mount Abora&quot;);
println!(&quot;It was a bright, cold day in April, and \
there were four of us—\
more or less.&quot;);
let default_win_install_path = r&quot;C:\Program Files\Gorillas&quot;;
println!(r###&quot;
This raw string started with &apos;r###&quot;&apos;.
Therefore it does not end until we reach a quote mark (&apos;&quot;&apos;)
followed immediately by three pound signs (&apos;###&apos;):
&quot;###);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;In the room the women come and go,
Singing of Mount Abora
It was a bright, cold day in April, and there were four of us—more or less.

This raw string started with &apos;r###&quot;&apos;.
Therefore it does not end until we reach a quote mark (&apos;&quot;&apos;)
followed immediately by three pound signs (&apos;###&apos;):
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Byte Strings&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let method = b&quot;GET&quot;;
assert_eq!(method, &amp;#x26;[b&apos;G&apos;, b&apos;E&apos;, b&apos;T&apos;]);
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Strings&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let noodles = &quot;noodles&quot;.to_string();
let oodles = &amp;#x26;noodles[1..];
let poodles = &quot;ಠ_ಠ&quot;;
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;let oodles = &amp;#x26;noodles[1..];
let oodles = &amp;#x26;noodles[1..];
    ^^^^^^
The variable `oodles` contains a reference with a non-static lifetime so
can&apos;t be persisted. You can prevent this error by making sure that the
variable goes out of scope - i.e. wrapping the code in {}.
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/bf7a6a01-2122-4d2e-b30a-cc4a0d426a45.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;assert_eq!(&quot;ಠ_ಠ&quot;.len(), 7);
assert_eq!(&quot;ಠ_ಠ&quot;.chars().count(), 3)
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/a151916a-fb68-454e-a13a-cd419eba1e4f.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let error_message = &quot;too many pets&quot;.to_string();
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;println!(&quot;{}&quot;,error_message)
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;too many pets
()
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;format string&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;println!(&quot;{}&quot;,format!(&quot;{}°{:02}′{:02}″N&quot;, 24, 5, 23))
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;24°05′23″N
()
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let bits = vec![&quot;veni&quot;, &quot;vidi&quot;, &quot;vici&quot;];
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;bits.concat()
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;&quot;venividivici&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;bits.join(&quot;,&quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;&quot;veni,vidi,vici&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;&quot;ONE&quot;.to_lowercase()
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;&quot;one&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;&quot;peanut&quot;.contains(&quot;nut&quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;true
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;&quot;ಠ_ಠ&quot;.replace(&quot;ಠ&quot;, &quot;■&quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;&quot;■_■&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Ownership-and-Moves&lt;/h3&gt;
&lt;h4&gt;Ownership&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;{
let point = Box::new((0.625, 0.5)); // point allocated here
let label = format!(&quot;{:?}&quot;, point); // label allocated here
assert_eq!(label, &quot;(0.625, 0.5)&quot;);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/aaddb7b8-02c8-4189-91c6-b3bead455bc9.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;struct Person { name: String, birth: i32 }
let mut composers = Vec::new();
composers.push(Person {
    name: &quot;Abc&quot;.to_string(),
    birth: 123,
});
composers.push(Person {
    name: &quot;DEF&quot;.to_string(),
    birth: 444,
});
composers.push(Person {
    name: &quot;ASD&quot;.to_string(),
    birth: 555,
});
for composer in &amp;#x26;composers {
println!(&quot;{}, born {}&quot;, composer.name, composer.birth);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;Abc, born 123
DEF, born 444
ASD, born 555
()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/7110e28f-1295-4ba9-b514-de204f6ae63f.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;h4&gt;Moves&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let s = vec![&quot;udon&quot;.to_string(), &quot;ramen&quot;.to_string(), &quot;soba&quot;.to_string()];
let t = s;
let u = s;
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;[E0382] Error: use of moved value: `s`
   ╭─[command_4:1:1]
   │
 1 │ let s = vec![&quot;udon&quot;.to_string(), &quot;ramen&quot;.to_string(), &quot;soba&quot;.to_string()];
   │     ┬
   │     ╰── move occurs because `s` has type `Vec&amp;#x3C;String&gt;`, which does not implement the `Copy` trait
 2 │ let t = s;
   │         ┬│
   │         ╰── value moved here
   │          │
   │          ╰─ help: consider cloning the value if the performance cost is acceptable: `.clone()`
 3 │ let u = s;
   │         ┬
   │         ╰── value used here after move
───╯
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/d39ea566-7ad3-4cb6-ab97-02fb8c581644.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let s = vec![&quot;udon&quot;.to_string(), &quot;ramen&quot;.to_string(), &quot;soba&quot;.to_string()];
let t = s.clone();
let u = s.clone();
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;More Operations That Move&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let mut s = &quot;Govinda&quot;.to_string();
s = &quot;Siddhartha&quot;.to_string(); // value &quot;Govinda&quot; dropped here
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let mut s = &quot;Govinda&quot;.to_string();
let t = s;
s = &quot;Siddhartha&quot;.to_string(); // nothing is dropped here
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Moves and Control Flow&lt;/h4&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/25d8c903-2c3d-4db2-a755-690dc494a7c8.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;h4&gt;Moves and Indexed Content&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;// Build a vector of the strings &quot;101&quot;, &quot;102&quot;, ... &quot;105&quot;
let mut v = Vec::new();
for i in 101 .. 106 {
v.push(i.to_string());
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;()
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;// Pull out random elements from the vector.
let third = v[2]; // error: Cannot move out of index of Vec
let fifth = v[4]; // here too
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;[E0507] Error: cannot move out of index of `Vec&amp;#x3C;String&gt;`
   ╭─[command_9:1:1]
   │
 2 │ let third = v[2]; // error: Cannot move out of index of Vec
   │             ┬─┬─
   │             ╰───── help: consider borrowing here: `&amp;#x26;`
   │               │
   │               ╰─── move occurs because value has type `String`, which does not implement the `Copy` trait
───╯
[E0507] Error: cannot move out of index of `Vec&amp;#x3C;String&gt;`
   ╭─[command_9:1:1]
   │
 3 │ let fifth = v[4]; // here too
   │             ┬─┬─
   │             ╰───── help: consider borrowing here: `&amp;#x26;`
   │               │
   │               ╰─── move occurs because value has type `String`, which does not implement the `Copy` trait
───╯
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;// 1. Pop a value off the end of the vector:
let fifth = v.pop().expect(&quot;vector empty!&quot;);
assert_eq!(fifth, &quot;105&quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;// 2. Move a value out of a given index in the vector,
// and move the last element into its spot:
let second = v.swap_remove(1);
assert_eq!(second, &quot;102&quot;);
// 3. Swap in another value for the one we&apos;re taking out:
let third = std::mem::replace(&amp;#x26;mut v[2], &quot;substitute&quot;.to_string());
assert_eq!(third, &quot;103&quot;);
// Let&apos;s see what&apos;s left of our vector.
assert_eq!(v, vec![&quot;101&quot;, &quot;104&quot;, &quot;substitute&quot;]);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;struct Person { name: Option&amp;#x3C;String&gt;, birth: i32 }
let mut composers = Vec::new();
composers.push(Person { name: Some(&quot;Palestrina&quot;.to_string()),
birth: 1525 });
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let first_name = composers[0].name;
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;[E0507] Error: cannot move out of index of `Vec&amp;#x3C;Person&gt;`
   ╭─[command_13:1:1]
   │
 1 │ let first_name = composers[0].name;
   │                  ┬───────┬────────
   │                  ╰────────────────── help: consider borrowing here: `&amp;#x26;`
   │                          │
   │                          ╰────────── move occurs because value has type `Option&amp;#x3C;String&gt;`, which does not implement the `Copy` trait
───╯
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let first_name = std::mem::replace(&amp;#x26;mut composers[0].name, None);
assert_eq!(first_name, Some(&quot;Palestrina&quot;.to_string()));
assert_eq!(composers[0].name, None);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let first_name = composers[0].name.take();
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Copy Types: The Exception to Moves&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let string1 = &quot;somnambulance&quot;.to_string();
let string2 = string1;
let num1: i32 = 36;
let num2 = num1;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/96ff5866-2fb4-4196-a574-a799687139c4.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;struct Label { number: u32 }
fn print(l: Label) { println!(&quot;STAMP: {}&quot;, l.number); }
let l = Label { number: 3 };
print(l);
println!(&quot;My label number is: {}&quot;, l.number);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;[E0382] Error: borrow of moved value: `l`
   ╭─[command_17:1:1]
   │
 3 │ let l = Label { number: 3 };
   │     ┬
   │     ╰── move occurs because `l` has type `Label`, which does not implement the `Copy` trait
 4 │ print(l);
   │       ┬
   │       ╰── value moved here
 5 │ println!(&quot;My label number is: {}&quot;, l.number);
   │                                    ────┬───
   │                                        ╰───── value borrowed here after move
───╯
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;#[derive(Copy, Clone)]
struct Label { number: u32 }
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;#[derive(Copy, Clone)]
struct StringLabel { name: String }
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;[E0204] Error: the trait `Copy` cannot be implemented for this type
   ╭─[command_19:1:1]
   │
 1 │ #[derive(Copy, Clone)]
   │          ──┬─
   │            ╰─── error: the trait `Copy` cannot be implemented for this type
 2 │ struct StringLabel { name: String }
   │                      ──────┬─────
   │                            ╰─────── this field does not implement `Copy`
───╯
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Rc and Arc: Shared Ownership&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::rc::Rc;
// Rust can infer all these types; written out for clarity
let s: Rc&amp;#x3C;String&gt; = Rc::new(&quot;shirataki&quot;.to_string());
let t: Rc&amp;#x3C;String&gt; = s.clone();
let u: Rc&amp;#x3C;String&gt; = s.clone();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/518c58f9-1e90-47b7-9711-f07a93e71239.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;assert!(s.contains(&quot;shira&quot;));
assert_eq!(t.find(&quot;taki&quot;), Some(5));
println!(&quot;{} are quite chewy, almost bouncy, but lack flavor&quot;, u);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;shirataki are quite chewy, almost bouncy, but lack flavor
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;s.push_str(&quot; noodles&quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;[E0596] Error: cannot borrow data in an `Rc` as mutable
   ╭─[command_22:1:1]
   │
 1 │ s.push_str(&quot; noodles&quot;);
   │ ┬
   │ ╰── cannot borrow as mutable
   │
   │ Note: You can change an existing variable to mutable like: `let mut x = x;`
───╯
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/ba23770b-80e7-4969-9420-c05d2e079256.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;References&lt;/h3&gt;
&lt;blockquote&gt;
&lt;p&gt;Libraries cannot provide new inabilities.
—Mark Miller&lt;/p&gt;
&lt;/blockquote&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::collections::HashMap;
type Table = HashMap&amp;#x3C;String, Vec&amp;#x3C;String&gt;&gt;;
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;fn show(table:Table) {
    for (artist,works) in table {
        println!(&quot;works by {}&quot;,artist);
        for work in works {
            println!(&quot;  {}&quot;,work);
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let mut table = Table::new();
table.insert(&quot;Gesualdo&quot;.to_string(),
vec![&quot;many madrigals&quot;.to_string(),
&quot;Tenebrae Responsoria&quot;.to_string()]);
table.insert(&quot;Caravaggio&quot;.to_string(),
vec![&quot;The Musicians&quot;.to_string(),
&quot;The Calling of St. Matthew&quot;.to_string()]);
table.insert(&quot;Cellini&quot;.to_string(),
vec![&quot;Perseus with the head of Medusa&quot;.to_string(),
&quot;a salt cellar&quot;.to_string()]);
show(table);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;works by Gesualdo
  many madrigals
  Tenebrae Responsoria
works by Caravaggio
  The Musicians
  The Calling of St. Matthew
works by Cellini
  Perseus with the head of Medusa
  a salt cellar
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;fn sort_works(table: &amp;#x26;mut Table) {
for (_artist, works) in table {
works.sort();
}
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let mut table = Table::new();
table.insert(&quot;Gesualdo&quot;.to_string(),
vec![&quot;many madrigals&quot;.to_string(),
&quot;Tenebrae Responsoria&quot;.to_string()]);
table.insert(&quot;Caravaggio&quot;.to_string(),
vec![&quot;The Musicians&quot;.to_string(),
&quot;The Calling of St. Matthew&quot;.to_string()]);
table.insert(&quot;Cellini&quot;.to_string(),
vec![&quot;Perseus with the head of Medusa&quot;.to_string(),
&quot;a salt cellar&quot;.to_string()]);
sort_works(&amp;#x26;mut table);
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Assigning References&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let x = 10;
let y = 20;
let mut r = &amp;#x26;x;
if true { r = &amp;#x26;y; }
assert!(*r == 10 || *r == 20);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;Error: The variable `r` contains a reference with a non-static lifetime so
can&apos;t be persisted. You can prevent this error by making sure that the
variable goes out of scope - i.e. wrapping the code in {}.
Error: The variable `r` contains a reference with a non-static lifetime so
can&apos;t be persisted. You can prevent this error by making sure that the
variable goes out of scope - i.e. wrapping the code in {}.
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/4cd47f41-3649-4392-916f-22107ffdb606.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;h4&gt;References to References&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;{
    struct Point { x: i32, y: i32 }
    let point = Point { x: 1000, y: 729 };
    let r: &amp;#x26;Point = &amp;#x26;point;
    let rr: &amp;#x26;&amp;#x26;Point = &amp;#x26;r;
    let rrr: &amp;#x26;&amp;#x26;&amp;#x26;Point = &amp;#x26;rr;
    assert_eq!(rrr.y, 729);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/c1ff25d4-0fc9-44f0-a1d0-b15e7113dc13.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;h4&gt;Comparing References&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;{
    let x = 10;
let y = 10;
let rx = &amp;#x26;x;
let ry = &amp;#x26;y;
let rrx = &amp;#x26;rx;
let rry = &amp;#x26;ry;
assert!(rrx &amp;#x3C;= rry);
assert!(rrx == rry);
    assert!(rx == ry); // their referents are equal
assert!(!std::ptr::eq(rx, ry)); // but occupy different addresses
    assert!(rx == rrx); // error: type mismatch: `&amp;#x26;i32` vs `&amp;#x26;&amp;#x26;i32`
assert!(rx == *rrx); // this is okay
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;[E0277] Error: can&apos;t compare `{integer}` with `&amp;#x26;{integer}`
    ╭─[command_19:1:1]
    │
 13 │     assert!(rx == rrx); // error: type mismatch: `&amp;#x26;i32` vs `&amp;#x26;&amp;#x26;i32`
    │                ─┬
    │                 ╰── no implementation for `{integer} == &amp;#x26;{integer}`
────╯
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Borrowing a Local Variable&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;{
    let r;
    {
        let x = 1;
        r = &amp;#x26;x;
    }
    assert_eq!(*r,1);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;[E0597] Error: `x` does not live long enough
   ╭─[command_20:1:1]
   │
 4 │         let x = 1;
   │             ┬
   │             ╰── binding `x` declared here
 5 │         r = &amp;#x26;x;
   │             ─┬
   │              ╰── borrowed value does not live long enough
 6 │     }
   │     ┬
   │     ╰── `x` dropped here while still borrowed
 7 │     assert_eq!(*r,1);
   │     ────────┬───────
   │             ╰───────── borrow later used here
───╯
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/56e8d3e0-2b0e-4f49-ad89-22d60391275c.png&quot; alt=&quot;image.png&quot;&gt;
&lt;img src=&quot;/jupyter-img/1d4c66dd-e81f-4ead-a297-f6d7f8138d3f.png&quot; alt=&quot;image.png&quot;&gt;
&lt;img src=&quot;/jupyter-img/7fb44e1e-1cc9-4e6f-a0a6-21f9283afb63.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;h4&gt;Receiving References as Function Arguments&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;// This code has several problems, and doesn&apos;t compile.
static mut STASH: &amp;#x26;i32;
fn f(p: &amp;#x26;i32) { STASH = p; }
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;Error: free static item without body
   ╭─[command_21:1:1]
   │
 2 │ static mut STASH: &amp;#x26;i32;
   │ ───────────┬──────────┬
   │            ╰───────────── error: free static item without body
   │                       │
   │                       ╰── help: provide a definition for the static: ` = &amp;#x3C;expr&gt;;`
───╯
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;static mut STASH: &amp;#x26;i32 = &amp;#x26;128;
fn f(p: &amp;#x26;i32) { // still not good enough
unsafe {
STASH = p;
}
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;Error: lifetime may not live long enough
   ╭─[command_22:1:1]
   │
 2 │ fn f(p: &amp;#x26;i32) { // still not good enough
   │         ┬
   │         ╰── let&apos;s call the lifetime of this reference `&apos;1`
   │
 4 │ STASH = p;
   │ ────┬────
   │     ╰────── assignment requires that `&apos;1` must outlive `&apos;static`
───╯
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;static mut STASH: &amp;#x26;i32 = &amp;#x26;10;
fn f(p: &amp;#x26;&apos;static i32) {
unsafe {
STASH = p;
    println!(&quot;{}&quot;,STASH);
}
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;static WORTH_POINTING_AT: i32 = 1000;
f(&amp;#x26;WORTH_POINTING_AT);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;1000
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;{
    unsafe {
        println!(&quot;{}&quot;,STASH);
        println!(&quot;{}&quot;,WORTH_POINTING_AT);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;10
1000
()
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Passing References to Functions&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;// This could be written more briefly: fn g(p: &amp;#x26;i32),
// but let&apos;s write out the lifetimes for now.
fn g&amp;#x3C;&apos;a&gt;(p: &amp;#x26;&apos;a i32) {  }
let x = 10;
g(&amp;#x26;x);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;fn f(p: &amp;#x26;&apos;static i32) {  }
let x = 10;
f(&amp;#x26;x);
// This fails to compile: the reference &amp;#x26;x must not outlive x, but by passing it to f, we
// constrain it to live at least as long as &apos;static. There’s no way to satisfy everyone here,
// so Rust rejects the code.
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;fn f(p: &amp;#x26;&apos;static i32) {  }
     ^ warning: unused variable: `p`
unused variable: `p`
help: if this is intentional, prefix it with an underscore

_p
warning: unused variable: `p`
unused variable: `p`
help: if this is intentional, prefix it with an underscore

_p
f(&amp;#x26;x);
  ^^ borrowed value does not live long enough
let x = 10;
    ^ binding `x` declared here
f(&amp;#x26;x);
^^^^^ argument requires that `x` is borrowed for `&apos;static`
`x` does not live long enough
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Returning References&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;fn smallest(v: &amp;#x26;[i32]) -&gt; &amp;#x26;i32 {
let mut s = &amp;#x26;v[0];
for r in &amp;#x26;v[1..] {
if *r &amp;#x3C; *s { s = r; }
}
s
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;// fn smallest&amp;#x3C;&apos;a&gt;(v: &amp;#x26;&apos;a [i32]) -&gt; &amp;#x26;&apos;a i32 {  }
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let s;
{
let parabola = [9, 4, 1, 0, 1, 4, 9];
s = smallest(&amp;#x26;parabola);
}
assert_eq!(*s, 0);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;[unused_variables] Error: unused variable: `p`
[E0597] Error: `parabola` does not live long enough
   ╭─[command_42:1:1]
   │
 3 │ let parabola = [9, 4, 1, 0, 1, 4, 9];
   │     ────┬───
   │         ╰───── binding `parabola` declared here
 4 │ s = smallest(&amp;#x26;parabola);
   │              ────┬────
   │                  ╰────── borrowed value does not live long enough
   │                  │
   │                  ╰────── cast requires that `parabola` is borrowed for `&apos;static`
 5 │ }
   │ ┬
   │ ╰── `parabola` dropped here while still borrowed
───╯
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;{
let parabola = [9, 4, 1, 0, 1, 4, 9];
let s = smallest(&amp;#x26;parabola);
assert_eq!(*s, 0); // fine: parabola still alive
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;()
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Structs Containing References&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;// This does not compile.
struct S {
r: &amp;#x26;i32
}
let s;
{
let x = 10;
s = S { r: &amp;#x26;x };
}
assert_eq!(*s.r, 10); // bad: reads from dropped `x`
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;[E0106] Error: missing lifetime specifier
   ╭─[command_44:1:1]
   │
 3 │ r: &amp;#x26;i32
   │    ┬
   │    ╰── expected named lifetime parameter
───╯
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;struct S&amp;#x3C;&apos;a&gt; {
r: &amp;#x26;&apos;a i32
}
{
    let s;
{
let x = 10;
s = S { r: &amp;#x26;x };
}
assert_eq!(*s.r, 10);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;[unused_variables] Error: unused variable: `p`
[E0597] Error: `x` does not live long enough
    ╭─[command_49:1:1]
    │
  7 │ let x = 10;
    │     ┬
    │     ╰── binding `x` declared here
  8 │ s = S { r: &amp;#x26;x };
    │            ─┬
    │             ╰── borrowed value does not live long enough
  9 │ }
    │ ┬
    │ ╰── `x` dropped here while still borrowed
 10 │ assert_eq!(*s.r, 10);
    │ ──────────┬─────────
    │           ╰─────────── borrow later used here
────╯
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Distinct Lifetime Parameters&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;struct S&amp;#x3C;&apos;a&gt; {
x: &amp;#x26;&apos;a i32,
y: &amp;#x26;&apos;a i32
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;{
    let x = 10;
let r;
{
let y = 20;
{
let s = S { x: &amp;#x26;x, y: &amp;#x26;y };
r = s.x;
}
}
println!(&quot;{}&quot;, r);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;[unused_variables] Error: unused variable: `p`
[E0597] Error: `y` does not live long enough
    ╭─[command_56:1:1]
    │
  5 │ let y = 20;
    │     ┬
    │     ╰── binding `y` declared here
    │
  7 │ let s = S { x: &amp;#x26;x, y: &amp;#x26;y };
    │                       ─┬
    │                        ╰── borrowed value does not live long enough
    │
 10 │ }
    │ ┬
    │ ╰── `y` dropped here while still borrowed
 11 │ println!(&quot;{}&quot;, r);
    │                ┬
    │                ╰── borrow later used here
────╯
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;struct S&amp;#x3C;&apos;a, &apos;b&gt; {
x: &amp;#x26;&apos;a i32,
y: &amp;#x26;&apos;b i32
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;{
    let x = 10;
let r;
{
let y = 20;
{
let s = S { x: &amp;#x26;x, y: &amp;#x26;y };
r = s.x;
}
}
println!(&quot;{}&quot;, r);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;10
()
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;fn f&amp;#x3C;&apos;a&gt;(r: &amp;#x26;&apos;a i32, s: &amp;#x26;&apos;a i32) -&gt; &amp;#x26;&apos;a i32 { r } // perhaps too tight
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;fn f&amp;#x3C;&apos;a, &apos;b&gt;(r: &amp;#x26;&apos;a i32, s: &amp;#x26;&apos;b i32) -&gt; &amp;#x26;&apos;a i32 { r } // looser
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;fn f&amp;#x3C;b&gt;(r: &amp;#x26;&apos;a i32, s: &amp;#x26;&apos;b i32) -&gt; &amp;#x26;&apos;a i32 { r }
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;[E0261] Error: use of undeclared lifetime name `&apos;a`
   ╭─[command_64:1:1]
   │
 1 │ fn f&amp;#x3C;b&gt;(r: &amp;#x26;&apos;a i32, s: &amp;#x26;&apos;b i32) -&gt; &amp;#x26;&apos;a i32 { r }
   │      │      ─┬
   │      ╰────────── help: consider introducing lifetime `&apos;a` here: `&apos;a, `
   │              │
   │              ╰── undeclared lifetime
───╯
[E0261] Error: use of undeclared lifetime name `&apos;b`
   ╭─[command_64:1:1]
   │
 1 │ fn f&amp;#x3C;b&gt;(r: &amp;#x26;&apos;a i32, s: &amp;#x26;&apos;b i32) -&gt; &amp;#x26;&apos;a i32 { r }
   │      │                  ─┬
   │      ╰────────────────────── help: consider introducing lifetime `&apos;b` here: `&apos;b, `
   │                          │
   │                          ╰── undeclared lifetime
───╯
[E0261] Error: use of undeclared lifetime name `&apos;a`
   ╭─[command_64:1:1]
   │
 1 │ fn f&amp;#x3C;b&gt;(r: &amp;#x26;&apos;a i32, s: &amp;#x26;&apos;b i32) -&gt; &amp;#x26;&apos;a i32 { r }
   │      │                              ─┬
   │      ╰────────────────────────────────── help: consider introducing lifetime `&apos;a` here: `&apos;a, `
   │                                      │
   │                                      ╰── undeclared lifetime
───╯
[non_camel_case_types] Error: type parameter `b` should have an upper camel case name
   ╭─[command_64:1:1]
   │
 1 │ fn f&amp;#x3C;b&gt;(r: &amp;#x26;&apos;a i32, s: &amp;#x26;&apos;b i32) -&gt; &amp;#x26;&apos;a i32 { r }
   │      ┬
   │      ╰── warning: type parameter `b` should have an upper camel case name
   │      │
   │      ╰── help: convert the identifier to upper camel case: `B`
───╯
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Omitting Lifetime Parameters&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;struct S&amp;#x3C;&apos;a, &apos;b&gt; {
x: &amp;#x26;&apos;a i32,
y: &amp;#x26;&apos;b i32
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;fn sum_r_xy(r: &amp;#x26;i32, s: S) -&gt; i32 {
r + s.x + s.y
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;// fn sum_r_xy&amp;#x3C;&apos;a, &apos;b, &apos;c&gt;(r: &amp;#x26;&apos;a i32, s: S&amp;#x3C;&apos;b, &apos;c&gt;) -&gt; i32
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;fn first_third(point: &amp;#x26;[i32; 3]) -&gt; (&amp;#x26;i32, &amp;#x26;i32) {
(&amp;#x26;point[0], &amp;#x26;point[2])
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;// fn first_third&amp;#x3C;&apos;a&gt;(point: &amp;#x26;&apos;a [i32; 3]) -&gt; (&amp;#x26;&apos;a i32, &amp;#x26;&apos;a i32)
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;struct StringTable {
elements: Vec&amp;#x3C;String&gt;,
}
impl StringTable {
    fn find_by_prefix(&amp;#x26;self,prefix:&amp;#x26;str) -&gt; Option&amp;#x3C;&amp;#x26;String&gt; {
        for i in 0..self.elements.len() {
            if self.elements[i].starts_with(prefix) {
                return Some(&amp;#x26;self.elements[i]);
            }
        }
        None
    }
}
// fn find_by_prefix&amp;#x3C;&apos;a, &apos;b&gt;(&amp;#x26;&apos;a self, prefix: &amp;#x26;&apos;b str) -&gt; Option&amp;#x3C;&amp;#x26;&apos;a String&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Sharing Versus Mutation&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let v = vec![4, 8, 19, 27, 34, 10];
let r = &amp;#x26;v;
let aside = v; // move vector to aside
r[0]; // bad: uses `v`, which is now uninitialized
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;[unused_variables] Error: unused variable: `s`
[unused_variables] Error: unused variable: `p`
Error: The variable `r` contains a reference with a non-static lifetime so
can&apos;t be persisted. You can prevent this error by making sure that the
variable goes out of scope - i.e. wrapping the code in {}.
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/1073d201-7a5b-4c98-af64-3dbb820f9a06.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let v = vec![4, 8, 19, 27, 34, 10];
{
let r = &amp;#x26;v;
r[0]; // ok: vector is still there
}
let aside = v;
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;fn extend(vec: &amp;#x26;mut Vec&amp;#x3C;f64&gt;, slice: &amp;#x26;[f64]) {
for elt in slice {
vec.push(*elt);
}
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let mut wave = Vec::new();
let head = vec![0.0, 1.0];
let tail = [0.0, -1.0];
extend(&amp;#x26;mut wave, &amp;#x26;head); // extend wave with another vector
extend(&amp;#x26;mut wave, &amp;#x26;tail); // extend wave with an array
assert_eq!(wave, vec![0.0, 1.0, 0.0, -1.0]);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;extend(&amp;#x26;mut wave, &amp;#x26;wave);
assert_eq!(wave, vec![0.0, 1.0, 0.0, -1.0,
0.0, 1.0, 0.0, -1.0])
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;[unused_variables] Error: unused variable: `s`
[unused_variables] Error: unused variable: `p`
[E0502] Error: cannot borrow `wave` as immutable because it is also borrowed as mutable
   ╭─[command_83:1:1]
   │
 1 │ extend(&amp;#x26;mut wave, &amp;#x26;wave);
   │ ───┬── ────┬────  ──┬──
   │    ╰───────────────────── mutable borrow later used by call
   │            │        │
   │            ╰───────────── mutable borrow occurs here
   │                     │
   │                     ╰──── immutable borrow occurs here
───╯
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/e0f4719a-3156-4d73-ad0f-0d24d63e8153.png&quot; alt=&quot;image.png&quot;&gt;
&lt;img src=&quot;/jupyter-img/432a9253-43b5-488d-a9ae-e9e1d0f58c58.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;h4&gt;Taking Arms Against a Sea of Objects&lt;/h4&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/3a55ee40-d791-40a3-a4c9-9dc90dedc946.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;struct-enums-patterns&lt;/h3&gt;
&lt;blockquote&gt;
&lt;p&gt;Long ago, when shepherds wanted to see if two herds of sheep were isomorphic, they would
look for an explicit isomorphism.
—John C. Baez and James Dolan, “&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h4&gt;Named-Field Structs&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;// A rectangle of eight-bit grayscale pixels.
struct GrayscaleMap {
pixels: Vec&amp;#x3C;u8&gt;,
size: (usize, usize)
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let width = 1024;
let height = 576;
let image = GrayscaleMap {
pixels: vec![0; width * height],
size: (width, height)
};
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;image
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;[E0277] Error: `GrayscaleMap` doesn&apos;t implement `Debug`
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;/// A rectangle of eight-bit grayscale pixels.
// 模块外访问
pub struct GrayscaleMap {
pub pixels: Vec&amp;#x3C;u8&gt;,
pub size: (usize, usize)
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Tuple-Like Structs&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;#[derive(Copy, Clone, Debug)]
struct Bounds(usize, usize);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let image_bounds = Bounds(1024, 768);
image_bounds
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;The type of the variable image was redefined, so was lost.
Bounds(1024, 768)
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Unit-Like Structs&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;struct A;
let a=A;
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Struct Layout 内存布局&lt;/h4&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/b93b85e2-fc3d-4674-95ef-644154876809.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;h4&gt;Defining Methods with impl&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;/// A first-in, first-out queue of characters.
pub struct Queue {
older: Vec&amp;#x3C;char&gt;, // older elements, eldest last.
younger: Vec&amp;#x3C;char&gt; // younger elements, youngest last.
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;impl Queue {
    pub fn push(&amp;#x26;mut self,c: char) {
        self.younger.push(c);
    }
    pub fn pop(&amp;#x26;mut self) -&gt; Option&amp;#x3C;char&gt; {
        if self.older.is_empty() {
            if self.younger.is_empty() {
                return None;
            }
            use std::mem::swap;
            swap(&amp;#x26;mut self.older,&amp;#x26;mut self.younger);
            self.older.reverse();
        }
        self.older.pop()
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let mut q = Queue { older: Vec::new(), younger: Vec::new() };
q.push(&apos;0&apos;);
q.push(&apos;1&apos;);
assert_eq!(q.pop(), Some(&apos;0&apos;));
q.push(&apos;∞&apos;);
assert_eq!(q.pop(), Some(&apos;1&apos;));
assert_eq!(q.pop(), Some(&apos;∞&apos;));
assert_eq!(q.pop(), None);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;impl Queue {
pub fn is_empty(&amp;#x26;self) -&gt; bool {
self.older.is_empty() &amp;#x26;&amp;#x26; self.younger.is_empty()
}
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;assert!(q.is_empty());
q.push(&apos;☉&apos;);
assert!(!q.is_empty());
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;impl Queue {
pub fn split(self) -&gt; (Vec&amp;#x3C;char&gt;, Vec&amp;#x3C;char&gt;) {
(self.older, self.younger)
}
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let mut q = Queue { older: Vec::new(), younger: Vec::new() };
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;q.push(&apos;P&apos;);
q.push(&apos;D&apos;);
assert_eq!(q.pop(), Some(&apos;P&apos;));
q.push(&apos;X&apos;);
let (older, younger) = q.split();
// q is now uninitialized.
assert_eq!(older, vec![&apos;D&apos;]);
assert_eq!(younger, vec![&apos;X&apos;])

&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;()
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;q
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;[E0425] Error: cannot find value `q` in this scope
   ╭─[command_23:1:1]
   │
 1 │ q
   │ ┬
   │ ╰── error: cannot find value `q` in this scope
   │ │
   │ ╰── help: a unit struct with a similar name exists: `A`
───╯
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;impl Queue {
    fn new() -&gt; Queue {
        Queue { older: Vec::new(), younger: Vec::new() }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let mut bq = Box::new(Queue::new());
bq.push(&apos;A&apos;)
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;()
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::rc::Rc;
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;struct Node {
tag: String,
children: Vec&amp;#x3C;Rc&amp;#x3C;Node&gt;&gt;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;impl Node {
    fn new(tag: &amp;#x26;str) -&gt;Node {
        Node {
            tag: tag.to_string(),
            children: vec![],
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;impl Node {
fn append_to(self: Rc&amp;#x3C;Self&gt;, parent: &amp;#x26;mut Node) {
parent.children.push(self);
}
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let shared_node = Rc::new(Node::new(&quot;first&quot;));
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;pub struct Vector2 {
x: f32,
y: f32,
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;impl Vector2 {
const ZERO: Vector2 = Vector2 { x: 0.0, y: 0.0 };
const UNIT: Vector2 = Vector2 { x: 1.0, y: 0.0 };
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let scaled = Vector2::UNIT.x;
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Generic Structs&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;pub struct TheQueue&amp;#x3C;T&gt; {
older: Vec&amp;#x3C;T&gt;,
younger: Vec&amp;#x3C;T&gt;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;impl&amp;#x3C;T&gt; TheQueue&amp;#x3C;T&gt; {
pub fn new() -&gt; TheQueue&amp;#x3C;T&gt; {
TheQueue { older: Vec::new(), younger: Vec::new() }
}
pub fn push(&amp;#x26;mut self, t: T) {
self.younger.push(t);
}
pub fn is_empty(&amp;#x26;self) -&gt; bool {
self.older.is_empty() &amp;#x26;&amp;#x26; self.younger.is_empty()
}
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;impl TheQueue&amp;#x3C;f64&gt; {
    fn sum(&amp;#x26;self) -&gt; f64 {
        0_f64
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let mut q = TheQueue::&amp;#x3C;char&gt;::new();
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;q.push(&apos;a&apos;);
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Structs with Lifetime Parameters&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;struct Extrema&amp;#x3C;&apos;elt&gt; {
    greatest: &amp;#x26;&apos;elt i32,
    least: &amp;#x26;&apos;elt i32,
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;fn find_extrema&amp;#x3C;&apos;s&gt;(slice: &amp;#x26;&apos;s [i32]) -&gt; Extrema&amp;#x3C;&apos;s&gt; {
let mut greatest = &amp;#x26;slice[0];
let mut least = &amp;#x26;slice[0];
for i in 1..slice.len() {
if slice[i] &amp;#x3C; *least { least = &amp;#x26;slice[i]; }
if slice[i] &gt; *greatest { greatest = &amp;#x26;slice[i]; }
}
Extrema { greatest, least }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Deriving Common Traits for Struct Types&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;#[derive(Copy, Clone, Debug, PartialEq)]
struct Point {
x: f64,
y: f64
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;{
    use std::cell::RefCell;
let ref_cell: RefCell&amp;#x3C;String&gt; =  RefCell::new(&quot;hello&quot;.to_string());
let r = ref_cell.borrow();
let count = r.len();
assert_eq!(count,5);
let mut w = ref_cell.borrow_mut();
w.push_str(&quot;world&quot;);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;thread &apos;&amp;#x3C;unnamed&gt;&apos; panicked at src/lib.rs:247:22:
already borrowed: BorrowMutError
stack backtrace:
   0: rust_begin_unwind
             at /rustc/a28077b28a02b92985b3a3faecf92813155f1ea1/library/std/src/panicking.rs:597:5
   1: core::panicking::panic_fmt
             at /rustc/a28077b28a02b92985b3a3faecf92813155f1ea1/library/core/src/panicking.rs:72:14
   2: core::cell::panic_already_borrowed
             at /rustc/a28077b28a02b92985b3a3faecf92813155f1ea1/library/core/src/cell.rs:762:5
   3: &amp;#x3C;core::panic::unwind_safe::AssertUnwindSafe&amp;#x3C;F&gt; as core::ops::function::FnOnce&amp;#x3C;()&gt;&gt;::call_once
   4: run_user_code_39
   5: evcxr::runtime::Runtime::run_loop
   6: evcxr::runtime::runtime_hook
   7: evcxr_jupyter::main
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Enums and Patterns&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::cmp::Ordering;
fn compare(a: i32,b: i32) -&gt; Ordering {
    if a &gt; b {
        Ordering::Greater
    } else if a &amp;#x3C; b {
        Ordering::Less
    } else {
        Ordering::Equal
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;enum HttpStatus {
Ok = 200,
NotModified = 304,
NotFound = 404,
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::mem::size_of;
assert_eq!(size_of::&amp;#x3C;Ordering&gt;(), 1);
assert_eq!(size_of::&amp;#x3C;HttpStatus&gt;(), 2); // 404 doesn&apos;t fit in a u8
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum TimeUnit {
Seconds, Minutes, Hours, Days, Months, Years,
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;impl TimeUnit {
/// Return the plural noun for this time unit.
fn plural(self) -&gt; &amp;#x26;&apos;static str {
match self {
TimeUnit::Seconds =&gt; &quot;seconds&quot;,
TimeUnit::Minutes =&gt; &quot;minutes&quot;,
TimeUnit::Hours =&gt; &quot;hours&quot;,
TimeUnit::Days =&gt; &quot;days&quot;,
TimeUnit::Months =&gt; &quot;months&quot;,
TimeUnit::Years =&gt; &quot;years&quot;,
}
}
/// Return the singular noun for this time unit.
fn singular(self) -&gt; &amp;#x26;&apos;static str {
self.plural().trim_end_matches(&apos;s&apos;)
}
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Enums in Memory&lt;/h4&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/656d933b-19a8-4378-a502-609564fbe923.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;h4&gt;Patterns&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;enum RoughTime {
InThePast(TimeUnit, u32),
JustNow,
InTheFuture(TimeUnit, u32),
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;fn rough_time_to_english(rt: RoughTime) -&gt; String {
 match rt {
 RoughTime::InThePast(units, count) =&gt;
 format!(&quot;{} {} ago&quot;, count, units.plural()),
 RoughTime::JustNow =&gt;
 format!(&quot;just now&quot;),
 RoughTime::InTheFuture(units, count) =&gt;
 format!(&quot;{} {} from now&quot;, count, units.plural()),
 }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/69ae2794-c2dc-48c0-9489-a0d8e8029345.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;fn greet_people(names: &amp;#x26;[&amp;#x26;str]) {
match names {
[] =&gt; { println!(&quot;Hello, nobody.&quot;) },
[a] =&gt; { println!(&quot;Hello, {}.&quot;, a) },
[a, b] =&gt; { println!(&quot;Hello, {} and {}.&quot;, a, b) },
[a, .., b] =&gt; { println!(&quot;Hello, everyone from {} to {}.&quot;, a, b) }
}
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/b03243e0-860e-4a83-8e46-4d77ebc4de85.png&quot; alt=&quot;image.png&quot;&gt;
&lt;img src=&quot;/jupyter-img/1ca56bda-6de1-4bb2-b90c-350d48394238.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;// An ordered collection of `T`s.
enum BinaryTree&amp;#x3C;T&gt; {
Empty,
NonEmpty(Box&amp;#x3C;TreeNode&amp;#x3C;T&gt;&gt;),
}
// A part of a BinaryTree.
struct TreeNode&amp;#x3C;T&gt; {
element: T,
left: BinaryTree&amp;#x3C;T&gt;,
right: BinaryTree&amp;#x3C;T&gt;,
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;impl &amp;#x3C;T: Ord&gt; BinaryTree&amp;#x3C;T&gt; {
    fn add(&amp;#x26;mut self,value :T) {
        match *self {
            BinaryTree::Empty =&gt; {
                *self = BinaryTree::NonEmpty(Box::new(
                    TreeNode {
                        element: value,
                        left: BinaryTree::Empty,
                        right: BinaryTree::Empty,
                    }
                ))
            },
            BinaryTree::NonEmpty(ref mut node) =&gt; {
                if value &amp;#x3C;= node.element {
                    node.left.add(value);
                } else {
                    node.right.add(value);
                }
            }
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Structs&lt;/h3&gt;
&lt;blockquote&gt;
&lt;p&gt;LISP programmers know the value of everything, but the cost of nothing.
—Alan Perlis, epigram
&lt;img src=&quot;/jupyter-img/21e25dae-b3f9-4587-942d-af8ec132c8b8.png&quot; alt=&quot;image.png&quot;&gt; &gt; &lt;img src=&quot;/jupyter-img/ccf0417a-913c-4e8c-babe-5c19cc25ba1d.png&quot; alt=&quot;image.png&quot;&gt; &gt; &lt;img src=&quot;/jupyter-img/c0a2a8dc-1b5c-44ab-b9f2-185a8db4dd85.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h4&gt;Error Handling&lt;/h4&gt;
&lt;blockquote&gt;
&lt;p&gt;I knew if I stayed around long enough, something like this would happen.
—George Bernard Shaw on dying&lt;/p&gt;
&lt;/blockquote&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::error::Error;
use std::io::{Write,stderr};
fn print_error(mut err: &amp;#x26;dyn Error) {
    let _ = writeln!(stderr(),&quot;error: {}&quot;,err);
    while let Some(source) = err.source() {
        let _ = writeln!(stderr(),&quot;cased by :{}&quot;,source);
        err = source;
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let weather = match get_weather(hometown) {
Ok(success_value) =&gt; success_value,
Err(err) =&gt; return Err(err)
};
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Crates and Modules&lt;/h4&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/a9d0618e-861c-4625-a863-4be8aa487ef9.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;mod spores {
use cells::{Cell, Gene};
/// A cell made by an adult fern. It disperses on the wind as part of
/// the fern life cycle. A spore grows into a prothallus -- a whole
/// separate organism, up to 5mm across -- which produces the zygote
/// that grows into a new fern. (Plant sex is complicated.)
pub struct Spore {
...
}
/// Simulate the production of a spore by meiosis.
pub fn produce_spore(factory: &amp;#x26;mut Sporangium) -&gt; Spore {
...
}
/// Extract the genes in a particular spore.
pub(crate) fn genes(spore: &amp;#x26;Spore) -&gt; Vec&amp;#x3C;Gene&gt; {
...
}
/// Mix genes to prepare for meiosis (part of interphase).
fn recombine(parent: &amp;#x26;mut Cell) {
...
}
...
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/8472e729-453a-4c43-808e-7c5cf1639bf1.png&quot; alt=&quot;image.png&quot;&gt;
&lt;img src=&quot;/jupyter-img/e414d739-daa0-4786-b6b9-3827ac84a419.png&quot; alt=&quot;image.png&quot;&gt;
&lt;img src=&quot;/jupyter-img/027f1e01-3508-418c-b839-31045ca8e82d.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;h3&gt;bin&lt;/h3&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/17e6f2e0-9b8c-4f5c-844f-a52bb10c2f3b.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;h4&gt;Attributes&lt;/h4&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/aefcb440-826f-4556-a3cf-62de4434bf61.png&quot; alt=&quot;image.png&quot;&gt;
&lt;img src=&quot;/jupyter-img/60e0319d-cf6c-4d4c-b352-21c49b6fbb8c.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;h4&gt;Test&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;#[test]
fn trig_works() {
use std::f64::consts::PI;
assert!(roughly_equal(PI.sin(), 0.0));
}
```rust
#[cfg(test)] // 仅当run test时才会include 这个模块
// include this module only when testing
mod tests {
fn roughly_equal(a: f64, b: f64) -&gt; bool {
(a - b).abs() &amp;#x3C; 1e-6
}
#[test]
fn trig_works() {
use std::f64::consts::PI;
assert!(roughly_equal(PI.sin(), 0.0));
}
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Documentation&lt;/h4&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/2d315fef-e805-4886-a676-c16bcef27db9.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;h4&gt;Package Versions&lt;/h4&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/090bdf90-3553-420b-9f61-cfad8bcd580d.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Input and Output&lt;/h3&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/e583023e-88a5-42b6-b5b2-d378f15359c4.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::io::{self, Read, Write, ErrorKind};
const DEFAULT_BUF_SIZE: usize = 8 * 1024;
pub fn copy&amp;#x3C;R: ?Sized, W: ?Sized&gt;(reader: &amp;#x26;mut R, writer: &amp;#x26;mut W)
    -&gt; io::Result&amp;#x3C;u64&gt;
    where R: Read,W: Write
    {
        let mut buf = [0; DEFAULT_BUF_SIZE];
        let mut writern = 0;
        loop {
            let len = match reader.read(&amp;#x26;mut buf) {
                Ok(0) =&gt; return Ok(writern),
                Ok(len) =&gt; len,
                Err(ref e) if e.kind() == ErrorKind::Interrupted =&gt; continue,
                Err(e) =&gt; return Err(e),
            };
            writer.write_all(&amp;#x26;buf[..len])?;
            writern += len as u64;
        }
    }
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/bcd41019-ca75-43c0-894f-f9c78ce92046.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::io;
use std::io::prelude::*;
fn grep(target: &amp;#x26;str) -&gt; io::Result&amp;#x3C;()&gt; {
    let stdin = io::stdin();
    for line_result in stdin.lock().lines() {
        let line = line_result?;
        if line.contains(target) {
            println!(&quot;{}&quot;,line);
        }
    }
    Ok(())
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;fn grep&amp;#x3C;R&gt;(target: &amp;#x26;str, reader: R) -&gt; io::Result&amp;#x3C;()&gt;
where R: BufRead
{
for line_result in reader.lines() {
let line = line_result?;
if line.contains(target) {
println!(&quot;{}&quot;, line);
}
}
Ok(())
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;// let stdin = io::stdin();
// grep(&amp;#x26;target, stdin.lock())?; // ok
// let f = File::open(file)?;
// grep(&amp;#x26;target, BufReader::new(f))?; // also o
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::fs::OpenOptions;
let log = OpenOptions::new()
    .append(true)
    .open(&quot;server.log&quot;).unwrap_err();
let file = OpenOptions::new()
    .write(true)
    .create_new(true)
    .open(&quot;new_file.log&quot;).unwrap_err();
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;thread &apos;&amp;#x3C;unnamed&gt;&apos; panicked at src/lib.rs:138:27:
called `Result::unwrap_err()` on an `Ok` value: File { fd: 3, path: &quot;/home/realcpf/Documents/rustRepos/rust-prog-2021/new_file.log&quot;, read: false, write: true }
stack backtrace:
   0: rust_begin_unwind
             at /rustc/a28077b28a02b92985b3a3faecf92813155f1ea1/library/std/src/panicking.rs:597:5
   1: core::panicking::panic_fmt
             at /rustc/a28077b28a02b92985b3a3faecf92813155f1ea1/library/core/src/panicking.rs:72:14
   2: core::result::unwrap_failed
             at /rustc/a28077b28a02b92985b3a3faecf92813155f1ea1/library/core/src/result.rs:1652:5
   3: &amp;#x3C;unknown&gt;
   4: &amp;#x3C;unknown&gt;
   5: evcxr::runtime::Runtime::run_loop
   6: evcxr::runtime::runtime_hook
   7: evcxr_jupyter::main
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::process::{Command, Stdio};
let mut child =
Command::new(&quot;grep&quot;)
.arg(&quot;-e&quot;)
.arg(&quot;a.*e.*i.*o.*u&quot;)
.stdin(Stdio::piped())
.spawn()?;
let mut to_child = child.stdin.take().unwrap();
for word in my_words {
writeln!(to_child, &quot;{}&quot;, word)?;
}
drop(to_child); // close grep&apos;s stdin, so it will exit
child.wait()?;
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;[E0425] Error: cannot find value `my_words` in this scope
   ╭─[command_12:1:1]
   │
 9 │ for word in my_words {
   │             ────┬───
   │                 ╰───── not found in this scope
───╯
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/e04b9db8-43b6-4cbf-a023-40c7da76d476.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::path::Path;
let home_dir = Path::new(&quot;/home/realcpf&quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;assert_eq!(home_dir.parent(),Some(Path::new(&quot;/home&quot;)));
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::ffi::OsStr;
assert_eq!(Path::new(&quot;/home/fwolfe/program.txt&quot;).file_name(),
Some(OsStr::new(&quot;program.txt&quot;)));
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let path1 = Path::new(&quot;/usr/share/dict&quot;);
assert_eq!(path1.join(&quot;words&quot;),
Path::new(&quot;/usr/share/dict/words&quot;));
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let file = Path::new(&quot;/home/jimb/calendars/calendar-18x18.pdf&quot;);
assert_eq!(file.ancestors().collect::&amp;#x3C;Vec&amp;#x3C;_&gt;&gt;(),
vec![Path::new(&quot;/home/jimb/calendars/calendar-18x18.pdf&quot;),
Path::new(&quot;/home/jimb/calendars&quot;),
Path::new(&quot;/home/jimb&quot;),
Path::new(&quot;/home&quot;),
Path::new(&quot;/&quot;)])
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/6c8ffd9d-a2f2-4e77-aae6-84bc5d289d9b.png&quot; alt=&quot;image.png&quot;&gt;
&lt;img src=&quot;/jupyter-img/d80bc8d5-ea58-4530-bd9c-46270ded34e2.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::fs;
use std::io;
use std::path::Path;
/// Copy wha tever is at `src` to the target path `dst`.
fn copy_to(src: &amp;#x26;Path, src_type: &amp;#x26;fs::FileType, dst: &amp;#x26;Path)
-&gt; io::Result&amp;#x3C;()&gt;
{
if src_type.is_file() {
fs::copy(src, dst)?;
} else if src_type.is_dir() {
copy_dir_to(src, dst)?;
} else {
return Err(io::Error::new(io::ErrorKind::Other,
format!(&quot;don&apos;t know how to copy: {}&quot;,
src.display())));
}
Ok(())
}
// Copy the existing directory `src` to the target path `dst`.
fn copy_dir_to(src: &amp;#x26;Path, dst: &amp;#x26;Path) -&gt; io::Result&amp;#x3C;()&gt; {
if !dst.is_dir() {
fs::create_dir(dst)?;
}
for entry_result in src.read_dir()? {
let entry = entry_result?;
let file_type = entry.file_type()?;
copy_to(&amp;#x26;entry.path(), &amp;#x26;file_type, &amp;#x26;dst.join(entry.file_name()))?;
}
Ok(())
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;#[cfg(unix)]
use std::os::unix::fs::symlink;
/// Stub implementation of `symlink` for platforms that don&apos;t provide it.
#[cfg(not(unix))]
fn symlink&amp;#x3C;P: AsRef&amp;#x3C;Path&gt;, Q: AsRef&amp;#x3C;Path&gt;&gt;(src: P, _dst: Q)
-&gt; std::io::Result&amp;#x3C;()&gt;
{
Err(io::Error::new(io::ErrorKind::Other,
format!(&quot;can&apos;t copy symbolic link: {}&quot;,
src.as_ref().display())))
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::net::TcpListener;
use std::io;
use std::thread::spawn;
/// Accept connections forever, spawning a thread for each one.
fn echo_main(addr: &amp;#x26;str) -&gt; io::Result&amp;#x3C;()&gt; {
let listener = TcpListener::bind(addr)?;
println!(&quot;listening on {}&quot;, addr);
loop {
// Wait for a client to connect.
let (mut stream, addr) = listener.accept()?;
println!(&quot;connection received from {}&quot;, addr);
// Spawn a thread to handle this client.
let mut write_stream = stream.try_clone()?;
spawn(move || {
// Echo everything we receive from `stream` back to it.
io::copy(&amp;#x26;mut stream, &amp;#x26;mut write_stream)
.expect(&quot;error in client thread: &quot;);
println!(&quot;connection closed&quot;);
});
}
}
fn main() {
echo_main(&quot;127.0.0.1:17007&quot;).expect(&quot;error: &quot;);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::error::Error;
use std::io;
fn http_get_main(url: &amp;#x26;str) -&gt; Result&amp;#x3C;(), Box&amp;#x3C;dyn Error&gt;&gt; {
// Send the HTTP request and get a response.
let mut response = reqwest::blocking::get(url)?;
if !response.status().is_success() {
Err(format!(&quot;{}&quot;, response.status()))?;
}
    // Read the response body and write it to stdout.
let stdout = io::stdout();
io::copy(&amp;#x26;mut response, &amp;#x26;mut stdout.lock())?;
Ok(())
}
fn main() {
let args: Vec&amp;#x3C;String&gt; = std::env::args().collect();
if args.len() != 2 {
eprintln!(&quot;usage: http-get URL&quot;);
return;
}
if let Err(err) = http_get_main(&amp;#x26;args[1]) {
eprintln!(&quot;error: {}&quot;, err);
}
}
```rust
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Strings and Text&lt;/h3&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/2b6e90ad-4428-4ef3-bec9-f129fc0f3031.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;assert_eq!(&quot;うどん: udon&quot;.as_bytes(),
&amp;#x26;[0xe3, 0x81, 0x86, //う
0xe3, 0x81, 0xa9, //ど
0xe3, 0x82, 0x93, //ん
0x3a, 0x20, 0x75, 0x64, 0x6f, 0x6e // : udon
]);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;assert_eq!(&quot; ערבטוב &quot;.chars().next(), Some(&apos;ע&apos;));
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;thread &apos;&amp;#x3C;unnamed&gt;&apos; panicked at src/lib.rs:6:1:
assertion `left == right` failed
  left: Some(&apos; &apos;)
 right: Some(&apos;ע&apos;)
stack backtrace:
   0: rust_begin_unwind
             at /rustc/a28077b28a02b92985b3a3faecf92813155f1ea1/library/std/src/panicking.rs:597:5
   1: core::panicking::panic_fmt
             at /rustc/a28077b28a02b92985b3a3faecf92813155f1ea1/library/core/src/panicking.rs:72:14
   2: core::panicking::assert_failed_inner
   3: &amp;#x3C;unknown&gt;
   4: &amp;#x3C;unknown&gt;
   5: evcxr::runtime::Runtime::run_loop
   6: evcxr::runtime::runtime_hook
   7: evcxr_jupyter::main
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;assert_eq!(&quot;カニ&quot;.chars().next(), Some(&apos;カ&apos;))
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/4e2e6839-5a55-4a17-ab44-ed2f35a14f50.png&quot; alt=&quot;image.png&quot;&gt;
&lt;img src=&quot;/jupyter-img/b15b122b-9036-468c-ac38-fd2c19acae0e.png&quot; alt=&quot;image.png&quot;&gt;
&lt;img src=&quot;/jupyter-img/9f309897-cf21-4249-9ade-b5a14be6f4e0.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;assert!(32u8.is_ascii_whitespace());
assert!(b&apos;9&apos;.is_ascii_digit())
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;()
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;// char::is_ascii_whitespace函数实现了许多Web标准通用的空格定义，
// 而char::is_whitespace遵循Unicode标准。

let line_tab = &apos;\u{000b}&apos;; // &apos;line tab&apos;, AKA &apos;vertical tab&apos;
assert_eq!(line_tab.is_whitespace(), true);
assert_eq!(line_tab.is_ascii_whitespace(), false)
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;()
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;assert_eq!(&apos;F&apos;.to_digit(16), Some(15));
assert_eq!(std::char::from_digit(15, 16), Some(&apos;f&apos;));
assert!(char::is_digit(&apos;f&apos;, 16));
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let mut upper = &apos;s&apos;.to_uppercase();
assert_eq!(upper.next(), Some(&apos;S&apos;));
assert_eq!(upper.next(), None);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;// The uppercase form of the German letter &quot;sharp S&quot; is &quot;SS&quot;:
let mut upper = &apos;ß&apos;.to_uppercase();
assert_eq!(upper.next(), Some(&apos;S&apos;));
assert_eq!(upper.next(), Some(&apos;S&apos;));
assert_eq!(upper.next(), None);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;// Unicode says to lowercase Turkish dotted capital &apos;İ&apos; to &apos;i&apos;
// followed by `&apos;\u{307}&apos;`, COMBINING DOT ABOVE, so that a
// subsequent conversion back to uppercase preserves the dot.
let ch = &apos;İ&apos;; // `&apos;\u{130}&apos;`
let mut lower = ch.to_lowercase();
assert_eq!(lower.next(), Some(&apos;i&apos;));
assert_eq!(lower.next(), Some(&apos;\u{307}&apos;));
assert_eq!(lower.next(), None)
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;()
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;assert_eq!(&apos;B&apos; as u32, 66);
assert_eq!(&apos;饂&apos; as u8, 66); // upper bits truncated
assert_eq!(&apos;二&apos; as i8, -116); // same
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;assert_eq!(char::from(66), &apos;B&apos;);
assert_eq!(std::char::from_u32(0x9942), Some(&apos;饂&apos;));
assert_eq!(std::char::from_u32(0xd800), None); // reserved for UTF-16
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/052cadae-7baa-4f0d-9654-5df70a5feff7.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let spacey = &quot;man hat tan&quot;;
let spaceless: String =
spacey.chars().filter(|c| !c.is_whitespace()).collect();
assert_eq!(spaceless, &quot;manhattan&quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let full = &quot;bookkeeping&quot;;
assert_eq!(&amp;#x26;full[..4], &quot;book&quot;);
assert_eq!(&amp;#x26;full[5..], &quot;eeping&quot;);
assert_eq!(&amp;#x26;full[2..4], &quot;ok&quot;);
assert_eq!(full[..].len(), 11);
assert_eq!(full[5..].contains(&quot;boo&quot;), false)
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;()
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let parenthesized = &quot;Rust (饂)&quot;;
assert_eq!(parenthesized[6..].chars().next(), Some(&apos;饂&apos;));
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let mut also_spaceless = &quot;con&quot;.to_string();
also_spaceless.extend(&quot;tri but ion&quot;.split_whitespace());
assert_eq!(also_spaceless, &quot;contribution&quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::fmt::Write;
let mut letter = String::new();
writeln!(letter, &quot;Whose {} these are I think I know&quot;, &quot;rutabagas&quot;)?;
writeln!(letter, &quot;His house is in the village though;&quot;)?;
assert_eq!(letter, &quot;Whose rutabagas these are I think I know\n\
His house is in the village though;\n&quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let left = &quot;partners&quot;.to_string();
let mut right = &quot;crime&quot;.to_string();
assert_eq!(left + &quot; in &quot; + &amp;#x26;right, &quot;partners in crime&quot;);
right += &quot; doesn&apos;t pay&quot;;
assert_eq!(right, &quot;crime doesn&apos;t pay&quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;()
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;// 返回给定字节索引范围内的迭代器，并在删除迭代器后删除字符。范围后的字符向前面移动
let mut choco = &quot;chocolate&quot;.to_string();
assert_eq!(choco.drain(3..6).collect::&amp;#x3C;String&gt;(), &quot;col&quot;);
assert_eq!(choco, &quot;choate&quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let mut beverage = &quot;a piña colada&quot;.to_string();
beverage.replace_range(2..7, &quot;kahlua&quot;); // &apos;ñ&apos; is two bytes!
assert_eq!(beverage, &quot;a kahlua colada&quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let haystack = &quot;One fine day, in the middle of the night&quot;;
assert_eq!(haystack.find(&apos;,&apos;), Some(12));
assert_eq!(haystack.find(&quot;night&quot;), Some(35));
assert_eq!(haystack.find(char::is_whitespace), Some(3));
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;assert_eq!(&quot;## Elephants&quot;
.trim_start_matches(|ch: char| ch == &apos;#&apos; || ch.is_whitespace()),
&quot;Elephants&quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let code = &quot;\t function noodle() { &quot;;
assert_eq!(code.trim_start_matches([&apos; &apos;, &apos;\t&apos;].as_ref()),
&quot;function noodle() { &quot;);
// Shorter equivalent: &amp;#x26;[&apos; &apos;, &apos;\t&apos;][..]
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;assert!(&quot;2017&quot;.starts_with(char::is_numeric));
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let quip = &quot;We also know there are known unknowns&quot;;
assert_eq!(quip.find(&quot;know&quot;), Some(8));
assert_eq!(quip.rfind(&quot;know&quot;), Some(31));
assert_eq!(quip.find(&quot;ya know&quot;), None);
assert_eq!(quip.rfind(char::is_uppercase), Some(0));
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;assert_eq!(&quot;The only thing we have to fear is fear itself&quot;
.replace(&quot;fear&quot;, &quot;spin&quot;),
&quot;The only thing we have to spin is spin itself&quot;);
assert_eq!(&quot;`Borrow` and `BorrowMut`&quot;
.replace(|ch:char| !ch.is_alphanumeric(), &quot;&quot;),
&quot;BorrowandBorrowMut&quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/23e7075d-4e97-4c77-857f-905be912dd82.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;assert_eq!(&quot;élan&quot;.char_indices().collect::&amp;#x3C;Vec&amp;#x3C;_&gt;&gt;(),
vec![(0, &apos;é&apos;), // has a two-byte UTF-8 encoding
(2, &apos;l&apos;),
(3, &apos;a&apos;),
(4, &apos;n&apos;)]);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;assert_eq!(&quot;élan&quot;.bytes().collect::&amp;#x3C;Vec&amp;#x3C;_&gt;&gt;(),
vec![195, 169, b&apos;l&apos;, b&apos;a&apos;, b&apos;n&apos;]);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;// The &apos;:&apos; characters are separators here. Note the final &quot;&quot;.
assert_eq!(&quot;jimb:1000:Jim Blandy:&quot;.split(&apos;:&apos;).collect::&amp;#x3C;Vec&amp;#x3C;_&gt;&gt;(),
vec![&quot;jimb&quot;, &quot;1000&quot;, &quot;Jim Blandy&quot;, &quot;&quot;]);
// The &apos;\n&apos; characters are terminators here.
assert_eq!(&quot;127.0.0.1 localhost\n\
127.0.0.1 www.reddit.com\n&quot;
.split_terminator(&apos;\n&apos;).collect::&amp;#x3C;Vec&amp;#x3C;_&gt;&gt;(),
vec![&quot;127.0.0.1 localhost&quot;,
&quot;127.0.0.1 www.reddit.com&quot;]);
// Note, no final &quot;&quot;!
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let poem = &quot;This is just to say\n\
I have eaten\n\
the plums\n\
again\n&quot;;
assert_eq!(poem.split_whitespace().collect::&amp;#x3C;Vec&amp;#x3C;_&gt;&gt;(),
vec![&quot;This&quot;, &quot;is&quot;, &quot;just&quot;, &quot;to&quot;, &quot;say&quot;,
&quot;I&quot;, &quot;have&quot;, &quot;eaten&quot;, &quot;the&quot;, &quot;plums&quot;,
&quot;again&quot;]);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;assert_eq!(&quot;\t*.rs &quot;.trim(), &quot;*.rs&quot;);
assert_eq!(&quot;\t*.rs &quot;.trim_start(), &quot;*.rs &quot;);
assert_eq!(&quot;\t*.rs &quot;.trim_end(), &quot;\t*.rs&quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;assert_eq!(&quot;001990&quot;.trim_start_matches(&apos;0&apos;), &quot;1990&quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::str::FromStr;
assert_eq!(usize::from_str(&quot;3628800&quot;), Ok(3628800));
assert_eq!(f64::from_str(&quot;128.5625&quot;), Ok(128.5625));
assert_eq!(bool::from_str(&quot;true&quot;), Ok(true));
assert!(f64::from_str(&quot;not a float at all&quot;).is_err());
assert!(bool::from_str(&quot;TRUE&quot;).is_err());
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;assert_eq!(char::from_str(&quot;é&quot;), Ok(&apos;é&apos;));
assert!(char::from_str(&quot;abcdefg&quot;).is_err());
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::net::IpAddr;
let address = IpAddr::from_str(&quot;fe80::0000:3ea9:f4ff:fe34:7a50&quot;)?;
assert_eq!(address,
IpAddr::from([0xfe80, 0, 0, 0, 0x3ea9, 0xf4ff, 0xfe34, 0x7a50]));
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let address = &quot;fe80::0000:3ea9:f4ff:fe34:7a50&quot;.parse::&amp;#x3C;IpAddr&gt;().unwrap();
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;assert_eq!(format!(&quot;{}, wow&quot;, &quot;doge&quot;), &quot;doge, wow&quot;);
assert_eq!(format!(&quot;{}&quot;, true), &quot;true&quot;);
assert_eq!(format!(&quot;({:.3}, {:.3})&quot;, 0.5, f64::sqrt(3.0)/2.0),
&quot;(0.500, 0.866)&quot;);
// Using `address` from above.
let formatted_addr: String = format!(&quot;{}&quot;, address);
assert_eq!(formatted_addr, &quot;fe80::3ea9:f4ff:fe34:7a50&quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Producing Text from UTF-8 Data&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let good_utf8: Vec&amp;#x3C;u8&gt; = vec![0xe9, 0x8c, 0x86];
assert_eq!(String::from_utf8(good_utf8).ok(), Some(&quot;錆&quot;.to_string()));
let bad_utf8: Vec&amp;#x3C;u8&gt; = vec![0x9f, 0xf0, 0xa6, 0x80];
let result = String::from_utf8(bad_utf8);
assert!(result.is_err());
// Since String::from_utf8 failed, it didn&apos;t consume the original
// vector, and the error value hands it back to us unharmed.
assert_eq!(result.unwrap_err().into_bytes(),
vec![0x9f, 0xf0, 0xa6, 0x80])
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;()
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;fn get_name() -&gt; String {
std::env::var(&quot;USER&quot;) // Windows uses &quot;USERNAME&quot;
.unwrap_or(&quot;whoever you are&quot;.to_string())
}
println!(&quot;Greetings, {}!&quot;, get_name())
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;Greetings, realcpf!

()
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::borrow::Cow;
fn get_name() -&gt; Cow&amp;#x3C;&apos;static ,str&gt; {
    std::env::var(&quot;USER&quot;)
    .map(|v|Cow::Owned(v))
    .unwrap_or(Cow::Borrowed(&quot;whover you are&quot;))
}
println!(&quot;Greetings, {}!&quot;, get_name())
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;Greetings, realcpf!

()
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Formatting Values&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;println!(&quot;{:.3}μs: relocated {} at {:#x} to {:#x}, {} bytes&quot;,
0.84391, &quot;object&quot;,
140737488346304_usize, 6299664_usize, 64);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;0.844μs: relocated object at 0x7fffffffdcc0 to 0x602010, 64 bytes
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/975caaa7-06c8-477f-aab8-553e9aaf62e2.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;assert_eq!(format!(&quot;{{a, c}} ⊂ {{a, b, c}}&quot;),
&quot;{a, c} ⊂ {a, b, c}&quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Formatting Text Values&lt;/h4&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/e0c76d86-16a0-4b4f-afdf-f84c9cc9b38e.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;assert_eq!(format!(&quot;{:4}&quot;, &quot;th\u{e9}&quot;), &quot;th\u{e9} &quot;);
assert_eq!(format!(&quot;{:4}&quot;, &quot;the\u{301}&quot;), &quot;the\u{301}&quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Formatting Numbers&lt;/h4&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/b9b25db2-f7fc-4c6f-add6-510c32ac7fd2.png&quot; alt=&quot;image.png&quot;&gt;
&lt;img src=&quot;/jupyter-img/e0a112eb-f800-4f19-8f18-89735ce84828.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::collections::HashMap;
let mut map = HashMap::new();
map.insert(&quot;Portland&quot;, (45.5237606,-122.6819273));
map.insert(&quot;Taipei&quot;, (25.0375167, 121.5637));
println!(&quot;{:?}&quot;, map);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;{&quot;Taipei&quot;: (25.0375167, 121.5637), &quot;Portland&quot;: (45.5237606, -122.6819273)}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;println!(&quot;ordinary: {:02?}&quot;, [9, 15, 240]);
println!(&quot;hex: {:02x?}&quot;, [9, 15, 240]);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;ordinary: [09, 15, 240]
hex: [09, 0f, f0]
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;#[derive(Copy, Clone, Debug)]
struct Complex { re: f64, im: f64 }
let third = Complex { re: -0.5, im: f64::sqrt(0.75) };
println!(&quot;{:?}&quot;, third)
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;Complex { re: -0.5, im: 0.8660254037844386 }

()
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Formatting Pointers for Debugging&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::rc::Rc;
let original = Rc::new(&quot;mazurka&quot;.to_string());
let cloned = original.clone();
let impostor = Rc::new(&quot;mazurka&quot;.to_string());
println!(&quot;text: {}, {}, {}&quot;, original, cloned, impostor);
println!(&quot;pointers: {:p}, {:p}, {:p}&quot;, original, cloned, impostor);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;text: mazurka, mazurka, mazurka
pointers: 0x55ab5c90f080, 0x55ab5c90f080, 0x55ab5c917540
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;assert_eq!(format!(&quot;{1},{0},{2}&quot;, &quot;zeroth&quot;, &quot;first&quot;, &quot;second&quot;),
&quot;first,zeroth,second&quot;);
assert_eq!(format!(&quot;{2:#06x},{1:b},{0:=&gt;10}&quot;, &quot;first&quot;, 10, 100),
&quot;0x0064,1010,=====first&quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;format!(&quot;{description:.&amp;#x3C;25}{quantity:2} @ {price:5.2}&quot;,
price=3.25,
quantity=3,
description=&quot;Maple Turmeric Latte&quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;&quot;Maple Turmeric Latte..... 3 @  3.25&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;format!(&quot;{mode} {2} {} {}&quot;,
&quot;people&quot;, &quot;eater&quot;, &quot;purple&quot;, mode=&quot;flying&quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;&quot;flying purple people eater&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/a5559be6-9098-433f-b8d9-cb4dc63cc5ca.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::fmt;
impl fmt::Display for Complex {
fn fmt(&amp;#x26;self, dest: &amp;#x26;mut fmt::Formatter) -&gt; fmt::Result {
let im_sign = if self.im &amp;#x3C; 0.0 { &apos;-&apos; } else { &apos;+&apos; };
write!(dest, &quot;{} {} {}i&quot;, self.re, im_sign, f64::abs(self.im))
}
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let one_twenty = Complex { re: -0.5, im: 0.866 };
assert_eq!(format!(&quot;{}&quot;, one_twenty),
&quot;-0.5 + 0.866i&quot;);
let two_forty = Complex { re: -0.5, im: -0.866 };
assert_eq!(format!(&quot;{}&quot;, two_forty),
&quot;-0.5 - 0.866i&quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Fundamental-Types&lt;/h3&gt;
&lt;blockquote&gt;
&lt;p&gt;There are many, many types of books in the world, which makes good sense, because there are many, many types of people, and everybody wants to read something different.
—Lemony Snicke
&lt;img src=&quot;/jupyter-img/7272218c-e7b9-4a3c-841c-8e70158e6cd8.png&quot; alt=&quot;image.png&quot;&gt; &gt; &lt;img src=&quot;/jupyter-img/273479eb-91ca-450a-b065-dcddb54493eb.png&quot; alt=&quot;image.png&quot;&gt; &gt; &lt;img src=&quot;/jupyter-img/9d18a5b2-dd1c-4912-8c26-82192ff707e9.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h4&gt;Fixed-Width Numeric Types&lt;/h4&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/fde9c118-8af2-4e88-babc-e9e74eccffe2.png&quot; alt=&quot;image.png&quot;&gt;
&lt;img src=&quot;/jupyter-img/338ecab3-09c6-457e-a7e3-77a3551c3813.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;// 10_u8.checked_mul(10).expect(&quot;数值溢出&quot;);
// 100_u8.checked_add(200).expect(&quot;&quot;);
// let x = 100_u8;
// let y = 100_u8;
// // Do the addition; panic if it overflows.
// let sum = x.checked_add(y).unwrap();
// 超出不报错
500_u16.wrapping_mul(500);  // 53392
500_i16.wrapping_mul(500); // -12144
// In bitwise shift operations, the shift distance
// is wrapped to fall within the size of the value.
// So a shift of 17 bits in a 16-bit type is a shift
// of 1.
// assert_eq!(5_i16.wrapping_shl(17), 10);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/c16a8623-53aa-4bce-a299-07032df98262.png&quot; alt=&quot;image.png&quot;&gt;
&lt;img src=&quot;/jupyter-img/16a70a25-fa52-42a9-b9c0-6cd40ae276c2.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;h4&gt;Characters&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;assert_eq!(&apos;*&apos; as i32, 42);
assert_eq!(&apos;ಠ&apos; as u16, 0xca0);
assert_eq!(&apos;ಠ&apos; as i8, -0x60); // U+0CA0 truncated to eight bits, signed
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;assert_eq!(&apos;*&apos;.is_alphabetic(), false);
assert_eq!(&apos;β&apos;.is_alphabetic(), true);
assert_eq!(&apos;8&apos;.to_digit(10), Some(8));
assert_eq!(&apos;ಠ&apos;.len_utf8(), 3);
assert_eq!(std::char::from_digit(2, 10), Some(&apos;2&apos;));
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Tuples&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let text = &quot;I see the eigenvalue in thine eye&quot;;
let (head, tail) = text.split_at(21);
assert_eq!(head, &quot;I see the eigenvalue &quot;);
assert_eq!(tail, &quot;in thine eye&quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let text = &quot;I see the eigenvalue in thine eye&quot;;
let temp = text.split_at(21);
let head = temp.0;
let tail = temp.1;
assert_eq!(head, &quot;I see the eigenvalue &quot;);
assert_eq!(tail, &quot;in thine eye&quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;h1&gt;Slices&lt;/h1&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let v: Vec&amp;#x3C;f64&gt; = vec![0.0, 0.707, 1.0, 0.707];
let a: [f64; 4] = [0.0, -0.707, -1.0, -0.707];
let sv: &amp;#x26;[f64] = &amp;#x26;v;
let sa: &amp;#x26;[f64] = &amp;#x26;a;
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;Error: The variable `sv` contains a reference with a non-static lifetime so
can&apos;t be persisted. You can prevent this error by making sure that the
variable goes out of scope - i.e. wrapping the code in {}.
[E0597] Error: `a` does not live long enough
   ╭─[command_23:1:1]
   │
 2 │ let a: [f64; 4] = [0.0, -0.707, -1.0, -0.707];
   │     ┬
   │     ╰── binding `a` declared here
   │
 4 │ let sa: &amp;#x26;[f64] = &amp;#x26;a;
   │                  ─┬
   │                   ╰── borrowed value does not live long enough
   │                   │
   │                   ╰── cast requires that `a` is borrowed for `&apos;static`
───╯
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/52556aaf-7d7f-4d8a-b235-ca5d3b192482.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;h4&gt;String Literals&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;println!(&quot;In the room the women come and go,
Singing of Mount Abora&quot;);
println!(&quot;It was a bright, cold day in April, and \
there were four of us—\
more or less.&quot;);
let default_win_install_path = r&quot;C:\Program Files\Gorillas&quot;;
println!(r###&quot;
This raw string started with &apos;r###&quot;&apos;.
Therefore it does not end until we reach a quote mark (&apos;&quot;&apos;)
followed immediately by three pound signs (&apos;###&apos;):
&quot;###);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;In the room the women come and go,
Singing of Mount Abora
It was a bright, cold day in April, and there were four of us—more or less.

This raw string started with &apos;r###&quot;&apos;.
Therefore it does not end until we reach a quote mark (&apos;&quot;&apos;)
followed immediately by three pound signs (&apos;###&apos;):
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Byte Strings&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let method = b&quot;GET&quot;;
assert_eq!(method, &amp;#x26;[b&apos;G&apos;, b&apos;E&apos;, b&apos;T&apos;]);
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Strings&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let noodles = &quot;noodles&quot;.to_string();
let oodles = &amp;#x26;noodles[1..];
let poodles = &quot;ಠ_ಠ&quot;;
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;let oodles = &amp;#x26;noodles[1..];
let oodles = &amp;#x26;noodles[1..];
    ^^^^^^
The variable `oodles` contains a reference with a non-static lifetime so
can&apos;t be persisted. You can prevent this error by making sure that the
variable goes out of scope - i.e. wrapping the code in {}.
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/bf7a6a01-2122-4d2e-b30a-cc4a0d426a45.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;assert_eq!(&quot;ಠ_ಠ&quot;.len(), 7);
assert_eq!(&quot;ಠ_ಠ&quot;.chars().count(), 3)
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/a151916a-fb68-454e-a13a-cd419eba1e4f.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let error_message = &quot;too many pets&quot;.to_string();
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;println!(&quot;{}&quot;,error_message)
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;too many pets

()
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;format string&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;println!(&quot;{}&quot;,format!(&quot;{}°{:02}′{:02}″N&quot;, 24, 5, 23))
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;24°05′23″N

()
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let bits = vec![&quot;veni&quot;, &quot;vidi&quot;, &quot;vici&quot;];
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;bits.concat()
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;&quot;venividivici&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;bits.join(&quot;,&quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;&quot;veni,vidi,vici&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;&quot;ONE&quot;.to_lowercase()
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;&quot;one&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;&quot;peanut&quot;.contains(&quot;nut&quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;true
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;&quot;ಠ_ಠ&quot;.replace(&quot;ಠ&quot;, &quot;■&quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;&quot;■_■&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Iterator&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;// You should usually use HashSet, but its iteration order is
// nondeterministic, so BTreeSet works better in examples.
use std::collections::BTreeSet;
let mut favorites = BTreeSet::new();
favorites.insert(&quot;Lucy in the Sky With Diamonds&quot;.to_string());
favorites.insert(&quot;Liebesträume No. 3&quot;.to_string());
let mut it = favorites.into_iter();
assert_eq!(it.next(), Some(&quot;Liebesträume No. 3&quot;.to_string()));
assert_eq!(it.next(), Some(&quot;Lucy in the Sky With Diamonds&quot;.to_string()));
assert_eq!(it.next(), None);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use rand::random; // In Cargo.toml dependencies: rand = &quot;0.7&quot;
use std::iter::from_fn;
// Generate the lengths of 1000 random line segments whose endpoints
// are uniformly distributed across the interval [0, 1]. (This isn&apos;t a
// distribution you&apos;re going to find in the `rand_distr` crate, but
// it&apos;s easy to make yourself.)
let lengths: Vec&amp;#x3C;f64&gt; =
from_fn(|| Some((random::&amp;#x3C;f64&gt;() - random::&amp;#x3C;f64&gt;()).abs()))
.take(1000)
.collect();
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;[E0432] Error: unresolved import `rand`
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;fn fibonacci() -&gt; impl Iterator&amp;#x3C;Item = usize&gt; {
    let mut state = (0,1);
    std::iter::from_fn(move || {
        state = (state.1,state.0 + state.1);
        Some(state.0)
    })
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;assert_eq!(fibonacci().take(8).collect::&amp;#x3C;Vec&amp;#x3C;_&gt;&gt;(),
          vec![1, 1, 2, 3, 5, 8, 13, 21])
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;()
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;drain Methods&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::iter::FromIterator;
let mut outer = &quot;Earth&quot;.to_string();
let inner = String::from_iter(outer.drain(1..4));
assert_eq!(outer, &quot;Eh&quot;);
assert_eq!(inner, &quot;art&quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;()
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Iterator Sources&lt;/h4&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/817086fe-335d-4562-9aa7-d45d183f720f.png&quot; alt=&quot;image.png&quot;&gt;
&lt;img src=&quot;/jupyter-img/67ee1555-daf7-4060-877b-69e4b56dbfe6.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;h4&gt;map and filter&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;{
    let text = &quot; ponies \n giraffes\niguanas \nsquid&quot;.to_string();
    let v: Vec&amp;#x3C;&amp;#x26;str&gt; = text.lines()
    .map(str::trim)
    .collect();
    assert_eq!(v, [&quot;ponies&quot;, &quot;giraffes&quot;, &quot;iguanas&quot;, &quot;squid&quot;]);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;()
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;{
    let text = &quot; ponies \n giraffes\niguanas \nsquid&quot;.to_string();
    let v: Vec&amp;#x3C;&amp;#x26;str&gt; = text.lines()
    .map(str::trim)
    .filter(|s| *s != &quot;iguanas&quot;)
    .collect();
    assert_eq!(v, [&quot;ponies&quot;, &quot;giraffes&quot;, &quot;squid&quot;]);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;()
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;filter_map and flat_map&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::str::FromStr;
let text = &quot;1\nfrond .25 289\n3.1415 estuary\n&quot;;
for number in text.split_whitespace()
    .filter_map(|w| f64::from_str(w).ok()){
    println!(&quot;{:4.2}&quot;,number.sqrt());
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;1.00
0.50
17.00
1.77

()
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::collections::HashMap;
let mut major_cities = HashMap::new();
major_cities.insert(&quot;Japan&quot;, vec![&quot;Tokyo&quot;, &quot;Kyoto&quot;]);
major_cities.insert(&quot;The United States&quot;, vec![&quot;Portland&quot;, &quot;Nashville&quot;]);
major_cities.insert(&quot;Brazil&quot;, vec![&quot;São Paulo&quot;, &quot;Brasília&quot;]);
major_cities.insert(&quot;Kenya&quot;, vec![&quot;Nairobi&quot;, &quot;Mombasa&quot;]);
major_cities.insert(&quot;The Netherlands&quot;, vec![&quot;Amsterdam&quot;, &quot;Utrecht&quot;]);
let countries = [&quot;Japan&quot;, &quot;Brazil&quot;, &quot;Kenya&quot;];
for &amp;#x26;city in countries.iter().flat_map(|country| &amp;#x26;major_cities[country]) {
println!(&quot;{}&quot;, city);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;Tokyo
Kyoto
São Paulo
Brasília
Nairobi
Mombasa

()
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;flatten&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::collections::BTreeMap;
// A table mapping cities to their parks: each value is a vector.
let mut parks = BTreeMap::new();
parks.insert(&quot;Portland&quot;, vec![&quot;Mt. Tabor Park&quot;, &quot;Forest Park&quot;]);
parks.insert(&quot;Kyoto&quot;, vec![&quot;Tadasu-no-Mori Forest&quot;, &quot;Maruyama Koen&quot;]);
parks.insert(&quot;Nashville&quot;, vec![&quot;Percy Warner Park&quot;, &quot;Dragon Park&quot;]);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::collections::BTreeMap;
// A table mapping cities to their parks: each value is a vector.
let mut parks = BTreeMap::new();
parks.insert(&quot;Portland&quot;, vec![&quot;Mt. Tabor Park&quot;, &quot;Forest Park&quot;]);
parks.insert(&quot;Kyoto&quot;, vec![&quot;Tadasu-no-Mori Forest&quot;, &quot;Maruyama Koen&quot;]);
parks.insert(&quot;Nashville&quot;, vec![&quot;Percy Warner Park&quot;, &quot;Dragon Park&quot;]);
// Build a vector of all parks. `values` gives us an iterator producing
// vectors, and then `flatten` produces each vector&apos;s elements in turn.
let all_parks: Vec&amp;#x3C;_&gt; = parks.values().flatten().cloned().collect();
assert_eq!(all_parks,
vec![&quot;Tadasu-no-Mori Forest&quot;, &quot;Maruyama Koen&quot;, &quot;Percy Warner Park&quot;,
&quot;Dragon Park&quot;, &quot;Mt. Tabor Park&quot;, &quot;Forest Park&quot;]);
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;take and take_while&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let message = &quot;To: jimb\r\n\
From: superego &amp;#x3C;editor@oreilly.com&gt;\r\n\
\r\n\
Did you get any writing done today?\r\n\
When will you stop wasting time plotting fractals?\r\n&quot;;
for header in message.lines().take_while(|l| !l.is_empty()) {
println!(&quot;{}&quot; , header);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;To: jimb
From: superego &amp;#x3C;editor@oreilly.com&gt;

()
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;skip and skip_while&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;for body in message.lines()
.skip_while(|l| !l.is_empty())
.skip(1) {
println!(&quot;{}&quot; , body);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;Did you get any writing done today?
When will you stop wasting time plotting fractals?

()
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;peekable&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::iter::Peekable;
fn parse_number&amp;#x3C;I&gt;(tokens: &amp;#x26;mut Peekable&amp;#x3C;I&gt;) -&gt; u32
    where I:Iterator&amp;#x3C;Item = char&gt;{
    let mut n = 0;
    loop {
        match tokens.peek() {
            Some(r) if r.is_digit(10) =&gt; {
                n = n * 10 + r.to_digit(10).unwrap();
            }
            _ =&gt; return  n
        }
        tokens.next();
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let mut chars = &quot;226153980,1766319049&quot;.chars().peekable();
assert_eq!(parse_number(&amp;#x26;mut chars), 226153980);
// Look, `parse_number` didn&apos;t consume the comma! So we will.
assert_eq!(chars.next(), Some(&apos;,&apos;));
assert_eq!(parse_number(&amp;#x26;mut chars), 1766319049);
assert_eq!(chars.next(), None);
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;fuse&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;struct Flaky(bool);
impl Iterator for Flaky {
type Item = &amp;#x26;&apos;static str;
fn next(&amp;#x26;mut self) -&gt; Option&amp;#x3C;Self::Item&gt; {
if self.0 {
self.0 = false;
Some(&quot;totally the last item&quot;)
} else {
self.0 = true; // D&apos;oh!
None
}
}
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let mut flaky = Flaky(true);
assert_eq!(flaky.next(), Some(&quot;totally the last item&quot;));
assert_eq!(flaky.next(), None);
assert_eq!(flaky.next(), Some(&quot;totally the last item&quot;));
let mut not_flaky = Flaky(true).fuse();
assert_eq!(not_flaky.next(), Some(&quot;totally the last item&quot;));
assert_eq!(not_flaky.next(), None);
assert_eq!(not_flaky.next(), None);
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Reversible Iterators and rev&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;{
    let bee_parts = [&quot;head&quot;, &quot;thorax&quot;, &quot;abdomen&quot;];
    let mut iter = bee_parts.iter();
    assert_eq!(iter.next(), Some(&amp;#x26;&quot;head&quot;));
    assert_eq!(iter.next_back(), Some(&amp;#x26;&quot;abdomen&quot;));
    assert_eq!(iter.next(), Some(&amp;#x26;&quot;thorax&quot;));
    assert_eq!(iter.next_back(), None);
    assert_eq!(iter.next(), None);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;()
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;// fn rev(self) -&gt; impl Iterator&amp;#x3C;Item=Self&gt;
// where Self: Sized + DoubleEndedIterator;
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;{
    let meals = [&quot;breakfast&quot;, &quot;lunch&quot;, &quot;dinner&quot;];
    let mut iter = meals.iter().rev();
    assert_eq!(iter.next(), Some(&amp;#x26;&quot;dinner&quot;));
    assert_eq!(iter.next(), Some(&amp;#x26;&quot;lunch&quot;));
    assert_eq!(iter.next(), Some(&amp;#x26;&quot;breakfast&quot;));
    assert_eq!(iter.next(), None);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;()
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;inspect&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let upper_case: String = &quot;große&quot;.chars()
.inspect(|c| println!(&quot;before: {:?}&quot;, c))
.flat_map(|c| c.to_uppercase())
.inspect(|c| println!(&quot; after: {:?}&quot;, c))
.collect();
assert_eq!(upper_case, &quot;GROSSE&quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;before: &apos;g&apos;
 after: &apos;G&apos;
before: &apos;r&apos;
 after: &apos;R&apos;
before: &apos;o&apos;
 after: &apos;O&apos;
before: &apos;ß&apos;
 after: &apos;S&apos;
 after: &apos;S&apos;
before: &apos;e&apos;
 after: &apos;E&apos;
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;chain&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let v: Vec&amp;#x3C;i32&gt; = (1..4).chain(vec![20, 30, 40]).collect();
assert_eq!(v, [1, 2, 3, 20, 30, 40]);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let v: Vec&amp;#x3C;i32&gt; = (1..4).chain(vec![20, 30, 40]).rev().collect();
assert_eq!(v, [40, 30, 20, 3, 2, 1]);
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;enumerate&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let vlist = vec![&apos;A&apos;,&apos;B&apos;,&apos;C&apos;,&apos;D&apos;];
for (i,c) in vlist.into_iter().enumerate() {
    println!(&quot;{}--{}&quot;,i,c);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;0--A
1--B
2--C
3--D

()
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;zip&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let v:Vec&amp;#x3C;_&gt; = (0..).zip(&quot;ABCD&quot;.chars()).collect();
assert_eq!(v, vec![(0, &apos;A&apos;), (1, &apos;B&apos;), (2, &apos;C&apos;), (3, &apos;D&apos;)]);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::iter::repeat;
let endings = vec![&quot;once&quot;, &quot;twice&quot;, &quot;chicken soup with rice&quot;];
let rhyme: Vec&amp;#x3C;_&gt; = repeat(&quot;going&quot;)
.zip(endings)
.collect();
assert_eq!(rhyme, vec![(&quot;going&quot;, &quot;once&quot;),
(&quot;going&quot;, &quot;twice&quot;),
(&quot;going&quot;, &quot;chicken soup with rice&quot;)]);
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;by_ref&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let message = &quot;To: jimb\r\n\
From: id\r\n\
\r\n\
    Oooooh, donuts!!\r\n&quot;;
let mut lines = message.lines();
println!(&quot;Headers:&quot;);
for header in lines.by_ref().take_while(|l| !l.is_empty()) {
println!(&quot;{}&quot; , header);
}
println!(&quot;\nBody:&quot;);
for body in lines {
println!(&quot;{}&quot; , body);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;Headers:
To: jimb
From: id

Body:
Oooooh, donuts!!

()
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;cloned, copied&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let a = [&apos;1&apos;, &apos;2&apos;, &apos;3&apos;, &apos;∞&apos;];
assert_eq!(a.iter().next(), Some(&amp;#x26;&apos;1&apos;));
assert_eq!(a.iter().cloned().next(), Some(&apos;1&apos;));
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;cycle&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;{
    let dirs = [&quot;North&quot;, &quot;East&quot;, &quot;South&quot;, &quot;West&quot;];
let mut spin = dirs.iter().cycle();
assert_eq!(spin.next(), Some(&amp;#x26;&quot;North&quot;));
assert_eq!(spin.next(), Some(&amp;#x26;&quot;East&quot;));
assert_eq!(spin.next(), Some(&amp;#x26;&quot;South&quot;));
assert_eq!(spin.next(), Some(&amp;#x26;&quot;West&quot;));
assert_eq!(spin.next(), Some(&amp;#x26;&quot;North&quot;));
assert_eq!(spin.next(), Some(&amp;#x26;&quot;East&quot;))
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;()
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::iter::{once, repeat};
{
    let fizzes = repeat(&quot;&quot;).take(2).chain(once(&quot;fizz&quot;)).cycle();
    let buzzes = repeat(&quot;&quot;).take(4).chain(once(&quot;buzz&quot;)).cycle();
    let fizzes_buzzes = fizzes.zip(buzzes);
    let fizz_buzz = (1..100).zip(fizzes_buzzes)
    .map(|tuple|
    match tuple {
    (i, (&quot;&quot;, &quot;&quot;)) =&gt; i.to_string(),
    (_, (fizz, buzz)) =&gt; format!(&quot;{}{}&quot;, fizz, buzz)
    });
    for line in fizz_buzz {
    println!(&quot;{}&quot;, line);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;1
2
fizz
4
buzz
fizz
7
8
fizz
buzz
11
fizz
13
14
fizzbuzz
16
17
fizz
19
buzz
fizz
22
23
fizz
buzz
26
fizz
28
29
fizzbuzz
31
32
fizz
34
buzz
fizz
37
38
fizz
buzz
41

()
fizz
43
44
fizzbuzz
46
47
fizz
49
buzz
fizz
52
53
fizz
buzz
56
fizz
58
59
fizzbuzz
61
62
fizz
64
buzz
fizz
67
68
fizz
buzz
71
fizz
73
74
fizzbuzz
76
77
fizz
79
buzz
fizz
82
83
fizz
buzz
86
fizz
88
89
fizzbuzz
91
92
fizz
94
buzz
fizz
97
98
fizz
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Simple Accumulation: count, sum, product&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::cmp::Ordering;
fn cmp(lhs: &amp;#x26;f64,rhs:&amp;#x26;f64) -&gt; Ordering {
    lhs.partial_cmp(rhs).unwrap()
}
let numbers = [1.0, 4.0, 2.0];
assert_eq!(numbers.iter().copied().max_by(cmp), Some(4.0));
assert_eq!(numbers.iter().copied().min_by(cmp), Some(1.0));
let numbers = [1.0, 4.0, std::f64::NAN, 2.0];
assert_eq!(numbers.iter().copied().max_by(cmp), Some(4.0)); // panics
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;thread &apos;&amp;#x3C;unnamed&gt;&apos; panicked at src/lib.rs:8:26:
called `Option::unwrap()` on a `None` value
stack backtrace:
   0: rust_begin_unwind
             at /rustc/a28077b28a02b92985b3a3faecf92813155f1ea1/library/std/src/panicking.rs:597:5
   1: core::panicking::panic_fmt
             at /rustc/a28077b28a02b92985b3a3faecf92813155f1ea1/library/core/src/panicking.rs:72:14
   2: core::panicking::panic
             at /rustc/a28077b28a02b92985b3a3faecf92813155f1ea1/library/core/src/panicking.rs:127:5
   3: &amp;#x3C;core::panic::unwind_safe::AssertUnwindSafe&amp;#x3C;F&gt; as core::ops::function::FnOnce&amp;#x3C;()&gt;&gt;::call_once
   4: run_user_code_29
   5: evcxr::runtime::Runtime::run_loop
   6: evcxr::runtime::runtime_hook
   7: evcxr_jupyter::main
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;max_by_key, min_by_key&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::collections::HashMap;
let mut populations = HashMap::new();
populations.insert(&quot;Portland&quot;, 583_776);
populations.insert(&quot;Fossil&quot;, 449);
populations.insert(&quot;Greenhorn&quot;, 2);
populations.insert(&quot;Boring&quot;, 7_762);
populations.insert(&quot;The Dalles&quot;, 15_340);
assert_eq!(populations.iter().max_by_key(|&amp;#x26;(_name, pop)| pop),
Some((&amp;#x26;&quot;Portland&quot;, &amp;#x26;583_776)));
assert_eq!(populations.iter().min_by_key(|&amp;#x26;(_name, pop)| pop),
Some((&amp;#x26;&quot;Greenhorn&quot;, &amp;#x26;2)));
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Comparing Item Sequences&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let packed = &quot;Helen of Troy&quot;;
let spaced = &quot;Helen of Troy&quot;;
let obscure = &quot;Helen of Sandusky&quot;; // nice person, just not famous
assert!(packed != spaced);
assert!(packed.split_whitespace().eq(spaced.split_whitespace()));
// This is true because &apos; &apos; &amp;#x3C; &apos;o&apos;.
assert!(spaced &amp;#x3C; obscure);
// This is true because &apos;Troy&apos; &gt; &apos;Sandusky&apos;.
assert!(spaced.split_whitespace().gt(obscure.split_whitespace()));
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;thread &apos;&amp;#x3C;unnamed&gt;&apos; panicked at src/lib.rs:178:1:
assertion failed: packed != spaced
stack backtrace:
   0: rust_begin_unwind
             at /rustc/a28077b28a02b92985b3a3faecf92813155f1ea1/library/std/src/panicking.rs:597:5
   1: core::panicking::panic_fmt
             at /rustc/a28077b28a02b92985b3a3faecf92813155f1ea1/library/core/src/panicking.rs:72:14
   2: core::panicking::panic
             at /rustc/a28077b28a02b92985b3a3faecf92813155f1ea1/library/core/src/panicking.rs:127:5
   3: &amp;#x3C;unknown&gt;
   4: &amp;#x3C;unknown&gt;
   5: evcxr::runtime::Runtime::run_loop
   6: evcxr::runtime::runtime_hook
   7: evcxr_jupyter::main
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;any and all&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let id = &quot;Iterator&quot;;
assert!( id.chars().any(char::is_uppercase));
assert!(!id.chars().all(char::is_uppercase));
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;position, rposition, and ExactSizeIterator&lt;/h4&gt;
&lt;p&gt;let text = &quot;Xerxes&quot;;
assert_eq!(text.chars().position(|c| c == &apos;e&apos;), Some(1));
assert_eq!(text.chars().position(|c| c == &apos;z&apos;), None);
let bytes = b&quot;Xerxes&quot;;
assert_eq!(bytes.iter().rposition(|&amp;#x26;c| c == b&apos;e&apos;), Some(4));
assert_eq!(bytes.iter().rposition(|&amp;#x26;c| c == b&apos;X&apos;), Some(0));&lt;/p&gt;
&lt;h4&gt;fold and rfold&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let a = [5, 6, 7, 8, 9, 10];
assert_eq!(a.iter().fold(0, |n, _| n+1), 6); // count
assert_eq!(a.iter().fold(0, |n, i| n+i), 45); // sum
assert_eq!(a.iter().fold(1, |n, i| n*i), 151200); // produc
// max
assert_eq!(a.iter().cloned().fold(i32::min_value(), std::cmp::max),
10);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let a = [&quot;Pack&quot;, &quot;my&quot;, &quot;box&quot;, &quot;with&quot;,
&quot;five&quot;, &quot;dozen&quot;, &quot;liquor&quot;, &quot;jugs&quot;];
// See also: the `join` method on slices, which won&apos;t
// give you that extra space at the end.
let pangram = a.iter()
.fold(String::new(), |s, w| s + w + &quot; &quot;);
assert_eq!(pangram, &quot;Pack my box with five dozen liquor jugs &quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let weird_pangram = a.iter()
.rfold(String::new(), |s, w| s + w + &quot; &quot;);
assert_eq!(weird_pangram, &quot;jugs liquor dozen five with box my Pack &quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;try_fold and try_rfold&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;The nth method takes an index n, skips that many items from the iterator, and
returns the next item, or None if the sequence ends before that point. Calling .nth(0)
is equivalent to .next()
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;pre&gt;&lt;code&gt;第nth方法采用索引n，从迭代器中跳过那么多项，并返回下一项，如果序列在该点之前结束，则返回无。调用. nth（0）等价于.next（）
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let mut squares = (0..10).map(|i| i*i);
assert_eq!(squares.nth(4), Some(16));
assert_eq!(squares.nth(0), Some(25));
assert_eq!(squares.nth(6), None);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;The variable `squares` has type `std::iter::Map&amp;#x3C;std::ops::Range&amp;#x3C;i32&gt;, impl Fn(i32) -&gt; i32&gt;` which cannot be persisted.
You might be able to fix this by creating a `Box&amp;#x3C;dyn YourType&gt;`. e.g.
let v: Box&amp;#x3C;dyn core::fmt::Debug&gt; = Box::new(foo());
Alternatively, you can prevent evcxr from attempting to persist
the variable by wrapping your code in braces.
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;last&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let squares = (0..10).map(|i| i*i);
assert_eq!(squares.last(), Some(81));
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;The variable `squares` has type `std::iter::Map&amp;#x3C;std::ops::Range&amp;#x3C;i32&gt;, impl Fn(i32) -&gt; i32&gt;` which cannot be persisted.
You might be able to fix this by creating a `Box&amp;#x3C;dyn YourType&gt;`. e.g.
let v: Box&amp;#x3C;dyn core::fmt::Debug&gt; = Box::new(foo());
Alternatively, you can prevent evcxr from attempting to persist
the variable by wrapping your code in braces.
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;find, rfind, and find_map&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;assert_eq!(populations.iter().find(|&amp;#x26;(_name, &amp;#x26;pop)| pop &gt; 1_000_000),
None);
assert_eq!(populations.iter().find(|&amp;#x26;(_name, &amp;#x26;pop)| pop &gt; 500_000),
Some((&amp;#x26;&quot;Portland&quot;, &amp;#x26;583_776)));
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let big_city_with_volcano_park = populations.iter()
.find_map(|(&amp;#x26;city, _)| {
if let Some(park) = find_volcano_park(city, &amp;#x26;parks) {
// find_map returns this value, so our caller knows
// *which* park we found.
return Some((city, park.name));
}
// Reject this item, and continue the search.
None
});
assert_eq!(big_city_with_volcano_park,
Some((&quot;Portland&quot;, &quot;Mt. Tabor Park&quot;)));
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;[E0425] Error: cannot find function `find_volcano_park` in this scope
   ╭─[command_50:1:1]
   │
 3 │ if let Some(park) = find_volcano_park(city, &amp;#x26;parks) {
   │                     ────────┬────────
   │                             ╰────────── not found in this scope
───╯
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Building Collections: collect and FromIterator&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let args: Vec&amp;#x3C;String&gt; = std::env::args().collect();
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::collections::{HashSet, BTreeSet, LinkedList, HashMap, BTreeMap};
let args: HashSet&amp;#x3C;String&gt; = std::env::args().collect();
let args: BTreeSet&amp;#x3C;String&gt; = std::env::args().collect();
let args: LinkedList&amp;#x3C;String&gt; = std::env::args().collect();
// Collecting a map requires (key, value) pairs, so for this example,
// zip the sequence of strings with a sequence of integers.
let args: HashMap&amp;#x3C;String, usize&gt; = std::env::args().zip(0..).collect();
let args: BTreeMap&amp;#x3C;String, usize&gt; = std::env::args().zip(0..).collect();
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;The Extend Trait&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let mut v: Vec&amp;#x3C;i32&gt; = (0..5).map(|i| 1 &amp;#x3C;&amp;#x3C; i).collect();
v.extend(&amp;#x26;[31, 57, 99, 163]);
assert_eq!(v, &amp;#x26;[1, 2, 4, 8, 16, 31, 57, 99, 163]);
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;partition&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let things = [&quot;doorknob&quot;, &quot;mushroom&quot;, &quot;noodle&quot;, &quot;giraffe&quot;, &quot;grapefruit&quot;];
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;// odd-numbered letter.
let (living, nonliving): (Vec&amp;#x3C;&amp;#x26;str&gt;, Vec&amp;#x3C;&amp;#x26;str&gt;)
= things.iter().partition(|name| name.as_bytes()[0] &amp;#x26; 1 != 0);
assert_eq!(living, vec![&quot;mushroom&quot;, &quot;giraffe&quot;, &quot;grapefruit&quot;]);
assert_eq!(nonliving, vec![&quot;doorknob&quot;, &quot;noodle&quot;]);
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;for_each and try_for_each&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;[&quot;doves&quot;, &quot;hens&quot;, &quot;birds&quot;].iter()
.zip([&quot;turtle&quot;, &quot;french&quot;, &quot;calling&quot;].iter())
.zip(2..5)
.rev()
.map(|((item, kind), quantity)| {
format!(&quot;{} {} {}&quot;, quantity, kind, item)
})
.for_each(|gift| {
println!(&quot;You have received: {}&quot;, gift);
});
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;You have received: 4 calling birds
You have received: 3 french hens
You have received: 2 turtle doves
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;for gift in [&quot;doves&quot;, &quot;hens&quot;, &quot;birds&quot;].iter()
.zip([&quot;turtle&quot;, &quot;french&quot;, &quot;calling&quot;].iter())
.zip(2..5)
.rev()
.map(|((item, kind), quantity)| {
format!(&quot;{} {} {}&quot;, quantity, kind, item)
})
{
println!(&quot;You have received: {}&quot;, gift);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;You have received: 4 calling birds
You have received: 3 french hens
You have received: 2 turtle doves

()
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Macro&lt;/h3&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/aa067d20-784d-447d-bc6f-72a0ac0022f2.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;macro_rules! bad_assert_eq {
($left:expr, $right:expr) =&gt; ({
match ($left, $right) {
(left_val, right_val) =&gt; {
if !(left_val == right_val) {
panic!(&quot;assertion failed&quot; /* ... */);
}
}
}
});
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let s= &quot;a rose&quot;.to_string();
bad_assert_eq!(s,&quot;a rose&quot;);
println!(&quot;{}&quot;,s)
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;[E0382] Error: borrow of moved value: `s`
   ╭─[command_3:1:1]
   │
 1 │ let s= &quot;a rose&quot;.to_string();
   │     ┬
   │     ╰── move occurs because `s` has type `String`, which does not implement the `Copy` trait
 2 │ bad_assert_eq!(s,&quot;a rose&quot;);
   │                ┬│
   │                ╰── value moved here
   │                 │
   │                 ╰─ help: consider cloning the value if the performance cost is acceptable: `.clone()`
 3 │ println!(&quot;{}&quot;,s)
   │               ┬
   │               ╰── value borrowed here after move
───╯
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/5dcafa2b-4fbd-4ced-98f9-2f137f42197c.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;println!(stringify!(&quot;hello&quot;))
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;&quot;hello&quot;

()
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;println!(env!(&quot;USER&quot;))
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;realcpf

()
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;const TEXT : &amp;#x26;str = include_str!(&quot;/home/realcpf/Documents/rustRepos/rust-prog-2021/hello.txt&quot;);
println!(&quot;{}&quot;,TEXT);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;hello world
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::collections::HashMap;
#[derive(Clone, PartialEq, Debug)]
enum Json {
    Null,
    Boolean(bool),
    Number(f64),
    String(String),
    Array(Vec&amp;#x3C;Json&gt;),
    Object(Box&amp;#x3C;HashMap&amp;#x3C;String, Json&gt;&gt;)
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let students = Json::Array(vec![
Json::Object(Box::new(vec![
(&quot;name&quot;.to_string(), Json::String(&quot;Jim Blandy&quot;.to_string())),
(&quot;class_of&quot;.to_string(), Json::Number(1926.0)),
(&quot;major&quot;.to_string(), Json::String(&quot;Tibetan throat singing&quot;.to_string()))
].into_iter().collect())),
Json::Object(Box::new(vec![
(&quot;name&quot;.to_string(), Json::String(&quot;Jason Orendorff&quot;.to_string())),
(&quot;class_of&quot;.to_string(), Json::Number(1702.0)),
(&quot;major&quot;.to_string(), Json::String(&quot;Knots&quot;.to_string()))
].into_iter().collect()))
]);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;macro_rules! json {
    (null) =&gt; {
        Json::Null
    };
    ([ $( $element:expr ),*]) =&gt; {
        Json:Array(vec![ $( $element ),*])
    };
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;assert_eq!(json!(null),Json::Null)
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;()
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let mm = json!(
    [
        {
            &quot;a&quot;:3.33
        }
    ]
);
let hand_coded_value =
Json::Array(vec![
Json::Object(Box::new(vec![
(&quot;pitch&quot;.to_string(), Json::Number(440.0))
].into_iter().collect()))
]);
assert_eq!(mm,hand_coded_value)
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;Error: expected one of `.`, `;`, `?`, `}`, or an operator, found `:`
   ╭─[command_15:1:1]
   │
 4 │             &quot;a&quot;:3.33
   │                ┬
   │                ╰── expected one of `.`, `;`, `?`, `}`, or an operator
───╯
Error: path separator must be a double colon
[unused_macros] Error: unused macro definition: `bad_assert_eq`
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/6bde3a60-3b61-4d76-9793-1d225d63588f.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;macro_rules! json {
(null) =&gt; {
Json::Null
};
([ $( $element:tt ),* ]) =&gt; {
Json::Array(...)
};
({ $( $key:tt : $value:tt ),* }) =&gt; {
Json::Object(...)
};
($other:tt) =&gt; {
... // TODO: Return Number, String, or Boolean
};
    }
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;macro_rules! impl_from_num_for_json {
    ( $( $t:ident )* ) =&gt; {
        $(
            impl From&amp;#x3C;$t&gt; for Json {
                fn from(n: $t) -&gt; Json {
                    Json::Number(n as f64)
                }
            }
        )*
    };
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;impl_from_num_for_json!(u8 i8 u16 i16 u32 i32 u64 i64 u128 i128
usize isize f32 f64);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;macro_rules! json {
(null) =&gt; {
Json::Null
};
([ $( $element:tt ),* ]) =&gt; {
Json::Array(vec![ $( json!($element) ),* ])
};
({ $( $key:tt : $value:tt ),* }) =&gt; {
Json::Object(Box::new(vec![
$( ($key.to_string(), json!($value)) ),*
].into_iter().collect()))
};
( $other:tt ) =&gt; {
Json::from($other) // Handle Boolean/number/string
};
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let width = 4.0;
let desc =
json!({
&quot;width&quot;: width,
&quot;height&quot;: (width * 9.0 / 4.0)
});
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;[unused_macros] Error: unused macro definition: `bad_assert_eq`
[unused_macros] Error: unused macro definition: `impl_from_num_for_json`
[E0308] Error: mismatched types
   ╭─[command_20:1:1]
   │
 3 │ ╭─▶ json!({
 4 │ │   &quot;width&quot;: width,
   │ │            ──┬──
   │ │              ╰──── expected `Json`, found floating-point number
   ┆ ┆
 6 │ ├─▶ });
   │ │
   │ ╰──────── arguments to this function are incorrect
   │
   │     Note: note: associated function defined here
───╯
[E0308] Error: mismatched types
   ╭─[command_20:1:1]
   │
 3 │ ╭─▶ json!({
   ┆ ┆
 5 │ │   &quot;height&quot;: (width * 9.0 / 4.0)
   │ │             ─────────┬─────────
   │ │                      ╰─────────── expected `Json`, found floating-point number
 6 │ ├─▶ });
   │ │
   │ ╰──────── arguments to this function are incorrect
   │
   │     Note: note: associated function defined here
───╯
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Collections&lt;/h3&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/a2e4466c-65f2-42c3-973a-a151cce15cf4.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;// Create an empty vector
let mut numbers: Vec&amp;#x3C;i32&gt; = vec![];
// Create a vector with given contents
let words = vec![&quot;step&quot;, &quot;on&quot;, &quot;no&quot;, &quot;pets&quot;];
let mut buffer = vec![0u8; 1024]; // 1024 zeroed-out bytes
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/56207e46-e1f8-42a9-86da-d0001feeec5b.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let lines=vec![];
let numbers = vec![];
// Get a reference to an element
let first_line = &amp;#x26;lines[0];
// Get a copy of an element
let fifth_number = numbers[4]; // requires Copy
let second_line = lines[1].clone(); // requires Clone
// Get a reference to a slice
let my_ref = &amp;#x26;buffer[4..12];
// Get a copy of a slice
let my_copy = buffer[4..12].to_vec(); // requires Clone
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;[E0282] Error: type annotations needed for `&amp;#x26;T`
   ╭─[command_5:1:1]
   │
 4 │ let first_line = &amp;#x26;lines[0];
   │     ─────┬────│
   │          ╰────── error: type annotations needed for `&amp;#x26;T`
   │               │
   │               ╰─ help: consider giving `first_line` an explicit type, where the placeholders `_` are specified: `: &amp;#x26;T`
   │
 7 │ let second_line = lines[1].clone(); // requires Clone
   │                   ────┬───
   │                       ╰───── type must be known at this point
───╯
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let slice = [0, 1, 2, 3];
if let Some(item) = slice.first() {
    println!(&quot;we got {}&quot;,item);
}
assert_eq!(slice.get(2), Some(&amp;#x26;2));
assert_eq!(slice.get(4), None);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;we got 0
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let mut slice = [0, 1, 2, 3];
{
    let last = slice.last_mut().unwrap();
    assert_eq!(*last,3);
    *last = 99;
}
assert_eq!(slice,[0,1,2,99]);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let v = [1, 2, 3, 4, 5, 6, 7, 8, 9];
assert_eq!(v.to_vec(),
vec![1, 2, 3, 4, 5, 6, 7, 8, 9]);
assert_eq!(v[0..6].to_vec(),
vec![1, 2, 3, 4, 5, 6]);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::collections::HashSet;
let mut byte_vec = b&quot;Misssssssissippi&quot;.to_vec();
byte_vec.dedup();
assert_eq!(&amp;#x26;byte_vec, b&quot;Misisipi&quot;);
let mut byte_vec = b&quot;Misssssssissippi&quot;.to_vec();
let mut seen = HashSet::new();
byte_vec.retain(|r| seen.insert(*r));
assert_eq!(&amp;#x26;byte_vec, b&quot;Misp&quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;assert_eq!([[1, 2], [3, 4], [5, 6]].concat(),
vec![1, 2, 3, 4, 5, 6]);
assert_eq!([[1, 2], [3, 4], [5, 6]].join(&amp;#x26;0),
vec![1, 2, 0, 3, 4, 0, 5, 6]);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;{
    let v = vec![0, 1, 2, 3];
    let i = 1;
    let j = 2;
    let a = &amp;#x26;v[i];
    let b = &amp;#x26;v[j];
    let mid = v.len() / 2;
    let front_half = &amp;#x26;v[..mid];
    let back_half = &amp;#x26;v[mid..];
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;()
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;{
    let mut v = vec![0, 1, 2, 3];
        let i = 1;
    let j = 2;
    let a = &amp;#x26;mut v[i];
    let b = &amp;#x26;mut v[j]; // error: cannot borrow `v` as mutable
    // more than once at a time
    *a = 6; // references `a` and `b` get used here,
    *b = 7; // so their lifetimes must overlap
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;[E0499] Error: cannot borrow `v` as mutable more than once at a time
   ╭─[command_19:1:1]
   │
 5 │     let a = &amp;#x26;mut v[i];
   │                  ┬
   │                  ╰── first mutable borrow occurs here
 6 │     let b = &amp;#x26;mut v[j]; // error: cannot borrow `v` as mutable
   │                  ┬
   │                  ╰── second mutable borrow occurs here
   │
 8 │     *a = 6; // references `a` and `b` get used here,
   │     ───┬──
   │        ╰──── first borrow later used here
───╯
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/62ad5f88-92d7-42b4-898a-2b3480ca0745.png&quot; alt=&quot;image.png&quot;&gt;
&lt;img src=&quot;/jupyter-img/0abc295d-57c3-4477-a60e-461bea7729a1.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;assert_eq!([1, 2, 3, 4].starts_with(&amp;#x26;[1, 2]), true);
assert_eq!([1, 2, 3, 4].starts_with(&amp;#x26;[2, 3]), false);
assert_eq!([1, 2, 3, 4].ends_with(&amp;#x26;[3, 4]), true);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::collections::VecDeque;
let v = VecDeque::from(vec![1, 2, 3, 4]);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::collections::binary_heap::PeekMut;
use std::collections::BinaryHeap;
{

    let mut heap = BinaryHeap::from(vec![2, 3, 8, 6, 9, 5, 4]);
    if let Some(top) = heap.peek_mut() {
        if *top &gt; 10 {
            PeekMut::pop(top);
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;[E0597] Error: `heap` does not live long enough
    ╭─[command_28:1:1]
    │
  6 │     let mut heap = BinaryHeap::from(vec![2, 3, 8, 6, 9, 5, 4]);
    │         ────┬───
    │             ╰───── binding `heap` declared here
  7 │     if let Some(top) = heap.peek_mut() {
    │                        ──┬────┬───────
    │                          ╰────────────── borrowed value does not live long enough
    │                               │
    │                               ╰───────── a temporary with access to the borrow is created here ...
    │
 11 │     }
    │      │
    │      ╰─ help: consider adding semicolon after the expression so its temporaries are dropped sooner, before the local variables declared by the block are dropped: `;`
    │
 13 │ }
    │ ┬
    │ ╰── `heap` dropped here while still borrowed
────╯
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::collections::HashMap;
let mut vote_counts: HashMap&amp;#x3C;String, usize&gt; = HashMap::new();
vote_counts.insert(String::from(&quot;a&quot;),1);
let ballots = vec![String::from(&quot;a&quot;)];
for name in ballots {
    let count = vote_counts.entry(name).or_insert(0);
    *count += 1;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;()
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let s1 = &quot;hello&quot;.to_string();
let s2 = &quot;hello&quot;.to_string();
println!(&quot;{:p}&quot;, &amp;#x26;s1 as &amp;#x26;str); // 0x7f8b32060008
println!(&quot;{:p}&quot;, &amp;#x26;s2 as &amp;#x26;str); // 0x7f8b32060010
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;0x55ae0bc7af70
0x55ae0bc7e270
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::hash::{Hash, Hasher, BuildHasher};
fn compute_hash&amp;#x3C;B, T&gt;(builder: &amp;#x26;B, value: &amp;#x26;T) -&gt; u64
where B: BuildHasher, T: Hash
{
let mut hasher = builder.build_hasher(); // 1. start the algorithm
value.hash(&amp;#x26;mut hasher); // 2. feed it data
hasher.finish() // 3. finish, producing a u64
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Concurrency&lt;/h3&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/4f01713e-d7f9-4227-ae8a-8847c07a5570.png&quot; alt=&quot;image.png&quot;&gt;
&lt;img src=&quot;/jupyter-img/9145a2a1-54c1-459c-a9d0-eac9100cf350.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::thread;
thread::spawn(||{
    let curr = thread::current();
    let name = curr.name().unwrap_or(&quot;wrong&quot;).to_string();
    println!(&quot;hello in thread {}&quot;,name);
})
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;JoinHandle { .. }
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::{fs, thread};
use std::sync::mpsc;
let (sender, receiver) = mpsc::channel();
let handle = thread::spawn(move || {
for filename in documents {
let text = fs::read_to_string(filename)?;
if sender.send(text).is_err() {
break;
}
}
Ok(())
});
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;[E0425] Error: cannot find value `documents` in this scope
   ╭─[command_10:1:1]
   │
 5 │ for filename in documents {
   │                 ────┬────
   │                     ╰────── not found in this scope
───╯
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::thread;
use std::rc::Rc;
fn main() {
let rc1 = Rc::new(&quot;ouch&quot;.to_string());
let rc2 = rc1.clone();
thread::spawn(move || { // error
rc2.clone();
});
rc1.clone();
}
Rust refuses to compile it, giving a detailed error message:
error[E0277]: `Rc&amp;#x3C;String&gt;` cannot be sent between threads safely
--&gt; concurrency_send_rc.rs:10:5
|
10 | thread::spawn(move || { // error
| ^^^^^ `Rc&amp;#x3C;String&gt;` cannot be sent between threads safely
|
= help: the trait `std::marker::Send` is not implemented for `Rc&amp;#x3C;String&gt;`
= note: required because it appears within the type `[closure@...]`
= note: required by `std::thread::spawn
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::thread;
impl&amp;#x3C;T&gt; OffThreadExt for T
where T: Iterator + Send + &apos;static,
T::Item: Send + &apos;static
{
fn off_thread(self) -&gt; mpsc::IntoIter&amp;#x3C;Self::Item&gt; {
// Create a channel to transfer items from the worker thread.
let (sender, receiver) = mpsc::sync_channel(1024);
// Move this iterator to a new worker thread and run it there.
thread::spawn(move || {
for item in self {
if sender.send(item).is_err() {
break;
}
}
});
// Return an iterator that pulls values from the channel.
receiver.into_iter()
}
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;[E0405] Error: cannot find trait `OffThreadExt` in this scope
   ╭─[command_12:1:1]
   │
 2 │ impl&amp;#x3C;T&gt; OffThreadExt for T
   │         ──────┬─────
   │               ╰─────── not found in this scope
───╯

[E0433] Error: failed to resolve: use of undeclared crate or module `mpsc`
   ╭─[command_12:1:1]
   │
 6 │ fn off_thread(self) -&gt; mpsc::IntoIter&amp;#x3C;Self::Item&gt; {
   │                        ──┬─
   │                          ╰─── use of undeclared crate or module `mpsc`
   │
   │ Note: help: consider importing this module: `use std::sync::mpsc;
`
───╯

[E0433] Error: failed to resolve: use of undeclared crate or module `mpsc`
   ╭─[command_12:1:1]
   │
 8 │ let (sender, receiver) = mpsc::sync_channel(1024);
   │                          ──┬─
   │                            ╰─── use of undeclared crate or module `mpsc`
   │
   │ Note: help: consider importing this module: `use std::sync::mpsc;
`
───╯
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Multiconsumer Channels Using Mutexes&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;pub mod shared_channel {
    use std::sync::{Arc,Mutex};
    use std::sync::mpsc::{channel,Sender,Receiver};
    /// A thread-safe wrapper around a `Receiver`.
    #[derive(Clone)]
    pub struct SharedReceiver&amp;#x3C;T&gt;(Arc&amp;#x3C;Mutex&amp;#x3C;Receiver&amp;#x3C;T&gt;&gt;&gt;);

    impl&amp;#x3C;T&gt; Iterator for SharedReceiver&amp;#x3C;T&gt; {
        type Item = T;
        fn next(&amp;#x26;mut self) -&gt; Option&amp;#x3C;Self::Item&gt; {
            let guard = self.0.lock().unwrap();
            guard.recv().ok()
        }
    }
    pub fn shared_channel&amp;#x3C;T&gt;() -&gt; (Sender&amp;#x3C;T&gt;,SharedReceiver&amp;#x3C;T&gt;) {
        let (sender,receiver) = channel();
        (sender,SharedReceiver(Arc::new(Mutex::new(receiver))))
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/65b75b25-d648-4992-9d46-93e6175311dd.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;h4&gt;Read/Write Locks (RwLock)&lt;/h4&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/57cc2853-d528-4309-a818-80d33a9fce56.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;h4&gt;Condition Variables (Condvar)&lt;/h4&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/e24c3fee-ec9e-44c5-bd12-138274d4fddd.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;h4&gt;Atomics&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::sync::atomic::{AtomicIsize,Ordering};
let atom = AtomicIsize::new(0);
atom.fetch_add(1, Ordering::SeqCst);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;These methods may compile to specialized machine language instructions. On the
x86-64 architecture, this .fetch_add() call compiles to a lock incq instruction,
where an ordinary n += 1 might compile to a plain incq instruction or any number
of variations on that theme. The Rust compiler also has to forgo some optimizations
around the atomic operation, since—unlike a normal load or store—it can legiti‐
mately affect or be affected by other threads right away
这些方法可以编译成专门的机器语言指令。在x86-64架构上，this.fetch_add（）调用编译成锁incq指令，其中普通的n+=1可能编译成普通的incq指令或该主题的任何数量的变体。Rust编译器还必须放弃围绕原子操作的一些优化，因为与正常的加载或存储不同，它可以合法地立即影响或受到其他线程的影响&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::sync::Arc;
use std::sync::atomic::AtomicBool;
let cancel_flag = Arc::new(AtomicBool::new(false));
let worker_cancel_flag = cancel_flag.clone();
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Traits and Generics&lt;/h3&gt;
&lt;blockquote&gt;
&lt;p&gt;[A] computer scientist tends to be able to deal with nonuniform structures—case 1, case 2,
case 3—while a mathematician will tend to want one unifying axiom that governs an entire
system.
—Donald Knuth&lt;/p&gt;
&lt;/blockquote&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::io::Write;
fn say_hello(out: &amp;#x26;mut dyn Write) -&gt; std::io::Result&amp;#x3C;()&gt; {
    out.write_all(b&quot;hello world\n&quot;)?;
    out.flush()
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::fs::File;
let mut local_file = File::create(&quot;hello.txt&quot;)?;
say_hello(&amp;#x26;mut local_file)?;
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let mut bytes = vec![];
say_hello(&amp;#x26;mut bytes)?;
assert_eq!(bytes,b&quot;hello world\n&quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;fn min&amp;#x3C;T: Ord&gt;(v1: T,v2: T) -&gt; T {
    if v1 &amp;#x3C;= v2 {
        v1
    } else {
        v2
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/0a891cbf-a8ba-4bec-bf63-e94522a50c38.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;h4&gt;Trait Objects&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::io::Write;
let mut buf: Vec&amp;#x3C;u8&gt; = vec![];
let writer: dyn Write = buf;
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;[E0308] Error: mismatched types
   ╭─[command_6:1:1]
   │
 4 │ let writer: dyn Write = buf;
   │             ────┬────   ─┬─
   │                 ╰──────────── expected due to this
   │                          │
   │                          ╰─── expected `dyn Write`, found `Vec&amp;#x3C;u8&gt;`
───╯

[E0277] Error: the size for values of type `dyn std::io::Write` cannot be known at compilation time
   ╭─[command_6:1:1]
   │
 4 │ let writer: dyn Write = buf;
   │     ───┬──  │
   │        ╰────── doesn&apos;t have a size known at compile-time
   │             │
   │             ╰─ help: consider borrowing here: `&amp;#x26;`
───╯
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;{
    let mut buf: Vec&amp;#x3C;u8&gt; =  vec![];
    let writer: &amp;#x26;mut dyn Write = &amp;#x26;mut buf;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;()
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;内存布局&lt;/h4&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/864d03c8-57c7-4db6-8ac4-30e88e77652f.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;h4&gt;Generic Functions and Type Parameters&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let v1 = (0..100).collect();
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;[E0282] Error: type annotations needed
   ╭─[command_11:1:1]
   │
 1 │ let v1 = (0..100).collect();
   │     ─┬│
   │      ╰── error: type annotations needed
   │       │
   │       ╰─ help: consider giving `v1` an explicit type: `: Vec&amp;#x3C;_&gt;`
───╯
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let v2 = (0..100).collect::&amp;#x3C;Vec&amp;#x3C;i32&gt;&gt;();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/330646cb-106e-429c-9eda-e7173988d783.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;h4&gt;Defining and Implementing Traits&lt;/h4&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/45ce7c12-6158-497e-8843-5371bd79c5a1.png&quot; alt=&quot;image.png&quot;&gt;
&lt;img src=&quot;/jupyter-img/45f4b4ba-8a6b-47d8-91a5-24eaa8315047.png&quot; alt=&quot;image.png&quot;&gt;
&lt;img src=&quot;/jupyter-img/de75de94-2ae6-4e80-8f84-61c4d61ff7ff.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;h4&gt;Traits and Other People’s Types&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;trait IsEmoji {
    fn is_emoji(&amp;#x26;self) -&gt; bool;
}
impl IsEmoji for char {
    fn is_emoji(&amp;#x26;self) -&gt; bool {
        false
    }
}
assert_eq!(&apos;$&apos;.is_emoji(), false);
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Subtraits&lt;/h4&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/e603a06f-ff5b-40a3-aa57-3d6e71002f2f.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;fn dot(v1: &amp;#x26;[i64], v2: &amp;#x26;[i64]) -&gt; i64 {
let mut total = 0;
for i in 0 .. v1.len() {
total = total + v1[i] * v2[i];
}
total
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;fn dot&amp;#x3C;N&gt;(v1: &amp;#x26;[N], v2: &amp;#x26;[N]) -&gt; N {
let mut total: N = 0;
for i in 0 .. v1.len() {
total = total + v1[i] * v2[i];
}
total
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;[E0308] Error: mismatched types
   ╭─[command_19:1:1]
   │
 1 │ fn dot&amp;#x3C;N&gt;(v1: &amp;#x26;[N], v2: &amp;#x26;[N]) -&gt; N {
   │        ┬
   │        ╰── this type parameter
 2 │ let mut total: N = 0;
   │                ┬   ┬
   │                ╰────── expected due to this
   │                    │
   │                    ╰── expected type parameter `N`, found integer
───╯

[E0369] Error: cannot multiply `N` by `N`
   ╭─[command_19:1:1]
   │
 1 │ fn dot&amp;#x3C;N&gt;(v1: &amp;#x26;[N], v2: &amp;#x26;[N]) -&gt; N {
   │         │
   │         ╰─ help: consider restricting type parameter `N`: `: std::ops::Mul`
   │
 4 │ total = total + v1[i] * v2[i];
   │                 ──┬── ┬ ──┬──
   │                   ╰──────────── N
   │                       │   │
   │                       ╰──────── error: cannot multiply `N` by `N`
   │                           │
   │                           ╰──── N
───╯
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::ops::{Add, Mul};
fn dot&amp;#x3C;N: Add + Mul + Default&gt;(v1: &amp;#x26;[N], v2: &amp;#x26;[N]) -&gt; N {
let mut total = N::default();
for i in 0 .. v1.len() {
total = total + v1[i] * v2[i];
}
total
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;[E0308] Error: mismatched types
   ╭─[command_20:1:1]
   │
 2 │ fn dot&amp;#x3C;N: Add + Mul + Default&gt;(v1: &amp;#x26;[N], v2: &amp;#x26;[N]) -&gt; N {
   │        ┬           │
   │        ╰───────────── this type parameter
   │                    │
   │                    ╰─ help: consider further restricting this bound: `&amp;#x3C;Output = N&gt;`
   │
 5 │ total = total + v1[i] * v2[i];
   │         ──┬──   ──────┬──────
   │           ╰──────────────────── expected because this is `N`
   │                       │
   │                       ╰──────── expected type parameter `N`, found associated type
───╯

[E0308] Error: mismatched types
   ╭─[command_20:1:1]
   │
 2 │ fn dot&amp;#x3C;N: Add + Mul + Default&gt;(v1: &amp;#x26;[N], v2: &amp;#x26;[N]) -&gt; N {
   │        ┬     │
   │        ╰─────── this type parameter
   │              │
   │              ╰─ help: consider further restricting this bound: `&amp;#x3C;Output = N&gt;`
 3 │ let mut total = N::default();
   │                 ──────┬─────
   │                       ╰─────── expected due to this value
   │
 5 │ total = total + v1[i] * v2[i];
   │         ──────────┬──────────
   │                   ╰──────────── expected type parameter `N`, found associated type
───╯
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::ops::{Add, Mul};
fn dot&amp;#x3C;N&gt;(v1: &amp;#x26;[N], v2: &amp;#x26;[N]) -&gt; N
where N: Add&amp;#x3C;Output=N&gt; + Mul&amp;#x3C;Output=N&gt; + Default + Copy
{
let mut total = N::default();
for i in 0 .. v1.len() {
total = total + v1[i] * v2[i];
}
total
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Operator Overloading&lt;/h3&gt;
&lt;h4&gt;Operator Overloading&lt;/h4&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/f35bcc73-a112-4970-a9db-6e5039355761.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::ops::Add;
assert_eq!(4.125f32.add(5.75), 9.875);
assert_eq!(10.add(20), 10 + 20);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;
use std::ops::Add;
impl&amp;#x3C;T&gt; Add for Complex&amp;#x3C;T&gt;
where
T: Add&amp;#x3C;Output = T&gt;,
{
type Output = Self;
fn add(self, rhs: Self) -&gt; Self {
Complex {
re: self.re + rhs.re,
im: self.im + rhs.im,
}
}
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/b350af5a-36c5-4c45-8cf7-2dd5b5863256.png&quot; alt=&quot;image.png&quot;&gt;
&lt;img src=&quot;/jupyter-img/f426af2e-6d96-4b41-bcd4-7c46ce400cb3.png&quot; alt=&quot;image.png&quot;&gt;
&lt;img src=&quot;/jupyter-img/ea393f98-d18d-4786-b3c3-0cbf822c8f46.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let s = &quot;d\x6fv\x65t\x61i\x6c&quot;.to_string();
let t = &quot;\x64o\x76e\x74a\x69l&quot;.to_string();
assert!(s == t); // s and t are only borrowed...
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;// ... so they still have their values here.
assert_eq!(format!(&quot;{} {}&quot;, s, t), &quot;dovetail dovetail&quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;assert!(&quot;ungula&quot; != &quot;ungulate&quot;);
assert!(&quot;ungula&quot;.ne(&quot;ungulate&quot;));
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;assert!(f64::is_nan(0.0 / 0.0));
assert_eq!(0.0 / 0.0 == 0.0 / 0.0, false);
assert_eq!(0.0 / 0.0 != 0.0 / 0.0, true);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;assert_eq!(0.0 / 0.0 &amp;#x3C; 0.0 / 0.0, false);
assert_eq!(0.0 / 0.0 &gt; 0.0 / 0.0, false);
assert_eq!(0.0 / 0.0 &amp;#x3C;= 0.0 / 0.0, false);
assert_eq!(0.0 / 0.0 &gt;= 0.0 / 0.0, false);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/ce472979-283c-4461-a6af-42149b43cca4.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;#[derive(Debug, PartialEq)]
struct Interval&amp;#x3C;T&gt; {
lower: T, // inclusive
upper: T, // exclusive
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::cmp::{Ordering, PartialOrd}
impl &amp;#x3C;T: PartialOrd&gt; PartialOrd&amp;#x3C;Interval&amp;#x3C;T&gt;&gt; for Interval&amp;#x3C;T&gt; {
    fn partial_cmp(&amp;#x26;self, other: &amp;#x26;Interval&amp;#x3C;T&gt;) -&gt; Option&amp;#x3C;Ordering&gt; {
        if self == other {
            Some(Ordering::Equal)
        } else if self.lower &gt;= other.upper {
            Some(Ordering::Greater)
        } else if self.upper &amp;#x3C;= other.lower {
            Some(Ordering::Less)
        } else {
            None
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;assert!(Interval { lower: 10, upper: 20 } &amp;#x3C; Interval { lower: 20, upper: 40 });
assert!(Interval { lower: 7, upper: 8 } &gt;= Interval { lower: 0, upper: 1 });
assert!(Interval { lower: 7, upper: 8 } &amp;#x3C;= Interval { lower: 7, upper: 8 });
// Overlapping intervals aren&apos;t ordered with respect to each other.
let left = Interval { lower: 10, upper: 30 };
let right = Interval { lower: 20, upper: 40 };
assert!(!(left &amp;#x3C; right));
assert!(!(left &gt;= right));
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Index and IndexMut&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::collections::HashMap;
let mut m = HashMap::new();
m.insert(&quot;十&quot;, 10);
m.insert(&quot;百&quot;, 100);
m.insert(&quot;千&quot;, 1000);
m.insert(&quot;万&quot;, 1_0000);
m.insert(&quot;億&quot;, 1_0000_0000);
assert_eq!(m[&quot;十&quot;], 10);
assert_eq!(m[&quot;千&quot;], 1000);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::ops::Index;
assert_eq!(*m.index(&quot;十&quot;), 10);
assert_eq!(*m.index(&quot;千&quot;), 1000);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let mut desserts =
vec![&quot;Howalon&quot;.to_string(), &quot;Soan papdi&quot;.to_string()];
desserts[0].push_str(&quot; (fictional)&quot;);
desserts[1].push_str(&quot; (real)&quot;);
use std::ops::IndexMut;
(*desserts.index_mut(0)).push_str(&quot; (fictional)&quot;);
(*desserts.index_mut(1)).push_str(&quot; (real)&quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;struct Image&amp;#x3C;P&gt; {
    width: usize,
    pixels: Vec&amp;#x3C;P&gt;,
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;impl&amp;#x3C;P: Default + Copy&gt; Image&amp;#x3C;P&gt; {
    fn new(width: usize, height:usize) -&gt; Image&amp;#x3C;P&gt; {
        Image { width: width, pixels: vec![P::default();width * height], }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;impl&amp;#x3C;P&gt; std::ops::Index&amp;#x3C;usize&gt; for Image&amp;#x3C;P&gt; {
    type Output = [P];
    fn index(&amp;#x26;self, index: usize) -&gt; &amp;#x26;Self::Output {
        let start = index * self.width;
        &amp;#x26;self.pixels[start .. start + self.width]
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;impl&amp;#x3C;P&gt; std::ops::IndexMut&amp;#x3C;usize&gt; for Image&amp;#x3C;P&gt; {
fn index_mut(&amp;#x26;mut self, row: usize) -&gt; &amp;#x26;mut [P] {
let start = row * self.width;
&amp;#x26;mut self.pixels[start..start + self.width]
}
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;Science is nothing else than the search to discover unity in the wild variety of nature—or,
more exactly, in the variety of our experience. Poetry, painting, the arts are the same search,
in Coleridge’s phrase, for unity in variety.
—Jacob Bronowski
&lt;img src=&quot;/jupyter-img/a43d94ec-7a9d-429d-b223-035591fa513e.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h4&gt;Drop&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;struct Appellation {
name: String,
nicknames: Vec&amp;#x3C;String&gt;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;impl Drop for Appellation {
    fn drop(&amp;#x26;mut self) {
        println!(&quot;Droping {}&quot;,&amp;#x26;self.name);
        if !&amp;#x26;self.nicknames.is_empty() {
            println!(&quot;AKA {}&quot;,&amp;#x26;self.nicknames.join(&quot;,&quot;));
        }
        println!(&quot;&quot;);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;{
let mut a = Appellation {
name: &quot;Zeus&quot;.to_string(),
nicknames: vec![&quot;cloud collector&quot;.to_string(),
&quot;king of the gods&quot;.to_string()]
};
println!(&quot;before assignment&quot;);
a = Appellation { name: &quot;Hera&quot;.to_string(), nicknames: vec![] };
println!(&quot;at end of block&quot;);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;before assignment
Droping Zeus
AKA cloud collector,king of the gods

at end of block
Droping Hera



()
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Sized&lt;/h4&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/b625185a-ff46-47d0-973a-db74ffd9a304.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;struct RcBox&amp;#x3C;T: ?Sized&gt; {
ref_count: usize,
value: T,
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::fmt::Display;
fn display(boxed: &amp;#x26;RcBox&amp;#x3C;dyn Display&gt;) {
println!(&quot;For your enjoyment: {}&quot;, &amp;#x26;boxed.value);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;{
    let boxed_lunch: RcBox&amp;#x3C;String&gt; = RcBox {
ref_count: 1,
value: &quot;lunch&quot;.to_string()
};
use std::fmt::Display;
let boxed_displayable: &amp;#x26;RcBox&amp;#x3C;dyn Display&gt; = &amp;#x26;boxed_lunch;
    display(&amp;#x26;boxed_lunch);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;For your enjoyment: lunch


()
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Clone&lt;/h4&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/90515bf3-1684-4d0b-afd1-3cc2bda5ce4e.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;h4&gt;Copy&lt;/h4&gt;
&lt;p&gt;&lt;img src=&quot;/jupyter-img/95e4ffb4-9630-4ccb-ab70-a70ec1eefb9f.png&quot; alt=&quot;image.png&quot;&gt;&lt;/p&gt;
&lt;h4&gt;Deref and DerefMut&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;struct Selector&amp;#x3C;T&gt; {
/// Elements available in this `Selector`.
elements: Vec&amp;#x3C;T&gt;,
/// The index of the &quot;current&quot; element in `elements`. A `Selector`
/// behaves like a pointer to the current element.
current: usize
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::ops::{Deref, DerefMut};
impl&amp;#x3C;T&gt; Deref for Selector&amp;#x3C;T&gt; {
type Target = T;
fn deref(&amp;#x26;self) -&gt; &amp;#x26;T {
&amp;#x26;self.elements[self.current]
}
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;impl&amp;#x3C;T&gt; DerefMut for Selector&amp;#x3C;T&gt; {
    fn deref_mut(&amp;#x26;mut self) -&gt; &amp;#x26;mut Self::Target {
        &amp;#x26;mut self.elements[self.current]
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;[E0119] Error: conflicting implementations of trait `DerefMut` for type `Selector&amp;#x3C;_&gt;`
   ╭─[command_17:1:1]
   │
 1 │ impl&amp;#x3C;T&gt; DerefMut for Selector&amp;#x3C;T&gt; {
   │ ────────────────┬───────────────
   │                 ╰───────────────── conflicting implementation for `Selector&amp;#x3C;_&gt;`
───╯
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let mut s = Selector { elements: vec![&apos;x&apos;, &apos;y&apos;, &apos;z&apos;],
current: 2 };
// Because `Selector` implements `Deref`, we can use the `*` operator to
// refer to its current element.
assert_eq!(*s, &apos;z&apos;);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;// Assert that &apos;z&apos; is alphabetic, using a method of `char` directly on a
// `Selector`, via deref coercion.
assert!(s.is_alphabetic());
// Change the &apos;z&apos; to a &apos;w&apos;, by assigning to the `Selector`&apos;s referent.
*s = &apos;w&apos;;
assert_eq!(s.elements, [&apos;x&apos;, &apos;y&apos;, &apos;w&apos;]);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let s = Selector { elements: vec![&quot;good&quot;, &quot;bad&quot;, &quot;ugly&quot;],
current: 2 };
fn show_it(thing: &amp;#x26;str) { println!(&quot;{}&quot;, thing); }
show_it(&amp;#x26;s);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;ugly
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::fmt::Display;
fn show_it_generic&amp;#x3C;T: Display&gt;(thing: T) { println!(&quot;{}&quot;, thing); }
show_it_generic(&amp;#x26;s);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;[E0277] Error: `Selector&amp;#x3C;&amp;#x26;str&gt;` doesn&apos;t implement `std::fmt::Display`
   ╭─[command_22:1:1]
   │
 2 │ fn show_it_generic&amp;#x3C;T: Display&gt;(thing: T) { println!(&quot;{}&quot;, thing); }
   │                       ───┬───
   │                          ╰───── required by this bound in `show_it_generic`
 3 │ show_it_generic(&amp;#x26;s);
   │ ───────┬───────  ┬
   │        ╰──────────── required by a bound introduced by this call
   │                  │
   │                  ╰── `Selector&amp;#x3C;&amp;#x26;str&gt;` cannot be formatted with the default formatter
   │                  │
   │                  ╰── help: consider dereferencing here: `*`
───╯
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;show_it(&amp;#x26;*s)
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;ugly


()
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;show_it(&amp;#x26;s as &amp;#x26;str)
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;ugly


()
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Default&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::collections::HashSet;
let squares = [4, 9, 16, 25, 36, 49, 64];
let (powers_of_two, impure): (HashSet&amp;#x3C;i32&gt;, HashSet&amp;#x3C;i32&gt;)
= squares.iter().partition(|&amp;#x26;n| n &amp;#x26; (n-1) == 0);
assert_eq!(powers_of_two.len(), 3);
assert_eq!(impure.len(), 4);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let (upper, lower): (String, String)
= &quot;Great Teacher Onizuka&quot;.chars().partition(|&amp;#x26;c| c.is_uppercase());
assert_eq!(upper, &quot;GTO&quot;);
assert_eq!(lower, &quot;reat eacher nizuka&quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;AsRef and AsMut&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;/*
What open really wants is a &amp;#x26;Path, the type representing a filesystem path. But with
this signature, open accepts anything it can borrow a &amp;#x26;Path from—that is, anything
that implements AsRef&amp;#x3C;Path&gt;. Such types include String and str, the operating sys‐
tem interface string types OsString and OsStr, and of course PathBuf and Path; see
the library documentation for the full list. This is what allows you to pass string liter‐
als to open:
*/
let dot_vim = std::fs::File::open(&quot;/home/realcpf/.vim&quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Borrow and BorrowMut&lt;/h4&gt;
&lt;h4&gt;From and Into&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::net::Ipv4Addr;
fn ping&amp;#x3C;A&gt;(address: A) -&gt; std::io::Result&amp;#x3C;bool&gt;
    where A: Into&amp;#x3C;Ipv4Addr&gt;{
        let ipv4_address = address.into();
        std::io::Result::Ok(true)
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;println!(&quot;{:?}&quot;, ping(Ipv4Addr::new(23, 21, 68, 141))); // pass an Ipv4Addr
println!(&quot;{:?}&quot;, ping([66, 146, 219, 98])); // pass a [u8; 4]
println!(&quot;{:?}&quot;, ping(0xd076eb94_u32)); // pass a u32
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;Ok(true)
Ok(true)
Ok(true)
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let addr1 = Ipv4Addr::from([66, 146, 219, 98]);
let addr2 = Ipv4Addr::from(0xd076eb94_u32);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let text = &quot;hello world&quot;.to_string();
let bytes: Vec&amp;#x3C;u8&gt; = text.into();
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;TryFrom and TryInto&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let huge = 2_000_000_000_000i64;
let smaller = huge as i32;
println!(&quot;{}&quot;, smaller); // -1454759936
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;-1454759936
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;use std::convert::TryInto;
let smaller: i32 = huge.try_into().unwrap_or(i32::MAX);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let smaller: i32 = huge.try_into().unwrap_or_else(|_| {
    if huge &gt;= 0 {
        i32::MAX
    } else {
        i32::MIN
    }
});
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;&lt;/code&gt;&lt;/pre&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>关于Serde Syn quote那些不得不说的故事</title><link>https://realcpf.tech/blog/serde-syn-quote</link><guid isPermaLink="true">https://realcpf.tech/blog/serde-syn-quote</guid><description>关于Serde Syn quote那些不得不说的故事</description><pubDate>Wed, 28 Feb 2024 18:22:00 GMT</pubDate><content:encoded>&lt;h3&gt;serde&lt;/h3&gt;
&lt;blockquote&gt;
&lt;p&gt;Serde is a framework for serializing and deserializing Rust data structures efficiently and generically.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;blockquote&gt;
&lt;p&gt;仅依赖syn ,quote ,proc-macro2&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h4&gt;基本操作&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;
use serde::{Deserialize, Serialize};
// 主要是 Serialize，Deserialize 这两个宏
#[derive(Serialize, Deserialize, Debug)]
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let point = Point { x: 1, y: 2 };

    // Convert the Point to a JSON string.
    let serialized = serde_json::to_string(&amp;#x26;point).unwrap();

    // Prints serialized = {&quot;x&quot;:1,&quot;y&quot;:2}
    println!(&quot;serialized = {}&quot;, serialized);

    // Convert the JSON string back to a Point.
    let deserialized: Point = serde_json::from_str(&amp;#x26;serialized).unwrap();

    // Prints deserialized = Point { x: 1, y: 2 }
    println!(&quot;deserialized = {:?}&quot;, deserialized);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Deserialize&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;// 以该结构为例子
#[derive(Serialize,Debug)]
struct Duration{
    secs:usize,
    nanos:usize,
}

// 方便反序列化
impl Duration {
    fn new(secs:usize,nanos:usize) -&gt; Duration{
        return Duration {
            secs:secs,
            nanos:nanos,
        }
    }
}

// 实现反序列化

impl&amp;#x3C;&apos;de&gt; Deserialize&amp;#x3C;&apos;de&gt; for Duration {
    fn deserialize&amp;#x3C;D&gt;(deserializer: D) -&gt; Result&amp;#x3C;Self, D::Error&gt;
    where
        D: Deserializer&amp;#x3C;&apos;de&gt;,
    {
        enum Field { Secs, Nanos }

        // This part could also be generated independently by:
        //
        //    #[derive(Deserialize)]
        //    #[serde(field_identifier, rename_all = &quot;lowercase&quot;)]
        //    enum Field { Secs, Nanos }
        // 给每个字段实现反序列化
        impl&amp;#x3C;&apos;de&gt; Deserialize&amp;#x3C;&apos;de&gt; for Field {
            fn deserialize&amp;#x3C;D&gt;(deserializer: D) -&gt; Result&amp;#x3C;Field, D::Error&gt;
            where
                D: Deserializer&amp;#x3C;&apos;de&gt;,
            {

                struct FieldVisitor;
                // visitor用于处理基本类型
                impl&amp;#x3C;&apos;de&gt; Visitor&amp;#x3C;&apos;de&gt; for FieldVisitor {
                    type Value = Field;

                    fn expecting(&amp;#x26;self, formatter: &amp;#x26;mut fmt::Formatter) -&gt; fmt::Result {
                        formatter.write_str(&quot;`secs` or `nanos`&quot;)
                    }

                    fn visit_str&amp;#x3C;E&gt;(self, value: &amp;#x26;str) -&gt; Result&amp;#x3C;Field, E&gt;
                    where
                        E: de::Error,
                    {
                        match value {
                            &quot;secs&quot; =&gt; Ok(Field::Secs),
                            &quot;nanos&quot; =&gt; Ok(Field::Nanos),
                            _ =&gt; Err(de::Error::unknown_field(value, FIELDS)),
                        }
                    }
                }

                // 处理字段名
                deserializer.deserialize_identifier(FieldVisitor)
            }
        }

        struct DurationVisitor;

        impl&amp;#x3C;&apos;de&gt; Visitor&amp;#x3C;&apos;de&gt; for DurationVisitor {
            type Value = Duration;

            fn expecting(&amp;#x26;self, formatter: &amp;#x26;mut fmt::Formatter) -&gt; fmt::Result {
                formatter.write_str(&quot;struct Duration&quot;)
            }
            // 针对序列
            fn visit_seq&amp;#x3C;V&gt;(self, mut seq: V) -&gt; Result&amp;#x3C;Duration, V::Error&gt;
            where
                V: SeqAccess&amp;#x3C;&apos;de&gt;,
            {
                let secs = seq.next_element()?
                    .ok_or_else(|| de::Error::invalid_length(0, &amp;#x26;self))?;
                let nanos = seq.next_element()?
                    .ok_or_else(|| de::Error::invalid_length(1, &amp;#x26;self))?;
                Ok(Duration::new(secs, nanos))
            }
            // 常见的反序列化map
            fn visit_map&amp;#x3C;V&gt;(self, mut map: V) -&gt; Result&amp;#x3C;Duration, V::Error&gt;
            where
                V: MapAccess&amp;#x3C;&apos;de&gt;,
            {
                let mut secs = None;
                let mut nanos = None;
                while let Some(key) = map.next_key()? {
                    match key {
                        Field::Secs =&gt; {
                            if secs.is_some() {
                                return Err(de::Error::duplicate_field(&quot;secs&quot;));
                            }
                            secs = Some(map.next_value()?);
                        }
                        Field::Nanos =&gt; {
                            if nanos.is_some() {
                                return Err(de::Error::duplicate_field(&quot;nanos&quot;));
                            }
                            nanos = Some(map.next_value()?);
                        }
                    }
                }
                let secs = secs.ok_or_else(|| de::Error::missing_field(&quot;secs&quot;))?;
                let nanos = nanos.ok_or_else(|| de::Error::missing_field(&quot;nanos&quot;))?;
                Ok(Duration::new(secs, nanos))
            }
        }

        const FIELDS: &amp;#x26;&apos;static [&amp;#x26;&apos;static str] = &amp;#x26;[&quot;secs&quot;, &quot;nanos&quot;];
        deserializer.deserialize_struct(&quot;Duration&quot;, FIELDS, DurationVisitor)
    }
}

// 最后测试
    let d = Duration{secs:123,nanos:345};
    let ds = serde_json::to_string(&amp;#x26;d).unwrap();
    println!(&quot;{}&quot;,ds);
    let dd:Duration = serde_json::from_str(&amp;#x26;ds).unwrap();
    println!(&quot;{:#?}&quot;,dd);


&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;quote&lt;/h3&gt;
&lt;blockquote&gt;
&lt;p&gt;This crate provides the quote! macro for turning Rust syntax tree data structures into tokens of source code.
The idea of quasi-quoting is that we write code that we treat as data.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h4&gt;基本类型&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let u = 12usize;
let i = -38i32;
let f = 3.1415926f64;
let c = &apos;\r&apos;;
let s = &quot;\r\nhello\tworld\r\n&quot;;

assert_eq!(
    &quot;12usize - 38i32 3.1415926f64 &apos;\\r&apos; \&quot;\\r\\nhello\\tworld\\r\\n\&quot;&quot;,
    quote! {
        #u #i #f #c #s
    }
    .to_string()
);
macro_rules! m {
    ($literal:literal) =&gt; {
        quote!($literal)
    };
}

let expected = &quot;- false&quot;;
assert_eq!(expected, m!(-false).to_string());
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;重复、循环&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let f0 = format_ident!(&quot;World&quot;);
let f1 = format_ident!(&quot;Hello{x}&quot;, x = f0);
assert_eq!(&quot;HelloWorld&quot;,f1.to_string());
// ident not impl f64
let f2 = format_ident!(&quot;Hello{x}&quot;, x = 4050usize);

assert_eq!(&quot;Hello4050&quot;,f2.to_string());
let num: u32 = 10;

let octal = format_ident!(&quot;Id_{:o}&quot;, num);
assert_eq!(octal, &quot;Id_12&quot;);

let binary = format_ident!(&quot;Id_{:b}&quot;, num);
assert_eq!(binary, &quot;Id_1010&quot;);

let lower_hex = format_ident!(&quot;Id_{:x}&quot;, num);
assert_eq!(lower_hex, &quot;Id_a&quot;);

let upper_hex = format_ident!(&quot;Id_{:X}&quot;, num);
assert_eq!(upper_hex, &quot;Id_A&quot;);

&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;注释&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;
let token1 = quote!{
/* comment */
};
let token2 = quote!{
// comment
};

assert_eq!(token1.to_string(),token2.to_string())

&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;syn&lt;/h3&gt;
&lt;blockquote&gt;
&lt;p&gt;Syn is a parsing library for parsing a stream of Rust tokens into a syntax tree of Rust source code.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h4&gt;syn::File&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;let mut file = File::open(&amp;#x26;filename).expect(&quot;Unable to open file&quot;);

let mut src = String::new();
file.read_to_string(&amp;#x26;mut src).expect(&quot;Unable to read file&quot;);

let ast = syn::parse_file(&amp;#x26;src).unwrap();
if let Some(shebang) = ast.shebang {
    println!(&quot;{}&quot;, shebang);
}
println!(&quot;{} items&quot;, ast.items.len());
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;DeriveInput for proc_macro_derive&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;#[proc_macro_derive(HeapSize)]
pub fn derive_heap_size(input: proc_macro::TokenStream) -&gt; proc_macro::TokenStream {
    // Parse the input tokens into a syntax tree.
    let input = parse_macro_input!(input as DeriveInput);

    // Used in the quasi-quotation below as `#name`.
    let name = input.ident;

    // Add a bound `T: HeapSize` to every type parameter T.
    let generics = add_trait_bounds(input.generics);
    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();

    // Generate an expression to sum up the heap size of each field.
    let sum = heap_size_sum(&amp;#x26;input.data);

    let expanded = quote! {
        // The generated impl.
        ...
    };

    // Hand the output tokens back to the compiler.
    proc_macro::TokenStream::from(expanded)
}

&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;fold 可以在语法转换时hook&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;impl Fold for Args {
    // 处理expr类型时
    fn fold_expr(&amp;#x26;mut self, e: Expr) -&gt; Expr {
        match e {
            Expr::Assign(e) =&gt; {
                if self.should_print_expr(&amp;#x26;e.left) {
                    self.assign_and_print(*e.left, &amp;#x26;e.eq_token, *e.right)
                } else {
                    Expr::Assign(fold::fold_expr_assign(self, e))
                }
            }
            Expr::Binary(e) if is_assign_op(e.op) =&gt; {
                if self.should_print_expr(&amp;#x26;e.left) {
                    self.assign_and_print(*e.left, &amp;#x26;e.op, *e.right)
                } else {
                    Expr::Binary(fold::fold_expr_binary(self, e))
                }
            }
            _ =&gt; fold::fold_expr(self, e),
        }
    }
    // 处理stmt类型
    fn fold_stmt(&amp;#x26;mut self, s: Stmt) -&gt; Stmt {
        match s {
            Stmt::Local(s) =&gt; {
                if s.init.is_some() &amp;#x26;&amp;#x26; self.should_print_pat(&amp;#x26;s.pat) {
                    self.let_and_print(s)
                } else {
                    Stmt::Local(fold::fold_local(self, s))
                }
            }
            _ =&gt; fold::fold_stmt(self, s),
        }
    }
}


&lt;/code&gt;&lt;/pre&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>关于data sync那些不得不说的故事</title><link>https://realcpf.tech/blog/the-data-sync</link><guid isPermaLink="true">https://realcpf.tech/blog/the-data-sync</guid><description>关于data sync那些不得不说的故事</description><pubDate>Wed, 28 Feb 2024 18:20:00 GMT</pubDate><content:encoded>&lt;h3&gt;DataX&lt;/h3&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/alibaba/DataX/blob/master/introduction.md&quot;&gt;DataX&lt;/a&gt; is a batch sync framework also an efficient and concise solution&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;&lt;img src=&quot;/article-img/ec7e36f4-6927-11e6-8f5f-ffc43d6a468b.png&quot; alt=&quot;design&quot;&gt;&lt;/p&gt;
&lt;h4&gt;这是一个极其简化的代码示例 &lt;code&gt;reader -&gt; queue -&gt; writer&lt;/code&gt;&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class DemoTransport {

    // demo Exchanger
    private class DemoExchanger {
        // 用于从reader到writer传输record的队列
        private final BlockingQueue&amp;#x3C;Object&gt; queue = new ArrayBlockingQueue&amp;#x3C;&gt;(128);
        // writer
        private final Runnable writer = new Runnable() {
            private final int batchSize = 4;
            // record接收器
            private Object rev(){
                return doPoll();
            }
            @Override
            public void run() {
                System.out.println(&quot;writer:&quot;);
                Object o;
                // 写入批
                List&amp;#x3C;Object&gt; batch = new ArrayList&amp;#x3C;&gt;(batchSize);
                while (null != (o = rev())) {
                    batch.add(o);
                    if (batch.size() &gt;= batchSize) {
                        batch.forEach(System.out::println);
                        batch.clear();
                    }
                }
                if (batch.size() &gt;= batchSize) {
                    batch.forEach(System.out::println);
                    batch.clear();
                }
            }
        };

        // reader
        private final Runnable reader = new Runnable() {
            // record 发送器
            private void send(Object o){
                doPush(o);
            }
            @Override
            public void run() {
                Random random = new Random();
                int i = 0;
                System.out.println(&quot;reader:&quot;);
                // 生成数据
                while (true) {
                    if (i &gt; 12) {
                        i = 0;
                    }
                    send(random.nextLong());
                    i++;
                }

            }
        };

        /**
         * reader push
         * @param o record
         */
        private void doPush(Object o) {
            try {
                queue.put(o);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new IllegalStateException(e);
            }
        }
        /**
         * writer poll
         * @return
         */
        private Object doPoll() {
            try {
                return queue.take();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new IllegalStateException(e);
            }
        }
        public void test(){

            Thread writerThread = new Thread(writer);
            Thread readerThread = new Thread(reader);
            //先启动writer 再启动reader
            writerThread.start();
            readerThread.start();

        }

    }
}

&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;reader&lt;/h4&gt;
&lt;blockquote&gt;
&lt;p&gt;https://github.com/alibaba/DataX/blob/master/dataxPluginDev.md&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;&lt;img src=&quot;/article-img/ec7e36f4-6927-11e6-8f5f-ffc43d6a468b.png&quot; alt=&quot;datax_framework_new&quot;&gt;&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;关于分片这里有一个可供参考的计算方法&lt;a href=&quot;https://github.com/alibaba/DataX/blob/82680c4c634197bb4ba983866eb8b8e17d6bfd06/plugin-rdbms-util/src/main/java/com/alibaba/datax/plugin/rdbms/reader/util/ReaderSplitUtil.java#L16&quot;&gt;ReaderSplitUtil&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;

import com.alibaba.datax.common.element.Column;
import com.alibaba.datax.common.element.Record;
import com.alibaba.datax.common.element.StringColumn;
import com.alibaba.datax.common.plugin.RecordSender;
import com.alibaba.datax.common.spi.Reader;
import com.alibaba.datax.common.util.Configuration;

import java.util.List;


public class DemoReader extends Reader{
    // job
    // 需要实现的方法有
    // split(int i) 分片方法
    // init() 初始化
    // destroy() 销毁
    public static class Job extends Reader.Job{
        private Configuration originalConfig;
        @Override
        public List&amp;#x3C;Configuration&gt; split(int i) {
            return null;
        }

        @Override
        public void init() {
            this.originalConfig = this.getPluginJobConf();
        }

        @Override
        public void destroy() {

        }
    }
    // Task
    // 需要实现的方法
    // startRead(RecordSender recordSender) reader的开始方法
    // 这里会生成Record 送往Writer
    // init() 初始化
    // destroy() 销毁
    public static class Task extends Reader.Task {
        private Configuration readerSliceConfig;
        @Override
        public void startRead(RecordSender recordSender) {
            Record record = recordSender.createRecord();
            //
            Column column = new StringColumn(&quot;&quot;);
            record.addColumn(column);

            recordSender.sendToWriter(record);
        }

        @Override
        public void init() {
            this.readerSliceConfig = super.getPeerPluginJobConf();
            // init
        }

        @Override
        public void destroy() {

        }
    }
}

&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;writer&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;
import com.alibaba.datax.common.element.Record;
import com.alibaba.datax.common.plugin.RecordReceiver;
import com.alibaba.datax.common.spi.Writer;
import com.alibaba.datax.common.util.Configuration;

import java.util.List;

public class DemoWriter extends Writer {
    // init split destroy
    public static class Job extends Writer.Job{
        private Configuration originalConfig;

        @Override
        public List&amp;#x3C;Configuration&gt; split(int i) {
            return null;
        }

        @Override
        public void init() {
            this.originalConfig = this.getPluginJobConf();
        }

        @Override
        public void destroy() {

        }
    }
    // startWrite init destroy
    public static class Task extends Writer.Task {
        private Configuration writerSliceConfig;
        @Override
        public void startWrite(RecordReceiver recordReceiver) {
            Record record = recordReceiver.getFromReader();
            String s = record.getColumn(0).asString();

        }

        @Override
        public void init() {
            this.writerSliceConfig = super.getPluginJobConf();
        }

        @Override
        public void destroy() {

        }
    }
}


&lt;/code&gt;&lt;/pre&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>关于doc ops那些不得不说的故事</title><link>https://realcpf.tech/blog/the-doc-ops</link><guid isPermaLink="true">https://realcpf.tech/blog/the-doc-ops</guid><description>关于doc ops那些不得不说的故事</description><pubDate>Wed, 28 Feb 2024 18:20:00 GMT</pubDate><content:encoded>&lt;h3&gt;Excelize&lt;/h3&gt;
&lt;h4&gt;设置单元格的值&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-go&quot;&gt;
func DemoExcelCreate() {
	fmt.Println(&quot;hello&quot;)

	f := excelize.NewFile()

	defer func() {
		if err := f.Close(); err != nil {
			fmt.Println(err)
		}
	}()

	sheetName := &quot;MySheet&quot;

	index, err := f.NewSheet(sheetName)
	if err != nil {
		fmt.Println(err)
	}

	// 设置指定单元格的值 需要 sheetName 座标
	f.SetCellValue(sheetName, &quot;A2&quot;, &quot;Hello World&quot;)
	f.SetCellValue(sheetName, &quot;B2&quot;, 100)

	f.SetActiveSheet(index)

	if err := f.SaveAs(&quot;tmp/excelize.xlsx&quot;); err != nil {
		fmt.Println(err)
	}

}

&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;读取单元格的值&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-go&quot;&gt;
func DemoExcelRead() {

	f, err := excelize.OpenFile(&quot;tmp/excelize.xlsx&quot;)

	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() {
		if err := f.Close(); err != nil {
			fmt.Println(err)
		}
	}()

	sheetName := &quot;MySheet&quot;

	// 读取指定单元格的值 需要 sheetName 座标
	cell, err := f.GetCellValue(sheetName, &quot;B2&quot;)
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(cell)

	// 也可以获取整个sheet的数据
	rows, err := f.GetRows(sheetName)
	if err != nil {
		fmt.Println(err)
		return
	}

	// 便利表格
	for _, row := range rows {
		for _, colCell := range row {
			fmt.Print(colCell, &quot;\t&quot;)
		}
		fmt.Println()
	}

}
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;在Libre Office中创建chart图如下&lt;/h4&gt;
&lt;p&gt;&lt;img src=&quot;/image/excel-series-1.png&quot; alt=&quot;excel-series&quot;&gt;&lt;/p&gt;
&lt;h4&gt;根据表格数据创建chart&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-go&quot;&gt;
func DemoMakeChart() {
	f := excelize.NewFile()
	defer func() {
		if err := f.Close(); err != nil {
			fmt.Println(err)
		}
	}()

	data := [][]interface{}{
		{nil, &quot;Apple&quot;, &quot;Orange&quot;, &quot;Pear&quot;}, {&quot;Small&quot;, 2, 3, 3},
		{&quot;Normal&quot;, 5, 2, 4}, {&quot;Large&quot;, 6, 7, 8},
	}

	index, err := f.NewSheet(&quot;DemoSheet&quot;)
	if err != nil {
		fmt.Println(err)
		return
	}
	f.SetActiveSheet(index)

	for idx, row := range data {
		// 坐标到单元格名称将 [X， Y] 坐标转换为单元格
		cell, err := excelize.CoordinatesToCellName(1, idx+1)
		if err != nil {
			fmt.Println(err)
			return
		}
		// 设置一行数据
		f.SetSheetRow(&quot;DemoSheet&quot;, cell, &amp;#x26;row)
	}

	chartSeries := []excelize.ChartSeries{
		{
			Name:       &quot;DemoSheet!$A$2&quot;,
			Categories: &quot;DemoSheet!$B$1:$D$1&quot;, // 和图里对应
			Values:     &quot;DemoSheet!$B$2:$D$2&quot;,
		},
		{
			Name:       &quot;DemoSheet!$A$3&quot;,
			Categories: &quot;DemoSheet!$B$1:$D$1&quot;,
			Values:     &quot;DemoSheet!$B$3:$D$3&quot;,
		},
		{
			Name:       &quot;DemoSheet!$A$4&quot;,
			Categories: &quot;DemoSheet!$B$1:$D$1&quot;,
			Values:     &quot;DemoSheet!$B$4:$D$4&quot;,
		},
	}

	if err := f.AddChart(&quot;DemoSheet&quot;, &quot;E1&quot;, &amp;#x26;excelize.Chart{
		Type:   excelize.Col3DClustered,
		Series: chartSeries,
		Title: excelize.ChartTitle{
			Name: &quot;My Demo 3D Chart&quot;,
		},
	}); err != nil {
		fmt.Println(err)
	}

	if err := f.SaveAs(&quot;tmp/abc.xlsx&quot;); err != nil {
		fmt.Println(err)
	}

}
// 插入图片
func DemoInsertImg() {
	f, err := excelize.OpenFile(&quot;tmp/excelize.xlsx&quot;)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() {
		if err := f.Close(); err != nil {
			fmt.Println(err)
		}
	}()
	// 插入图片
	if err := f.AddPicture(&quot;Sheet1&quot;, &quot;A2&quot;, &quot;image.png&quot;, nil); err != nil {
		fmt.Println(err)
		return
	}
	// 在工作表中插入图片，并设置图片的缩放比例
	if err := f.AddPicture(&quot;Sheet1&quot;, &quot;D2&quot;, &quot;image.jpg&quot;,
		&amp;#x26;excelize.GraphicOptions{ScaleX: 0.5, ScaleY: 0.5}); err != nil {
		fmt.Println(err)
		return
	}
	// 在工作表中插入图片，并设置图片的打印属性
	enable, disable := true, false
	if err := f.AddPicture(&quot;Sheet1&quot;, &quot;H2&quot;, &quot;image.gif&quot;,
		&amp;#x26;excelize.GraphicOptions{
			PrintObject:     &amp;#x26;enable,
			LockAspectRatio: false,
			OffsetX:         15,
			OffsetY:         10,
			Locked:          &amp;#x26;disable,
		}); err != nil {
		fmt.Println(err)
		return
	}
	// 保存文件
	if err = f.Save(); err != nil {
		fmt.Println(err)
	}
}

func DemoTemplate1() {
	f := excelize.NewFile()
	defer func() {
		if err := f.Close(); err != nil {
			fmt.Println(err)
		}
	}()

	index, err := f.NewSheet(&quot;Sheet1&quot;)
	if err != nil {
		fmt.Println(err)
	}
	f.SetActiveSheet(index)

	row := []interface{}{&quot;col1&quot;, &quot;col2&quot;, &quot;col3&quot;}
	f.SetSheetRow(&quot;Sheet1&quot;, &quot;A1&quot;, &amp;#x26;row)

	if err := f.SaveAs(&quot;Book1.xlsx&quot;); err != nil {
		fmt.Println(err)
	}

}


&lt;/code&gt;&lt;/pre&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>关于actor那些不得不说的故事</title><link>https://realcpf.tech/blog/the-actor</link><guid isPermaLink="true">https://realcpf.tech/blog/the-actor</guid><description>关于actor那些不得不说的故事</description><pubDate>Wed, 28 Feb 2024 18:16:00 GMT</pubDate><content:encoded>&lt;h3&gt;Actix - actor in rust&lt;/h3&gt;
&lt;h4&gt;Actor 创建并发送和接收消息&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;
struct MyActor{
    count:usize
}

///
/// Actor
impl Actor for MyActor {
    // 每个actor都有一个context
    type Context = Context&amp;#x3C;Self&gt;;
}

#[derive(Message)]
#[rtype(result = &quot;usize&quot;)]
struct Ping(usize);



impl Handler&amp;#x3C;Ping&gt; for MyActor {
    type Result = usize;

    ///
    /// 接受Ping类型的消息 然后返回usize
    fn handle(&amp;#x26;mut self, msg: Ping, ctx: &amp;#x26;mut Self::Context) -&gt; Self::Result {
        self.count += msg.0;
        self.count
    }
}


&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;发送，接收处理&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;
#[actix::test]
async fn test1(){
    // 开启新的actor并且返回地址也就近似于akka 中的 ActorRef
    let addr = MyActor { count:10}.start();

    // send 然后handler处理返回
    let res = addr.send(Ping(10)).await;

    print!(&quot;Res : {}\n&quot;,res.unwrap());

    let id = System::current().id();

    print!(&quot;id:{} will stop&quot;,id);

    System::current().stop();
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;生命周期函数&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;///
/// 生命周期有
/// + Started
/// + Running
/// + Stopping
/// + Stopped
///
/// 重写生命周期函数started,stopped
impl Actor for MineActor {
    type Context = Context&amp;#x3C;Self&gt;;

    fn started(&amp;#x26;mut self, ctx: &amp;#x26;mut Self::Context) {
        println!(&quot;started&quot;);
    }
    fn stopped(&amp;#x26;mut self, ctx: &amp;#x26;mut Self::Context) {
        println!(&quot;stopped&quot;)
    }
}



&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;可Response的Message&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;
///
/// 为了可以返回Responses 我们为Responses实现MessageResponse
impl&amp;#x3C;A,M&gt; MessageResponse&amp;#x3C;A,M&gt; for Responses
where A:Actor,
        M:Message&amp;#x3C;Result = Responses&gt; {
    fn handle(self, ctx: &amp;#x26;mut &amp;#x3C;A as Actor&gt;::Context, tx: Option&amp;#x3C;actix::dev::OneshotSender&amp;#x3C;&amp;#x3C;M as Message&gt;::Result&gt;&gt;) {
        if let Some(tx) = tx {
            tx.send(self);
        }
    }
}

&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;两个Actor互相发的结构&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;
use actix::prelude::*;
use std::time::Duration;

#[derive(Message)]
#[rtype(result = &quot;()&quot;)]
struct Ping {
    pub id: usize,
}

struct Game {
    counter: usize,
    name: String,
    // 给其他actor发送
    recipient: Recipient&amp;#x3C;Ping&gt;,
}

impl Actor for Game {
    type Context = Context&amp;#x3C;Game&gt;;
}

impl Handler&amp;#x3C;Ping&gt; for Game {
    type Result = ();

    fn handle(&amp;#x26;mut self, msg: Ping, ctx: &amp;#x26;mut Context&amp;#x3C;Self&gt;) {
        self.counter += 1;

        if self.counter &gt; 10 {
            System::current().stop();
        } else {
            println!(&quot;[{0}] Ping received {1}&quot;, self.name, msg.id);

            ctx.run_later(Duration::new(0, 100), move |act, _| {
                // 给recipient发 在这个例子里就是 另一个Game Actor
                act.recipient.do_send(Ping { id: msg.id + 1 });
            });
        }
    }
}

&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;示例互啄术&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;
///
/// game 互啄
fn main() {
    let mut system = System::new();
    let addr = system.block_on(async {
        Game::create(|ctx| {
            // game1 的 addr
            let addr = ctx.address();

            // game2
            let addr2 = Game {
                counter: 0,
                name: String::from(&quot;Game 2&quot;),
                // game1 的 recipient
                recipient: addr.recipient(),
            }
            .start();

            // game2 先发送
            addr2.do_send(Ping { id: 10 });

            Game {
                counter: 0,
                name: String::from(&quot;Game 1&quot;),
                recipient: addr2.recipient(),
            }
        });
    });

    system.run();
}

&lt;/code&gt;&lt;/pre&gt;
&lt;h5&gt;Arbiter&lt;/h5&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;    let sys = System::new();

    let exec = async {
        TheActor.start();
    };

    // 使用Arbiter管理Actor
    let arbiter = Arbiter::new();

    Arbiter::spawn(&amp;#x26;arbiter, exec);


    System::current().stop();

    sys.run();
&lt;/code&gt;&lt;/pre&gt;
&lt;h5&gt;SyncArbiter&lt;/h5&gt;
&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;
use actix::prelude::*;

struct MySyncActor;

impl Actor for MySyncActor {
    type Context = SyncContext&amp;#x3C;Self&gt;;
}
// 线程数2则可以有同时两个Actor在处理
let addr = SyncArbiter::start(2, || MySyncActor);

&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Akka - actor in jvm&lt;/h3&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;a href=&quot;https://pekko.apache.org/index.html&quot;&gt;Apache Pekko&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h5&gt;创建&lt;/h5&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;import akka.actor.AbstractActor;
import akka.actor.Props;

import java.time.Duration;

public class DemoRev extends AbstractActor {
    public DemoRev(){
        // 设置接收消息的超时时间
        getContext().setReceiveTimeout(Duration.ofSeconds(10));
    }
    /**
     * 用于创建ActorRef
    **/
    public static Props props(){
        return Props.create(DemoRev.class, DemoRev::new);
    }
    @Override
    public Receive createReceive() {
        return receiveBuilder()
                .match(String.class ,//如果是string类型
                r-&gt;{
                    System.out.println(&quot;rev :&quot; + r);
                    getSender().tell(&quot;rev done&quot;,getSelf());
                }).match(Integer.class, // 如果是Interger类型
                r-&gt;{
                    getSender().tell(&quot;give me more!&quot;,getSelf());
                }).matchAny(a-&gt;{ // 其他
                    System.out.println(&quot;any&quot;);
                }).build();
    }
}


&lt;/code&gt;&lt;/pre&gt;
&lt;h5&gt;传递消息&lt;/h5&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;ActorSystem system = ActorSystem.create(&quot;linux&quot;);
// 创建
ActorRef p1 = system.actorOf(DemoRev.props());
ActorRef s1 = system.actorOf(DemoSend.props());
// s1 -&gt; p1
p1.tell(&quot;hello&quot;,s1);
system.terminate();
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Inbox 消息&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;
ActorSystem system = ActorSystem.create(&quot;linux&quot;);
ActorRef p1 = system.actorOf(DemoRev.props());

final Inbox inbox = Inbox.create(system);
// inbox也是一个actor
inbox.send(p1,&quot;hello&quot;);

System.out.println(inbox.receive(Duration.ofSeconds(1)));
system.terminate();

&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;周期性消息&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;import akka.actor.AbstractActorWithTimers;

import java.time.Duration;

public class DemoTimer extends AbstractActorWithTimers {
    private static Object TICK_KEY = &quot;TickKey&quot;;

    private static final class FirstTick {}

    private static final class Tick {}

    public DemoTimer(){
        // 相当于settimeout
        getTimers().startSingleTimer(TICK_KEY,new FirstTick(), Duration.ofMillis(500));
    }

    @Override
    public Receive createReceive() {
        return receiveBuilder().match(
                FirstTick.class,
                message -&gt; {
                    // 周期执行
                    getTimers().startPeriodicTimer(TICK_KEY,new Tick(),Duration.ofSeconds(1));
                }
        ).match(Tick.class,message -&gt; {
            System.out.println(message);
        }).build();
    }
}



&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;生命周期&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;import akka.actor.AbstractActor;
import akka.actor.Props;

public class StartStopActor1 extends AbstractActor {
    static Props props() {
        return Props.create(StartStopActor1.class, StartStopActor1::new);
    }
    // 启动hock
    @Override
    public void preStart() throws Exception {
        System.out.printf(&quot;start %s \n&quot;,getSelf().path().toSerializationFormat());
        getContext().actorOf(StartStopActor2.props(),&quot;second&quot;);
    }
    // 停止hock
    @Override
    public void postStop() throws Exception {
        System.out.printf(&quot;stop %s \n&quot;,getSelf().path().toSerializationFormat());
    }

    /*

    也可以用信号停止
     victim.tell(akka.actor.PoisonPill.getInstance(), ActorRef.noSender());
    */

    @Override
    public Receive createReceive() {
        return receiveBuilder()
                .matchEquals(&quot;stop&quot;,s-&gt;{
                    getContext().stop(getSelf());
                }).build();
    }
}

&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Receive&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;// 支持动态改变receive方法
public Receive createReceive() {
return receiveBuilder()
    .matchEquals(
        &quot;init&quot;,
        m1 -&gt; {
            initializeMe = &quot;Up and running&quot;;
            getContext()
                .become(
                    receiveBuilder()
                        .matchEquals(
                            &quot;U OK?&quot;,
                            m2 -&gt; {
                            getSender().tell(initializeMe, getSelf());
                            })
                        .build());
        })
    .build();
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;ask , pipie&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;

import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import scala.Tuple2;
import tech.realcpf.sendrev.DemoRev;
import tech.realcpf.sendrev.DemoSend;

import static akka.pattern.Patterns.ask;
import static akka.pattern.Patterns.pipe;

import java.time.Duration;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;

public class AskDemo {
    public static void main(String[] args) {
        ActorSystem system = ActorSystem.create(&quot;sys&quot;);
        ActorRef actorA = system.actorOf(DemoRev.props());
        ActorRef actorB = system.actorOf(DemoRev.props());
        ActorRef actorC = system.actorOf(DemoRev.props());
        CompletableFuture&amp;#x3C;Object&gt; future1 =
                ask(actorA,&quot;hi A&quot;, Duration.ofMillis(1000)).toCompletableFuture();
        CompletableFuture&amp;#x3C;Object&gt; future2 =
                ask(actorB,&quot;hi B&quot;, Duration.ofMillis(1000)).toCompletableFuture();

        CompletableFuture&amp;#x3C;Tuple2&amp;#x3C;String,String&gt;&gt; transformed =
                CompletableFuture.allOf(future1,future2)
                        .thenApply(v-&gt;{
                           String x = (String) future1.join();
                           String s = (String) future2.join();
                           return new Tuple2(x,s);
                        });

        pipe(transformed,system.dispatcher()).to(actorC);

        system.terminate();
    }
}

&lt;/code&gt;&lt;/pre&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>关于kafka那些不得不说的故事</title><link>https://realcpf.tech/blog/the-kafka</link><guid isPermaLink="true">https://realcpf.tech/blog/the-kafka</guid><description>关于kafka那些不得不说的故事</description><pubDate>Wed, 03 Jan 2024 18:16:00 GMT</pubDate><content:encoded>&lt;h3&gt;查看Topic&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;
private static void testCreateTopic() {

/**
 * bin/kafka-topics.sh --create \
 *     --bootstrap-server localhost:9092 \
 *     --replication-factor 1 \
 *     --partitions 1 \
 *     --topic streams-wordcount-output \
 *     --config cleanup.policy=compact
 */
    Properties props = new Properties();
    props.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, &quot;localhost:9092&quot;);

    try (Admin admin = Admin.create(props)) {
        String topicName = &quot;create-topic-with-java&quot;;
        int partitions = 1;
        short replicationFactor = 1;
        // Create a compacted topic
        CreateTopicsResult result = admin.createTopics(Collections.singleton(
                new NewTopic(topicName, partitions, replicationFactor)
                        .configs(Collections.singletonMap(TopicConfig.CLEANUP_POLICY_CONFIG,
                                TopicConfig.CLEANUP_POLICY_COMPACT))));

        // Call values() to get the result for a specific topic
        KafkaFuture&amp;#x3C;Void&gt; future = result.values().get(topicName);

        // Call get() to block until the topic creation is complete or has failed
        // if creation failed the ExecutionException wraps the underlying cause.
        future.get();
    } catch (ExecutionException e) {
        throw new RuntimeException(e);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }

}

&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;创建Topic&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;/**
 * bin/kafka-topics.sh --bootstrap-server localhost:9092 --describe
 */
private static void testTopicDescribe() {

    /*
    bin/kafka-topics.sh --bootstrap-server localhost:9092 --describe
    */
    Properties props = new Properties();
    props.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, &quot;localhost:9092&quot;);

    try (Admin admin = Admin.create(props)) {
            ListTopicsResult result = admin.listTopics();
        result.namesToListings().whenComplete(((stringTopicListingMap, throwable) -&gt; {

            for (Map.Entry&amp;#x3C;String, TopicListing&gt; entity:stringTopicListingMap.entrySet()) {
                System.out.println(entity.getKey());
                System.out.println(entity.getValue().topicId());
                System.out.println(entity.getValue().name());
                System.out.println(entity.getValue());

                System.out.println(&quot;------------------------------------------&quot;);
            }
        }));
    } catch (Throwable e) {
        throw new RuntimeException(e);
    }

}

&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;删除Topic&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;
private static void testTopicDelete() {


    Properties props = new Properties();
    props.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, &quot;localhost:9092&quot;);

    try (Admin admin = Admin.create(props)) {

        TopicCollection topicCollection = TopicCollection.ofTopicNames(
                Collections.singleton(&quot;create-topic-with-java&quot;));
        DeleteTopicsResult result = admin.deleteTopics(topicCollection);
        result.all().whenComplete((r,t) -&gt;{
            if (t != null) {
                t.printStackTrace();
            }
            System.out.println(&quot;delete done!&quot;);
        });
    } catch (Throwable e) {
        throw new RuntimeException(e);
    }


}

&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;基本消费者代码&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;

private static void testAutoConsumer(){

    // 配置属性
    Properties props = new Properties();
    props.setProperty(&quot;bootstrap.servers&quot;, &quot;localhost:9092&quot;);
    props.setProperty(&quot;group.id&quot;, &quot;test&quot;);
    props.setProperty(&quot;enable.auto.commit&quot;, &quot;true&quot;);
    props.setProperty(&quot;auto.commit.interval.ms&quot;, &quot;1000&quot;);
    props.setProperty(&quot;key.deserializer&quot;, &quot;org.apache.kafka.common.serialization.StringDeserializer&quot;);
    props.setProperty(&quot;value.deserializer&quot;, &quot;org.apache.kafka.common.serialization.StringDeserializer&quot;);

    try(KafkaConsumer&amp;#x3C;String, String&gt; consumer = new KafkaConsumer&amp;#x3C;&gt;(props)) {
        // 订阅
        consumer.subscribe(Arrays.asList(&quot;quickstart-events&quot;));
        while (true) {
            // 拉取
            ConsumerRecords&amp;#x3C;String, String&gt; records = consumer.poll(Duration.ofMillis(100));
            for (ConsumerRecord&amp;#x3C;String, String&gt; record : records)
                System.out.printf(&quot;offset = %d, key = %s, value = %s%n&quot;, record.offset(), record.key(), record.value());
        }
    }

}

&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;更详细的消费控制&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt; private static void testManualConsumer() {

    Properties props = new Properties();

    props.setProperty(&quot;bootstrap.servers&quot;, &quot;localhost:9092&quot;);
    props.setProperty(&quot;group.id&quot;, &quot;test&quot;);
    props.setProperty(&quot;enable.auto.commit&quot;, &quot;false&quot;);
    props.setProperty(&quot;key.deserializer&quot;, &quot;org.apache.kafka.common.serialization.StringDeserializer&quot;);
    props.setProperty(&quot;value.deserializer&quot;, &quot;org.apache.kafka.common.serialization.StringDeserializer&quot;);
    KafkaConsumer&amp;#x3C;String, String&gt; consumer = new KafkaConsumer&amp;#x3C;&gt;(props);

    consumer.subscribe(Arrays.asList(&quot;quickstart-events&quot;), new ConsumerRebalanceListener() {
        @Override
        public void onPartitionsRevoked(Collection&amp;#x3C;TopicPartition&gt; collection) {
            for (TopicPartition part:collection) {
                // 获取offset 可以自行处理
                Long currOffset = consumer.position(part);
                // we can save the offset in own db
            }
        }

        @Override
        public void onPartitionsAssigned(Collection&amp;#x3C;TopicPartition&gt; collection) {

//                consumer.seekToBeginning(collection);
            for (TopicPartition part:collection) {
                // get offset from own db
                // 可以从自己的系统取得offset 以达将offset与业务系统进行关联
                Long currOffset = 0L;
                consumer.seek(part,currOffset);
            }

        }
    });
    // 按照批去
    final int minBatchSize = 10;

    List&amp;#x3C;ConsumerRecord&amp;#x3C;String, String&gt;&gt; buffer = new ArrayList&amp;#x3C;&gt;();
    while (true) {
        ConsumerRecords&amp;#x3C;String, String&gt; records = consumer.poll(Duration.ofMillis(100));
        for (ConsumerRecord&amp;#x3C;String, String&gt; record : records) {
            buffer.add(record);
        }
        if (buffer.size() &gt;= minBatchSize) {
            printThis(buffer);
            // 手动提交
            consumer.commitAsync();
            buffer.clear();
        }
    }

}

&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;指定分区&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    // 指定分区
String topic = &quot;foo&quot;;
TopicPartition partition0 = new TopicPartition(topic, 0);
TopicPartition partition1 = new TopicPartition(topic, 1);
consumer.assign(Arrays.asList(partition0, partition1));
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;基本生产者&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;
Properties props = new Properties();
props.put(&quot;bootstrap.servers&quot;, &quot;localhost:9092&quot;);
props.put(&quot;linger.ms&quot;, 1);
props.put(&quot;key.serializer&quot;, &quot;org.apache.kafka.common.serialization.StringSerializer&quot;);
props.put(&quot;value.serializer&quot;, &quot;org.apache.kafka.common.serialization.StringSerializer&quot;);


try(Producer&amp;#x3C;String, String&gt; producer = new KafkaProducer&amp;#x3C;&gt;(props)){
    for (int i = 0; i &amp;#x3C; 100; i++) {
        producer.send(new ProducerRecord&amp;#x3C;String, String&gt;(&quot;quickstart-events&quot;, Integer.toString(i), Integer.toString(i)));
    }
    producer.flush();
}

&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;事务&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;private static void testTransactions(){

    Properties props = new Properties();
    props.put(&quot;bootstrap.servers&quot;, &quot;localhost:9092&quot;);
    props.put(&quot;transactional.id&quot;, &quot;my-transactional-id&quot;);
    try(Producer&amp;#x3C;String, String&gt; producer = new KafkaProducer&amp;#x3C;&gt;(props, new StringSerializer(), new StringSerializer())) {
        producer.initTransactions();

        producer.beginTransaction();
        for (int i = 0;i&amp;#x3C;10;i++){
            producer.send(new ProducerRecord&amp;#x3C;&gt;(&quot;quickstart-events&quot;,Integer.toString(i),Integer.toString(i)));
        }
        producer.commitTransaction();
    } catch (ProducerFencedException | OutOfOrderSequenceException | AuthorizationException e) {

    } catch (KafkaException e) {

    }

}


&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Stream 基本结构&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;// 属性配置
Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, &quot;streams-wordcount&quot;);
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, &quot;localhost:9092&quot;);
props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass());

// stream 构建器
final StreamsBuilder builder = new StreamsBuilder();

// builder.stream(&quot;Source-Topic&quot;).xxx.xxx.to(&quot;Sink-Topic&quot;)
builder.&amp;#x3C;String, String&gt;stream(&quot;streams-plaintext-input&quot;)
        .flatMapValues(value -&gt; Arrays.asList(value.toLowerCase(Locale.getDefault()).split(&quot;\\W+&quot;)))
        .groupBy((key, value) -&gt; value)
        .count(Materialized.&amp;#x3C;String, Long, KeyValueStore&amp;#x3C;Bytes, byte[]&gt;&gt;as(&quot;counts-store&quot;))
        .toStream()
        .to(&quot;streams-wordcount-output&quot;, Produced.with(Serdes.String(), Serdes.Long()));

final Topology topology = builder.build();
final KafkaStreams streams = new KafkaStreams(topology, props);
final CountDownLatch latch = new CountDownLatch(1);

// attach shutdown handler to catch control-c
Runtime.getRuntime().addShutdownHook(new Thread(&quot;streams-shutdown-hook&quot;) {
    @Override
    public void run() {
        streams.close();
        latch.countDown();
    }
});

try {
    streams.start();
    latch.await();
} catch (Throwable e) {
    System.exit(1);
}
System.exit(0);

&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Processor&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;

public class WorldCountProcessor implements Processor&amp;#x3C;String,String,String,String&gt; {
    private KeyValueStore&amp;#x3C;String,Integer&gt; keyValueStore;

    @Override
    public void process(Record&amp;#x3C;String,String&gt; record) {

        final String[] words =
                record.value().toUpperCase(Locale.ROOT).split(&quot;\\W+&quot;);
        for (final String word:words) {
            final Integer oldValue = keyValueStore.get(word);
            if (oldValue == null) {
                keyValueStore.put(word,1);
            }else {
                keyValueStore.put(word,oldValue + 1);
            }
        }

    }

    @Override
    public void close() {

    }

    @Override
    public void init(ProcessorContext context) {
        context.schedule(Duration.ofSeconds(1),
                PunctuationType.STREAM_TIME,
                timestamp -&gt;{
                    try(final KeyValueIterator&amp;#x3C;String,Integer&gt; iter = keyValueStore.all()) {
                        while (iter.hasNext()) {
                            final KeyValue&amp;#x3C;String,Integer&gt; entry = iter.next();
                            context.forward(new Record(entry.key,entry.value.toString(),timestamp));
                        }
                    }
                });
        keyValueStore = context.getStateStore(&quot;Counts&quot;);
    }
}


&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Topology use Processor&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;Topology builder = new Topology();
    final StoreBuilder&amp;#x3C;KeyValueStore&amp;#x3C;String, Long&gt;&gt; countsStoreBuilder =
            Stores
                    .keyValueStoreBuilder(
                            Stores.persistentKeyValueStore(&quot;Counts&quot;),
                            Serdes.String(),
                            Serdes.Long()
                    );
    builder.addSource(&quot;Source&quot;,&quot;source-topic&quot;)
            .addProcessor(&quot;Processor&quot;, () -&gt; new WorldCountProcessor(),&quot;Source&quot;)
            .addStateStore(countsStoreBuilder,&quot;Process&quot;)
            .addSink(&quot;Sink&quot;,&quot;sink-topic&quot;,&quot;Process&quot;);

&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Kafka 设计思想&lt;/h3&gt;
&lt;blockquote&gt;
&lt;p&gt;https://kafka.apache.org/documentation/#design&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h4&gt;&lt;a href=&quot;https://kafka.apache.org/documentation/#design_pull&quot;&gt;Poll or Push&lt;/a&gt;&lt;/h4&gt;
&lt;h4&gt;&lt;a href=&quot;https://kafka.apache.org/documentation/#messageformat&quot;&gt;Message Format&lt;/a&gt;&lt;/h4&gt;
&lt;h4&gt;log 文件&lt;/h4&gt;
&lt;p&gt;&lt;img src=&quot;/article-img/kafka_log.png&quot; alt=&quot;log_file&quot;&gt;&lt;/p&gt;
&lt;h3&gt;&lt;a href=&quot;https://kafka.apache.org/35/documentation/streams/developer-guide/testing&quot;&gt;Test Driver&lt;/a&gt;&lt;/h3&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>关于kotlin那些不得不说的故事</title><link>https://realcpf.tech/blog/the-kotlin</link><guid isPermaLink="true">https://realcpf.tech/blog/the-kotlin</guid><description>关于kotlin那些不得不说的故事</description><pubDate>Wed, 03 Jan 2024 18:16:00 GMT</pubDate><content:encoded>&lt;h4&gt;kotlin compose&lt;/h4&gt;
&lt;h4&gt;启动入口&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;
/*
 main函数运行

 */
fun main() =
    //An entry point for the Compose application.
    // 启动函数
    application {
        // window
    Window(title = &quot;first demo&quot;,
        onCloseRequest = ::exitApplication,
        ) {
        // window &gt; 组件
        App()
    }
}


&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;组件&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;
/**
 * @Composable 组件注解 给函数加上注解就代表一个页面组件
 * @Preview 可以借助IDEA上的插件进行组件预览
 */
@Composable
@Preview
fun App() {

    // 计算 状态 当值变化并需要页面变得时会重新运行相关作用域代码的这个组件
    var text by remember { mutableStateOf(&quot;Hello, World!&quot;) }
    println(&quot;app scope&quot;)
    MaterialTheme {
        Button(onClick = {
            text = &quot;Hello, Desktop!&quot;
        }) {
            println(&quot;text scope&quot;)
            Text(text)
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Idea 预览效果&lt;/h4&gt;
&lt;p&gt;&lt;img src=&quot;/image/kotlin-compose-img-1.png&quot; alt=&quot;image1&quot;&gt;&lt;/p&gt;
&lt;h4&gt;自定义组件&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;
@Composable
fun MyPart(color:Color, // 属性
           onClick:() -&gt; Unit, // 事件
           context:@Composable ()-&gt;Unit // 内部Context
){
    Box(modifier = Modifier.background(color).padding(10.dp)
        .clickable(true,onClick={
        onClick()
    })){
        context()
    }
}

// 像其他组件一样使用

@Composable
@Preview
fun App() {
    var text by remember { mutableStateOf(&quot;Hello, World!&quot;) }
    MaterialTheme {
        // 自定义组件
        MyPart(Color.Red, onClick = {
            text = &quot;my part onclick&quot;
        }){
            Text(text)
        }
    }

}

&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;鼠标事件&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;

@Composable
@Preview
fun DemoEvent(){
    var color by remember { mutableStateOf(Color(0,0,0)) }
    var text by remember { mutableStateOf(&quot;0,0&quot;) }
    @OptIn(ExperimentalComposeUiApi::class)
    Box(
        modifier = Modifier
            .wrapContentSize(Alignment.Center)
            .fillMaxSize()
            .background(color=color)
            .onPointerEvent(PointerEventType.Move) { // 鼠标事件
                // it 可以获取事件属性

                val position = it.changes.first().position
                color = Color(
                    position.x.toInt() % 256, // x 座标映射到256
                    position.y.toInt() % 256, // y 座标 映射到256
                    0)

                text = &quot;${position.x},${position.y}&quot;

            }.onPointerEvent(PointerEventType.Scroll){
                println(&quot;${it.changes.first().scrollDelta.x},${it.changes.first().scrollDelta.y}&quot;)
            }
    ){
        Text(text=text)
    }
}

&lt;/code&gt;&lt;/pre&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>关于netty那些不得不说的故事</title><link>https://realcpf.tech/blog/the-netty</link><guid isPermaLink="true">https://realcpf.tech/blog/the-netty</guid><description>关于netty那些不得不说的故事</description><pubDate>Wed, 03 Jan 2024 18:16:00 GMT</pubDate><content:encoded>&lt;h3&gt;EventLoopGroup&lt;/h3&gt;
&lt;blockquote&gt;
&lt;p&gt;EventLoopGroup 如名是EventLoop的Group 用于管理EventLoop。EventLoopGroup可以理解为一个线程池，其中的线程（EventLoop）负责处理事件和任务。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h4&gt;selectable&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;// single thread pool
NioEventLoopGroup group = new NioEventLoopGroup(1);
// loop one
NioEventLoop loop = (NioEventLoop) group.next();
try {

    Channel channel = new NioServerSocketChannel();
    loop.register(channel).syncUninterruptibly();
    channel.bind(new InetSocketAddress(0)).syncUninterruptibly();
    // config selector
    SocketChannel selectableChannel = SocketChannel.open();
    selectableChannel.configureBlocking(false);
    selectableChannel.connect(channel.localAddress());

    final CountDownLatch latch = new CountDownLatch(1);
    // register key
    loop.register(selectableChannel, SelectionKey.OP_CONNECT, new NioTask&amp;#x3C;SocketChannel&gt;() {
        @Override
        public void channelReady(SocketChannel ch, SelectionKey key) {
            latch.countDown();
        }

        @Override
        public void channelUnregistered(SocketChannel ch, Throwable cause) {
        }
    });

    latch.await();

    selectableChannel.close();
    channel.close().syncUninterruptibly();
} catch (InterruptedException e) {
    throw new RuntimeException(e);
} finally {
    group.shutdownGracefully();
}

&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;full param group and new task queue&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;final AtomicBoolean called = new AtomicBoolean();

    NioEventLoopGroup group = new NioEventLoopGroup(
            1, // 线程数
            new ThreadPerTaskExecutor(new DefaultThreadFactory(NioEventLoopGroup.class)), // Executor
            DefaultEventExecutorChooserFactory.INSTANCE, SelectorProvider.provider(), // selector
            DefaultSelectStrategyFactory.INSTANCE, RejectedExecutionHandlers.reject(), // 拒绝策略
            new EventLoopTaskQueueFactory() { // task queue factory
                @Override
                public Queue&amp;#x3C;Runnable&gt; newTaskQueue(int maxCapacity) {
                    called.set(true);
                    return new LinkedBlockingQueue&amp;#x3C;Runnable&gt;(maxCapacity);
                }
            });

    final NioEventLoop loop = (NioEventLoop) group.next();

    try {
        loop.submit(new Runnable() {
            @Override
            public void run() {
                // do some
            }
        }).syncUninterruptibly();
        assert true == called.get();
    } finally {
        group.shutdownGracefully();
    }
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;delay await cancel&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;EventLoopGroup group = new NioEventLoopGroup(1);

final EventLoop el = group.next();
// schedule
Future&amp;#x3C;?&gt; future = el.schedule(() -&gt; {
    try {
        TimeUnit.SECONDS.sleep(10);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}, Long.MAX_VALUE, TimeUnit.MILLISECONDS);

// await
assert false == future.awaitUninterruptibly(100);
// cancel
assert true == future.cancel(true);

group.shutdownGracefully();


&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Channel&lt;/h3&gt;
&lt;blockquote&gt;
&lt;p&gt;Channel是网络传输中的实体，它代表了一个开放的连接，可以进行数据的读写操作。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h4&gt;channel init&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;final String A = &quot;a&quot;;
final String B = &quot;B&quot;;
// inbound handler
ChannelHandler handler = new ChannelInboundHandlerAdapter() {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ctx.fireChannelRead(A);
        ctx.fireChannelRead(B);
    }
};

// channel
EmbeddedChannel channel = new EmbeddedChannel(
        new ChannelInitializer&amp;#x3C;Channel&gt;() {
            @Override
            protected void initChannel(Channel channel) throws Exception {
                channel.pipeline().addLast(handler);
            }
        }
);

assert handler == channel.pipeline().firstContext().handler();

assert true ==  channel.writeInbound(&quot;C&quot;);

assert true == channel.finish();

assert A.equals(channel.readInbound());

assert B.equals(channel.readInbound());

&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Scheduling&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;EmbeddedChannel ch = new EmbeddedChannel(new ChannelInboundHandlerAdapter());
final CountDownLatch latch = new CountDownLatch(2);
// future
Future future = ch.eventLoop().schedule(new Runnable() {
    @Override
    public void run() {
        System.out.println(&quot;future&quot;);
        latch.countDown();
    }
}, 1, TimeUnit.SECONDS);
// 监听future完成
future.addListener(new FutureListener() {
    @Override
    public void operationComplete(Future future) throws Exception {
        System.out.println(&quot;operationComplete&quot;);
        latch.countDown();
    }
});

// run pending schedule task
long next = ch.runScheduledPendingTasks();

System.out.println(next);
assert next &gt; 0;
TimeUnit.NANOSECONDS.sleep(TimeUnit.NANOSECONDS.toMillis(next) + 66);
assert  ch.runScheduledPendingTasks() == -1;
System.out.println(next);
latch.await();

&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;ByteBuf&lt;/h3&gt;
&lt;blockquote&gt;
&lt;p&gt;ByteBuf作为java NIO中ByteBuffer的Netty版，其语义与ByteBuffer相同，只是操作方式更加丰富&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h4&gt;基本操作&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;ByteBuf buf = Unpooled.buffer(128);
List&amp;#x3C;Object&gt; objects = new LinkedList&amp;#x3C;&gt;();
objects.add(buf.capacity());
objects.add(buf.isReadable());
objects.add(buf.isDirect());
objects.add(buf.isReadable());
objects.forEach(System.out::println);

buf.writeByte(&apos;a&apos;);
buf.writeByte(&apos;b&apos;);
buf.writeByte(&apos;c&apos;);
System.out.println(buf.writerIndex());
System.out.println(buf.readerIndex());
System.out.println(buf.readableBytes());

assert &apos;a&apos; == buf.readByte();
assert &apos;b&apos; == buf.readByte();
assert &apos;c&apos; == buf.readByte();

buf.readerIndex(0);
buf.slice(0,3);

buf.release();


&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;ByteProcess&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;ByteBuf buf = Unpooled.buffer(128);
buf.writeCharSequence(&quot;abc d \re \n f \b c! ?&quot;, StandardCharsets.UTF_8);
int i = 0;
int last = 0;

while (-1 != (i = buf.forEachByte(b -&gt; b != &apos;c&apos;))) {
    if (i &gt; last) {
        byte[] bytes = new byte[i - last];
        buf.readBytes(buf,i,last);
        System.out.println(new String(bytes));
        buf.readerIndex(i + 1);
    }
    last = i;
}

buf.readerIndex(0);
buf.forEachByte(ByteProcessor.FIND_LF);

&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;UnPooled&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;byte[] bytes1 = &quot;hello&quot;.getBytes(StandardCharsets.US_ASCII);
byte[] space = &quot; &quot;.getBytes(StandardCharsets.US_ASCII);
byte[] bytes2 = &quot;world&quot;.getBytes(StandardCharsets.US_ASCII);
ByteBuf buf = Unpooled.wrappedBuffer(bytes1,space,bytes2);
int len = bytes1.length + bytes2.length + space.length;
byte[] helloWorld = new byte[len];
buf.readBytes(helloWorld,0,len);
System.out.println(new String(helloWorld));

buf.readerIndex(0);

ByteBuf buf3_14 = Unpooled.copyFloat(3.14f);

ByteBuf buf2 = Unpooled.wrappedBuffer(buf,buf3_14);

buf2.readerIndex(len);
assert &quot;3.14&quot; == buf2.readFloat() + &quot;&quot;;

&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;ByteToMessage,MessageToByte,MessageToMessage&lt;/h3&gt;
&lt;blockquote&gt;
&lt;p&gt;串行的数据流的编码解码&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h4&gt;ByteToMessage&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;
 // xxxx\r\nxxx\r\n
ByteToMessageDecoder decoder = new ByteToMessageDecoder() {
    @Override
    protected void decode(
        ChannelHandlerContext channelHandlerContext, // 上下文
        ByteBuf byteBuf, // 数据buffer
        List&amp;#x3C;Object&gt; list // 传给下一层的对象
        ) throws Exception {
        while (byteBuf.isReadable()) {
            int crlfIndex = byteBuf.forEachByte(ByteProcessor.FIND_CRLF);
            if (crlfIndex == -1) {
                break;
            }
            byte[] bytes = new byte[crlfIndex - byteBuf.readerIndex()];
            byteBuf.readBytes(bytes,0,crlfIndex - byteBuf.readerIndex());
            byteBuf.readerIndex(crlfIndex);
            byteBuf.readShort();
            list.add(new String(bytes));
        }
    }
};
EmbeddedChannel channel = new EmbeddedChannel(decoder);
channel.writeInbound(Unpooled.wrappedBuffer(&quot;hello\r\nworld\r\n&quot;.getBytes(StandardCharsets.UTF_8)));
assert &quot;hello&quot; == (String) channel.readInbound();
assert &quot;world&quot; == (String) channel.readInbound();


&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;MessageToMessage&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;ByteToMessageDecoder decoder = new ByteToMessageDecoder() {
    @Override
    protected void decode(
            ChannelHandlerContext channelHandlerContext, // 上下文
            ByteBuf byteBuf, // 数据buffer
            List&amp;#x3C;Object&gt; list // 传给下一层的对象
    ) throws Exception {
        while (byteBuf.isReadable()) {
            int crlfIndex = byteBuf.forEachByte(ByteProcessor.FIND_CRLF);
            if (crlfIndex == -1) {
                break;
            }
            byte[] bytes = new byte[crlfIndex - byteBuf.readerIndex()];
            byteBuf.readBytes(bytes,0,crlfIndex - byteBuf.readerIndex());
            byteBuf.readerIndex(crlfIndex);
            byteBuf.readShort();
            list.add(new String(bytes));
        }
    }
};

MessageToMessageDecoder decoderM2M = new MessageToMessageDecoder() {
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, Object o, List list) throws Exception {
        if (o instanceof String) {
            list.add(String.format(&quot;[%s]&quot;,o));
        }
    }
};

EmbeddedChannel channel = new EmbeddedChannel(decoder);
channel.pipeline().addLast(decoderM2M);

channel.writeInbound(Unpooled.wrappedBuffer(&quot;hello\r\nworld\r\n&quot;.getBytes(StandardCharsets.UTF_8)));
assert &quot;[hello]&quot; == (String) channel.readInbound();
assert &quot;[world]&quot; == (String) channel.readInbound();

&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Replaying&lt;/h2&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;
// replaying 可以用在一个Message再传输时不在同一时间到达的情况
ReplayingDecoder&amp;#x3C;Void&gt; replayingDecoder = new ReplayingDecoder&amp;#x3C;Void&gt;() {
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List&amp;#x3C;Object&gt; out) throws Exception {
        ByteBuf msg = in.readBytes(in.bytesBefore((byte) &apos;\n&apos;));
        out.add(msg);
        in.skipBytes(1);
    }
};
EmbeddedChannel ch = new EmbeddedChannel(replayingDecoder);

ch.writeInbound(Unpooled.wrappedBuffer(new byte[]{&apos;A&apos;}));
assert Objects.isNull(ch.readInbound());
ch.writeInbound(Unpooled.wrappedBuffer(new byte[]{&apos;B&apos;}));
assert Objects.isNull(ch.readInbound());
ch.writeInbound(Unpooled.wrappedBuffer(new byte[]{&apos;C&apos;}));
assert Objects.isNull(ch.readInbound());
// 直到 \n 传到才完成一个Message的decode
ch.writeInbound(Unpooled.wrappedBuffer(new byte[]{&apos;\n&apos;}));

ByteBuf buf = Unpooled.wrappedBuffer(new byte[] { &apos;A&apos;, &apos;B&apos;, &apos;C&apos; });
ByteBuf buf2 = ch.readInbound();

assert buf.toString(StandardCharsets.UTF_8).equals(buf2.toString(StandardCharsets.UTF_8));

buf2.release();
buf.release();

ch.finish();


&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Codec&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;
// codec 同时有decode和encode
ByteToMessageCodec&amp;#x3C;Integer&gt; codec = new ByteToMessageCodec&amp;#x3C;Integer&gt;() {
    @Override
    protected void encode(ChannelHandlerContext ctx, Integer msg, ByteBuf out) {
        out.writeInt(msg);
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List&amp;#x3C;Object&gt; out) {
        if (in.readableBytes() &gt;= 4) {
            out.add(in.readInt());
        }
    }
};
ByteBuf buffer = Unpooled.buffer();
buffer.writeInt(1);
buffer.writeByte(&apos;0&apos;);

EmbeddedChannel ch = new EmbeddedChannel(codec);
assert ch.writeInbound(buffer);
ch.pipeline().remove(codec);
assert ch.finish();
assert Integer.compare(1, (Integer) ch.readInbound()) == 0;


&lt;/code&gt;&lt;/pre&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>一些难以意识到的错误</title><link>https://realcpf.tech/blog/some-thing-maybe-wrong</link><guid isPermaLink="true">https://realcpf.tech/blog/some-thing-maybe-wrong</guid><description>关于一些难以意识到的错误</description><pubDate>Tue, 02 Jan 2024 18:16:00 GMT</pubDate><content:encoded>&lt;h3&gt;M Mi K Ki G Gi&lt;/h3&gt;
&lt;blockquote&gt;
&lt;p&gt;试试在各个操作系统上对文件大小单位的进制
&lt;a href=&quot;https://physics.nist.gov/cuu/Units/binary.html&quot;&gt;https://physics.nist.gov/cuu/Units/binary.html&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Prefixes for binary multiples
| &lt;strong&gt;Factor&lt;/strong&gt; | &lt;strong&gt;Name&lt;/strong&gt; | &lt;strong&gt;Symbol&lt;/strong&gt; | &lt;strong&gt;Origin&lt;/strong&gt; | &lt;strong&gt;Derivation&lt;/strong&gt; |
| ---------- | -------- | ---------- | ------------------ | -------------- |
| 2^10 | kibi | Ki | kilobinary: (210)1 | kilo: (103)1 |
| 2^20 | mebi | Mi | megabinary: (210)2 | mega: (103)2 |
| 2^30 | gibi | Gi | gigabinary: (210)3 | giga: (103)3 |
| 2^40 | tebi | Ti | terabinary: (210)4 | tera: (103)4 |
| 2^50 | pebi | Pi | petabinary: (210)5 | peta: (103)5 |
| 2^60 | exbi | Ei | exabinary: (210)6 | exa: (103)6 |&lt;/p&gt;
&lt;p&gt;| one &lt;strong&gt;kibibit&lt;/strong&gt;  | 1 Kibit = 210 bit = &lt;strong&gt;1024 bit&lt;/strong&gt;    |
| ---------------- | ----------------------------------- |
| one &lt;strong&gt;kilobit&lt;/strong&gt;  | 1 kbit = 103 bit = &lt;strong&gt;1000 bit&lt;/strong&gt;     |
| one &lt;strong&gt;byte&lt;/strong&gt;     | 1 B = 23 bit = &lt;strong&gt;8 bit&lt;/strong&gt;            |
| one &lt;strong&gt;mebibyte&lt;/strong&gt; | 1 MiB = 220 B = &lt;strong&gt;1 048 576 B&lt;/strong&gt;     |
| one &lt;strong&gt;megabyte&lt;/strong&gt; | 1 MB = 106 B = &lt;strong&gt;1 000 000 B&lt;/strong&gt;      |
| one &lt;strong&gt;gibibyte&lt;/strong&gt; | 1 GiB = 230 B = &lt;strong&gt;1 073 741 824 B&lt;/strong&gt; |
| one &lt;strong&gt;gigabyte&lt;/strong&gt; | 1 GB = 109 B = &lt;strong&gt;1 000 000 000 B&lt;/strong&gt;  |&lt;/p&gt;
&lt;p&gt;在linux的coreutil 里同样采用了这套国际标准&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://www.gnu.org/software/coreutils/manual/coreutils.html&quot;&gt;https://www.gnu.org/software/coreutils/manual/coreutils.html&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;With human-readable formats, output sizes are followed by a size letter such as ‘M’ for megabytes. BLOCK_SIZE=human-readable uses powers of 1024; ‘M’ stands for 1,048,576 bytes. BLOCK_SIZE=si is similar, but uses powers of 1000 and appends ‘B’; ‘MB’ stands for 1,000,000 bytes.&lt;/p&gt;
&lt;p&gt;A block size specification preceded by ‘&apos;’ causes output sizes to be displayed with thousands separators. The LC_NUMERIC locale specifies the thousands separator and grouping. For example, in an American English locale, ‘--block-size=&quot;&apos;1kB&quot;’ would cause a size of 1234000 bytes to be displayed as ‘1,234’. In the default C locale, there is no thousands separator so a leading ‘&apos;’ has no effect.&lt;/p&gt;
&lt;p&gt;An integer block size can be followed by a suffix to specify a multiple of that size. A bare size letter, or one followed by ‘iB’, specifies a multiple using powers of 1024. A size letter followed by ‘B’ specifies powers of 1000 instead. For example, ‘1M’ and ‘1MiB’ are equivalent to ‘1048576’, whereas ‘1MB’ is equivalent to ‘1000000’.&lt;/p&gt;
&lt;p&gt;A plain suffix without a preceding integer acts as if ‘1’ were prepended, except that it causes a size indication to be appended to the output. For example, ‘--block-size=&quot;kB&quot;’ displays 3000 as ‘3kB’.&lt;/p&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>关于jdk那些不得不说的故事</title><link>https://realcpf.tech/blog/the-jdk</link><guid isPermaLink="true">https://realcpf.tech/blog/the-jdk</guid><description>关于jdk那些不得不说的故事</description><pubDate>Tue, 02 Jan 2024 18:16:00 GMT</pubDate><content:encoded>&lt;h3&gt;VirtualThread Thread.yield() 从jdk测试里摘抄&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;var list = new CopyOnWriteArrayList&amp;#x3C;String&gt;();

var threadsStarted = new AtomicBoolean();

var threadA = Thread.ofVirtual().unstarted(() -&gt; {
    while (!threadsStarted.get()) {
        Thread.onSpinWait();
    }

    list.add(&quot;A&quot;);
    Thread.yield();
    list.add(&quot;A&quot;);
});

var threadB = Thread.ofVirtual().unstarted(() -&gt; {
    list.add(&quot;B&quot;);
});


threadA.start();
threadB.start();


threadsStarted.set(true);


threadA.join();
threadB.join();
assert  list.stream().collect(Collectors.joining(&quot;,&quot;)) == List.of(&quot;A&quot;, &quot;B&quot;, &quot;A&quot;).stream().collect(Collectors.joining(&quot;,&quot;));

&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;ScopedValue，StructuredTaskScope&lt;/h3&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;a href=&quot;https://openjdk.org/jeps/429&quot;&gt;JEP 429: Scoped Values (Incubator)&lt;/a&gt;
代码用的java版本是 openjdk 22-internal ,SOURCE=&quot;.:git:ad34be1f329e&quot;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;isBound, get&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;
// get
ScopedValue&amp;#x3C;String&gt; name = ScopedValue.newInstance();
String result = ScopedValue.getWhere(name, &quot;duke&quot;, ()-&gt;{
    // 在这个scope里是inbound的
    System.out.println(name.isBound());
    // 所以这个scope里才能get到值
    return name.get();
});
System.out.println(result);
System.out.println(name.isBound());

&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;几个开启scope的方法&lt;code&gt;runWhere&lt;/code&gt;,&lt;code&gt;callWhere&lt;/code&gt;,&lt;code&gt;getWhere&lt;/code&gt;&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;
ScopedValue&amp;#x3C;String&gt; v1 = ScopedValue.newInstance();
ScopedValue.runWhere(v1,&quot;new v1 run&quot;,()-&gt;{
    System.out.println(v1.get());
});
ScopedValue.callWhere(v1,&quot;new v1 call&quot;,()-&gt;{
    System.out.println(v1.get());
    return v1.get();
});

ScopedValue.getWhere(v1,&quot;new v1 get&quot;,() -&gt;{
    System.out.println(v1.get());
    return v1.get();
});

assert &quot;default&quot; == v1.orElse(&quot;default&quot;);

ScopedValue.runWhere(v1,&quot;the&quot;,()-&gt;{
    assert &quot;the&quot; ==  v1.orElse(null);
});

&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;scope嵌套&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;ScopedValue&amp;#x3C;String&gt; v1 = ScopedValue.newInstance();
ScopedValue.runWhere(v1,&quot;v1 leve1&quot;,()-&gt;{
    assert v1.isBound();
    assert &quot;v1 leve1&quot; == v1.get();
    ScopedValue.runWhere(v1,&quot;v1 leve2&quot;,()-&gt;{
        assert v1.isBound();
        assert &quot;v1 leve2&quot; == v1.get();
    });
    assert v1.isBound();
    assert &quot;v1 leve1&quot; == v1.get();
});

&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;多值&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;ScopedValue&amp;#x3C;String&gt; name = ScopedValue.newInstance();
ScopedValue&amp;#x3C;Integer&gt; age = ScopedValue.newInstance();
ScopedValue.where(name,&quot;my name&quot;)
        .where(age,22)
        .run(()-&gt;{
            assert name.isBound();
            assert age.isBound();
            System.out.println(name.get());
            System.out.println(age.get());

        });
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;StructuredTaskScope 的PreviewFeature的版本，与19release的版本略有不同&lt;/h2&gt;
&lt;blockquote&gt;
&lt;p&gt;对了 如果一些没有relase的版本的代码片段在IDEA上无法运行，就直接java XXX 吧，java已经可以直接执行java文件了， 加上&lt;code&gt;--enable-preview --source 22&lt;/code&gt;即可&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;fork with virtual thread&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;
Set&amp;#x3C;Thread&gt; threads = ConcurrentHashMap.newKeySet();
try (var scope = new StructuredTaskScope&amp;#x3C;Object&gt;(&quot;v&quot;,
                                // 通过虚拟线程创建100个fork非常快
                                    Thread.ofVirtual().factory())) {
    for (int i = 0; i &amp;#x3C; 100; i++) {
    scope.fork(() -&gt; {
        threads.add(Thread.currentThread());
        return null;
    });
    }
    scope.join();
} catch (InterruptedException e) {
    throw new RuntimeException(e);
}
assert 100 == threads.size();
assert 100 == threads.stream().filter(t-&gt;t.isVirtual()).count();

&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;ShutdownOnSuccess&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;
// 源码处
if (subtask.state() == Subtask.State.SUCCESS) {
    // task succeeded
    T result = subtask.get();
    Object r = (result != null) ? result : RESULT_NULL;
    if (FIRST_RESULT.compareAndSet(this, null, r)) {
        // 确认是第一个成功的就shutdown
        super.shutdown();
    }
}
// 比如

try(var scope = new StructuredTaskScope.ShutdownOnSuccess&amp;#x3C;&gt;()) {
    StructuredTaskScope.Subtask&amp;#x3C;Object&gt; f1 = scope.fork(()-&gt;{
    return &quot;1&quot;;
    });
    StructuredTaskScope.Subtask&amp;#x3C;Object&gt; f2 = scope.fork(()-&gt;{
    TimeUnit.SECONDS.sleep(1);
    return &quot;2&quot;;
    });
    System.out.println(f1.state());
    System.out.println(f2.state());
    scope.join();
    System.out.println(&quot;join&quot;);
    System.out.println(f1.state());
    System.out.println(f2.state());
    // get会报错，因为其中一个成功后其他的已经取消了
//      System.out.println(f1.get());
//      System.out.println(f2.get());

    System.out.println(scope.result());

} catch (InterruptedException e) {
    throw new RuntimeException(e);
} catch (ExecutionException e) {
    throw new RuntimeException(e);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;自定义scope handle&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;public static class MyScopeException extends RuntimeException {}

  public static class MyScope extends StructuredTaskScope&amp;#x3C;String&gt; {
    private final Collection&amp;#x3C;String&gt; oks = new ConcurrentLinkedDeque&amp;#x3C;&gt;();
    private final Collection&amp;#x3C;Throwable&gt; errs = new ConcurrentLinkedDeque&amp;#x3C;&gt;();

    @Override
    protected void handleComplete(Subtask&amp;#x3C;? extends String&gt; subtask) {
      switch (subtask.state()){
        case UNAVAILABLE : throw new IllegalStateException(&quot;&quot;);
        case SUCCESS : this.oks.add(subtask.get());break;
        case FAILED : this.errs.add(subtask.exception());break;
        default : {}break;
      }
    }

    public MyScopeException errors(){
      MyScopeException exception = new MyScopeException();
      errs.forEach(exception::addSuppressed);
      return exception;
    }

    public String myResult(){
      return oks.stream().findFirst().orElseThrow(this::errors);
    }
}


&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;使用自定义的scope&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;
try(var scope = new MyScope()) {
    scope.fork(()-&gt;{
    TimeUnit.SECONDS.sleep(1);
    return &quot;1&quot;;
    });
    scope.fork(()-&gt;{
    return &quot;2&quot;;
    });

    scope.join();

    System.out.println(scope.myResult());
} catch (InterruptedException e) {
    throw new RuntimeException(e);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;jdbc&lt;/h2&gt;
&lt;h3&gt;表结构、列信息获取&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;

private static void testTableStruct() {
    try (Connection connection = DriverManager.getConnection(&quot;&quot;);
            PreparedStatement preparedStatement = connection.prepareStatement(&quot;select * from table where 1=2&quot;)) {
        final ResultSetMetaData metaData = preparedStatement.getMetaData();
        int columnCount = metaData.getColumnCount();
        IntStream.rangeClosed(1, columnCount).forEach(i -&gt; {
            try {
                String colName = metaData.getColumnName(i);
                String colTypeName = metaData.getColumnTypeName(i);
                int colType = metaData.getColumnType(i);
                metaData.getPrecision(i);
                metaData.getScale(i);
                metaData.isAutoIncrement(i);
                metaData.isDefinitelyWritable(i);
                metaData.isReadOnly(i);
                metaData.isWritable(i);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        });
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;查询&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;private static void testQuery() {
    try (Connection connection = DriverManager.getConnection(&quot;&quot;);
            PreparedStatement statement = connection.prepareStatement(&quot;&quot;);
            ResultSet rs = statement.executeQuery()) {
        int colCount = rs.getMetaData().getColumnCount();
        while (rs.next()) {

            for (int i = 0; i &amp;#x3C; colCount; i++) {
                final int type = rs.getMetaData().getColumnType(i);
                switch (type) {
                    case Types.VARBINARY: {

                    }
                    break;
                    case Types.INTEGER: {

                    }
                    break;
                    default: {
                    }
                    break;
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;事务&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;
private static void testTransaction() throws SQLException {
    Connection connection = DriverManager.getConnection(&quot;&quot;);
    try (connection;
            PreparedStatement statement = connection.prepareStatement(&quot;&quot;);) {
        connection.setAutoCommit(false);
        connection.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
        statement.executeUpdate();
        connection.commit();

    } catch (Exception e) {
        connection.rollback();
        e.printStackTrace();
    } finally {
        connection.setAutoCommit(true);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;spi demo&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;// the driver interface
public interface MyDriver {
    String format();
    String who();
}
// the driver of my impl
public class TheDriver implements MyDriver{

    @Override
    public String format() {
        return &quot;mydriver://realcpf&quot;;
    }

    @Override
    public String who() {
        return &quot;realcpf&quot;;
    }
}
// SPI config file
// src\main\resources\META-INF\services\tech.realcpf.jdbc.MyDriver -&gt; tech.realcpf.jdbc.TheDriver
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;加载方式&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;
import java.sql.DriverManager;
import java.util.Iterator;
import java.util.ServiceLoader;

public class DemoSpi {


    class MyDriverManager {
        private  volatile boolean initFlag = false;
        public void init() {
            if (initFlag) {
                return;
            }

            ServiceLoader&amp;#x3C;MyDriver&gt; serviceLoader = ServiceLoader.load(MyDriver.class);

            Iterator&amp;#x3C;MyDriver&gt; driverIterator = serviceLoader.iterator();
            while (driverIterator.hasNext()) {
                MyDriver driver = driverIterator.next();
                System.out.println(driver.who() + &quot;:&quot; + driver.format());
            }

        }

    }

}

&lt;/code&gt;&lt;/pre&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item><item><title>2023观影回顾</title><link>https://realcpf.tech/blog/move-2023</link><guid isPermaLink="true">https://realcpf.tech/blog/move-2023</guid><description>关于2023年看了什么剧</description><pubDate>Mon, 01 Jan 2024 18:16:00 GMT</pubDate><content:encoded>&lt;h3&gt;我有一个朋友&lt;/h3&gt;
&lt;blockquote&gt;
&lt;p&gt;有些话说出来会得到同情，而不说出来却依然被懂得的则是交情。有时候还是会很想他们，撕心裂肺地想，但却不必找人诉说。
即便仍伴随着尘埃，矗立于荒芜……
天地间却不再只剩我一人。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;a href=&quot;https://movie.douban.com/review/15445536/&quot;&gt;有趣台词集锦&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;宇宙探索编辑部&lt;/h3&gt;
&lt;h3&gt;千寻小姐&lt;/h3&gt;
&lt;h3&gt;漫长的季节&lt;/h3&gt;
&lt;blockquote&gt;
&lt;p&gt;前面的人们此时尚不知情
遥远的事物将被震碎
我们打个共鸣的响指吧&lt;/p&gt;
&lt;/blockquote&gt;
&lt;blockquote&gt;
&lt;p&gt;向前走，别回头啊&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;&lt;img src=&quot;/img/man-chang-de-ren-sheng-1.webp&quot; alt=&quot;img-1&quot;&gt;&lt;/p&gt;
&lt;h3&gt;莲花楼&lt;/h3&gt;
&lt;blockquote&gt;
&lt;p&gt;10年后，我不再是名震江湖的大侠，只是一人一狗走江湖的游医，可老友见到我后说“我这样挺好！”
毕竟，过往也只是过往啊！&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;&lt;img src=&quot;/img/lian-hua-lou-1.webp&quot; alt=&quot;img-1&quot;&gt;&lt;/p&gt;
&lt;h3&gt;狂飙&lt;/h3&gt;
&lt;h3&gt;繁城之下&lt;/h3&gt;
&lt;h3&gt;超异能族&lt;/h3&gt;
&lt;h3&gt;黑暗荣耀&lt;/h3&gt;
&lt;h3&gt;重启人生&lt;/h3&gt;
&lt;blockquote&gt;
&lt;p&gt;我一遍有一遍的走过，有你们的人生，还好从未走散&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;&lt;img src=&quot;/img/chong-qi-ren-sheng-1.webp&quot; alt=&quot;img-1&quot;&gt;&lt;/p&gt;
&lt;h3&gt;葬送的芙莉莲&lt;/h3&gt;</content:encoded><h:img src="undefined"/><enclosure url="undefined"/></item></channel></rss>