<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="zh-CN">
  <title>了迹奇有没</title>
  <subtitle>互联网码农的博客：技术、折腾、生活和思考。</subtitle>
  <id>https://blog.whrss.com/</id>
  <link href="https://blog.whrss.com/"/>
  <link rel="self" type="application/atom+xml" href="https://blog.whrss.com/feed.xml"/>
  <updated>2026-10-04T05:00:49.000Z</updated>
  <author><name>了迹奇有没</name><email>whrss9527@gmail.com</email></author>
  <icon>https://blog.whrss.com/favicon.ico</icon>
  <entry>
    <title>猛蹬三天，我做了四个菜单栏 App，然后账号被封了</title>
    <link href="https://blog.whrss.com/posts/menu-bar-apps-week"/>
    <id>https://blog.whrss.com/posts/menu-bar-apps-week</id>
    <published>2026-10-04T05:00:49.000Z</published>
    <updated>2026-10-04T05:00:49.000Z</updated>
    <category term="折腾"/>
    <category term="ai"/>
    <category term="开源项目"/>
    <category term="GitHub"/>
    <summary>同事陆续被封号，我把两周额度、赠送额度和一次周额度重置用到了极致。国庆三天疯狂推进四个 Mac App，修了很多问题，也留下很多问题。以为自己是天选之人时，账号突然被封了。</summary>
    <content type="html">&lt;p&gt;一直想做点自己的产品。&lt;/p&gt;
&lt;p&gt;好几次动过念头去注册苹果开发者账号，每次都停在「算了」：Swift 要学，AppKit 要学，签名公证那一套更是一想就头大，下班之后那点精力根本撑不起来。&lt;/p&gt;
&lt;p&gt;九月份，我在 X 上陆续看到不少人说自己的 Claude 账号被封了。中秋前后，同事们也开始一个接一个地被封。我有心理预期，说不定哪天就轮到自己了。&lt;/p&gt;
&lt;p&gt;既然还能用，就抓紧把一直想做的东西做出来。我的 Claude Max 20x 周额度每到星期天更新，从中秋那周开始，两个完整周的额度，加上 250 美元的赠送额度，还有一次额外的周额度重置，我全都用到了极致。国庆这三天尤其疯狂，几个项目来回切，加功能、试用、报问题、修问题，再继续往前推。&lt;/p&gt;
&lt;p&gt;看着同事们陆续被封，自己这样蹬了一周却还没事，我渐渐开始觉得：难道我是天选之人？&lt;/p&gt;
&lt;p&gt;然后，突然就封了。页面上只剩下「Organization access is disabled」。有心理预期，和真的看到这行字，还是两回事。&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://blog.whrss.com/covers/menu-bar-apps-week/account-disabled.jpg&quot; alt=&quot;账号停用时的页面&quot; loading=&quot;eager&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;好在留下了四个住在菜单栏里的 Mac App：&lt;a href=&quot;https://github.com/whrss9527/pop&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;Pop&lt;/a&gt;、&lt;a href=&quot;https://github.com/whrss9527/meno&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;Meno&lt;/a&gt;、&lt;a href=&quot;https://github.com/whrss9527/stox&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;Stox&lt;/a&gt;、&lt;a href=&quot;https://github.com/whrss9527/proxi&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;Proxi&lt;/a&gt;。原生 Swift，玻璃质感，开源免费，已经做了签名公证和 App 内更新。它们解决了不少我平时用电脑时遇到的问题，开发过程中也修了很多问题。当然，到现在还有很多问题。&lt;/p&gt;
&lt;p&gt;这四个项目并不是国庆三天从零冒出来的。翻回提交记录，Proxi 的 Mac 版从 9 月 24 日开始，Pop 和 Stox 从 28 日开始，Meno 从 29 日开始。国庆三天是在已有的东西上疯狂推进，把功能、修复和发布流程一起往前赶。&lt;/p&gt;
&lt;p&gt;先说这四个东西是怎么来的，按我想到它们的顺序。&lt;/p&gt;
&lt;h4 id=&quot;proxi从一个代理开关开始&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#proxi从一个代理开关开始&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;Proxi：从一个代理开关开始&lt;/h4&gt;
&lt;p&gt;源头是公司网络。连内网要设代理，Windows 上没有一个顺手的一键切换，我想要的是平时自己用不受影响，要干活了立刻连上。所以最早做的其实是个 Go 写的 Windows 托盘小工具：一个开关，切系统代理、PAC、环境变量、git、npm。&lt;/p&gt;
&lt;p&gt;做着做着发现 Mac 上单纯切代理也不好用，就想要一个 Mac 版。但我不想要一个和 Windows 一模一样的东西：它得是原生的，主要活在菜单栏里，界面要高级一点，有玻璃的质感。这个要求后来成了四个 App 共同的调性。&lt;/p&gt;
&lt;p&gt;然后就把平时会碰到的网络相关的事都往里加：填一个订阅地址就能选节点，全局或者按规则分流，不用再装第二个软件。我特别想要的一个场景是 PS5 和 Switch——游戏机平时得靠加速器，我想让它们直接用电脑的网络。从局域网共享，到发现游戏机上的 App 不认代理设置，再到网关模式，一步步做下来，功能越长越多。后来又收了一次范围：Proxi 本体回到给开发者切换系统代理、终端、git、npm 的开关，代理内核相关的功能拆成默认关闭的可选扩展。做着做着，除了加功能，也开始想清楚哪些东西应该放在一起。&lt;/p&gt;
&lt;p&gt;名字反而是折腾最久的。中间叫过 Kaze，连改名迁移都做完了，发布流水线正在跑，我忽然觉得它还是太像一个工具，而不是一个产品，又叫停重来。最后定了 Proxi：把 proxy 的 y 换成 i，少一个 why，多一个 I，代理应该是交到自己手里的遥控器。&lt;/p&gt;
&lt;h4 id=&quot;pop长按右键一划即达&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#pop长按右键一划即达&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;Pop：长按右键，一划即达&lt;/h4&gt;
&lt;p&gt;这是我挂了很久的痛点。我一直想要一个全局的一键翻译；选中一段 JSON 一键格式化，Base64 一键解码，时间戳一键转换，甚至图片相关的乱七八糟的功能，都想一键搞定。之前用 uTools，相对方便，但各种功能都有额度，也不是原生的，后来只剩翻译在用，也不太好用。&lt;/p&gt;
&lt;p&gt;这次我想清楚了交互：长按右键，鼠标旁边弹出一个圆盘，往某个方向一划，松手就执行；选中的是外文就直接翻译，是算式就直接出结果，认不出来才弹圆盘。有两点是我坚持的：松开右键圆盘就关，不要常驻；划到哪一格就临时选中哪一格，松手即点击。熟练之后不用看，肌肉记忆就够了。功能做成插件，后来也做了插件包单独发布和更新，不必每加一个功能就发整个 App 的新版。&lt;/p&gt;
&lt;p&gt;名字是建仓库时随手起的，释义后来才补：Pop 像泡泡，按住右键冒出来一个，往想去的方向一划，松手「啵」地破掉，事情也就办完了。&lt;/p&gt;
&lt;h4 id=&quot;stox一眼看盘一键隐身&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#stox一眼看盘一键隐身&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;Stox：一眼看盘，一键隐身&lt;/h4&gt;
&lt;p&gt;应用市场里的股票软件实在不行，要收费，功能还做得一塌糊涂。我想要的是很多有用但不复杂的功能：菜单栏上看一眼，持仓盈亏自己算，到价提醒，不想看了右键一下只留个图标。&lt;/p&gt;
&lt;p&gt;「一键隐身」是我插的一句话——Claude 最初把它理解成面板上加个眼睛按钮，我说右键就行，设置放到面板底部去。数据源选了免费、不用注册、不用 Key 的公开接口，装上就能用。&lt;/p&gt;
&lt;p&gt;名字是 Claude 起的：stocks 六个字母压成四个，念起来还是 stocks；行情也一样，压缩成菜单栏里小小的一格。&lt;/p&gt;
&lt;h4 id=&quot;meno菜单栏放不下了&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#meno菜单栏放不下了&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;Meno：菜单栏放不下了&lt;/h4&gt;
&lt;p&gt;做到这里发现一个新问题：这么多软件都占着菜单栏，MacBook 的菜单栏放多了就被刘海藏掉。GitHub 上有一个 Ice，但很久没维护了。我决定从零做一个，不去看它怎么实现的，只借鉴功能不借鉴代码，让「空白的大脑」自己发挥。&lt;/p&gt;
&lt;p&gt;常用的留下，不常用的收起来，需要的时候点一下、悬停或者轻扫就回来；再加一个「暗格」放那些几乎用不到的图标，和按场景自动切换的规则——开会时麦克风一亮就进专注模式这种。&lt;/p&gt;
&lt;p&gt;Meno 是意大利语「少一点」，乐谱里的 meno mosso 是「慢一点，别那么急」，而且和 Menu 只差一个字母。&lt;/p&gt;
&lt;h4 id=&quot;三天里很多时间其实在修问题&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#三天里很多时间其实在修问题&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;三天里，很多时间其实在修问题&lt;/h4&gt;
&lt;p&gt;功能列表长得很快，但提交记录里同样显眼的是修复。有些问题看起来很小，真用起来却绕不过去。&lt;/p&gt;
&lt;p&gt;Pop 最后集中修的是卡顿。它要监听右键和键盘，自己的工作一旦堵住，就可能连别的软件里的右键、打字都拖慢。大段文字的识别和格式化、图片解码、剪贴板搜索、插件签名检查，都一点点搬到后台；鼠标和键盘监听也放到单独的线程。测试里还专门塞进几 MB 的 JSON，让演示流程检查主线程有没有停顿。&lt;a href=&quot;https://github.com/whrss9527/pop/pull/77&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;0.68.0 的改动&lt;/a&gt;几乎就是一轮「别让一个小工具拖住整台电脑」的清理。&lt;/p&gt;
&lt;p&gt;Meno 的麻烦在于，界面说图标藏好了，不代表它真的离开了屏幕。菜单栏图标可能躲在刘海后面，鼠标够不到；多个显示器和全屏状态又会改变它们的位置。于是既要做按图标窗口移动，也要用端到端检查验证移动和隐藏；后来连隐藏完之后都要再看一遍，不成功就切换实现方式。&lt;a href=&quot;https://github.com/whrss9527/meno/pull/43&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;这次隐藏检查的修复&lt;/a&gt;让我更清楚：按钮能按、状态会变，离真正完成这件事还有一段距离。&lt;/p&gt;
&lt;p&gt;Proxi 则是在补「开关之后怎么办」。开着代理时改配置，要立即生效；关闭时要恢复开启前的设置；拔掉的网线对应的网络服务，也不能留下旧代理。重启、一键更新、手动退出、注销，又不能全当成同一件事处理。10 月 3 日连续几版都在修这些边界，还有代理密码不该进入剪贴板历史和错误信息的问题。&lt;a href=&quot;https://github.com/whrss9527/proxi/pull/21&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;0.14.5 的修复&lt;/a&gt;不是多了一个大功能，而是让已有的功能少留下一点麻烦。&lt;/p&gt;
&lt;p&gt;Stox 也不是把报价显示出来就结束了。早期就补了主数据源不可用时的备用来源，又修了 A 股开盘前不该触发止盈检查、面板内容太多时跑出屏幕等问题。国庆期间还在准备 Mac App Store 的打包、文案和截图；有了这套流程，并不等于已经上架。&lt;/p&gt;
&lt;p&gt;这些都是仓库里已经留下的修复，后面仍然需要继续用、继续找。Meno 的发布说明里还列着一些限制：某些情况下移动图标需要短暂接管鼠标，多屏上的图标顺序受系统限制，菜单栏着色和图标间距仍属于实验或测试功能。版本发得快，修复也多，离稳定省心还差不少。&lt;/p&gt;
&lt;h4 id=&quot;不间断开发记录留在哪里&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#不间断开发记录留在哪里&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;不间断开发，记录留在哪里&lt;/h4&gt;
&lt;p&gt;为了让开发尽量不停下来，我用的是 Claude Cloud。聊天记录都在 Claude 云端，本地没有。好在我让它做的工作流是围绕 GitHub 的 issue 和 PR 来组织的。&lt;/p&gt;
&lt;p&gt;任务放进 issue，在分支里改，改完开 PR，检查和讨论也跟着留下来。现在 Meno 的仓库约定里已经明确写着：一个 issue 一个分支、一个 PR，PR 关联对应的 issue，合并权限另行约定。这套东西让任务可以在不同的会话里接着做，也让我能回头找到某个功能为什么改成现在这样。&lt;/p&gt;
&lt;p&gt;发布流程也逐渐搬进仓库。比如 Pop，改完先过编译、测试、启动和更新检查；合并进主分支后，如果更新日志里写了还没发布的新版本，流程再打包、签名公证、发布。Meno 则通过标签或手动触发发布。各个项目的做法并不完全一样，但都在减少每次发版需要我重复操作的步骤。&lt;/p&gt;
&lt;p&gt;账号被封之后，这个区别就很明显了：聊天留在云端，代码、issue、PR 和工作流留在 GitHub。它们不能还原每一句对话，但至少任务、修改和合并的过程有迹可循，后续还有地方接着做。&lt;/p&gt;
&lt;h4 id=&quot;学到的&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#学到的&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;学到的&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;说清品类和一个交互约束，把设计交出去。四个起点都是一两句话，设计文档我一份都没评审过，只验收产品。&lt;/li&gt;
&lt;li&gt;给参照物，不给方案。「参考我另一个仓库」「参考某知名仓库」。自己的旧仓库是最好的规格说明。&lt;/li&gt;
&lt;li&gt;自己当第一个用户。CI 通过之后，真机上仍然会碰到问题；发现了就尽量补成检查。Pop 的卡顿检测、Meno 的隐藏和移动检查，就是让后面的改动少踩一次同样的坑。&lt;/li&gt;
&lt;li&gt;放权是阶梯式的。先逐次批准合并，再把持续开发、检查和发布的规则写下来。哪些可以自动做，哪些还要我决定，各个项目都需要说清楚。&lt;/li&gt;
&lt;li&gt;规则要写进仓库。口头说的只在一个窗口生效——我在 Pop 的窗口说了「请你总是回复中文」，同一天另一个窗口照样飘成英文。写进 CLAUDE.md 的，续接之后和另一个窗口都遵守。&lt;/li&gt;
&lt;li&gt;最花时间的反而是小事。DNS、token 的权限——这些都是只有我能动手的。&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id=&quot;代价&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#代价&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;代价&lt;/h4&gt;
&lt;p&gt;额度当然是成本。我把两个完整周的额度、250 美元赠送额度和一次额外的周额度重置都用到了极致。留下的一张截图里，全模型周额度已经用了 92%，距离重置还有 3 小时 50 分钟。这只是其中一个时刻，不是整个开发过程的用量总结。&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://blog.whrss.com/covers/menu-bar-apps-week/usage-limits.jpg&quot; alt=&quot;开发期间的一次额度使用截图&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;另外一份投入，是试用、验收和反复修问题的精力。功能做出来很快，但右键卡不卡、图标是不是真的藏好了、退出之后代理有没有恢复，都需要继续追。版本数量不能替这些问题作答。&lt;/p&gt;
&lt;p&gt;封号前，我还让 Claude 翻过自己的旧聊天。它在回溯里说，能找到的最早对话是 2023 年 7 月 14 日，从 Claude 2 开始。这个日期是它当时检索聊天记录给出的结果，我没有另外核对注册时间。现在回头看，那张截图也成了这几年使用经历的一点纪念。&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://blog.whrss.com/covers/menu-bar-apps-week/early-chats.jpg&quot; alt=&quot;封号前回溯早期聊天记录的对话&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;h4 id=&quot;写在最后&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#写在最后&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;写在最后&lt;/h4&gt;
&lt;p&gt;四个 App 都在 GitHub 上，免费开源，README 里有下载和 Homebrew 安装方式。它们都很新，解决了一些问题，也还有很多问题，用着有什么不对的，欢迎提 issue，或者直接告诉我。&lt;/p&gt;
&lt;p&gt;回头看，这段时间最大的变化是，「做产品」从「等我有精力学会了再说」变成了「想清楚要什么，然后开始」。开始做的门槛低了很多，但判断交互、发现问题、验收修复和维护软件，这些事情还在。&lt;/p&gt;
&lt;p&gt;以为自己是天选之人的时候，账号突然就封了。好在代码和开发记录留下来了。先把这四个软件继续打磨好，还有不少事情可以做。&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>博客又改了：这次连服务器都不要了</title>
    <link href="https://blog.whrss.com/posts/blog-goes-static"/>
    <id>https://blog.whrss.com/posts/blog-goes-static</id>
    <published>2026-10-02T02:00:00.000Z</published>
    <updated>2026-10-02T02:00:00.000Z</updated>
    <category term="折腾"/>
    <category term="blog"/>
    <category term="建站"/>
    <summary>上次大改才过去两周，这回干脆把 Go 后端整个删了：博客变成纯静态的页面应用，托管在 GitHub Pages 上，外观换成了冷色调的玻璃质感，每篇文章还多了一张按内容画出来的封面。</summary>
    <content type="html">&lt;p&gt;上次那轮&lt;a href=&quot;https://blog.whrss.com/posts/goblog-refactor&quot;&gt;大改&lt;/a&gt;才过去两周，我又把博客翻了一遍。这次改得更彻底：&lt;strong&gt;服务器不要了&lt;/strong&gt;。&lt;/p&gt;
&lt;h4 id=&quot;为什么&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#为什么&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;为什么&lt;/h4&gt;
&lt;p&gt;上次改完，我盘了一下这个博客真正在干的事：文章是 Markdown，放在 blog-data 仓库里；页面是服务端渲染好吐出来的；点赞、阅读数这些动态功能，我自己其实从来不看。&lt;/p&gt;
&lt;p&gt;说白了，它就是一堆静态页面，却要我维护一台服务器、一个 systemd 服务，外加一套登录后台。&lt;/p&gt;
&lt;p&gt;那还要后端干嘛？&lt;/p&gt;
&lt;h4 id=&quot;现在是什么样&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#现在是什么样&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;现在是什么样&lt;/h4&gt;
&lt;p&gt;睡前我把需求丢给了 Claude：去掉后端，改成纯页面应用，多用点玻璃特效和动画。第二天早上就有了一个能点的版本。&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;没有服务器了&lt;/strong&gt;。构建脚本读取 blog-data，生成整站静态文件，用 GitHub Actions 发布到 GitHub Pages。往 blog-data 推一篇文章，一小时内自动上线。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;像 App 一样切换页面&lt;/strong&gt;。每个页面都提前生成好 HTML，搜索引擎照样能读到全文；站内点链接时不整页刷新，卡片上的标题会「飞」进文章页。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;⌘K 搜索&lt;/strong&gt;。以前靠后端建索引，现在全文索引跟着站点一起生成，在浏览器里搜。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;旧链接都还在&lt;/strong&gt;。&lt;code&gt;/posts/...&lt;/code&gt;、&lt;code&gt;/?tag_id=&lt;/code&gt; 这些老地址一个没丢；评论区按文章原来的地址去找 GitHub Discussions，以前的评论也都在。&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;代价也有：点赞和实时阅读数没了，这两个离不开服务端。管理后台也没了，以后写文章就是直接往仓库里提交 Markdown——说实话，这反而是我最喜欢的写法。&lt;/p&gt;
&lt;h4 id=&quot;换了身衣服&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#换了身衣服&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;换了身衣服&lt;/h4&gt;
&lt;p&gt;第一版是粉紫绿的极光加毛玻璃，好看是好看，就是太「甜」了，不像一个后端的博客 😅️&lt;/p&gt;
&lt;p&gt;于是又改成了冷色调：深蓝、青、钢灰，背景铺一层很淡的工程网格，鼠标移到哪儿，哪儿的网格就被照亮。&lt;/p&gt;
&lt;p&gt;另一个变化是封面。以前卡片上要么是文章里的第一张截图，要么只有一个大字。现在每篇文章都有一张构建时画出来的封面：讲 &lt;code&gt;context&lt;/code&gt; 超时的那篇是一段 &lt;code&gt;WithTimeout&lt;/code&gt; 的代码，讲分表的是一个库拆成一堆分片，死锁那篇是两个协程抱着两把锁互相等，《五人墓碑记》是一块刻着原文的石碑。全是 SVG，不依赖任何图床。&lt;/p&gt;
&lt;h4 id=&quot;顺便说说-ai&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#顺便说说-ai&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;顺便说说 AI&lt;/h4&gt;
&lt;p&gt;和上次一样，这一轮几乎都是 Claude 干的。我做的事情只有几件：提需求，看效果，说「太甜了，要冷峻一点」「大字封面不好看」，然后决定什么时候收手。&lt;/p&gt;
&lt;p&gt;有意思的是，它自己会写测试、开浏览器截图检查效果，还会对着截图挑毛病。中途它发现导航栏的毛玻璃糊不住后面的字，来回排查了半天，最后确认是它所在的云端容器没有 GPU，软件渲染出来的假象——换成真浏览器就正常了。这种事要是我自己碰上，大概会对着 CSS 怀疑人生一晚上。&lt;/p&gt;
&lt;p&gt;从服务端渲染到纯静态，两周时间，博客的形态变了两次，而我写的代码几乎为零。&lt;/p&gt;
&lt;p&gt;上一篇结尾我说希望科技慢一点。两周过去，它并没有慢下来。&lt;/p&gt;
&lt;p&gt;既然拗不过它，那就加入它吧。&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>给博客做了一轮大改：多端、离线、服务端渲染和一堆小东西</title>
    <link href="https://blog.whrss.com/posts/goblog-refactor"/>
    <id>https://blog.whrss.com/posts/goblog-refactor</id>
    <published>2026-09-20T01:24:11.000Z</published>
    <updated>2026-09-20T01:24:11.000Z</updated>
    <category term="折腾"/>
    <category term="blog"/>
    <category term="建站"/>
    <category term="go"/>
    <summary>周末 Claude 的额度有富余，就拿来收拾许久没更新的博客。结果先发现 robots.txt 一直在拒绝所有搜索引擎，索性从前端到后台整个翻修了一遍：去掉 Bootstrap 和 jQuery 重做多端适配，Markdown 改成服务端直出，加上离线阅读、即时搜索、草稿和标签管理。最后聊了聊这轮里 Claude 帮上了什么、在哪儿翻了车，以及一点对未来的憧憬和不安。</summary>
    <content type="html">&lt;p&gt;我的博客 goblog 是自己用 Go 写的，建站 5 年多了。&lt;/p&gt;
&lt;p&gt;最近开了 Claude 的 20x 套餐——之前 5x 不够用，换成 20x 之后每周又总能剩下一些。于是周末就变着法儿想，剩下的算力还能用在哪儿。这不，许久没更新的博客正好可以拿来收拾一下 😆️&lt;/p&gt;
&lt;p&gt;在这之前，其实已经让它做过一次类似的优化：今年春天，博客从 MySQL 迁到了 GitHub 仓库存储——文章以 Markdown 放在一个叫 blog-data 的仓库里，不再需要数据库。那次也是 Claude 干的。&lt;/p&gt;
&lt;p&gt;有了上次的经验，这次我索性把整个项目连同数据一起丢给它通读了一遍，本来想看看还能加点什么好玩的功能，结果先被泼了一盆冷水。&lt;/p&gt;
&lt;h4 id=&quot;先说个让我哭笑不得的&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#先说个让我哭笑不得的&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;先说个让我哭笑不得的&lt;/h4&gt;
&lt;p&gt;我的 &lt;code&gt;robots.txt&lt;/code&gt; 里写的一直是 &lt;code&gt;Disallow: /&lt;/code&gt;——翻译过来就是：所有搜索引擎，请不要收录我的任何页面。&lt;/p&gt;
&lt;p&gt;但一直没生效，因为这文件以前叫 &lt;code&gt;robot.txt&lt;/code&gt;，少一个 s。爬虫请求 &lt;code&gt;/robots.txt&lt;/code&gt; 拿到 404，等于这文件不存在，等于随便抓。&lt;/p&gt;
&lt;p&gt;坏就坏在 5 月 7 日那次重构，我顺手把它改名成了标准的 &lt;code&gt;robots.txt&lt;/code&gt;。&lt;strong&gt;同一个提交里，我还加了 sitemap、canonical 和 OG 标签。&lt;/strong&gt; 于是从那天起，我一边认真做 SEO，一边正式通知全世界的搜索引擎：别来了。四个多月 😲️&lt;/p&gt;
&lt;p&gt;既然都发现了，索性把整个博客好好整了一遍。下面是这轮改动的点。&lt;/p&gt;
&lt;h4 id=&quot;多端适配顺便把-bootstrap-和-jquery-扔了&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#多端适配顺便把-bootstrap-和-jquery-扔了&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;多端适配，顺便把 Bootstrap 和 jQuery 扔了&lt;/h4&gt;
&lt;p&gt;原来前端是 Bootstrap + jQuery，手机上勉强能看。这次整个去掉，换成 CSS 变量加原生 JS，主题跟随系统深浅色。&lt;/p&gt;
&lt;p&gt;文章目录在宽屏是右侧粘性侧栏，窄屏收成底部抽屉。表格在手机上改成横向滚动，不再被压成一字一行。&lt;/p&gt;
&lt;h4 id=&quot;阅读体验&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#阅读体验&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;阅读体验&lt;/h4&gt;
&lt;p&gt;版面顺了，读文章这件事本身也跟着打磨了一遍：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;文末有上一篇 / 下一篇，还有相关文章（按共同标签每个 +3 分、同分类 +1 分排出来，最多 4 篇）&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;/li&gt;
&lt;/ul&gt;
&lt;h4 id=&quot;搜索与发现&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#搜索与发现&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;搜索与发现&lt;/h4&gt;
&lt;p&gt;文章多了，找起来也得方便。加了个 ⌘K 呼出的即时搜索面板，在内存里建索引，边打字边出结果。另外有个「随便看看」随机跳一篇，以及几个键盘快捷键。&lt;/p&gt;
&lt;h4 id=&quot;markdown-改成服务端直出&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#markdown-改成服务端直出&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;Markdown 改成服务端直出&lt;/h4&gt;
&lt;p&gt;前面这些都是看得见的，这块看不见，却最花时间。原来正文是在浏览器里用 editor.md（也就是 marked 0.3.3）渲染的，意味着首屏是白的、必须加载 jQuery 和整套 editor.md，而且爬虫看到的 HTML 里根本没有正文。&lt;/p&gt;
&lt;p&gt;现在改成在 Go 里用 blackfriday 直接渲染好再吐出来。麻烦在于两个渲染器对&lt;strong&gt;写得松散的 Markdown&lt;/strong&gt; 理解不一样——我这几年随手写的那些缩进不规范的嵌套列表、紧挨着列表项的代码块、中文里的 &lt;code&gt;**强调**&lt;/code&gt;，两边结果能差出十万八千里。&lt;/p&gt;
&lt;p&gt;最后是在 blackfriday 前面加了一层预处理，把这些写法按 marked 的语义先规整一遍。验证方法比较笨：同时跑服务端和客户端两个渲染实例，逐篇对比 44 篇文章的 DOM，一直调到完全一致为止。&lt;/p&gt;
&lt;p&gt;含流程图、时序图、公式的文章会自动回退到浏览器渲染，那些是 editor.md 的独有扩展。&lt;/p&gt;
&lt;h4 id=&quot;可以离线看了&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#可以离线看了&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;可以离线看了&lt;/h4&gt;
&lt;p&gt;正文直出之后，缓存下来的一份 HTML 就是完整的文章，离线阅读也就顺理成章了。于是加了 PWA，可以装到手机主屏和桌面。读过的文章会自动存下来，断网也能打开；没读过的地址会显示一个离线页，并列出本地已经缓存的文章。&lt;/p&gt;
&lt;p&gt;策略是页面走网络优先（5 秒超时回落到缓存），带指纹的静态资源缓存优先。配置里 &lt;code&gt;pwa: false&lt;/code&gt; 可以一键关掉，而且会让已经装在访客浏览器里的 Service Worker 自己注销掉，不会留尾巴。&lt;/p&gt;
&lt;h4 id=&quot;后台&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#后台&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;后台&lt;/h4&gt;
&lt;p&gt;前台说完，说说后台。手机上终于能用了，列表、表单、编辑器都重新排过。&lt;/p&gt;
&lt;p&gt;另外几个实用的：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;草稿&lt;/strong&gt;。没写完的文章存在服务器的 &lt;code&gt;.drafts/&lt;/code&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;code&gt; blog&lt;/code&gt;、&lt;code&gt; mysql&lt;/code&gt; 就是这么清掉的。&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id=&quot;seo-和性能&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#seo-和性能&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;SEO 和性能&lt;/h4&gt;
&lt;p&gt;再回到开头那个 &lt;code&gt;robots.txt&lt;/code&gt;。除了把它改成只屏蔽 &lt;code&gt;/admin/&lt;/code&gt;、&lt;code&gt;/api/&lt;/code&gt; 这些，还补上了 canonical、Open Graph / Twitter Card（自动取文内首图）、JSON-LD 结构化数据，sitemap 地址也自动带在 robots 里。&lt;/p&gt;
&lt;p&gt;静态资源加了指纹，带指纹的缓存一年，其余缓存一天。&lt;/p&gt;
&lt;h4 id=&quot;一些小玩意&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#一些小玩意&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;一些小玩意&lt;/h4&gt;
&lt;p&gt;最后是一些纯属好玩的东西。做了个 &lt;code&gt;/stats&lt;/code&gt; 博客数据页，能看到写了多少字、各分类占比、时间进度这些。还有「那年今日」、文章点赞、一个终端风格的 404 页，以及几个彩蛋。&lt;/p&gt;
&lt;p&gt;改动大概就是这些。前后跑了 11 个版本，从 1.1.0 到 1.10.0，现在在手机上读自己的文章终于是件舒服的事了，断网也能看，完美～&lt;/p&gt;
&lt;h4 id=&quot;顺便说说-ai&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#顺便说说-ai&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;顺便说说 AI&lt;/h4&gt;
&lt;p&gt;这轮改动基本是我和 Claude 一起做的，感受挺复杂。&lt;/p&gt;
&lt;p&gt;强的地方是穷举和耐心。&lt;code&gt;robots.txt&lt;/code&gt; 那个问题，得把文件内容、改名历史、还有“同一个提交里顺手加了 SEO 标签”这三件事串起来才能看出名堂，我自己盯一百遍也不会往那儿想。服务端渲染那块更典型——为了让输出和 editor.md 对得上，它去模拟 marked 对松散 Markdown 的理解，然后逐篇对比 44 篇文章的 DOM，一直调到完全一致。这种活儿枯燥到人根本干不下去。&lt;/p&gt;
&lt;p&gt;但翻车也不少。上线时它没料到我服务器上压根没装 Go，部署断在一半，站点样式花了好几分钟；给我写的部署脚本在 macOS 自带的 bash 3.2 上直接报错，因为它是按 bash 5 的行为写的；这篇文章的第一版整个写偏了方向，我说不对味儿才回炉重写。初稿里还有它自己记岔的细节，比如把文章过期提醒的阈值写成三年——代码里明明是它自己写的两年——这种硬伤还是靠事后逐条核对才揪出来的。&lt;/p&gt;
&lt;p&gt;不过话说回来，这些翻车基本都是我提一句、它自己就改回来了。整个过程里真正需要我动手的地方非常少，我只需要管一个大的方向：做什么、做到什么程度、什么时候收手。&lt;/p&gt;
&lt;h4 id=&quot;最后一点憧憬和不安&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#最后一点憧憬和不安&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;最后，一点憧憬和不安&lt;/h4&gt;
&lt;p&gt;就这次的体验来说，目前的 Claude Fable 5.1 已经足够支撑这种要求和标准都不那么严苛的项目开发了，人工介入的内容非常少，只需要管理一个大的方向。&lt;/p&gt;
&lt;p&gt;再往后，算力持续提升，模型能力和硬件一起往上走，感觉「程序员」这个岗位会缩减得非常厉害——每家公司可能只需要若干个“懂产品”的架构师就差不多了。或许在看得见的几年里，就能有非常明显的变化。&lt;/p&gt;
&lt;p&gt;三年多前我写过一篇&lt;a href=&quot;https://blog.whrss.com/posts/the-ai-challenge&quot;&gt;《惊喜又焦虑，AI 技术的发展》&lt;/a&gt;，那时候担心的事，现在正在一件件变成现实。&lt;/p&gt;
&lt;p&gt;说实话，我现在越来越希望科技发展得慢一点。这个变化对于我们这一代人来说，似乎还是太快了，充满了不确定性。&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>一致性事务：从 2PC 到 Outbox pattern</title>
    <link href="https://blog.whrss.com/posts/transaction-consistency-patterns-2pc-outbox"/>
    <id>https://blog.whrss.com/posts/transaction-consistency-patterns-2pc-outbox</id>
    <published>2025-11-28T15:08:22.000Z</published>
    <updated>2025-11-28T15:08:22.000Z</updated>
    <category term="技术"/>
    <summary>如果你做过一点微服务开发，大概率都遇到过这种场景：
用户下单 → 扣库存 → 扣余额 → 更新积分。
这听上去很简单，按顺序写几行逻辑就好，但问题是——这些操作分散在不同的服务、不同的数据库里。 于是问题来了： 如果中间有一步失败了，整个流程该怎么办？
- 订单创建了，但库存没扣？ - 库存扣了，但支付失败？ - 消息没发出去，用户看不到状态？
这就是经典的分布式事务一致性问题。</summary>
    <content type="html">&lt;h2 id=&quot;前言分布式系统里最让人头疼的事&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#前言分布式系统里最让人头疼的事&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;前言：分布式系统里最让人头疼的事&lt;/h2&gt;
&lt;p&gt;如果你做过一点微服务开发，大概率都遇到过这种场景：&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;用户下单 → 扣库存 → 扣余额 → 更新积分。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;这听上去很简单，按顺序写几行逻辑就好，但问题是——这些操作分散在不同的服务、不同的数据库里。&lt;br&gt;于是问题来了：&lt;br&gt;&lt;strong&gt;如果中间有一步失败了，整个流程该怎么办？&lt;/strong&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;strong&gt;分布式事务一致性问题&lt;/strong&gt;。&lt;br&gt;今天我们就从最早的 2PC（两阶段提交）开始，一路讲到现在大家更常用的 Outbox 模式，看看这一路我们是怎么在”理想”和”现实”之间反复拉扯的。&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;一理想中的完美方案2pc两阶段提交&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#一理想中的完美方案2pc两阶段提交&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;一、理想中的完美方案：2PC（两阶段提交）&lt;/h2&gt;
&lt;p&gt;2PC，全称 Two Phase Commit。&lt;br&gt;听起来就很有那味儿：&lt;strong&gt;让多个数据库像一个事务一样提交或回滚。&lt;/strong&gt;&lt;/p&gt;
&lt;h3 id=&quot;它是怎么工作的&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#它是怎么工作的&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;它是怎么工作的？&lt;/h3&gt;
&lt;p&gt;顾名思义，它分两步走：&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Prepare 阶段（投票阶段）&lt;/strong&gt;&lt;br&gt; 协调者（Coordinator）告诉所有参与者（数据库、服务）：”兄弟们，准备一下，看你们能不能提交。”&lt;br&gt; 每个参与者检查本地事务是否能成功，如果没问题，就写好日志、&lt;strong&gt;锁住资源&lt;/strong&gt;，回复一句”我准备好了（YES）”。如果不行，就回复”NO”。&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Commit/Abort 阶段（执行阶段）&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;如果&lt;strong&gt;所有人&lt;/strong&gt;都回复”YES”，协调者就广播”Commit！”，大家正式提交。&lt;/li&gt;
&lt;li&gt;如果&lt;strong&gt;任何一个&lt;/strong&gt;回复”NO”或超时，协调者就广播”Abort！”，大家全部回滚。&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;听上去很完美，对吧？所有操作都能保持一致，&lt;strong&gt;要么都成功，要么都失败。&lt;/strong&gt;&lt;/p&gt;
&lt;h3 id=&quot;举个例子&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#举个例子&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;举个例子&lt;/h3&gt;
&lt;p&gt;假设我们有订单服务、库存服务、支付服务。&lt;br&gt;在一次下单操作里：&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;协调者发送”Prepare”命令。&lt;/li&gt;
&lt;li&gt;三个服务各自检查：订单能建、库存够、余额足。&lt;/li&gt;
&lt;li&gt;都返回”YES”。&lt;/li&gt;
&lt;li&gt;协调者发送”Commit”，大家一起完成事务。&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;理想中，这就是”强一致性”的完美世界。&lt;/p&gt;
&lt;h3 id=&quot;可惜现实很骨感&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#可惜现实很骨感&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;可惜，现实很骨感&lt;/h3&gt;
&lt;p&gt;2PC 在实际应用中面临严重的工程问题：&lt;/p&gt;
&lt;h4 id=&quot;1-阻塞问题&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#1-阻塞问题&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;1. &lt;strong&gt;阻塞问题&lt;/strong&gt;&lt;/h4&gt;
&lt;p&gt;参与者在 Prepare 阶段后会&lt;strong&gt;持有锁&lt;/strong&gt;并等待协调者的最终指令。如果协调者响应慢或网络延迟，所有参与者都会阻塞，严重影响系统吞吐量。&lt;/p&gt;
&lt;h4 id=&quot;2-单点故障&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#2-单点故障&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;2. &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;发送 Commit/Abort 的过程中&lt;/strong&gt;崩溃（部分参与者收到消息，部分没收到），就会导致&lt;strong&gt;数据不一致&lt;/strong&gt;：&lt;ul&gt;
&lt;li&gt;收到 Commit 的节点已经提交&lt;/li&gt;
&lt;li&gt;没收到消息的节点还在等待或已超时回滚&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id=&quot;3-网络问题&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#3-网络问题&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;3. &lt;strong&gt;网络问题&lt;/strong&gt;&lt;/h4&gt;
&lt;p&gt;在网络状况的影响下，部分参与者可能收不到协调者的消息，导致长时间持锁或数据不一致。&lt;/p&gt;
&lt;h4 id=&quot;4-性能问题&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#4-性能问题&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;4. &lt;strong&gt;性能问题&lt;/strong&gt;&lt;/h4&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;br&gt;所以 2PC 在实际分布式场景中，&lt;strong&gt;主要用于数据库内部实现，很少在应用层使用。&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;一句话总结：&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;2PC 理论完美，工程地狱。它保证了强一致性，但牺牲了可用性和性能。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;hr&gt;
&lt;h2 id=&quot;二退一步saga-模式补偿事务&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#二退一步saga-模式补偿事务&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;二、退一步：Saga 模式（补偿事务）&lt;/h2&gt;
&lt;p&gt;既然”强一致”做不到，那我们退一步，追求”&lt;strong&gt;最终一致&lt;/strong&gt;“。&lt;br&gt;这就是 Saga 模式的思路。&lt;/p&gt;
&lt;h3 id=&quot;核心思想&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#核心思想&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;核心思想&lt;/h3&gt;
&lt;p&gt;不再要求”原子性地回滚”，而是让每个服务各自完成自己的本地事务。&lt;br&gt;如果中间某一步失败，就执行 &lt;strong&gt;“补偿操作”（Compensation）&lt;/strong&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;h3 id=&quot;saga-的两种实现方式&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#saga-的两种实现方式&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;Saga 的两种实现方式&lt;/h3&gt;
&lt;h4 id=&quot;1-编排式orchestration&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#1-编排式orchestration&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;1. &lt;strong&gt;编排式（Orchestration）&lt;/strong&gt;&lt;/h4&gt;
&lt;p&gt;由一个中央协调器负责调度各个步骤：&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs&quot;&gt;订单服务（协调器）：
1. 调用库存服务扣库存
2. 调用支付服务扣款
3. 调用积分服务加积分
4. 如果任一步失败，依次调用补偿接口&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;h4 id=&quot;2-编舞式choreography&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#2-编舞式choreography&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;2. &lt;strong&gt;编舞式（Choreography）&lt;/strong&gt;&lt;/h4&gt;
&lt;p&gt;各服务通过事件驱动自行协作：&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs&quot;&gt;订单服务 → 发布&amp;quot;订单已创建&amp;quot;事件
库存服务 → 监听事件，扣库存，发布&amp;quot;库存已扣&amp;quot;事件
支付服务 → 监听事件，扣款，发布&amp;quot;支付成功&amp;quot;事件
如果支付失败 → 发布&amp;quot;支付失败&amp;quot;事件
库存服务 → 监听到失败事件，执行库存补偿&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;h3 id=&quot;举个例子下单流程-saga-化&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#举个例子下单流程-saga-化&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;举个例子：下单流程 Saga 化&lt;/h3&gt;
&lt;p&gt;假设业务流程：&lt;/p&gt;
&lt;ol&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;/ol&gt;
&lt;p&gt;如果第 3 步（扣余额）失败了，那就&lt;strong&gt;按相反顺序&lt;/strong&gt;触发补偿逻辑：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;恢复库存（补偿操作）&lt;/li&gt;
&lt;li&gt;取消订单（补偿操作）&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;需要注意的关键问题&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#需要注意的关键问题&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;需要注意的关键问题&lt;/h3&gt;
&lt;h4 id=&quot;1-补偿操作的设计难度&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#1-补偿操作的设计难度&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;1. &lt;strong&gt;补偿操作的设计难度&lt;/strong&gt;&lt;/h4&gt;
&lt;ul&gt;
&lt;li&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;h4 id=&quot;2-某些操作难以或无法补偿&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#2-某些操作难以或无法补偿&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;2. &lt;strong&gt;某些操作难以或无法补偿&lt;/strong&gt;&lt;/h4&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;h4 id=&quot;3-中间状态可见性&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#3-中间状态可见性&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;3. &lt;strong&gt;中间状态可见性&lt;/strong&gt;&lt;/h4&gt;
&lt;p&gt;Saga 过程中，其他事务可能看到&lt;strong&gt;不一致的中间状态&lt;/strong&gt;：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;订单已创建，但支付还在处理中&lt;/li&gt;
&lt;li&gt;库存已扣，但订单被取消（正在补偿）&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;这要求业务设计时考虑这些中间态。&lt;/p&gt;
&lt;h3 id=&quot;优缺点&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#优缺点&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;优缺点&lt;/h3&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;：单个服务故障不会阻塞整个流程&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;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;：分布式环境下追踪问题链路长&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;p&gt;一句话总结：&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Saga 是”可控的混乱”：牺牲了强一致性和隔离性，换来了性能和可用性。适合大部分业务场景，但需要精心设计。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;hr&gt;
&lt;h2 id=&quot;三现实中更优雅的方案outbox-pattern事件表&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#三现实中更优雅的方案outbox-pattern事件表&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;三、现实中更优雅的方案：Outbox Pattern（事件表）&lt;/h2&gt;
&lt;p&gt;再往后，很多系统变成了&lt;strong&gt;事件驱动架构&lt;/strong&gt;。&lt;br&gt;这时一个新问题出现了：&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;我更新了数据库后，要发一条消息到 MQ，但如果发 MQ 时系统挂了怎么办？&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;比如：&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;创建订单（DB 成功）&lt;/li&gt;
&lt;li&gt;发送 “OrderCreated” 消息到 Kafka（&lt;strong&gt;失败或未执行&lt;/strong&gt;）&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;数据库里已经有订单，但消息没发出去，下游服务不知道有新订单，系统就不一致了。&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;你可能会想：那我先发消息，再写数据库？&lt;/strong&gt;&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs&quot;&gt;1. 发送消息到 Kafka（成功）
2. 创建订单（失败）&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;这样更糟：消息发出去了，但数据库里没有订单，下游收到的是”幽灵订单”。&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;核心问题是：这是两个不同的系统（数据库 + 消息队列），无法在一个事务中原子性地完成。&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;这时，Outbox Pattern 登场。&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;核心思路&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#核心思路&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;核心思路&lt;/h3&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;ol&gt;
&lt;li&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;同时插入一条待发送的消息到 &lt;code&gt;outbox_messages&lt;/code&gt; 表&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;后台异步发送&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;定时任务/CDC/消息中继扫描 &lt;code&gt;outbox_messages&lt;/code&gt; 表&lt;/li&gt;
&lt;li&gt;找到未发送的消息&lt;/li&gt;
&lt;li&gt;发送到 MQ&lt;/li&gt;
&lt;li&gt;标记为”已发送”&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;这样，&lt;strong&gt;数据库保证了业务数据和消息记录的原子性&lt;/strong&gt;，即使系统崩溃，重启后也能继续发送未完成的消息。&lt;br&gt;&lt;img src=&quot;https://github.com/aws-samples/transactional-outbox-pattern/blob/main/img/outbox-sample-infra.png?raw=true&quot; alt=&quot;这是图片&quot; title=&quot;Magic Gardens&quot; loading=&quot;eager&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;h3 id=&quot;举个实际例子&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#举个实际例子&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;举个实际例子&lt;/h3&gt;
&lt;h4 id=&quot;业务代码&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#业务代码&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;业务代码：&lt;/h4&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;sql&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sql&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;BEGIN&lt;/span&gt; TRANSACTION;

&lt;span class=&quot;hljs-comment&quot;&gt;-- 1. 插入订单&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;INSERT INTO&lt;/span&gt; orders (id, user_id, amount, status) 
&lt;span class=&quot;hljs-keyword&quot;&gt;VALUES&lt;/span&gt; (&lt;span class=&quot;hljs-number&quot;&gt;123&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;42&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;100&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;created&amp;#x27;&lt;/span&gt;);

&lt;span class=&quot;hljs-comment&quot;&gt;-- 2. 插入待发送的消息（同一个事务）&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;INSERT INTO&lt;/span&gt; outbox_messages (
    id, 
    aggregate_type, 
    aggregate_id, 
    event_type, 
    payload, 
    status,
    created_at
) &lt;span class=&quot;hljs-keyword&quot;&gt;VALUES&lt;/span&gt; (
    &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;msg-uuid-001&amp;#x27;&lt;/span&gt;,
    &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;Order&amp;#x27;&lt;/span&gt;,
    &lt;span class=&quot;hljs-number&quot;&gt;123&lt;/span&gt;,
    &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;OrderCreated&amp;#x27;&lt;/span&gt;,
    &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;{&amp;quot;order_id&amp;quot;:123,&amp;quot;user_id&amp;quot;:42,&amp;quot;amount&amp;quot;:100}&amp;#x27;&lt;/span&gt;,
    &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;pending&amp;#x27;&lt;/span&gt;,
    NOW()
);

&lt;span class=&quot;hljs-keyword&quot;&gt;COMMIT&lt;/span&gt;;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;h4 id=&quot;异步消息发送器&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#异步消息发送器&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;异步消息发送器：&lt;/h4&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;// 定时任务或 CDC 流程&lt;/span&gt;
&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;publishOutboxMessages&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;()&lt;/span&gt;&lt;/span&gt; {
    &lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; {
        &lt;span class=&quot;hljs-comment&quot;&gt;// 查询待发送的消息（带锁，避免并发冲突）&lt;/span&gt;
        messages := db.Query(&lt;span class=&quot;hljs-string&quot;&gt;`
            SELECT id, event_type, payload 
            FROM outbox_messages 
            WHERE status = &amp;#x27;pending&amp;#x27;
            ORDER BY created_at ASC
            LIMIT 100
            FOR UPDATE SKIP LOCKED
        `&lt;/span&gt;)
        
        &lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; msg := &lt;span class=&quot;hljs-keyword&quot;&gt;range&lt;/span&gt; messages {
            &lt;span class=&quot;hljs-comment&quot;&gt;// 先标记为处理中&lt;/span&gt;
            db.Exec(&lt;span class=&quot;hljs-string&quot;&gt;`
                UPDATE outbox_messages 
                SET status = &amp;#x27;processing&amp;#x27; 
                WHERE id = ?
            `&lt;/span&gt;, msg.id)
            
            &lt;span class=&quot;hljs-comment&quot;&gt;// 发送到消息队列&lt;/span&gt;
            err := kafka.Send(msg.eventType, msg.payload)
            
            &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; err != &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt; {
                &lt;span class=&quot;hljs-comment&quot;&gt;// 失败，重置状态，稍后重试&lt;/span&gt;
                db.Exec(&lt;span class=&quot;hljs-string&quot;&gt;`
                    UPDATE outbox_messages 
                    SET status = &amp;#x27;pending&amp;#x27;, 
                        retry_count = retry_count + 1 
                    WHERE id = ?
                `&lt;/span&gt;, msg.id)
            } &lt;span class=&quot;hljs-keyword&quot;&gt;else&lt;/span&gt; {
                &lt;span class=&quot;hljs-comment&quot;&gt;// 成功，标记为已发送&lt;/span&gt;
                db.Exec(&lt;span class=&quot;hljs-string&quot;&gt;`
                    UPDATE outbox_messages 
                    SET status = &amp;#x27;sent&amp;#x27;, 
                        sent_at = NOW() 
                    WHERE id = ?
                `&lt;/span&gt;, msg.id)
            }
        }
        
        time.Sleep(&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt; * time.Second)
    }
}&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;h3 id=&quot;关键技术点&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#关键技术点&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;关键技术点&lt;/h3&gt;
&lt;h4 id=&quot;1-消息幂等性&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#1-消息幂等性&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;1. &lt;strong&gt;消息幂等性&lt;/strong&gt;&lt;/h4&gt;
&lt;p&gt;消费者必须能处理重复消息（Outbox 可能重发）：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;每条消息带唯一 ID （类似幂等 Key）&lt;/li&gt;
&lt;li&gt;消费者用消息 ID 去重&lt;/li&gt;
&lt;li&gt;或设计其他幂等的业务操作&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id=&quot;2-消息顺序&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#2-消息顺序&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;2. &lt;strong&gt;消息顺序&lt;/strong&gt;&lt;/h4&gt;
&lt;p&gt;如果业务需要保证顺序：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;按 &lt;code&gt;created_at&lt;/code&gt; 顺序发送&lt;/li&gt;
&lt;li&gt;或使用分区键保证同一实体的事件有序&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id=&quot;3-outbox-表清理&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#3-outbox-表清理&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;3. &lt;strong&gt;Outbox 表清理&lt;/strong&gt;&lt;/h4&gt;
&lt;p&gt;已发送的消息要定期清理或归档：&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;sql&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sql&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;DELETE&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;FROM&lt;/span&gt; outbox_messages 
&lt;span class=&quot;hljs-keyword&quot;&gt;WHERE&lt;/span&gt; status &lt;span class=&quot;hljs-operator&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;sent&amp;#x27;&lt;/span&gt; 
  &lt;span class=&quot;hljs-keyword&quot;&gt;AND&lt;/span&gt; sent_at &lt;span class=&quot;hljs-operator&quot;&gt;&amp;lt;&lt;/span&gt; NOW() &lt;span class=&quot;hljs-operator&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;INTERVAL&lt;/span&gt; &lt;span class=&quot;hljs-number&quot;&gt;7&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;DAY&lt;/span&gt;;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;h4 id=&quot;4-使用-cdc-change-data-capture-优化&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#4-使用-cdc-change-data-capture-优化&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;4. &lt;strong&gt;使用 CDC (Change Data Capture) 优化&lt;/strong&gt;&lt;/h4&gt;
&lt;p&gt;可以用 Debezium 等 CDC 工具监听数据库变更日志，自动捕获 Outbox 表的插入事件并发送到 Kafka，无需轮询。&lt;/p&gt;
&lt;h3 id=&quot;优缺点-2&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#优缺点-2&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;优缺点&lt;/h3&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;：异步解耦，不阻塞主流程&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;可靠性高&lt;/strong&gt;：消息不会丢失，故障恢复能力强&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;实现相对简单&lt;/strong&gt;：比 Saga 的补偿逻辑简单&lt;/li&gt;
&lt;/ul&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;需要额外维护 Outbox 表&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;p&gt;一句话总结：&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Outbox Pattern 是一种”落地级方案”：用一个本地事务表巧妙地解决了”数据库 + 消息队列”的一致性问题，既保证可靠性，又能保持高性能。是现代事件驱动架构的标配。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;hr&gt;
&lt;h2 id=&quot;四三种方案对比总结&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#四三种方案对比总结&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;⚖️ 四、三种方案对比总结&lt;/h2&gt;
&lt;div class=&quot;table-wrap&quot;&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;模式&lt;/th&gt;
&lt;th&gt;一致性保证&lt;/th&gt;
&lt;th&gt;性能&lt;/th&gt;
&lt;th&gt;复杂度&lt;/th&gt;
&lt;th&gt;隔离性&lt;/th&gt;
&lt;th&gt;典型场景&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;2PC&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;强一致&lt;/td&gt;
&lt;td&gt;中低&lt;br/&gt;（同步阻塞）&lt;/td&gt;
&lt;td&gt;中&lt;br/&gt;（协议简单但容错复杂）&lt;/td&gt;
&lt;td&gt;有&lt;br/&gt;（持锁）&lt;/td&gt;
&lt;td&gt;数据库内部事务&lt;br/&gt;小规模强一致场景&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Saga&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;最终一致&lt;/td&gt;
&lt;td&gt;高&lt;br/&gt;（无全局锁）&lt;/td&gt;
&lt;td&gt;高&lt;br/&gt;（补偿逻辑、状态机、幂等）&lt;/td&gt;
&lt;td&gt;无&lt;br/&gt;（中间态可见）&lt;/td&gt;
&lt;td&gt;长事务业务流程&lt;br/&gt;订单、支付、审批&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Outbox&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;最终一致&lt;/td&gt;
&lt;td&gt;高&lt;br/&gt;（异步解耦）&lt;/td&gt;
&lt;td&gt;中&lt;br/&gt;（消息表管理）&lt;/td&gt;
&lt;td&gt;不适用&lt;/td&gt;
&lt;td&gt;事件驱动系统&lt;br/&gt;可靠消息投递&lt;br/&gt;数据库-MQ 一致性&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;h3 id=&quot;如何选择&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#如何选择&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;如何选择？&lt;/h3&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs&quot;&gt;📌 单体应用内的操作
   → 用本地数据库事务（ACID）

📌 跨服务的业务流程（如下单、支付、发货）
   → 用 Saga（编排式或编舞式）

📌 数据库操作 + 发送消息到 MQ
   → 用 Outbox Pattern

📌 关键金融交易（转账、结算）
   → 考虑 TCC (Try-Confirm-Cancel) 或事件溯源

❌ 避免在应用层使用 2PC
   → 除非是数据库底层实现，或极小规模的强一致场景&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;hr&gt;
&lt;h2 id=&quot;五写在最后一致性没有完美解&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#五写在最后一致性没有完美解&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;五、写在最后：一致性没有完美解&lt;/h2&gt;
&lt;p&gt;现实世界里，没有完美的”分布式一致性”方案。&lt;br&gt;不同业务场景，不同需求下，我们都在平衡：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;一致性 vs 性能&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;简单 vs 灵活&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;强一致 vs 最终一致&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;理论完美 vs 工程可行&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;blockquote&gt;
&lt;p&gt;真正的目标不是”完美一致”，&lt;br&gt;而是”在可接受的时间窗口内，达到业务所需的一致程度”。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3 id=&quot;工程上的务实原则&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#工程上的务实原则&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;工程上的务实原则&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;能用单体事务就别分布式&lt;/strong&gt;&lt;br&gt; 如果功能可以在一个服务内完成，就用本地事务，不要为了”微服务”而微服务。&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;异步优于同步&lt;/strong&gt;&lt;br&gt; 大部分业务场景都能接受”最终一致”，几秒的延迟换来的是更高的性能和可用性。&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;补偿优于回滚&lt;/strong&gt;&lt;br&gt; 现实业务中很多操作本身就无法”撤销”，补偿是更符合业务语义的方式。&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;监控和可观测性是关键&lt;/strong&gt;&lt;br&gt; 分布式系统出问题是常态，重要的是能快速发现、定位和恢复。&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;测试、测试、还是测试&lt;/strong&gt;&lt;br&gt; 补偿逻辑、幂等性、重试机制都要充分测试，包括网络分区、节点宕机等异常场景。&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;hr&gt;
&lt;p&gt;如果你在设计”订单 + 库存 + 支付”这样的系统：&lt;/p&gt;
&lt;p&gt;✅ 用 &lt;strong&gt;Saga&lt;/strong&gt; 编排业务流程（订单创建 → 扣库存 → 扣款 → 发货）&lt;br&gt;✅ 用 &lt;strong&gt;Outbox&lt;/strong&gt; 保证每个服务的数据变更能可靠地发布事件&lt;br&gt;✅ 让消费者实现&lt;strong&gt;幂等&lt;/strong&gt;，处理可能的重复消息&lt;br&gt;✅ 设计好&lt;strong&gt;监控和告警&lt;/strong&gt;，及时发现补偿失败或消息积压&lt;/p&gt;
&lt;p&gt;这，就是工程上的”务实一致性”。&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;&lt;strong&gt;参考资料：&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Martin Fowler - &lt;a href=&quot;https://microservices.io/patterns/data/transactional-outbox.html&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;The Transactional Outbox Pattern&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Chris Richardson - &lt;a href=&quot;https://microservices.io/patterns/data/saga.html&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;Saga Pattern&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://dataintensive.net/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;Designing Data-Intensive Applications&lt;/a&gt; by Martin Kleppmann&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://docs.aws.amazon.com/prescriptive-guidance/latest/cloud-design-patterns/transactional-outbox.html&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;https://docs.aws.amazon.com/prescriptive-guidance/latest/cloud-design-patterns/transactional-outbox.html&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</content>
  </entry>
  <entry>
    <title>鸿蒙 OS 的签名密钥机制，我终于整明白了！</title>
    <link href="https://blog.whrss.com/posts/harmonyos-signing-key"/>
    <id>https://blog.whrss.com/posts/harmonyos-signing-key</id>
    <published>2025-07-20T04:47:36.000Z</published>
    <updated>2025-07-20T04:47:36.000Z</updated>
    <category term="技术"/>
    <category term="huawei"/>
    <category term="harmony"/>
    <category term="signing-key"/>
    <summary>在做移动应用开发时，不管是 Android 还是 iOS，我们都绕不开“签名”这件事。最近我们项目在筹备适配 HarmonyOS NEXT（鸿蒙 Next） 的 SDK，也顺势把鸿蒙的签名机制研究了一遍。这篇文章来分享下。</summary>
    <content type="html">&lt;p&gt;在做移动应用开发时，不管是 Android 还是 iOS，我们都绕不开“签名”这件事。最近我们项目在筹备适配 &lt;strong&gt;HarmonyOS NEXT（鸿蒙 Next）&lt;/strong&gt; 的 SDK，也顺势把鸿蒙的签名机制研究了一遍。这篇文章来分享下。&lt;/p&gt;
&lt;p&gt;简单来说，&lt;strong&gt;签名的目的是确保应用的来源可信、内容完整、平台可识别&lt;/strong&gt;。我们开发的应用，最终都要交给系统安装，那系统当然得确认一下：这个包是“你”发的、这包在传输过程中没被篡改、它是我允许安装的对象。这就要靠数字签名。&lt;/p&gt;
&lt;p&gt;说到底，数字签名就是：&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;用私钥对应用包里的内容摘要加密，生成一个签名块，塞进包里。&lt;/strong&gt;&lt;br&gt;系统在安装时用你当初的公钥解密它，校验签名是否匹配。如果一切对得上，才会放行。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;我们先复习下 Android 和 iOS 的签名流程，再看看鸿蒙的做法是怎么“融合创新”的。&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;android-签名机制回顾&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#android-签名机制回顾&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;Android 签名机制回顾&lt;/h2&gt;
&lt;p&gt;搞过 Android 的同学都知道，签名这套流程绕不开 &lt;strong&gt;Keystore 文件（.jks 或 .keystore）&lt;/strong&gt;。它是个密钥库，里面有你生成的一对公私钥。&lt;/p&gt;
&lt;p&gt;生成方法嘛，Android Studio 自带的工具或者命令行 &lt;code&gt;keytool&lt;/code&gt; 都能搞。你得设置密码、别名、组织机构之类的。&lt;/p&gt;
&lt;p&gt;签名流程一般是：&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;p&gt;用 &lt;code&gt;apksigner&lt;/code&gt; 或 &lt;code&gt;jarsigner&lt;/code&gt; 对 APK 进行签名；&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;安装时，系统会从 APK 中提取签名块；&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;用嵌入的 &lt;strong&gt;公钥&lt;/strong&gt; 验签；&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;检查包的内容有没有被改动。&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;重点是——&lt;strong&gt;升级包必须用相同密钥签名！&lt;/strong&gt;&lt;br&gt;否则就会被系统拦下来，提示你“签名不一致，不能覆盖安装”。&lt;/p&gt;
&lt;p&gt;后来 Google 推出了 &lt;strong&gt;App Signing by Google Play&lt;/strong&gt; 服务。你可以只上传未签名的 APK 或用上传密钥签过的 APK，真正的签名工作交给 Google，它用你存的密钥进行最终签名和分发。&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;ios-签名机制回顾&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#ios-签名机制回顾&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;iOS 签名机制回顾&lt;/h2&gt;
&lt;p&gt;iOS 的签名体系就偏“官僚”一点，全靠 Apple 的一套证书系统撑着。&lt;/p&gt;
&lt;p&gt;要发布一个 iOS 应用，你得准备这三样东西：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;.cer&lt;/code&gt;：Apple 颁发的开发者证书，内含你的公钥和身份；&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;.p12&lt;/code&gt;：你本地生成的私钥文件，用于签名；&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;.mobileprovision&lt;/code&gt;：描述文件，绑定了证书、App ID、设备 ID 等。&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;整个签名过程和证书链校验基本都在 Apple 的 Xcode 工具和 Apple 服务端完成。只要你照着官方流程来，一般不会出啥问题。&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;鸿蒙-next签名机制融合-android-ios-的思路&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#鸿蒙-next签名机制融合-android-ios-的思路&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;鸿蒙 Next：签名机制融合 Android + iOS 的思路&lt;/h2&gt;
&lt;p&gt;我们项目要接入鸿蒙 Next，第一件事就是：搞清楚签名密钥这一套怎么玩。研究之后发现，鸿蒙的机制融合了 Android 的密钥库和 iOS 的证书申请体系，整体看起来像是“&lt;strong&gt;Android 的私钥管理 + iOS 的证书申请 + 描述文件配置&lt;/strong&gt;”。&lt;/p&gt;
&lt;h3 id=&quot;一共涉及-4-个关键文件&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#一共涉及-4-个关键文件&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;一共涉及 4 个关键文件：&lt;/h3&gt;
&lt;div class=&quot;table-wrap&quot;&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;文件名&lt;/th&gt;
&lt;th&gt;用途&lt;/th&gt;
&lt;th&gt;格式&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;&lt;tr&gt;
&lt;td&gt;Keystore&lt;/td&gt;
&lt;td&gt;储存公私钥&lt;/td&gt;
&lt;td&gt;&lt;code&gt;.p12&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;CSR（证书请求）&lt;/td&gt;
&lt;td&gt;提交给华为申请证书&lt;/td&gt;
&lt;td&gt;&lt;code&gt;.csr&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;数字证书&lt;/td&gt;
&lt;td&gt;华为签发的开发/发布证书&lt;/td&gt;
&lt;td&gt;&lt;code&gt;.cer&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;描述文件 Profile&lt;/td&gt;
&lt;td&gt;应用权限、设备、证书绑定等信息&lt;/td&gt;
&lt;td&gt;&lt;code&gt;.p7b&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;hr&gt;
&lt;h2 id=&quot;签名流程详解一步步把包合法化&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#签名流程详解一步步把包合法化&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;签名流程详解：一步步把包“合法化”&lt;/h2&gt;
&lt;h3 id=&quot;1-本地生成-p12-文件-创建密钥对&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#1-本地生成-p12-文件-创建密钥对&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;1. 本地生成 &lt;code&gt;.p12&lt;/code&gt; 文件 —— 创建密钥对&lt;/h3&gt;
&lt;p&gt;你用 DevEco Studio 在本地生成 &lt;code&gt;.p12&lt;/code&gt;，里面有一对非对称密钥对（公钥 + 私钥）。&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;私钥以后用来签名 HAP（HarmonyOS 应用包）；&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;公钥则被嵌入到 &lt;code&gt;.csr&lt;/code&gt; 文件里，发给华为去申请证书。&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;2-生成-csr-文件-证书请求&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#2-生成-csr-文件-证书请求&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;2. 生成 &lt;code&gt;.csr&lt;/code&gt; 文件 —— 证书请求&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;.csr&lt;/code&gt; 文件是你发给华为的“申请信”，它里面包含了：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;你的身份信息（开发者名、组织名等）；&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;你刚刚生成的公钥。&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;这一点就跟 iOS 的证书申请很像。&lt;/p&gt;
&lt;h3 id=&quot;3-提交-csr-到-appgallery-connect申请-cer-数字证书&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#3-提交-csr-到-appgallery-connect申请-cer-数字证书&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;3. 提交 &lt;code&gt;.csr&lt;/code&gt; 到 AppGallery Connect，申请 &lt;code&gt;.cer&lt;/code&gt; 数字证书&lt;/h3&gt;
&lt;p&gt;这个时候，轮到华为出场了。它会用自己的 &lt;strong&gt;CA 私钥&lt;/strong&gt; 给你签发一张开发证书（&lt;code&gt;.cer&lt;/code&gt; 文件）。这个证书里包含：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;你的身份信息；&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;你的公钥；&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;华为 CA 的签名，确保这张证书是“正宗华为出品”。&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;blockquote&gt;
&lt;p&gt;通过解析 .csr 的公钥和 .cer 中的开发证书公钥可以发现是同一个。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;这样就构建了一条完整的信任链。&lt;/p&gt;
&lt;h3 id=&quot;4-构建证书链验证签名合法性&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#4-构建证书链验证签名合法性&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;4. 构建证书链，验证签名合法性&lt;/h3&gt;
&lt;p&gt;签了 &lt;code&gt;.cer&lt;/code&gt; 后，你的 &lt;code&gt;.p12&lt;/code&gt;（公私钥对）就算是“被认证过的开发者密钥”了。系统在安装你签名过的 HAP 包时，会验证：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;你的包是不是用这个私钥签的；&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;这个私钥有没有经过华为签发的证书认证；&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;这张证书是不是华为签的。&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;说白了：一层层往上追溯，直到能从信任的 CA 根证书“闭环”，才算合法。&lt;/p&gt;
&lt;h3 id=&quot;5-最后一步生成-p7b-描述文件-权限包名设备绑定&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#5-最后一步生成-p7b-描述文件-权限包名设备绑定&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;5. 最后一步，生成 &lt;code&gt;.p7b&lt;/code&gt; 描述文件 —— 权限、包名、设备绑定&lt;/h3&gt;
&lt;p&gt;这个 &lt;code&gt;.p7b&lt;/code&gt; 文件相当于一个“出入证”，告诉系统这个包：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;来自哪个包名；&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;拥有哪些权限；&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;是调试包还是发布包；&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;如果是调试包，哪些设备可以安装；&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;对应的证书有哪些。&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;它是以 &lt;strong&gt;PKCS#7 格式&lt;/strong&gt; 打包的，不能少，系统验证的时候会用上。&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;写在最后&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#写在最后&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;写在最后&lt;/h2&gt;
&lt;p&gt;鸿蒙的签名机制说起来复杂，但其实拆开来看就是融合了我们熟悉的 Android 和 iOS 的思路 —— 本地生成密钥，上传公钥申请证书，拿到证书签名包，加上一个描述文件来“做身份认证和权限声明”。&lt;/p&gt;
&lt;p&gt;整个流程稍微绕一点，但掌握之后就能把签名流程自动化集成到你的打包流程里。我们现在项目中已经把签名密钥的管理、HAP 签名打包全自动串起来了，做成了 CI/CD 中的一环。&lt;/p&gt;
&lt;p&gt;如果你也要做鸿蒙适配，早点熟悉这套流程，绝对事半功倍！&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>数据库分表实践：如何优雅地切换到分表架构</title>
    <link href="https://blog.whrss.com/posts/mysql-sharding-migration"/>
    <id>https://blog.whrss.com/posts/mysql-sharding-migration</id>
    <published>2025-07-05T06:21:04.000Z</published>
    <updated>2025-07-05T06:21:04.000Z</updated>
    <category term="技术"/>
    <category term="db"/>
    <summary>在我们的后端架构中，我们采用了以游戏为租户单位的多租户数据库设计。所有游戏共享同一套数据库 schema，每张表通过 game_id 字段进行逻辑隔离。这种设计在初期带来了显著的开发与维护效率，支持我们快速迭代、快速上线多个游戏项目。 然而，随着接入的游戏数量增加、业务数据持续增长，这种“共享单表”的设计逐渐暴露出一些架构层面的瓶颈与隐患。</summary>
    <content type="html">&lt;h1 id=&quot;写在前面&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#写在前面&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;写在前面&lt;/h1&gt;
&lt;p&gt;在我们的后端架构中，我们采用了&lt;strong&gt;以游戏为租户单位的多租户数据库设计&lt;/strong&gt;。所有游戏共享同一套数据库 schema，每张表通过 &lt;code&gt;game_id&lt;/code&gt; 字段进行逻辑隔离。这种设计在初期带来了显著的开发与维护效率，支持我们快速迭代、快速上线多个游戏项目。&lt;br&gt;然而，随着接入的游戏数量增加、业务数据持续增长，这种“共享单表”的设计逐渐暴露出一些架构层面的瓶颈与隐患。&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;某些高流量的游戏影响到了其他本应“风平浪静”的项目；一些核心表的索引开始变得笨重，甚至拖慢了查询性能；&lt;/li&gt;
&lt;li&gt;数据分析时需要频繁在庞大的表中筛选特定游戏数据，效率极低。&lt;br&gt;更不用说，MySQL 的单表上限正一步步逼近我们曾以为遥远的边界。&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;我们意识到，曾经高效的“共享单表”策略，已经成为了未来扩展的绊脚石。于是，在年初，我们启动了一项重要的系统演进计划：&lt;strong&gt;按服务维度进行数据库分表改造&lt;/strong&gt;。&lt;/p&gt;
&lt;p&gt;这不仅是一次技术重构，更是系统架构从“共享瓶颈”走向“弹性隔离”的转型。本篇将完整记录我们这次数据库分表的路径与实践细节——希望对你有所启发。&lt;/p&gt;
&lt;h1 id=&quot;实施原则与总体策略&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#实施原则与总体策略&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;实施原则与总体策略&lt;/h1&gt;
&lt;p&gt;数据库分表，不仅是表结构的变化，更是一套&lt;strong&gt;兼容旧有系统、可渐进式切换、可回滚&lt;/strong&gt;的工程设计。&lt;br&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;&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;基于这三条，我们制定了如下的整体方案：&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;我们将整个数据库分表的工作拆分为多个阶段，每次只处理一个服务的分表任务，避免全系统改动带来的风险，从影响面最小的服务开始进行实施，每个服务独立执行迁移程序，单独验证，按需上线。&lt;/li&gt;
&lt;li&gt;为了兼容旧表与新表，我们在每个服务内部引入了 &lt;code&gt;db_mode&lt;/code&gt; 配置项，&lt;strong&gt;按游戏粒度控制读写行为&lt;/strong&gt;：&lt;/li&gt;
&lt;/ol&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;write_mode&lt;/code&gt;:&lt;ul&gt;
&lt;li&gt;&lt;code&gt;old_table&lt;/code&gt;：仅写旧表&lt;/li&gt;
&lt;li&gt;&lt;code&gt;dual_write&lt;/code&gt;：写入旧表 + 新表（事务）&lt;/li&gt;
&lt;li&gt;&lt;code&gt;new_table&lt;/code&gt;：仅写新表&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;code&gt;read_mode&lt;/code&gt;:&lt;ul&gt;
&lt;li&gt;&lt;code&gt;old_table&lt;/code&gt;：仅从旧表读取&lt;/li&gt;
&lt;li&gt;&lt;code&gt;dark_read&lt;/code&gt;：主用旧表读取，同时异步比对新表&lt;/li&gt;
&lt;li&gt;&lt;code&gt;new_table&lt;/code&gt;：仅从新表读取&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;这套机制允许我们&lt;strong&gt;按游戏逐个切换&lt;/strong&gt;，并且在 write_mode 修改为 new_table 前，都可以进行回滚。 &lt;/p&gt;
&lt;ol start=&quot;3&quot;&gt;
&lt;li&gt;&lt;p&gt;自动建表：创建游戏即创建对应表&lt;br&gt; 我们在后台创建游戏时，会自动触发分表建表逻辑：&lt;br&gt; 这样，我们无需人工干预即可支持新游戏分表，游戏接入的流程保持不变。&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;数据访问层改造&lt;br&gt;  我们不改动业务代码，只修改数据库访问层。&lt;br&gt;  根据 db_mode 配置，进行不同表的数据库访问层操作。&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;内嵌迁移程序&lt;br&gt; 每个服务内置一个迁移命令行程序，支持：&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;dry-run 模式比对数据差异&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;支持幂等多次执行&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;支持按游戏、按表迁移&lt;/p&gt;
&lt;p&gt;  我们通过 Nomad Batch Job 管理迁移任务，通过 Jenkins Pipeline 提供可配置的执行入口。迁移日志也会自动上报到内部通知系统。&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;数据访问层的改造范式&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#数据访问层的改造范式&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;数据访问层的改造范式&lt;/h1&gt;
&lt;p&gt;在这次改造中，我们遵循了“&lt;strong&gt;只改访问逻辑，不动业务代码&lt;/strong&gt;”的原则，把所有分表逻辑封装在 repository 层内部，使业务代码无感知地享受分表带来的性能收益。&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;p&gt;注入 db_mode：为每个游戏配置读写模式&lt;br&gt;我们通过配置文件将每个游戏的读写策略注入到服务中。&lt;br&gt;这保证了即便是同一个服务，不同的游戏也可以处于&lt;strong&gt;不同的分表阶段&lt;/strong&gt;。&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;读操作：Old / New / DarkRead 三分法&lt;br&gt;每个原始读方法，都会被拆成三个版本&lt;br&gt;Dark Read 的核心逻辑是：&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;ul&gt;
&lt;li&gt;主流程从旧表读取并返回&lt;/li&gt;
&lt;li&gt;启动一个 goroutine，从新表读取&lt;/li&gt;
&lt;li&gt;对比业务字段是否一致，若不一致则记录日志（包括差异字段、原始数据、新数据）&lt;br&gt;这让我们能在不影响线上服务的前提下，实时监控新表的数据同步情况，确保切换 &lt;code&gt;read_mode=new_table&lt;/code&gt; 之前，新旧表是“业务等价”的。&lt;/li&gt;
&lt;/ul&gt;
&lt;ol start=&quot;3&quot;&gt;
&lt;li&gt;&lt;p&gt;写操作：Old / New / DualWrite 三分法&lt;br&gt;dual_write 模式必须通过事务包装，确保新旧表一致性&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;混合逻辑场景的改造&lt;br&gt;部分 repository 方法可能同时涉及读写，例如 &lt;code&gt;CreateAndGet()&lt;/code&gt;。&lt;br&gt;这类方法无法直接套用 read_mode / write_mode 的切换逻辑，需要将其内部 SQL 操作&lt;strong&gt;全部拆解成单一职责方法&lt;/strong&gt;后，再按以上的标准方式进行重构。&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;这样做虽然有很多的工作量，但换来了&lt;strong&gt;可控性、可测试性与安全性&lt;/strong&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;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;在新旧表切换阶段保障数据一致性&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;迁移程序设计与执行策略&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#迁移程序设计与执行策略&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;迁移程序设计与执行策略&lt;/h1&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;为什么内置在服务中呢？ 是为了保证迁移程序中所用的 db schema 对象与程序一致，无需新增代码仓库，保持迁移程序与原 service image 一致即可。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;这套程序采用命令行方式运行，按 &lt;code&gt;game_id&lt;/code&gt; 和表级别控制，具备如下核心特性：&lt;/p&gt;
&lt;h4 id=&quot;通过-cli-参数控制执行行为&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#通过-cli-参数控制执行行为&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;👉通过 CLI 参数控制执行行为&lt;/h4&gt;
&lt;div class=&quot;table-wrap&quot;&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;参数&lt;/th&gt;
&lt;th&gt;说明&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;&lt;tr&gt;
&lt;td&gt;&lt;code&gt;-game-id&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;必选，指定要迁移的游戏&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;-table&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;必选，指定要迁移的表&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;-dry-run&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;可选，是否启用试运行模式，默认 &lt;code&gt;true&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;h4 id=&quot;主键游标分页查询&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#主键游标分页查询&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;👉 主键游标分页查询&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;从旧表中按主键升序分页查询，避免 OFFSET 带来的性能问题。&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id=&quot;记录处理逻辑&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#记录处理逻辑&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;👉记录处理逻辑&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;仅处理指定 &lt;code&gt;game_id&lt;/code&gt; 的数据&lt;/li&gt;
&lt;li&gt;若新表无记录 → 插入 → &lt;code&gt;Inserted++&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;若新表有记录：&lt;ul&gt;
&lt;li&gt;若数据内容不同 → 更新 → &lt;code&gt;Updated++&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;若业务字段等价 → 忽略 → &lt;code&gt;Equivalent++&lt;/code&gt;&lt;br&gt; &lt;strong&gt;注意：&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;不对比自增 ID 和时间字段（&lt;code&gt;created_at&lt;/code&gt;, &lt;code&gt;updated_at&lt;/code&gt;）&lt;/li&gt;
&lt;li&gt;写操作忽略自增 ID，仅迁移业务字段&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id=&quot;幂等执行支持&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#幂等执行支持&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;👉 幂等执行支持&lt;/h4&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;h4 id=&quot;错误处理与退出机制&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#错误处理与退出机制&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;👉错误处理与退出机制&lt;/h4&gt;
&lt;ol&gt;
&lt;li&gt;全局 recover，优雅退出&lt;/li&gt;
&lt;/ol&gt;
&lt;ul&gt;
&lt;li&gt;迁移程序入口包装 panic-recover&lt;/li&gt;
&lt;li&gt;异常发生时输出详细日志、当前进度&lt;/li&gt;
&lt;li&gt;通过 Messenger 通知协作群&lt;/li&gt;
&lt;/ul&gt;
&lt;ol start=&quot;2&quot;&gt;
&lt;li&gt;中断信号监听&lt;/li&gt;
&lt;/ol&gt;
&lt;ul&gt;
&lt;li&gt;支持 &lt;code&gt;SIGINT&lt;/code&gt; / &lt;code&gt;SIGTERM&lt;/code&gt; 信号监听&lt;/li&gt;
&lt;li&gt;在每一批处理前检测 context 是否已取消&lt;/li&gt;
&lt;li&gt;收到信号后中止执行，输出中间状态并发送通知&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id=&quot;结构化统计信息-可追溯日志&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#结构化统计信息-可追溯日志&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;👉结构化统计信息 + 可追溯日志&lt;/h4&gt;
&lt;p&gt;每次执行完成后，程序会输出统计信息，并自动发送至内部通知群。&lt;/p&gt;
&lt;h1 id=&quot;上线切换流程与回滚策略&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#上线切换流程与回滚策略&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;上线切换流程与回滚策略&lt;/h1&gt;
&lt;p&gt;数据库分表的目标，并不是“改造完上线就完事”，而是&lt;strong&gt;从 old_table 模式平滑切换到 new_table 模式&lt;/strong&gt;，并确保在每一步都有明确的验证机制和可回退能力。&lt;/p&gt;
&lt;p&gt;这是一场有节奏的灰度迁移流程，我们为每一步都设计了&lt;strong&gt;验证手段、执行流程与回滚方案&lt;/strong&gt;。&lt;/p&gt;
&lt;h3 id=&quot;分阶段策略&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#分阶段策略&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;分阶段策略&lt;/h3&gt;
&lt;p&gt;我们将一次完整的分表切换流程拆解为以下 6 个阶段：&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;阶段一：部署改造完成的程序，此时所有的游戏都读写 old table。&lt;br&gt;以下阶段按游戏进行：&lt;/li&gt;
&lt;li&gt;阶段二：部署 dual_write，开始写新旧双表&lt;/li&gt;
&lt;li&gt;阶段三：多次执行数据迁移，确保新表一致&lt;/li&gt;
&lt;li&gt;阶段四：read_mode 切换为 dark_read，开始观测新表稳定性&lt;/li&gt;
&lt;li&gt;阶段五：read_mode 切换为 new_table&lt;/li&gt;
&lt;li&gt;阶段六：write_mode 切换为 new_table&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 id=&quot;回滚策略&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#回滚策略&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;回滚策略&lt;/h3&gt;
&lt;p&gt;我们特别强调：&lt;strong&gt;在任意切换阶段，如果发现异常，都可以回退到旧表访问模式。&lt;/strong&gt;&lt;br&gt;例如：&lt;/p&gt;
&lt;div class=&quot;table-wrap&quot;&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;异常场景&lt;/th&gt;
&lt;th&gt;回滚操作&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;&lt;tr&gt;
&lt;td&gt;dark_read 中发现大量差异&lt;/td&gt;
&lt;td&gt;read_mode → old_table&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;切换 new_table 后接口报错&lt;/td&gt;
&lt;td&gt;read_mode → dark_read 或 old_table&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;dual_write 写新表失败&lt;/td&gt;
&lt;td&gt;write_mode → old_table&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;p&gt;所有行为都是&lt;strong&gt;配置可控、逻辑封装良好、无须变更代码&lt;/strong&gt;。&lt;/p&gt;
&lt;h3 id=&quot;迁移状态判断与团队共识&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#迁移状态判断与团队共识&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;迁移状态判断与团队共识&lt;/h3&gt;
&lt;p&gt;我们曾讨论是否要在 Redis 或数据库中记录迁移状态（例如，某个游戏是否已完成迁移）。最终我们选择：&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;不使用自动标记机制，而是依靠 MR review 和群通知日志来确认状态。&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;具体判断依据：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;Inserted=0&lt;/code&gt; 且 &lt;code&gt;Updated=0&lt;/code&gt; 的绿色通知连续两次&lt;/li&gt;
&lt;li&gt;数据访问层未输出 dark_read_diff 日志&lt;/li&gt;
&lt;li&gt;多人 Review 确认可切换&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;结语&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#结语&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;结语&lt;/h1&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;br&gt;&lt;a href=&quot;https://github.com/whrss9527/blog-backup/blob/main/mysql-sharding-migration.md&quot; title=&quot;GitHub&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;GitHub&lt;/a&gt;&lt;br&gt;&lt;a href=&quot;https://mp.weixin.qq.com/s/HK9sGUFAwVuPxKYvaLo0YA&quot; title=&quot;微信公众号&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;微信公众号&lt;/a&gt;&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>“该省省，该花花”</title>
    <link href="https://blog.whrss.com/posts/smart-spending"/>
    <id>https://blog.whrss.com/posts/smart-spending</id>
    <published>2025-01-31T11:48:07.000Z</published>
    <updated>2025-01-31T11:48:07.000Z</updated>
    <category term="生活和思考"/>
    <category term="life"/>
    <summary>春节假期，我终于完成了两件大事：见了未来的岳父岳母，还带奶奶游览了北京。忙里偷闲，我决定总结一下这几天的经历，顺便分享一些“花钱”与“省钱”的小感悟。</summary>
    <content type="html">&lt;p&gt;春节假期，我终于完成了两件大事：见了未来的岳父岳母，还带奶奶游览了北京。忙里偷闲，我决定总结一下这几天的经历，顺便分享一些“花钱”与“省钱”的小感悟。&lt;/p&gt;
&lt;p&gt;作为一名农村出身的人，我的消费观念一直是：&lt;strong&gt;钱能不花，就不花。&lt;/strong&gt; 例如：&lt;/p&gt;
&lt;p&gt;• 旅游？自己带矿泉水，自己带干粮，景区里一瓶水8块？不可能！&lt;/p&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;h1 id=&quot;游泳花钱买经验少走弯路&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#游泳花钱买经验少走弯路&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;&lt;strong&gt;游泳：花钱买经验，少走弯路&lt;/strong&gt;&lt;/h1&gt;
&lt;p&gt;大学时，我决定学游泳。（ps: 一个月1000生活费，拮据～）当时面临两个选择：&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;办游泳年卡（500块），自学成才！&lt;/strong&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;请游泳教练（20节课500块），专业入门！&lt;/strong&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;作为精打细算的学生党，我毫不犹豫地选择了&lt;strong&gt;年卡&lt;/strong&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;strong&gt;当年如果花钱请教练，可能两个月就能达到现在的水平，少喝多少水啊！&lt;/strong&gt; （而且，大学时候的教练费是真的便宜啊～～）但当时的我，非要靠自己摸索，结果就是走了很多弯路，还差点呛成“水鬼”。&lt;/p&gt;
&lt;h1 id=&quot;滑雪没教练甚至不会穿板&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#滑雪没教练甚至不会穿板&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;&lt;strong&gt;滑雪：没教练，甚至不会穿板&lt;/strong&gt;&lt;/h1&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;strong&gt;甚至不会正确扣上固定器&lt;/strong&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;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;接下来，短短两个小时，教练带我从&lt;strong&gt;后刃滑行 → 落叶飘 → 陡坡尝试&lt;/strong&gt;，五次练习后，我已经能上中级道了！从一脸懵逼到掌握平衡、控制速度，我终于体会到：&lt;strong&gt;花钱买指导，真香！&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;如果没有教练，我可能得花&lt;strong&gt;三天&lt;/strong&gt;去摔跤，最后依旧漏洞百出。&lt;strong&gt;这几百块，等于帮我省下了两天的雪场门票、误伤自己可能花的医药费。&lt;/strong&gt;&lt;/p&gt;
&lt;h1 id=&quot;旅游没有导游可能只是打个卡&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#旅游没有导游可能只是打个卡&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;&lt;strong&gt;旅游：没有导游，可能只是“打个卡”&lt;/strong&gt;&lt;/h1&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;strong&gt;快关门了，最后一个拼团，给你俩便宜点～！&lt;/strong&gt;”&lt;/p&gt;
&lt;p&gt;本着&lt;strong&gt;反正也不贵&lt;/strong&gt;的心态，我们跟上了团。结果，这趟游览改变了我的旅游观念——&lt;/p&gt;
&lt;p&gt;沈阳故宫很小，随便逛一圈可能用不了20分钟。但&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;strong&gt;这里为什么只有一个大烟囱？为什么有一个杆子顶个碗？&lt;/strong&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;strong&gt;如果没有导游，我可能只会留下几张照片，走马观花地打个卡，最后啥也没学到。&lt;/strong&gt;&lt;/p&gt;
&lt;h1 id=&quot;人生的投资观该省省该花花&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#人生的投资观该省省该花花&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;&lt;strong&gt;人生的投资观：该省省，该花花&lt;/strong&gt;&lt;/h1&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;strong&gt;如何花最少的钱，跨过性价比最高的门槛。&lt;/strong&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;strong&gt;人生，就是一个不断投资自己的过程。&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;So，my friend，&lt;strong&gt;别再和我一样傻省钱了，学会“该省省，该花花”！&lt;/strong&gt;&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Golang 中的 EOF 与 read: connection reset by peer 错误深度剖析</title>
    <link href="https://blog.whrss.com/posts/golang-eof"/>
    <id>https://blog.whrss.com/posts/golang-eof</id>
    <published>2024-08-07T00:30:33.000Z</published>
    <updated>2024-08-07T00:30:33.000Z</updated>
    <category term="技术"/>
    <category term="golang"/>
    <summary>在 Golang 网络请求中，我们经常会遇到两种常见的错误：`EOF` 和 `read: connection reset by peer`。这两个错误虽然看似相似，但实际上有着本质的区别。这篇文章将深入探讨这两种错误的原因、区别以及如何优雅的处理它们。</summary>
    <content type="html">&lt;h2 id=&quot;引言&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#引言&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;引言&lt;/h2&gt;
&lt;p&gt;在 Golang 网络请求中，我们经常会遇到两种常见的错误：&lt;code&gt;EOF&lt;/code&gt; 和 &lt;code&gt;read: connection reset by peer&lt;/code&gt;。这两个错误虽然看似相似，但实际上有着本质的区别。这篇文章将深入探讨这两种错误的原因、区别以及如何优雅的处理它们。&lt;/p&gt;
&lt;h2 id=&quot;错误原因解析&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#错误原因解析&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;错误原因解析&lt;/h2&gt;
&lt;h3 id=&quot;eof-错误&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#eof-错误&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;EOF 错误&lt;/h3&gt;
&lt;p&gt;首先，让我们看看 Golang 标准库中对 &lt;code&gt;EOF&lt;/code&gt; 的定义：&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;// EOF is the error returned by Read when no more input is available.&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;// (Read must return EOF itself, not an error wrapping EOF,  &lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;// because callers will test for EOF using ==.)&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;// Functions should return EOF only to signal a graceful end of input.&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;// If the EOF occurs unexpectedly in a structured data stream,&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;// the appropriate error is either ErrUnexpectedEOF or some other error&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;// giving more detail.  &lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;var&lt;/span&gt; EOF = errors.New(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;EOF&amp;quot;&lt;/span&gt;)&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;从注释中我们可以看出：&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;code&gt;EOF&lt;/code&gt; 表示没有更多的输入可用。&lt;/li&gt;
&lt;li&gt;函数应该只在输入优雅结束时返回 &lt;code&gt;EOF&lt;/code&gt;。&lt;/li&gt;
&lt;li&gt;如果在结构化数据流中意外发生 &lt;code&gt;EOF&lt;/code&gt;，应该返回 &lt;code&gt;ErrUnexpectedEOF&lt;/code&gt; 或其他更详细的错误。&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 id=&quot;connection-reset-by-peer-错误&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#connection-reset-by-peer-错误&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;connection reset by peer 错误&lt;/h3&gt;
&lt;p&gt;在 Golang 源码中，&lt;code&gt;connection reset by peer&lt;/code&gt; 对应的错误码是 “ECONNRESET”。在 Linux 和类 Unix 系统上，&lt;code&gt;ECONNRESET&lt;/code&gt; 错误码表示连接被对端重置。&lt;/p&gt;
&lt;h2 id=&quot;模拟错误场景&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#模拟错误场景&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;模拟错误场景&lt;/h2&gt;
&lt;p&gt;为了更好地理解这两种错误，我们可以通过代码来模拟这些场景。&lt;/p&gt;
&lt;h3 id=&quot;服务端代码&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#服务端代码&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;服务端代码&lt;/h3&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;package&lt;/span&gt; main

&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; (
    &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;errors&amp;quot;&lt;/span&gt;
    &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;log&amp;quot;&lt;/span&gt;
    &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;net&amp;quot;&lt;/span&gt;
    &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;net/http&amp;quot;&lt;/span&gt;
    &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;os&amp;quot;&lt;/span&gt;
    &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;time&amp;quot;&lt;/span&gt;
)

&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;handler&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;(w http.ResponseWriter, r *http.Request)&lt;/span&gt;&lt;/span&gt; {
    conn, _, err := w.(http.Hijacker).Hijack()
    &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; err != &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt; {
        log.Printf(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;无法劫持连接: %v&amp;quot;&lt;/span&gt;, err)
        &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt;
    }
    &lt;span class=&quot;hljs-keyword&quot;&gt;defer&lt;/span&gt; conn.Close()

    &lt;span class=&quot;hljs-comment&quot;&gt;// 通过注释或取消注释下面这行来切换错误类型&lt;/span&gt;
    &lt;span class=&quot;hljs-comment&quot;&gt;// conn.(*net.TCPConn).SetLinger(0)&lt;/span&gt;
}

&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;main&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;()&lt;/span&gt;&lt;/span&gt; {
    server := &amp;amp;http.Server{
        Addr:         &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;:8788&amp;quot;&lt;/span&gt;,
        Handler:      http.HandlerFunc(handler),
        ReadTimeout:  &lt;span class=&quot;hljs-number&quot;&gt;5&lt;/span&gt; * time.Second,
        WriteTimeout: &lt;span class=&quot;hljs-number&quot;&gt;5&lt;/span&gt; * time.Second,
        IdleTimeout:  &lt;span class=&quot;hljs-number&quot;&gt;5&lt;/span&gt; * time.Second,
        ErrorLog:     log.New(os.Stderr, &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;http: &amp;quot;&lt;/span&gt;, log.LstdFlags),
    }

    listener, err := net.Listen(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;tcp&amp;quot;&lt;/span&gt;, server.Addr)
    &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; err != &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt; {
        log.Fatalf(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;无法监听端口 %s: %v&amp;quot;&lt;/span&gt;, server.Addr, err)
    }
    &lt;span class=&quot;hljs-keyword&quot;&gt;defer&lt;/span&gt; listener.Close()
    log.Printf(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;服务器在端口 %s 上等待连接...&amp;quot;&lt;/span&gt;, server.Addr)

    &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; err = server.Serve(listener); err != &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt; &amp;amp;&amp;amp; !errors.Is(err, http.ErrServerClosed) {
        log.Fatalf(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;服务器启动失败: %v&amp;quot;&lt;/span&gt;, err)
    }
}&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;h3 id=&quot;客户端代码&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#客户端代码&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;客户端代码&lt;/h3&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;TestHttpRequest&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;(t *testing.T)&lt;/span&gt;&lt;/span&gt; {
    reqUrl := &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;http://localhost:8788&amp;quot;&lt;/span&gt;
    req, err := http.NewRequest(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;GET&amp;quot;&lt;/span&gt;, reqUrl, &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt;)
    &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; err != &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt; {
        t.Fatalf(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;创建请求失败: %v&amp;quot;&lt;/span&gt;, err)
    }
    client := &amp;amp;http.Client{}
    resp, err := client.Do(req)
    &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; err != &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt; {
        t.Logf(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;请求错误: %v&amp;quot;&lt;/span&gt;, err)
        &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt;
    }
    &lt;span class=&quot;hljs-keyword&quot;&gt;defer&lt;/span&gt; resp.Body.Close()
}&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;在服务端代码中，通过注释或取消注释 &lt;code&gt;conn.(*net.TCPConn).SetLinger(0)&lt;/code&gt; 这行代码，我们可以模拟两种不同的错误场景：&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;当这行代码被注释时，客户端会收到 &lt;code&gt;EOF&lt;/code&gt; 错误。&lt;/li&gt;
&lt;li&gt;当这行代码未被注释时，客户端会收到 &lt;code&gt;read: connection reset by peer&lt;/code&gt; 错误。&lt;/li&gt;
&lt;/ol&gt;
&lt;h2 id=&quot;错误原因分析&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#错误原因分析&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;错误原因分析&lt;/h2&gt;
&lt;h3 id=&quot;eof-错误-2&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#eof-错误-2&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;EOF 错误&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;EOF&lt;/code&gt; 错误通常表示连接被对端优雅地关闭。这是一个正常的网络行为，表示数据传输已经完成。在 TCP 协议中，这对应于正常的四次挥手过程：&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;服务器发送 FIN 包。&lt;/li&gt;
&lt;li&gt;客户端回应 ACK 包。&lt;/li&gt;
&lt;li&gt;客户端发送 FIN 包。&lt;/li&gt;
&lt;li&gt;服务器回应 ACK 包。&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 id=&quot;connection-reset-by-peer-错误-2&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#connection-reset-by-peer-错误-2&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;connection reset by peer 错误&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;connection reset by peer&lt;/code&gt; 错误表示连接被对端强制关闭。这通常是由于以下原因之一：&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;对端进程崩溃。&lt;/li&gt;
&lt;li&gt;网络异常。&lt;/li&gt;
&lt;li&gt;对端主动选择立即断开连接（如使用 &lt;code&gt;SetLinger(0)&lt;/code&gt;）。&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;在这种情况下，TCP 连接没有经过正常的四次挥手过程，而是直接发送了 RST（重置）包。&lt;/p&gt;
&lt;h2 id=&quot;实际应用场景分析&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#实际应用场景分析&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;实际应用场景分析&lt;/h2&gt;
&lt;h3 id=&quot;eof-错误的常见场景&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#eof-错误的常见场景&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;EOF 错误的常见场景&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;对端完成数据发送后正常关闭连接。&lt;/li&gt;
&lt;li&gt;长连接超时被服务器主动关闭。&lt;/li&gt;
&lt;li&gt;读取固定长度的数据流结束。&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 id=&quot;connection-reset-by-peer-错误的常见场景&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#connection-reset-by-peer-错误的常见场景&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;connection reset by peer 错误的常见场景&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;服务器进程崩溃或被强制终止。&lt;/li&gt;
&lt;li&gt;网络设备（如防火墙）主动断开连接。&lt;/li&gt;
&lt;li&gt;服务器配置了短的 keep-alive 超时时间，客户端尝试使用已关闭的连接。&lt;/li&gt;
&lt;/ol&gt;
&lt;h2 id=&quot;如何处理这两种错误&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#如何处理这两种错误&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;如何处理这两种错误&lt;/h2&gt;
&lt;h3 id=&quot;处理-eof-错误&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#处理-eof-错误&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;处理 EOF 错误&lt;/h3&gt;
&lt;p&gt;1.对于预期的 EOF（如读取到文件末尾），可以正常处理，不需要特别的错误处理逻辑。&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;data, err := reader.Read(buffer)
&lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; err == io.EOF {
    &lt;span class=&quot;hljs-comment&quot;&gt;// 正常结束，处理完成的数据&lt;/span&gt;
    &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt;
} &lt;span class=&quot;hljs-keyword&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; err != &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt; {
    &lt;span class=&quot;hljs-comment&quot;&gt;// 处理其他错误&lt;/span&gt;
    &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; err
}&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;2.对于非预期的 EOF，应该进行错误处理和日志记录。&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; err == io.ErrUnexpectedEOF {
    log.Printf(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;意外的 EOF: %v&amp;quot;&lt;/span&gt;, err)
    &lt;span class=&quot;hljs-comment&quot;&gt;// 进行错误恢复或重试逻辑&lt;/span&gt;
}&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;h3 id=&quot;处理-connection-reset-by-peer-错误&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#处理-connection-reset-by-peer-错误&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;处理 connection reset by peer 错误&lt;/h3&gt;
&lt;p&gt;1.实现重试机制。&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;retryableHttpGet&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;(url &lt;span class=&quot;hljs-type&quot;&gt;string&lt;/span&gt;, maxRetries &lt;span class=&quot;hljs-type&quot;&gt;int&lt;/span&gt;)&lt;/span&gt;&lt;/span&gt; (*http.Response, &lt;span class=&quot;hljs-type&quot;&gt;error&lt;/span&gt;) {
    &lt;span class=&quot;hljs-keyword&quot;&gt;var&lt;/span&gt; resp *http.Response
    &lt;span class=&quot;hljs-keyword&quot;&gt;var&lt;/span&gt; err &lt;span class=&quot;hljs-type&quot;&gt;error&lt;/span&gt;
    &lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; i := &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt;; i &amp;lt; maxRetries; i++ {
        resp, err = http.Get(url)
        &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; err == &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt; {
            &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; resp, &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt;
        }
        &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; !strings.Contains(err.Error(), &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;connection reset by peer&amp;quot;&lt;/span&gt;) {
            &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt;, err
        }
        time.Sleep(time.Second * time.Duration(i+&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;))
    }
    &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt;, fmt.Errorf(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;最大重试次数已达到: %w&amp;quot;&lt;/span&gt;, err)
}&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;2.优化连接池配置。&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;client := &amp;amp;http.Client{
    Transport: &amp;amp;http.Transport{
        MaxIdleConns:        &lt;span class=&quot;hljs-number&quot;&gt;100&lt;/span&gt;,
        MaxIdleConnsPerHost: &lt;span class=&quot;hljs-number&quot;&gt;100&lt;/span&gt;,
        IdleConnTimeout:     &lt;span class=&quot;hljs-number&quot;&gt;90&lt;/span&gt; * time.Second,
    },
    Timeout: &lt;span class=&quot;hljs-number&quot;&gt;10&lt;/span&gt; * time.Second,
}&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;3.使用断路器模式。&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;github.com/sony/gobreaker&amp;quot;&lt;/span&gt;

cb := gobreaker.NewCircuitBreaker(gobreaker.Settings{
    Name:        &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;HTTP GET&amp;quot;&lt;/span&gt;,
    MaxRequests: &lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt;,
    Interval:    &lt;span class=&quot;hljs-number&quot;&gt;5&lt;/span&gt; * time.Second,
    Timeout:     &lt;span class=&quot;hljs-number&quot;&gt;30&lt;/span&gt; * time.Second,
    ReadyToTrip: &lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;(counts gobreaker.Counts)&lt;/span&gt;&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;bool&lt;/span&gt; {
        failureRatio := &lt;span class=&quot;hljs-type&quot;&gt;float64&lt;/span&gt;(counts.TotalFailures) / &lt;span class=&quot;hljs-type&quot;&gt;float64&lt;/span&gt;(counts.Requests)
        &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; counts.Requests &amp;gt;= &lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt; &amp;amp;&amp;amp; failureRatio &amp;gt;= &lt;span class=&quot;hljs-number&quot;&gt;0.6&lt;/span&gt;
    },
})

resp, err := cb.Execute(&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;()&lt;/span&gt;&lt;/span&gt; (&lt;span class=&quot;hljs-keyword&quot;&gt;interface&lt;/span&gt;{}, &lt;span class=&quot;hljs-type&quot;&gt;error&lt;/span&gt;) {
    &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; http.Get(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;http://example.com&amp;quot;&lt;/span&gt;)
})&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;h2 id=&quot;最佳实践&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#最佳实践&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;最佳实践&lt;/h2&gt;
&lt;ol&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;li&gt;代码 review：检查是否有不当的连接处理逻辑，如强制关闭连接等。&lt;/li&gt;
&lt;/ol&gt;
&lt;h2 id=&quot;总结一下&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#总结一下&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;总结一下&lt;/h2&gt;
&lt;p&gt;理解 &lt;code&gt;EOF&lt;/code&gt; 和 &lt;code&gt;connection reset by peer&lt;/code&gt; 错误的区别和处理方法，对于构建健壮的网络应用至关重要。&lt;code&gt;EOF&lt;/code&gt; 通常表示正常的连接关闭，而 &lt;code&gt;connection reset by peer&lt;/code&gt; 则可能指示更严重的问题。通过合理的错误处理、重试机制和监控，我们可以大大提高应用的可靠性和用户体验。&lt;/p&gt;
&lt;p&gt;在实际开发中，要根据具体的应用场景和需求，选择适当的错误处理策略。同时，持续监控和分析这些错误，可以帮助我们及时发现和解决潜在的问题，提高系统的整体稳定性。&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>为什么你应该在代码中消除 &quot;context deadline exceeded&quot; 错误</title>
    <link href="https://blog.whrss.com/posts/context-deadline-exceeded"/>
    <id>https://blog.whrss.com/posts/context-deadline-exceeded</id>
    <published>2024-06-13T20:17:32.000Z</published>
    <updated>2024-06-13T20:17:32.000Z</updated>
    <category term="技术"/>
    <category term="golang"/>
    <summary>在 Go 语言中，context 包提供了一种跨 API 和进程边界传递请求作用域值、取消信号以及超时信号的方式。使用 context 可以帮助我们更好地控制 goroutine，避免 goroutine 泄漏等问题。出现 &quot;context deadline exceeded&quot; 错误通常是因为在请求上下文中设置了超时时间，但请求在超时时间内未完成。我们应该尽量避免这种错误...</summary>
    <content type="html">&lt;p&gt;在 Go 语言中，&lt;code&gt;context&lt;/code&gt; 包提供了一种跨 API 和进程边界传递请求作用域值、取消信号以及超时信号的方式。使用 &lt;code&gt;context&lt;/code&gt; 可以帮助我们更好地控制 goroutine，避免 goroutine 泄漏等问题。&lt;/p&gt;
&lt;p&gt;出现 “context deadline exceeded” 错误通常是因为在请求上下文中设置了超时时间，但请求在超时时间内未完成。我们应该尽量避免这种错误，原因如下：&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;错误处理&lt;/strong&gt;：&lt;code&gt;context deadline exceeded&lt;/code&gt; 是一个错误，如果忽视它可能导致程序运行异常或产生其他错误。&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;错误分析&lt;/strong&gt;：当我们对数据埋点和日志进行分析时，如果出现 “context deadline exceeded” 错误，我们很难直接定位到具体的错误来源。&lt;/p&gt;
&lt;p&gt;&lt;em&gt;假设我们在一个分布式系统中处理多个请求，如果日志中充斥着 “context deadline exceeded” 错误，我们根本无法判断是哪里出现了问题。&lt;/em&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;资源泄漏&lt;/strong&gt;：未及时取消 goroutine 可能会导致资源（如内存、文件描述符等）无法及时释放，引起资源泄漏问题。&lt;/p&gt;
&lt;p&gt;&lt;em&gt;比如数据库慢查询，数据库连接可能会被占用，导致连接池耗尽。&lt;/em&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;性能问题&lt;/strong&gt;：长时间运行的请求未能取消，会消耗大量的系统资源，影响整体系统性能。&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;用户体验&lt;/strong&gt;：对于需要等待长时间的请求，用户可能会感到迷惑和不耐烦，影响用户体验。&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;为了消除 “context deadline exceeded” 错误，我们可以采取以下几种办法：&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;合理设置超时时间&lt;/strong&gt;：根据实际业务需求，设置合理的超时时间，避免过短或过长的设置。在对应位置返回转换后的业务错误。&lt;/p&gt;
&lt;p&gt;&lt;em&gt;比如，对于一个数据库查询操作，可以根据历史数据分析设置一个合理的超时时间，确保大多数查询都能在该时间内完成。&lt;/em&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;使用 &lt;code&gt;context.WithTimeout&lt;/code&gt;&lt;/strong&gt;：在请求开始时，使用 &lt;code&gt;context.WithTimeout&lt;/code&gt; 或 &lt;code&gt;context.WithDeadline&lt;/code&gt; 创建带超时时间的 context，并在请求完成或超时后及时取消该 context。&lt;/p&gt;
&lt;p&gt;&lt;em&gt;比如，在执行一个 HTTP 请求时，可以使用 &lt;code&gt;context.WithTimeout&lt;/code&gt; 设置一个 5 秒的超时时间，如果这个请求超时，可以返回对应的业务枚举错误，在进行错误定位时，可以直接找到问题出现的原因。&lt;/em&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;监控长时间运行的请求&lt;/strong&gt;：定期检查是否存在长时间运行的请求，如果有，则及时调整超时策略。&lt;/p&gt;
&lt;p&gt;&lt;em&gt;可以使用 Prometheus 监控请求的持续时间，并设置告警通知，提醒开发人员处理超时请求。&lt;/em&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;优化代码逻辑&lt;/strong&gt;：review 代码，优化潜在的低效或阻塞代码，减少执行时间。&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;记录及分析错误&lt;/strong&gt;：通过日志记录及时发现 “context deadline exceeded” 错误，并分析其根本原因。&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;消除 “context deadline exceeded” 错误不仅有利于系统的健康运行，也可以提高系统的可靠性和用户体验。在 Go 编程中，我们应该合理使用超时时间的设置，尽量避免这类错误的发生。&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>死锁日记：手写 GoLang 上报队列</title>
    <link href="https://blog.whrss.com/posts/golang-deadlock"/>
    <id>https://blog.whrss.com/posts/golang-deadlock</id>
    <published>2024-05-16T01:16:45.000Z</published>
    <updated>2024-05-16T01:16:45.000Z</updated>
    <category term="技术"/>
    <category term="golang"/>
    <category term="deadlock"/>
    <summary>我们团队负责的防沉迷上报服务突然在某一天遭遇了内存溢出（OOM）的情况。通过查看 Prometheus 监控数据，我们发现 Goroutines 的数量在中午十二点之后呈现出线性增长趋势，直至晚上十点 OOM 发生，Goroutines 数量骤降为零。</summary>
    <content type="html">&lt;p&gt;我们团队负责的防沉迷上报服务突然在某一天遭遇了内存溢出（OOM）的情况。通过查看 Prometheus 监控数据，我们发现 Goroutines 的数量在中午十二点之后呈现出线性增长趋势，直至晚上十点 OOM 发生，Goroutines 数量骤降为零。如下图所示：&lt;br&gt;&lt;img src=&quot;https://pic.whrss.com/2024/05/1715772642.png&quot; alt=&quot;image.png&quot; loading=&quot;eager&quot; decoding=&quot;async&quot;&gt;&lt;br&gt;从这个 Goroutine 的创建趋势图中，我们可以推断出服务在中午十二点触发了某个 bug，导致 Goroutine 不断创建，最终引发了内存溢出的问题。&lt;/p&gt;
&lt;h3 id=&quot;队列实现&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#队列实现&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;队列实现&lt;/h3&gt;
&lt;p&gt;在我们的服务中，有一个用于上下线上报的队列。当队列达到一定阈值或指定时间间隔时，会触发读取和上报。以下是队列的具体实现：&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;package&lt;/span&gt; main

&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; (
    &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;errors&amp;quot;&lt;/span&gt;
    &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;sync&amp;quot;&lt;/span&gt;)

&lt;span class=&quot;hljs-keyword&quot;&gt;type&lt;/span&gt; QueueError &lt;span class=&quot;hljs-type&quot;&gt;error&lt;/span&gt;

&lt;span class=&quot;hljs-keyword&quot;&gt;var&lt;/span&gt; CapacityExceededError QueueError = QueueError(errors.New(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;capacity exceeded&amp;quot;&lt;/span&gt;))

&lt;span class=&quot;hljs-comment&quot;&gt;// Queue 包含信号通知的队列&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;// 当队列长度大于等于 thresholdSize 时，触发信号，外部可以监听信号&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;// 当队列长度小于 thresholdSize 时，重置信号状态&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;type&lt;/span&gt; Queue &lt;span class=&quot;hljs-keyword&quot;&gt;struct&lt;/span&gt; {
    items    items
    capacity &lt;span class=&quot;hljs-type&quot;&gt;int&lt;/span&gt;
    lock     sync.Mutex
    &lt;span class=&quot;hljs-comment&quot;&gt;// 触发信号的阈值大小&lt;/span&gt;
    thresholdSize &lt;span class=&quot;hljs-type&quot;&gt;int&lt;/span&gt;
    &lt;span class=&quot;hljs-comment&quot;&gt;// 信号通知，当队列长度大于等于 thresholdSize 时，触发信号&lt;/span&gt;
    processSignal &lt;span class=&quot;hljs-keyword&quot;&gt;chan&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;bool&lt;/span&gt;
    &lt;span class=&quot;hljs-comment&quot;&gt;// 是否已经处理过信号&lt;/span&gt;
    signalProcessed &lt;span class=&quot;hljs-type&quot;&gt;bool&lt;/span&gt;
}

&lt;span class=&quot;hljs-keyword&quot;&gt;type&lt;/span&gt; items []&lt;span class=&quot;hljs-keyword&quot;&gt;interface&lt;/span&gt;{}

&lt;span class=&quot;hljs-comment&quot;&gt;// NewQueue 创建新队列, 指定容量和触发信号的阈值大小&lt;/span&gt;
&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;NewQueue&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;(thresholdSize &lt;span class=&quot;hljs-type&quot;&gt;int&lt;/span&gt;, capacity &lt;span class=&quot;hljs-type&quot;&gt;int&lt;/span&gt;)&lt;/span&gt;&lt;/span&gt; *Queue {
    q := &amp;amp;Queue{}
    q.processSignal = &lt;span class=&quot;hljs-built_in&quot;&gt;make&lt;/span&gt;(&lt;span class=&quot;hljs-keyword&quot;&gt;chan&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;bool&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;)
    q.thresholdSize = thresholdSize
    q.capacity = capacity
    &lt;span class=&quot;hljs-comment&quot;&gt;// 初始化与 thresholdSize 大小一致的队列&lt;/span&gt;
    q.items = &lt;span class=&quot;hljs-built_in&quot;&gt;make&lt;/span&gt;([]&lt;span class=&quot;hljs-keyword&quot;&gt;interface&lt;/span&gt;{}, &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt;, thresholdSize)
    &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; q
}

&lt;span class=&quot;hljs-comment&quot;&gt;// Put 添加元素到队列&lt;/span&gt;
&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-params&quot;&gt;(q *Queue)&lt;/span&gt;&lt;/span&gt; Put(item &lt;span class=&quot;hljs-keyword&quot;&gt;interface&lt;/span&gt;{}) &lt;span class=&quot;hljs-type&quot;&gt;error&lt;/span&gt; {
    q.lock.Lock()
    &lt;span class=&quot;hljs-keyword&quot;&gt;defer&lt;/span&gt; q.lock.Unlock()
    &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; q.&lt;span class=&quot;hljs-built_in&quot;&gt;len&lt;/span&gt;() &amp;gt;= q.capacity {
       &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; CapacityExceededError
    }
    q.items = &lt;span class=&quot;hljs-built_in&quot;&gt;append&lt;/span&gt;(q.items, item)
    &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; q.&lt;span class=&quot;hljs-built_in&quot;&gt;len&lt;/span&gt;() &amp;gt;= q.thresholdSize {
       q.triggerSignal()
    }
    &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt;
}

&lt;span class=&quot;hljs-comment&quot;&gt;// Poll 从队列中取出元素, 并返回取出的元素&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;// 如果队列内部元素小于 num, 则设定 signalProcessed 为 falsefunc (q *Queue) Poll(num int) []interface{} {&lt;/span&gt;
    q.lock.Lock()
    &lt;span class=&quot;hljs-keyword&quot;&gt;defer&lt;/span&gt; q.lock.Unlock()
    &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; q.&lt;span class=&quot;hljs-built_in&quot;&gt;len&lt;/span&gt;() &amp;lt;= num {
       num = q.&lt;span class=&quot;hljs-built_in&quot;&gt;len&lt;/span&gt;()
    }
    result := q.items.get(num)
    &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; q.&lt;span class=&quot;hljs-built_in&quot;&gt;len&lt;/span&gt;() &amp;lt; q.thresholdSize {
       q.resetSignalState()
    }
    &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; result
}

&lt;span class=&quot;hljs-comment&quot;&gt;// PollAll 返回队列中的所有元素，并清空队列&lt;/span&gt;
&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-params&quot;&gt;(q *Queue)&lt;/span&gt;&lt;/span&gt; PollAll() []&lt;span class=&quot;hljs-keyword&quot;&gt;interface&lt;/span&gt;{} {
    q.lock.Lock()
    &lt;span class=&quot;hljs-keyword&quot;&gt;defer&lt;/span&gt; q.lock.Unlock()
    &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; q.&lt;span class=&quot;hljs-built_in&quot;&gt;len&lt;/span&gt;() == &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt; {
       &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt;
    }
    &lt;span class=&quot;hljs-comment&quot;&gt;// 获取所有元素&lt;/span&gt;
    allItems := q.items
    q.items = &lt;span class=&quot;hljs-built_in&quot;&gt;make&lt;/span&gt;([]&lt;span class=&quot;hljs-keyword&quot;&gt;interface&lt;/span&gt;{}, &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt;, q.thresholdSize)
    q.resetSignalState()
    &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; allItems
}

&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-params&quot;&gt;(items *items)&lt;/span&gt;&lt;/span&gt; get(number &lt;span class=&quot;hljs-type&quot;&gt;int&lt;/span&gt;) []&lt;span class=&quot;hljs-keyword&quot;&gt;interface&lt;/span&gt;{} {
    returnItems := &lt;span class=&quot;hljs-built_in&quot;&gt;make&lt;/span&gt;([]&lt;span class=&quot;hljs-keyword&quot;&gt;interface&lt;/span&gt;{}, &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt;, number)
    index := &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt;
    &lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; i := &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt;; i &amp;lt; number; i++ {
       &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; i &amp;gt;= &lt;span class=&quot;hljs-built_in&quot;&gt;len&lt;/span&gt;(*items) {
          &lt;span class=&quot;hljs-keyword&quot;&gt;break&lt;/span&gt;
       }
       returnItems = &lt;span class=&quot;hljs-built_in&quot;&gt;append&lt;/span&gt;(returnItems, (*items)[i])
       (*items)[i] = &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt;
       index++
    }

    *items = (*items)[index:]
    &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; returnItems
}

&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-params&quot;&gt;(q *Queue)&lt;/span&gt;&lt;/span&gt; triggerSignal() {
    &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; q.signalProcessed {
       &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt;
    }
    q.processSignal &amp;lt;- &lt;span class=&quot;hljs-literal&quot;&gt;true&lt;/span&gt;
    q.signalProcessed = &lt;span class=&quot;hljs-literal&quot;&gt;true&lt;/span&gt;
}

&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-params&quot;&gt;(q *Queue)&lt;/span&gt;&lt;/span&gt; resetSignalState() {
    q.signalProcessed = &lt;span class=&quot;hljs-literal&quot;&gt;false&lt;/span&gt;
}

&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-params&quot;&gt;(q *Queue)&lt;/span&gt;&lt;/span&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;len&lt;/span&gt;() &lt;span class=&quot;hljs-type&quot;&gt;int&lt;/span&gt; {
    &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;len&lt;/span&gt;(q.items)
}

&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-params&quot;&gt;(q *Queue)&lt;/span&gt;&lt;/span&gt; ProcessSignal() &amp;lt;-&lt;span class=&quot;hljs-keyword&quot;&gt;chan&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;bool&lt;/span&gt; {
    &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; q.processSignal
}&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;在这个队列中，使用了一个无缓冲的 channel 来记录队列是否达到了阈值，还有一个布尔变量来标记队列是否已经被消费。当队列中的元素数量超过阈值时，channel 和布尔变量协作，通知外部读取队列。&lt;/p&gt;
&lt;h3 id=&quot;消费过程&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#消费过程&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;消费过程&lt;/h3&gt;
&lt;p&gt;在消费过程中，我们使用 &lt;code&gt;timer&lt;/code&gt; 和队列信号作为消费信号，持续读取队列。当到达指定的时间间隔或队列长度超过阈值时，进行队列的读取和上报。&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;// 到达 ReportInterval 或者 batchSize 进行发送&lt;/span&gt;
timer := time.NewTimer(w.config.ReportInterval)
&lt;span class=&quot;hljs-keyword&quot;&gt;defer&lt;/span&gt; timer.Stop()
&lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; {
    &lt;span class=&quot;hljs-comment&quot;&gt;// 缓存消息，定时发送或者足量发送&lt;/span&gt;
    &lt;span class=&quot;hljs-keyword&quot;&gt;select&lt;/span&gt; {
    &lt;span class=&quot;hljs-keyword&quot;&gt;case&lt;/span&gt; &amp;lt;-ctx.Done():
       slog.Info(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;report stop&amp;quot;&lt;/span&gt;)
       &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt;
    &lt;span class=&quot;hljs-keyword&quot;&gt;case&lt;/span&gt; &amp;lt;-timer.C:
       ReportMessages(ctx, que)
       timer.Reset(ReportInterval)
    &lt;span class=&quot;hljs-keyword&quot;&gt;case&lt;/span&gt; &amp;lt;-que.ProcessSignal():
       ReportMessages(ctx, que)
       timer.Reset(ReportInterval)
    }
}&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;在这段代码中：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;当到达配置的 &lt;code&gt;ReportInterval&lt;/code&gt; 时间时，计时器 &lt;code&gt;timer&lt;/code&gt; 触发，执行 &lt;code&gt;ReportMessages&lt;/code&gt; 函数消费队列，并重置计时器以等待下一个时间间隔。&lt;/li&gt;
&lt;li&gt;当队列长度超过阈值时，队列的 &lt;code&gt;ProcessSignal&lt;/code&gt; 信号触发，同样执行 &lt;code&gt;ReportMessages&lt;/code&gt; 函数消费队列，并重置计时器。&lt;/li&gt;
&lt;li&gt;如果上下文 &lt;code&gt;ctx&lt;/code&gt; 被取消，则记录日志并停止报告。&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;通过这种方式，我们确保了队列可以在定时或达到一定长度时进行消费，保持系统的高效运行。&lt;/p&gt;
&lt;h3 id=&quot;死锁分析&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#死锁分析&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;死锁分析&lt;/h3&gt;
&lt;p&gt;在队列的实现中，我们使用了锁 (&lt;code&gt;lock&lt;/code&gt;) 和无缓冲的信号通道 (&lt;code&gt;channel&lt;/code&gt;) 来管理队列状态。这两者都有可能会阻塞，如果它们同时阻塞并互相等待，就会导致死锁。通过观察 Goroutine 的创建趋势图，可以推测出请求在放入队列时发生阻塞，导致 Goroutines 数量不断增加，最终引发内存溢出。&lt;/p&gt;
&lt;p&gt;那么，在什么情况下会导致死锁呢？&lt;/p&gt;
&lt;p&gt;经过分析，只有一种情况会导致死锁：&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;队列大量写入瞬间到达阈值&lt;/strong&gt;：当队列中的元素数量瞬间达到阈值时，信号通道 (&lt;code&gt;channel&lt;/code&gt;) 被写入。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;进入定时器 (&lt;code&gt;timer&lt;/code&gt;) 进行消费&lt;/strong&gt;：此时，&lt;code&gt;timer&lt;/code&gt; 触发，消费队列并将 &lt;code&gt;flag&lt;/code&gt; 设置为 &lt;code&gt;false&lt;/code&gt;，但是信号通道 (&lt;code&gt;channel&lt;/code&gt;) 没有被消费。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;信号通道阻塞&lt;/strong&gt;：在这种情况下，写入队列操作 (&lt;code&gt;queue.Put&lt;/code&gt;) 会因信号通道阻塞而无法完成。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;再一次进入定时器&lt;/strong&gt;：此时不会进入 &lt;code&gt;&lt;-que.ProcessSignal()&lt;/code&gt; 的 case，而是再次进入 &lt;code&gt;timer&lt;/code&gt; case，尝试读取队列但获取锁 (&lt;code&gt;lock&lt;/code&gt;) 阻塞。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;互相阻塞&lt;/strong&gt;：队列的 &lt;code&gt;Put&lt;/code&gt; 和 &lt;code&gt;PollAll&lt;/code&gt; 操作互相阻塞，最终导致死锁。&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;总结来说，死锁发生在队列瞬间达到阈值时，信号通道被写入但未被消费，随后定时器再次触发消费操作时，导致队列的 &lt;code&gt;Put&lt;/code&gt; 和 &lt;code&gt;PollAll&lt;/code&gt; 操作互相阻塞。&lt;/p&gt;
&lt;h3 id=&quot;死锁原因深入分析&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#死锁原因深入分析&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;死锁原因深入分析&lt;/h3&gt;
&lt;p&gt;根据代码逻辑，每次执行完 &lt;code&gt;select&lt;/code&gt; 语句后都会调用 &lt;code&gt;timer.Reset(ReportInterval)&lt;/code&gt; 来重置定时器。因此，理论上不应该两次进入 &lt;code&gt;timer&lt;/code&gt; case，因为存在 &lt;code&gt;que.ProcessSignal()&lt;/code&gt; 信号量，会优先进入这个 case。然而，经过多次反复检查后，其他情况不可能导致死锁，最终怀疑的焦点集中在 &lt;code&gt;timer.Reset&lt;/code&gt; 上。&lt;/p&gt;
&lt;p&gt;通过查看 &lt;code&gt;timer.Reset&lt;/code&gt; 函数的源码及其注释，发现了几个关键点：&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;只对已停止或已到期的定时器使用&lt;/strong&gt;：对于通过 &lt;code&gt;NewTimer&lt;/code&gt; 创建的定时器，应当只在定时器已停止或已到期并且相关通道已清空的情况下调用 &lt;code&gt;Reset&lt;/code&gt;。这样可以避免定时器重置操作和通道接收操作之间的竞争条件。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;确保通道已被清空&lt;/strong&gt;：&lt;ul&gt;
&lt;li&gt;如果程序已经从 &lt;code&gt;t.C&lt;/code&gt; 接收到了值，表明定时器已经到期，并且通道已被清空，可以直接调用 &lt;code&gt;t.Reset&lt;/code&gt;。&lt;/li&gt;
&lt;li&gt;如果程序尚未从 &lt;code&gt;t.C&lt;/code&gt; 接收到值，应首先停止定时器：&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;  &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; !t.Stop() {
  	&amp;lt;-t.C  &lt;span class=&quot;hljs-comment&quot;&gt;// 清空通道&lt;/span&gt;
  }
  t.Reset(d)&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs&quot;&gt;此代码片段首先尝试停止定时器，如果定时器已经到期（`t.Stop()` 返回 `false`），则必须从通道中读取以清空通道，避免潜在的死锁或重复接收旧的过期值。&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;因此，如果定时器已经到达执行时间，需要先读取 &lt;code&gt;timer.C&lt;/code&gt; 再执行 &lt;code&gt;Reset&lt;/code&gt; 操作，否则 &lt;code&gt;Reset&lt;/code&gt; 可能不会生效，导致定时器相继执行两次，从而发生死锁。&lt;/p&gt;
&lt;p&gt;根据日志和错误分析，最近版署防沉迷系统“升级”后经常出现超时（time out），导致上报执行时间变长，队列堆积，从而暴露出这个 bug。&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;总结&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#总结&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;总结&lt;/h3&gt;
&lt;p&gt;在上面的描述中，我们发现了队列和上报逻辑中的两个主要 bug：&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;队列内部的死锁&lt;/strong&gt;：&lt;code&gt;put&lt;/code&gt; 和 &lt;code&gt;poll&lt;/code&gt; 操作可能会导致死锁。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;错误使用 &lt;code&gt;timer.Reset&lt;/code&gt;&lt;/strong&gt;：&lt;code&gt;timer.Reset&lt;/code&gt; 的使用方法不正确，可能导致定时器误触发。&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;此外，队列的设计也存在一些问题，例如多余的 flag 值和对 channel 信号的阻塞处理不当。我们对队列进行了优化，去掉了多余的 flag 值，并改进了 channel 信号处理。以下是优化后的队列代码：&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;package&lt;/span&gt; main

&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; (
    &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;errors&amp;quot;&lt;/span&gt;
    &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;sync&amp;quot;&lt;/span&gt;)

&lt;span class=&quot;hljs-keyword&quot;&gt;type&lt;/span&gt; QueueError &lt;span class=&quot;hljs-type&quot;&gt;error&lt;/span&gt;

&lt;span class=&quot;hljs-keyword&quot;&gt;var&lt;/span&gt; CapacityExceededError QueueError = QueueError(errors.New(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;capacity exceeded&amp;quot;&lt;/span&gt;))

&lt;span class=&quot;hljs-comment&quot;&gt;// Queue 包含信号通知的队列&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;// 当队列长度大于等于 thresholdSize 时，触发信号，外部可以监听信号&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;// 当队列长度小于 thresholdSize 时，重置信号状态&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;type&lt;/span&gt; Queue &lt;span class=&quot;hljs-keyword&quot;&gt;struct&lt;/span&gt; {
    items    items
    capacity &lt;span class=&quot;hljs-type&quot;&gt;int&lt;/span&gt;
    lock     sync.Mutex
    &lt;span class=&quot;hljs-comment&quot;&gt;// 触发信号的阈值大小&lt;/span&gt;
    thresholdSize &lt;span class=&quot;hljs-type&quot;&gt;int&lt;/span&gt;
    &lt;span class=&quot;hljs-comment&quot;&gt;// 信号通知，当队列长度大于等于 thresholdSize 时，触发信号&lt;/span&gt;
    processSignal &lt;span class=&quot;hljs-keyword&quot;&gt;chan&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;bool&lt;/span&gt;
}

&lt;span class=&quot;hljs-keyword&quot;&gt;type&lt;/span&gt; items []&lt;span class=&quot;hljs-keyword&quot;&gt;interface&lt;/span&gt;{}

&lt;span class=&quot;hljs-comment&quot;&gt;// NewQueue 创建新队列, 指定容量和触发信号的阈值大小&lt;/span&gt;
&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;NewQueue&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;(thresholdSize &lt;span class=&quot;hljs-type&quot;&gt;int&lt;/span&gt;, capacity &lt;span class=&quot;hljs-type&quot;&gt;int&lt;/span&gt;)&lt;/span&gt;&lt;/span&gt; *Queue {
    q := &amp;amp;Queue{}
    q.processSignal = &lt;span class=&quot;hljs-built_in&quot;&gt;make&lt;/span&gt;(&lt;span class=&quot;hljs-keyword&quot;&gt;chan&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;bool&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;)
    q.thresholdSize = thresholdSize
    q.capacity = capacity
    &lt;span class=&quot;hljs-comment&quot;&gt;// 初始化与 thresholdSize 大小一致的队列&lt;/span&gt;
    q.items = &lt;span class=&quot;hljs-built_in&quot;&gt;make&lt;/span&gt;([]&lt;span class=&quot;hljs-keyword&quot;&gt;interface&lt;/span&gt;{}, &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt;, thresholdSize)
    &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; q
}

&lt;span class=&quot;hljs-comment&quot;&gt;// Put 添加元素到队列&lt;/span&gt;
&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-params&quot;&gt;(q *Queue)&lt;/span&gt;&lt;/span&gt; Put(item &lt;span class=&quot;hljs-keyword&quot;&gt;interface&lt;/span&gt;{}) &lt;span class=&quot;hljs-type&quot;&gt;error&lt;/span&gt; {
    q.lock.Lock()
    &lt;span class=&quot;hljs-keyword&quot;&gt;defer&lt;/span&gt; q.lock.Unlock()
    &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; q.&lt;span class=&quot;hljs-built_in&quot;&gt;len&lt;/span&gt;() &amp;gt;= q.capacity {
       &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; CapacityExceededError
    }
    q.items = &lt;span class=&quot;hljs-built_in&quot;&gt;append&lt;/span&gt;(q.items, item)
    &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; q.&lt;span class=&quot;hljs-built_in&quot;&gt;len&lt;/span&gt;() &amp;gt;= q.thresholdSize {
       q.triggerSignal()
    }
    &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt;
}

&lt;span class=&quot;hljs-comment&quot;&gt;// Poll 从队列中取出元素, 并返回取出的元素&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;// 如果队列内部元素小于 num, 则设定 signalProcessed 为 falsefunc (q *Queue) Poll(num int) []interface{} {&lt;/span&gt;
    q.lock.Lock()
    &lt;span class=&quot;hljs-keyword&quot;&gt;defer&lt;/span&gt; q.lock.Unlock()
    &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; q.&lt;span class=&quot;hljs-built_in&quot;&gt;len&lt;/span&gt;() &amp;lt;= num {
       num = q.&lt;span class=&quot;hljs-built_in&quot;&gt;len&lt;/span&gt;()
    }
    result := q.items.get(num)
    &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; q.&lt;span class=&quot;hljs-built_in&quot;&gt;len&lt;/span&gt;() &amp;lt; q.thresholdSize {
       q.resetSignal()
    }
    &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; result
}

&lt;span class=&quot;hljs-comment&quot;&gt;// PollAll 返回队列中的所有元素，并清空队列&lt;/span&gt;
&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-params&quot;&gt;(q *Queue)&lt;/span&gt;&lt;/span&gt; PollAll() []&lt;span class=&quot;hljs-keyword&quot;&gt;interface&lt;/span&gt;{} {
    q.lock.Lock()
    &lt;span class=&quot;hljs-keyword&quot;&gt;defer&lt;/span&gt; q.lock.Unlock()
    &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; q.&lt;span class=&quot;hljs-built_in&quot;&gt;len&lt;/span&gt;() == &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt; {
       &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt;
    }
    &lt;span class=&quot;hljs-comment&quot;&gt;// 获取所有元素&lt;/span&gt;
    allItems := q.items
    q.items = &lt;span class=&quot;hljs-built_in&quot;&gt;make&lt;/span&gt;([]&lt;span class=&quot;hljs-keyword&quot;&gt;interface&lt;/span&gt;{}, &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt;, q.thresholdSize)
    &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;len&lt;/span&gt;(allItems) &amp;gt;= q.thresholdSize {
       q.resetSignal()
    }
    &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; allItems
}

&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-params&quot;&gt;(q *Queue)&lt;/span&gt;&lt;/span&gt; triggerSignal() {
    &lt;span class=&quot;hljs-keyword&quot;&gt;select&lt;/span&gt; {
    &lt;span class=&quot;hljs-keyword&quot;&gt;case&lt;/span&gt; q.processSignal &amp;lt;- &lt;span class=&quot;hljs-literal&quot;&gt;true&lt;/span&gt;:
    &lt;span class=&quot;hljs-keyword&quot;&gt;default&lt;/span&gt;:
    }
}

&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-params&quot;&gt;(q *Queue)&lt;/span&gt;&lt;/span&gt; resetSignal() {
    &lt;span class=&quot;hljs-keyword&quot;&gt;select&lt;/span&gt; {
    &lt;span class=&quot;hljs-keyword&quot;&gt;case&lt;/span&gt; &amp;lt;-q.processSignal:
    &lt;span class=&quot;hljs-keyword&quot;&gt;default&lt;/span&gt;:
    }
}

&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-params&quot;&gt;(items *items)&lt;/span&gt;&lt;/span&gt; get(number &lt;span class=&quot;hljs-type&quot;&gt;int&lt;/span&gt;) []&lt;span class=&quot;hljs-keyword&quot;&gt;interface&lt;/span&gt;{} {
    returnItems := &lt;span class=&quot;hljs-built_in&quot;&gt;make&lt;/span&gt;([]&lt;span class=&quot;hljs-keyword&quot;&gt;interface&lt;/span&gt;{}, &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt;, number)
    index := &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt;
    &lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; i := &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt;; i &amp;lt; number; i++ {
       &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; i &amp;gt;= &lt;span class=&quot;hljs-built_in&quot;&gt;len&lt;/span&gt;(*items) {
          &lt;span class=&quot;hljs-keyword&quot;&gt;break&lt;/span&gt;
       }
       returnItems = &lt;span class=&quot;hljs-built_in&quot;&gt;append&lt;/span&gt;(returnItems, (*items)[i])
       (*items)[i] = &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt;
       index++
    }

    *items = (*items)[index:]
    &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; returnItems
}

&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-params&quot;&gt;(q *Queue)&lt;/span&gt;&lt;/span&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;len&lt;/span&gt;() &lt;span class=&quot;hljs-type&quot;&gt;int&lt;/span&gt; {
    &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;len&lt;/span&gt;(q.items)
}

&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-params&quot;&gt;(q *Queue)&lt;/span&gt;&lt;/span&gt; ThresholdChan() &amp;lt;-&lt;span class=&quot;hljs-keyword&quot;&gt;chan&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;bool&lt;/span&gt; {
    &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; q.processSignal
}&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;同时，我们对 &lt;code&gt;timer.Reset&lt;/code&gt; 的使用进行了修改，以确保符合预期：&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;case&lt;/span&gt; &amp;lt;-que.ThresholdChan():
    ReportMessages(ctx, que)
    &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; !timer.Stop() {
       &amp;lt;-timer.C
    }
    timer.Reset(ReportInterval)&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;这是我第一次在 Go 语言中手写死锁代码，这次经历让我学习到了很多。虽然防沉迷上报这个业务价值并不高，影响很小，但通过这次优化，我对使用 channel 的方式有了更深刻的理解，也避免了以后可能会遇到的的坑。&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;&lt;em&gt;2024-08-15 更新：&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;在 &lt;a href=&quot;https://go.dev/doc/go1.23#timer-changes&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;golang 1.23&lt;/a&gt; 中，对 &lt;a href=&quot;https://go.dev/wiki/Go123Timer&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;Timer 和 Ticker 的行为做了修改&lt;/a&gt;：&lt;/em&gt;&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs&quot;&gt;Second, the timer channel associated with a `Timer` or `Ticker` is now unbuffered, with capacity 0. The main effect of this change is that Go now guarantees that for any call to a `Reset` or `Stop` method, no stale values prepared before that call will be sent or received after the call.
与定时器或计时器关联的定时器通道现在没有缓冲区，容量为 0。此更改的主要影响是 Go 现在可以保证对任何调用 Reset 或 Stop 方法的调用，在调用之前准备的过时值在调用之后不会被发送或接收。&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;&lt;em&gt;如果你也有同样的问题，可以升级到 golang 1.23～&lt;/em&gt;&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>gorm 中 MySQL 错误码映射与主键冲突错误处理</title>
    <link href="https://blog.whrss.com/posts/gorm-mysql-error-handling-duplicate-key-translations"/>
    <id>https://blog.whrss.com/posts/gorm-mysql-error-handling-duplicate-key-translations</id>
    <published>2024-03-27T03:43:05.000Z</published>
    <updated>2024-03-27T03:43:05.000Z</updated>
    <category term="技术"/>
    <category term="go"/>
    <category term="gorm"/>
    <summary>在使用 gorm 处理数据库操作时，尤其是针对 MySQL，有时我们会遇到 golang 标准库`errors.Is`函数无法直接识别特定的 gorm 错误类型的情况，如主键冲突错误。尽管 gorm 提供了`gorm.ErrDuplicatedKey`来表示此类错误，但在原始错误返回中并不能直接通过`errors.Is(err, gorm.ErrDuplicatedKey)`来进行判断。本文深入探究 gorm.io/driver/mysql 包中的错误转换机制，揭示了如何借助`error_translator`模块将 MySQL 的错误码映射为 gorm 的错误类型。</summary>
    <content type="html">&lt;p&gt;处理 &lt;code&gt;gorm&lt;/code&gt; 错误返回时，有一些错误是没有办法直接使用 &lt;code&gt;errors.Is&lt;/code&gt; 来进行判断的，比如主键冲突的错误，直接使用 &lt;code&gt;errors.Is(err, gorm.ErrDuplicatedKey)&lt;/code&gt; 是无法判断出主键冲突的错误返回的。&lt;/p&gt;
&lt;p&gt;如果没有办法进行判断，为什么 &lt;code&gt;gorm&lt;/code&gt; 要给这样一个 &lt;code&gt;error&lt;/code&gt; ，但又不能使用呢？&lt;/p&gt;
&lt;p&gt;&lt;code&gt;gorm.io/driver/mysql&lt;/code&gt; 包中有一个 &lt;code&gt;error_translator&lt;/code&gt; 的 go 文件&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;package&lt;/span&gt; mysql

&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; (
    &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;github.com/go-sql-driver/mysql&amp;quot;&lt;/span&gt;

    &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;gorm.io/gorm&amp;quot;&lt;/span&gt;)

&lt;span class=&quot;hljs-comment&quot;&gt;// The error codes to map mysql errors to gorm errors, here is the mysql error codes reference https://dev.mysql.com/doc/mysql-errors/8.0/en/server-error-reference.html.&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;var&lt;/span&gt; errCodes = &lt;span class=&quot;hljs-keyword&quot;&gt;map&lt;/span&gt;[&lt;span class=&quot;hljs-type&quot;&gt;uint16&lt;/span&gt;]&lt;span class=&quot;hljs-type&quot;&gt;error&lt;/span&gt;{
    &lt;span class=&quot;hljs-number&quot;&gt;1062&lt;/span&gt;: gorm.ErrDuplicatedKey,
    &lt;span class=&quot;hljs-number&quot;&gt;1451&lt;/span&gt;: gorm.ErrForeignKeyViolated,
    &lt;span class=&quot;hljs-number&quot;&gt;1452&lt;/span&gt;: gorm.ErrForeignKeyViolated,
}

&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-params&quot;&gt;(dialector Dialector)&lt;/span&gt;&lt;/span&gt; Translate(err &lt;span class=&quot;hljs-type&quot;&gt;error&lt;/span&gt;) &lt;span class=&quot;hljs-type&quot;&gt;error&lt;/span&gt; {
    &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; mysqlErr, ok := err.(*mysql.MySQLError); ok {
       &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; translatedErr, found := errCodes[mysqlErr.Number]; found {
          &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; translatedErr
       }
       &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; mysqlErr
    }

    &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; err
}&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;我们可以看到这个文件将 mysql 的几种错误码进行了枚举，使用 &lt;code&gt;Translate&lt;/code&gt; 函数会将对应的 &lt;code&gt;mysql error&lt;/code&gt; 转化为 &lt;code&gt;gorm error&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;那这里的 &lt;code&gt;Translate&lt;/code&gt; 函数，是谁进行使用了呢？在什么时候进行使用了呢？&lt;/p&gt;
&lt;p&gt;主键冲突的错误一定是出现在插入的时候，我们顺着 &lt;code&gt;gorm&lt;/code&gt; 的 &lt;code&gt;Create&lt;/code&gt; 方法向下找，可以发现它调用了一个 &lt;code&gt;AddError&lt;/code&gt; 的函数，如下&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;// AddError add error to dbfunc (db *DB) AddError(err error) error {&lt;/span&gt;
    &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; err != &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt; {
       &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; db.Config.TranslateError {
          &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; errTranslator, ok := db.Dialector.(ErrorTranslator); ok {
             err = errTranslator.Translate(err)
          }
       }

       &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; db.Error == &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt; {
          db.Error = err
       } &lt;span class=&quot;hljs-keyword&quot;&gt;else&lt;/span&gt; {
          db.Error = fmt.Errorf(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;%v; %w&amp;quot;&lt;/span&gt;, db.Error, err)
       }
    }
    &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; db.Error
}&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;这里有一行很关键，&lt;code&gt;db.Dialector.(ErrorTranslator)&lt;/code&gt; 对 &lt;code&gt;Dialector&lt;/code&gt; 接口进行了断言，断言成功，就调用对应 &lt;code&gt;Dialector&lt;/code&gt; 的 &lt;code&gt;Translate&lt;/code&gt; 函数，而当这里的 &lt;code&gt;Dialector&lt;/code&gt; 是上面 &lt;code&gt;gorm.io/driver/mysql&lt;/code&gt; 中的 &lt;code&gt;Dialector&lt;/code&gt; 时，就可以运行上面的翻译逻辑，将 mysql 的 error 转换为 gorm 的 error。&lt;/p&gt;
&lt;p&gt;那么，我们下一步就是找到方法，把这里使用的 &lt;code&gt;Dialector&lt;/code&gt; 替换成 &lt;code&gt;gorm.io/driver/mysql&lt;/code&gt; 包下的这个 &lt;code&gt;Dialector&lt;/code&gt;，这样我们就可以使用 &lt;code&gt;errors.Is(err, gorm.ErrDuplicatedKey)&lt;/code&gt; 对插入冲突进行判断了。&lt;/p&gt;
&lt;p&gt;gorm 中 DB 对象的结构是这样的&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;// DB GORM DB definition&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;type&lt;/span&gt; DB &lt;span class=&quot;hljs-keyword&quot;&gt;struct&lt;/span&gt; {
    *Config
    Error        &lt;span class=&quot;hljs-type&quot;&gt;error&lt;/span&gt;
    RowsAffected &lt;span class=&quot;hljs-type&quot;&gt;int64&lt;/span&gt;
    Statement    *Statement
    clone        &lt;span class=&quot;hljs-type&quot;&gt;int&lt;/span&gt;
}&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;这里的 Config 中就包含了 &lt;code&gt;Dialector&lt;/code&gt; 接口，我们只需要在创建 &lt;code&gt;gorm.DB&lt;/code&gt; 的时候，将接口的实例（&lt;code&gt;gorm.io/driver/mysql&lt;/code&gt; 包下的这个）传入进去，就可以让 &lt;code&gt;gorm&lt;/code&gt; 在之后的 error 判断时，对 mysql 的 error 进行翻译。&lt;/p&gt;
&lt;p&gt;到这儿，原理部分就明明白白了，接下来简单改写一下 &lt;code&gt;gorm.DB&lt;/code&gt; 的 init 过程即可！⬇️&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;gorm.io/driver/mysql&amp;quot;&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;gorm.io/gorm&amp;quot;&lt;/span&gt;

connUrl := &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;数据库连接地址&amp;quot;&lt;/span&gt;
db, err := gorm.Open(
	mysql.Open(connUrl).(*mysql.Dialector),
	TranslateError: &lt;span class=&quot;hljs-literal&quot;&gt;true&lt;/span&gt;, &lt;span class=&quot;hljs-comment&quot;&gt;// 开启 mysql 方言翻译 (开启后 duplicatedKey err 判断才能生效)&lt;/span&gt;
)&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;以上！&lt;/p&gt;
&lt;p&gt;参考链接：&lt;a href=&quot;https://gorm.io/docs/error_handling.html#Dialect-Translated-Errors&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;https://gorm.io/docs/error_handling.html#Dialect-Translated-Errors&lt;/a&gt;&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>CloudFlare Tunnel 免费内网穿透的简明教程</title>
    <link href="https://blog.whrss.com/posts/cloudflare-tunnel"/>
    <id>https://blog.whrss.com/posts/cloudflare-tunnel</id>
    <published>2024-02-27T05:01:35.000Z</published>
    <updated>2024-02-27T05:01:35.000Z</updated>
    <category term="折腾"/>
    <summary>Tunnel 可以做什么?
将本地网络的服务暴露到公网，可以理解为内网穿透。 将非常规端口服务转发到 80/443 常规端口。 自动为你的域名提供 HTTPS 认证。 为你的服务提供额外保护认证。 跳过国内服务器备案域名。 最重要的是——免费。</summary>
    <content type="html">&lt;h2 id=&quot;tunnel-可以做什么&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#tunnel-可以做什么&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;Tunnel 可以做什么&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;将本地网络的服务暴露到公网，可以理解为内网穿透。&lt;/strong&gt; 例如我们在本地服务器 &lt;code&gt;localhost:8091&lt;/code&gt; 搭建了一个 博客网站，我们只能在内网环境才能访问这个服务，但通过内网穿透技术，我们可以在任何广域网环境下访问该服务。相比 NPS 之类传统穿透服务，Tunnel 不需要公网云服务器，同时自带域名解析，无需 DDNS 和公网 IP。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;将非常规端口服务转发到 80/443 常规端口。&lt;/strong&gt; 无论是使用公网 IP + DDNS 还是传统内网穿透服务，都免不了使用非常规端口进行访问，如果某些服务使用了复杂的重定向可能会导致 URL 中端口号丢失而引起不可控的问题，同时也不够优雅。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;自动为你的域名提供 HTTPS 认证。&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;h2 id=&quot;tunnel-工作原理&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#tunnel-工作原理&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;Tunnel 工作原理&lt;/h2&gt;
&lt;p&gt;Tunnel 通过在本地网络运行的一个 Cloudflare 守护程序，与 Cloudflare 云端通信，将云端请求数据转发到本地网络的 IP + 端口。&lt;/p&gt;
&lt;h2 id=&quot;前置条件&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#前置条件&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;前置条件&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;持有一个域名&lt;/li&gt;
&lt;li&gt;将域名 DNS 解析托管到 CloudFlare (我目前都直接转到了 CloudFlare )&lt;/li&gt;
&lt;li&gt;有一台服务器（本地非本地都可以，有没有公网 IP 都 OK），用于运行本地与 cloudflare 通信的 cloudflared 程序&lt;/li&gt;
&lt;li&gt;一张境内双币信用卡（仅用于添加付款方式，服务是免费的）&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;开始&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#开始&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;开始&lt;/h2&gt;
&lt;h4 id=&quot;1-打开-cloudflare-zero-trust-工作台面板&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#1-打开-cloudflare-zero-trust-工作台面板&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;1. 打开 &lt;a href=&quot;https://one.dash.cloudflare.com/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;Cloudflare Zero Trust&lt;/a&gt; 工作台面板&lt;/h4&gt;
&lt;h4 id=&quot;2-创建-cloudflare-zero-trust-选择免费计划需要提供付款方式使用境内的双币卡即可&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#2-创建-cloudflare-zero-trust-选择免费计划需要提供付款方式使用境内的双币卡即可&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;2. 创建 &lt;strong&gt;Cloudflare Zero Trust&lt;/strong&gt; ，选择免费计划。需要提供付款方式，使用境内的双币卡即可&lt;/h4&gt;
&lt;p&gt;&lt;img src=&quot;https://pic.whrss.com/2024/02/1708419784.png&quot; alt=&quot;image.png&quot; loading=&quot;eager&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;填写 team name，随意填写&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://pic.whrss.com/2024/02/1708419807.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;选择免费计划&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://pic.whrss.com/2024/02/1708419823.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;添加付款方式&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://pic.whrss.com/2024/02/1708419835.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;填写信用卡信息（仅验证，不会扣款），完成配置&lt;/p&gt;
&lt;h4 id=&quot;3-完成后在-access-tunnels-中创建一个-tunnel&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#3-完成后在-access-tunnels-中创建一个-tunnel&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;3. 完成后，在 Access Tunnels 中，创建一个 Tunnel。&lt;/h4&gt;
&lt;p&gt;&lt;img src=&quot;https://pic.whrss.com/2024/02/1708419913.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;创建 Tunnel&lt;br&gt;&lt;img src=&quot;https://pic.whrss.com/2024/02/1708419932.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;h4 id=&quot;4-选择-cloudflared-部署方式&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#4-选择-cloudflared-部署方式&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;4. 选择 Cloudflared 部署方式。&lt;/h4&gt;
&lt;p&gt;Tunnel 需要通过 Cloudflared 来建立云端与本地网络的通道，这里推荐选择 Docker 部署 Cloudflared 守护进程以使用 Tunnel 功能。&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://pic.whrss.com/2024/02/1708420329.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;获取 Cloudflared 启动命令及 Token&lt;/p&gt;
&lt;p&gt;在本地网络主机上运行命令。我们还可以加上&lt;code&gt;--name cloudflared -d --restart unless-stop&lt;/code&gt;为 Docker 容器增加名称和后台运行。你可以使用下方我修改好命令来创建 Docker，注意替换你为自己的 Token（就是网页中&lt;code&gt;—-token&lt;/code&gt; 之后的长串字符）&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;shell&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-bash&quot;&gt;docker run --name cloudflared -d --restart unless-stop cloudflare/cloudflared:latest tunnel --no-autoupdate run --token &amp;lt;YourToken&amp;gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;h4 id=&quot;5-配置域名和转发-url&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#5-配置域名和转发-url&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;5. 配置域名和转发 URL&lt;/h4&gt;
&lt;p&gt;为你的域名配置一个子域名（Subdomain），Path 留空，URL 处填写内网服务的 IP 加端口号。注意 Type 处建议使用 HTTP，因为 Cloudflare 会自动为你提供 HTTPS，因此此处的转发目标可以是 HTTP 服务端口。&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://pic.whrss.com/2024/02/1708420312.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;配置内网目标 IP+端口&lt;/p&gt;
&lt;p&gt;这里要注意，配置的 ip 如果是 127.0.0.1 或者是 localhost，是不行的&lt;br&gt;对于 linux 可以创建一个桥接网络&lt;br&gt;下面的 localNet 是网络名字,可自行修改;关于 192.168.0.0 这个子网,也可以自行定义.&lt;br&gt;默认按照下面的命令,执行后将可以通过 192.168.1.100 访问宿主机.&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;sh&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-bash&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;# 使用192.168.1.100替换127.0.0.1,如mongodb://192.168.1.100:27017&lt;/span&gt;
docker network create -d bridge --subnet 192.168.0.0/24 --gateway 192.168.1.100 localNet&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;h2 id=&quot;完成&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#完成&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;完成&lt;/h2&gt;
&lt;p&gt;接着访问刚刚配置的三级域名，例如 &lt;a href=&quot;https://app.yourdomain.com/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;https://app.yourdomain.com&lt;/a&gt;（是的，你没看错，是 https，cloudflare 已经自动为域名提供了 https 证书）就可以访问到内网的非公端口号服务了。一个 Tunnel 中可以添加多条三级域名来跳转到不同的内网服务，在 Tunnel 页面的 Public Hostname 中新增即可。&lt;/p&gt;
&lt;h2 id=&quot;为你的服务添加额外验证&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#为你的服务添加额外验证&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;为你的服务添加额外验证&lt;/h2&gt;
&lt;p&gt;如果你觉得这种直接暴露内网服务的方式有较高的安全风险，我们还可以使用 Application 功能为服务添加额外的安全验证。&lt;/p&gt;
&lt;p&gt;1. 点击 Application - Get started。&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://pic.whrss.com/2024/02/1708420288.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;创建 Application&lt;/p&gt;
&lt;p&gt;2. 选择 Self-hosted。&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://pic.whrss.com/2024/02/1708420275.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;选择类型&lt;/p&gt;
&lt;p&gt;3. 填写配置，&lt;strong&gt;注意 Subdomain 和 Domain 需要使用刚刚创建的 Tunnel 服务相同的 Domain 配置&lt;/strong&gt;。&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://pic.whrss.com/2024/02/1708420257.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;配置三级域名&lt;/p&gt;
&lt;p&gt;4. 选择验证方式。填写 Policy name（任意）。在 Include 区域选择验证方式，示例图片中使用的是 Email 域名的方式，用户在访问该网络时需要使用指定的邮箱域名（如@gmail.com）验证，这种方式比较适合自定义域名的企业邮箱用户。另外你还可以指定特定完整邮箱地址、IP 地址范围等方式。&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://pic.whrss.com/2024/02/1708420237.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;选择验证方式&lt;/p&gt;
&lt;p&gt;5. 完成添加&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://pic.whrss.com/2024/02/1708420205.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;此时，访问 &lt;a href=&quot;https://app.yourdomain.com&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;https://app.yourdomain.com&lt;/a&gt; 可以看到网站多了一个验证页面，使用刚刚设置的域名邮箱，接收验证码来访问。&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://pic.whrss.com/2024/02/1708420185.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;h2 id=&quot;评价&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#评价&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;评价&lt;/h2&gt;
&lt;p&gt;除了上述直接转发 http 服务之外，Tunnel 还支持 RDP、SSH 等协议的转发，玩法丰富。&lt;/p&gt;
&lt;p&gt;作为一款免费的服务，简单的配置，低门槛使用条件，适合简单部署尝试。&lt;/p&gt;
&lt;p&gt;通过 ssh 隧道部署，还可以跳过国内服务器域名必须备案的条件。&lt;/p&gt;
&lt;p&gt;不过要注意的是 Tunnel 在国内访问速度不快，并且有断流的情况，请酌情使用。&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>2023 年购物回忆录：值不值得买</title>
    <link href="https://blog.whrss.com/posts/2023-shopping-journey-value-and-regrets"/>
    <id>https://blog.whrss.com/posts/2023-shopping-journey-value-and-regrets</id>
    <published>2024-01-13T19:24:59.000Z</published>
    <updated>2024-01-13T19:24:59.000Z</updated>
    <category term="生活和思考"/>
    <category term="2023"/>
    <summary>2023年，对我来说是充满购物冒险的一年，我购买了很多东西，今天，我想回顾一下，分享哪些购买对我来说物超所值，哪些则是我冲动消费的产物，让我感到后悔。让我们开始这段回忆旅程吧～??️</summary>
    <content type="html">&lt;p&gt;2023年，对我来说是充满购物冒险的一年，我购买了很多东西，今天，我想回顾一下，分享哪些购买对我来说物超所值，哪些则是我冲动消费的产物，让我感到后悔。让我们开始这段回忆旅程吧～??️&lt;/p&gt;
&lt;h2 id=&quot;超值购物体验&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#超值购物体验&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;超值购物体验&lt;/h2&gt;
&lt;h3 id=&quot;3d-打印机-拓竹-a1-2199rmb&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#3d-打印机-拓竹-a1-2199rmb&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;3D 打印机 拓竹 A1 2199RMB ?????&lt;/h3&gt;
&lt;p&gt;&lt;img src=&quot;https://pic.whrss.com/2024/01/1705200214.png&quot; alt=&quot;image.png&quot; loading=&quot;eager&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;长久以来，我一直对3D打印充满好奇。23年年尾，拓竹推出了尺寸价格各方面都还蛮契合我期望的A1，首发抢到！也可能是因为到目前时间很短，新鲜感未消，所以，他是我综合来看，2023年购买的最值、体验最好的产品，当然我还有很多的坑的知识要去补，慢慢把它玩好，说不定以后再升级更贵的P系列呢哈哈～ &lt;/p&gt;
&lt;h3 id=&quot;spotify-会员-120rmb年-爱合租&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#spotify-会员-120rmb年-爱合租&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;spotify 会员 120RMB/年 爱合租 ???&lt;/h3&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs&quot;&gt;使用的是爱合租这个平台（非广），已经忘了大概什么时候发现了爱合租这个平台，应该是之前推上有人说过还是谁的博客提了一嘴。
很多人说Spotify的推荐算法是最NB的，想从apple music 切过去看看，尝试尝试。所以我很早就下载体验了一下，但是单买太贵，而现在有了合租的渠道。
但是比较难受的是，苹果不支持语音控制播放，生态各方面不太行，快捷指令我也没有遇到什么合适的。总体来说，听歌的频率更低了，是不是也一方面说明我更忙了，没时间emo了? &lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;h3 id=&quot;youtube-会员-60rmb年&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#youtube-会员-60rmb年&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;youtube 会员 60RMB/年 ???&lt;/h3&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs&quot;&gt;之前一直是 YouTube的免费用户，努力贡献广告收入，但是非会员无法后台播放，就很气，得一直开着前台，受不了简直是受不了了，从推上发现了一个卖的，他在tg上有频道专门卖，60一年，很便宜，确实解决了我的问题。&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;h3 id=&quot;switch-双人成行-170rmb&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#switch-双人成行-170rmb&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;switch 双人成行 170RMB ?????&lt;/h3&gt;
&lt;p&gt;&lt;img src=&quot;https://pic.whrss.com/2024/01/1705200562.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;这应该是我在switch上通关的第一个大作，和女朋友一起玩的，确实很不错，是我玩过最好的双人游戏，也一定是目前switch上最好的双人游戏，值得每一对情侣去尝试。我比较晕3d（无缘塞尔达），但这个是可以玩的，游戏做的确实好，超值！&lt;/p&gt;
&lt;h3 id=&quot;卤素台灯-165rmb&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#卤素台灯-165rmb&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;卤素台灯 165RMB ?????&lt;/h3&gt;
&lt;p&gt;&lt;img src=&quot;https://pic.whrss.com/2024/01/1705200191.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;由于家里没啥光照，窗户为了保暖我也给封起来了，23年尾，我想给家里养几盆花，由于之前我养的无一例外的挂掉了，这次我直接就想到了我需要准备好的光照，充足的光照。我就从网上找什么生物灯、补光灯，最后发现这款卤素台灯不错，外观也好看，既可以当台灯，也可以给植物补光，一整个契合我的需求，完美！ 实际效果也非常非常给力，绿箩 发财树 常春藤都在夸夸长～&lt;br&gt;我后来买了一个小米智能插座3，配合快捷指令，每天语音、定时开关，体验翻倍！这里夸一下小米插座，其实小米插座也是一个五星产品哦～&lt;/p&gt;
&lt;h2 id=&quot;后悔的购物决定&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#后悔的购物决定&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;后悔的购物决定&lt;/h2&gt;
&lt;h3 id=&quot;风行折叠车-5300rmb无数配件&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#风行折叠车-5300rmb无数配件&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;风行折叠车 5300RMB+无数配件 ?&lt;/h3&gt;
&lt;p&gt;&lt;img src=&quot;https://pic.whrss.com/2024/01/1705200199.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;今年换工作的时候上头买了一辆折叠车，花了我今年最贵的单品价格，我之前还专门写了一篇去记录整个购买过程，唉，大几千买了回来吃灰，哈哈哈哈 最亏的一个，希望24年夏天可以骑起来！&lt;/p&gt;
&lt;h2 id=&quot;个人感慨&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#个人感慨&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;个人感慨&lt;/h2&gt;
&lt;h4 id=&quot;寻找生活的乐趣&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#寻找生活的乐趣&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;&lt;strong&gt;寻找生活的乐趣&lt;/strong&gt;&lt;/h4&gt;
&lt;p&gt;2023年，我在购物上的探索，不仅仅是物质的积累，更是我对生活质量追求的体现。每一次点击“购买”，背后都有我对生活品质的向往和对新鲜事物的好奇。尤其是3D打印机拓竹A1，它不仅仅是一件商品，更是我梦寐以求的创造工具。每当我看到它打印出的第一个作品时，那种成就感和快乐是无法用言语表达的。&lt;/p&gt;
&lt;h4 id=&quot;反思与成长&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#反思与成长&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;&lt;strong&gt;反思与成长&lt;/strong&gt;&lt;/h4&gt;
&lt;p&gt;然而，并不是每一次的购物都带来了预期中的满足。比如风行折叠车，它让我意识到，有时候我们对事物的渴望，更多是一时的冲动，而非真正的需要。这种反思让我学会了在冲动购物和理智选择之间找到平衡。&lt;/p&gt;
&lt;h2 id=&quot;未来展望&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#未来展望&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;未来展望&lt;/h2&gt;
&lt;h4 id=&quot;理性消费的决心&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#理性消费的决心&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;&lt;strong&gt;理性消费的决心&lt;/strong&gt;&lt;/h4&gt;
&lt;p&gt;面对2024年，我计划更加理性地对待我的购物欲望。在购买前，我会花时间思考这件物品是否真正适合我的生活方式，它是否能长期为我的生活带来价值。同时，我也想尝试减少不必要的开支，专注于提升现有物品的使用体验，比如学习更多关于3D打印的技巧，或是开发更多与Spotify相结合的智能生活场景。&lt;/p&gt;
&lt;h4 id=&quot;拥抱新技术追求高质量生活&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#拥抱新技术追求高质量生活&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;&lt;strong&gt;拥抱新技术，追求高质量生活&lt;/strong&gt;&lt;/h4&gt;
&lt;p&gt;我对新技术和高质量生活的追求不会停止。在未来，我期待能遇到更多像卤素台灯这样的产品，它们不仅美观实用，还能提升我的生活品质。同时，我也希望能够更加注重生态与健康，例如选择更环保的产品，或是投资于提升居家环境的物品。&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>探索服务端通信技术：短轮询、WebSocket、SSE 与长轮询的深度比较</title>
    <link href="https://blog.whrss.com/posts/server-communication-methods"/>
    <id>https://blog.whrss.com/posts/server-communication-methods</id>
    <published>2023-11-19T05:51:46.000Z</published>
    <updated>2023-11-19T05:51:46.000Z</updated>
    <category term="技术"/>
    <category term="短轮询"/>
    <category term="WebSocket"/>
    <category term="SSE"/>
    <category term="长轮询"/>
    <category term="polling"/>
    <category term="long polling"/>
    <summary>在现代 Web 应用中，服务端与客户端之间的高效通信至关重要。本文探讨了四种主流的服务端通信方法：短轮询、WebSocket、SSE（Server-Sent Events）和长轮询，分析它们的工作原理、适用场景及优缺点。</summary>
    <content type="html">&lt;p&gt;在现代 Web 应用中，服务端与客户端之间的高效通信至关重要。本文探讨了四种主流的服务端通信方法：短轮询、WebSocket、SSE（Server-Sent Events）和长轮询，分析它们的工作原理、适用场景及优缺点。&lt;/p&gt;
&lt;h3 id=&quot;一短轮询高兼容性的传统选择&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#一短轮询高兼容性的传统选择&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;一、短轮询：高兼容性的传统选择&lt;/h3&gt;
&lt;p&gt;短轮询是服务端通信的一种基本方法，客户端通过定期发送 HTTP 请求来检查服务器上的更新。&lt;br&gt;&lt;img src=&quot;https://pic.whrss.com/2023/11/1700400293.png&quot; alt=&quot;image.png&quot; loading=&quot;eager&quot; decoding=&quot;async&quot;&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; 高兼容性，适用于所有支持 HTTP 的客户端。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;缺点：&lt;/strong&gt; 高资源消耗，频繁建立和关闭 TCP 连接。&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;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;package&lt;/span&gt; main

&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; (
    &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;fmt&amp;quot;&lt;/span&gt;
    &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;net/http&amp;quot;&lt;/span&gt;
    &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;time&amp;quot;&lt;/span&gt;
)

&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;main&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;()&lt;/span&gt;&lt;/span&gt; {
    http.HandleFunc(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;/poll&amp;quot;&lt;/span&gt;, &lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;(w http.ResponseWriter, r *http.Request)&lt;/span&gt;&lt;/span&gt; {
        &lt;span class=&quot;hljs-comment&quot;&gt;// 假设这里是从数据库或某个存储检索最新消息的逻辑&lt;/span&gt;
        message := &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;Hello, world! - &amp;quot;&lt;/span&gt; + time.Now().Format(time.RFC1123)
        fmt.Fprint(w, message)
    })

    http.ListenAndServe(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;:8080&amp;quot;&lt;/span&gt;, &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt;)
}&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;h3 id=&quot;二websocket实时双向通信的理想选择&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#二websocket实时双向通信的理想选择&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;二、WebSocket：实时双向通信的理想选择&lt;/h3&gt;
&lt;p&gt;WebSocket 是一种在单个 TCP 连接上进行全双工通信的协议，适用于需要实时双向通信的应用。&lt;br&gt;&lt;img src=&quot;https://pic.whrss.com/2023/11/1700400421.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&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; 低延迟，适用于实时通信。&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;p&gt;最常用的一个场景：实时聊天应用&lt;/p&gt;
&lt;p&gt;服务端和客户端通过 WebSocket 保持连接，实现实时通讯。&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;package&lt;/span&gt; main

&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; (
    &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;net/http&amp;quot;&lt;/span&gt;
    &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;github.com/gorilla/websocket&amp;quot;&lt;/span&gt;
)

&lt;span class=&quot;hljs-keyword&quot;&gt;var&lt;/span&gt; upgrader = websocket.Upgrader{
    ReadBufferSize:  &lt;span class=&quot;hljs-number&quot;&gt;1024&lt;/span&gt;,
    WriteBufferSize: &lt;span class=&quot;hljs-number&quot;&gt;1024&lt;/span&gt;,
}

&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;main&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;()&lt;/span&gt;&lt;/span&gt; {
    http.HandleFunc(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;/ws&amp;quot;&lt;/span&gt;, &lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;(w http.ResponseWriter, r *http.Request)&lt;/span&gt;&lt;/span&gt; {
        conn, _ := upgrader.Upgrade(w, r, &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt;) &lt;span class=&quot;hljs-comment&quot;&gt;// 错误处理省略&lt;/span&gt;
        &lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; {
            messageType, p, _ := conn.ReadMessage() &lt;span class=&quot;hljs-comment&quot;&gt;// 错误处理省略&lt;/span&gt;
            conn.WriteMessage(messageType, p)       &lt;span class=&quot;hljs-comment&quot;&gt;// 错误处理省略&lt;/span&gt;
        }
    })

    http.ListenAndServe(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;:8080&amp;quot;&lt;/span&gt;, &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt;)
}
&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;h3 id=&quot;三-sse简单的单向服务器推送技术&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#三-sse简单的单向服务器推送技术&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;三、 SSE：简单的单向服务器推送技术&lt;/h3&gt;
&lt;p&gt;SSE 允许服务器向客户端单向发送更新，是一种基于 HTTP 的技术。&lt;br&gt;&lt;img src=&quot;https://pic.whrss.com/2023/11/1700400501.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&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; 实现简单，支持自动重连。&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;p&gt;一个典型的应用场景：股票价格更新&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;package&lt;/span&gt; main

&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; (
    &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;fmt&amp;quot;&lt;/span&gt;
    &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;net/http&amp;quot;&lt;/span&gt;
    &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;time&amp;quot;&lt;/span&gt;
)

&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;main&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;()&lt;/span&gt;&lt;/span&gt; {
    http.HandleFunc(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;/sse&amp;quot;&lt;/span&gt;, &lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;(w http.ResponseWriter, r *http.Request)&lt;/span&gt;&lt;/span&gt; {
        w.Header().Set(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;Content-Type&amp;quot;&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;text/event-stream&amp;quot;&lt;/span&gt;)
        w.Header().Set(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;Cache-Control&amp;quot;&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;no-cache&amp;quot;&lt;/span&gt;)
        w.Header().Set(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;Connection&amp;quot;&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;keep-alive&amp;quot;&lt;/span&gt;)

        &lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; i := &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt;; ; i++ {
            fmt.Fprintf(w, &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;data: Price update %d\n\n&amp;quot;&lt;/span&gt;, i)
            w.(http.Flusher).Flush()
            time.Sleep(time.Second * &lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;) &lt;span class=&quot;hljs-comment&quot;&gt;// 模拟数据更新&lt;/span&gt;
        }
    })

    http.ListenAndServe(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;:8080&amp;quot;&lt;/span&gt;, &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt;)
}
&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;h3 id=&quot;四长轮询短轮询的高效替代&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#四长轮询短轮询的高效替代&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;四、长轮询：短轮询的高效替代&lt;/h3&gt;
&lt;p&gt;长轮询在服务器有数据更新时才响应客户端请求，是短轮询的改进版。&lt;br&gt;&lt;img src=&quot;https://pic.whrss.com/2023/11/1700400647.png&quot; alt=&quot;&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;实际应用案例：&lt;/strong&gt; 社交媒体通知更新，如 Facebook 或 Twitter 的新消息提示。&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;li&gt;&lt;strong&gt;使用场景：&lt;/strong&gt; 适用于对实时性要求不是非常高，但更新频率较高的场景。&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;我最近使用到的一个应用场景：AI 生图以后，通知给客户端&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;package&lt;/span&gt; main

&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; (
    &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;fmt&amp;quot;&lt;/span&gt;
    &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;net/http&amp;quot;&lt;/span&gt;
    &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;time&amp;quot;&lt;/span&gt;
)

&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;main&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;()&lt;/span&gt;&lt;/span&gt; {
    messages := &lt;span class=&quot;hljs-built_in&quot;&gt;make&lt;/span&gt;(&lt;span class=&quot;hljs-keyword&quot;&gt;chan&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;string&lt;/span&gt;) &lt;span class=&quot;hljs-comment&quot;&gt;// 消息通道&lt;/span&gt;

    &lt;span class=&quot;hljs-keyword&quot;&gt;go&lt;/span&gt; &lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;()&lt;/span&gt;&lt;/span&gt; {
        &lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; {
            time.Sleep(time.Second * &lt;span class=&quot;hljs-number&quot;&gt;5&lt;/span&gt;) &lt;span class=&quot;hljs-comment&quot;&gt;// 每5秒生成一条消息&lt;/span&gt;
            messages &amp;lt;- fmt.Sprintf(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;New message at %v&amp;quot;&lt;/span&gt;, time.Now())
        }
    }()

    http.HandleFunc(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;/long-poll&amp;quot;&lt;/span&gt;, &lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;(w http.ResponseWriter, r *http.Request)&lt;/span&gt;&lt;/span&gt; {
        message := &amp;lt;-messages &lt;span class=&quot;hljs-comment&quot;&gt;// 等待新消息&lt;/span&gt;
        fmt.Fprint(w, message)
    })

    http.ListenAndServe(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;:8080&amp;quot;&lt;/span&gt;, &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt;)
}
&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;h3 id=&quot;结论&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#结论&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;结论&lt;/h3&gt;
&lt;p&gt;在选择服务端通信技术时，应考虑应用的具体需求和场景。WebSocket 适合需要高实时性和双向通信的应用；SSE 适用于简单的单向数据推送；而短轮询和长轮询则适用于更新频率不高的场景。&lt;br&gt;选择合适的技术可以显著提高用户体验和应用性能。&lt;br&gt;我也曾遇到 WebSocket 一把梭的，在一些性能不敏感的地方，确实没有什么区别，但是，这不应该是一个技术人员的追求。&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>API 设计中的多类型属性选择：OpenAPI 与 gRPC 的 oneof 与强类型对比</title>
    <link href="https://blog.whrss.com/posts/api-design-openapi&amp;grpc"/>
    <id>https://blog.whrss.com/posts/api-design-openapi&amp;grpc</id>
    <published>2023-11-03T02:30:52.000Z</published>
    <updated>2023-11-03T02:30:52.000Z</updated>
    <category term="技术"/>
    <category term="openapi"/>
    <category term="grpc"/>
    <summary>在谈论 API 设计和开发时，有时，一个属性可以是多种类型中的一个，但不能同时是多种类型。比如支付接口的回调处理，常常为了兼容不同平台的参数，会使用以下方式中的一种来进行接收，在程序开发中，我们往往会采用主流的 HTTP 协议和 gRPC 协议进行通信，两种技术都为开发者提供了强大的工具来描述、验证和生成 API，但它们的方法和原则有所不同。</summary>
    <content type="html">&lt;p&gt;在谈论 API 设计和开发时，有时，一个属性可以是多种类型中的一个，但不能同时是多种类型。比如支付接口的回调处理，常常为了兼容不同平台的参数，会使用以下方式中的一种来进行接收：&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;范型&lt;/li&gt;
&lt;li&gt;key-value 形式的 map &lt;/li&gt;
&lt;li&gt;所有的 Object 都去接收，枚举哪个取哪个&lt;br&gt;但这种模式，往往会造成参数内容的不规范 、接口维护困难 或者是浪费网络传输带宽。&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;在程序开发中，我们往往会采用主流的 HTTP 协议和 gRPC 协议进行通信，两种技术都为开发者提供了强大的工具来描述、验证和生成 API，但它们的方法和原则有所不同。&lt;/p&gt;
&lt;h2 id=&quot;openapi-和-oneof&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#openapi-和-oneof&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;OpenAPI 和 &lt;code&gt;oneof&lt;/code&gt;&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;OpenAPI&lt;/strong&gt;，早前被称为 Swagger，是一个用于描述 RESTful API 的规范。在其 3.0.1 版本中，引入了&lt;code&gt;oneof&lt;/code&gt;关键字。&lt;/p&gt;
&lt;h3 id=&quot;原因&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#原因&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;原因：&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;RESTful API 设计经常遇到一个属性可以是多种类型中的一个的情况。&lt;code&gt;oneof&lt;/code&gt;提供了一种简单、明确的方式来描述这种复杂性。&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;好处&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#好处&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;好处：&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;它使得模式更具表现力和灵活性，允许属性值匹配其中一个定义的模式。&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;grpc-和-oneof&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#grpc-和-oneof&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;gRPC 和 &lt;code&gt;oneof&lt;/code&gt;&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;gRPC&lt;/strong&gt; 使用 &lt;strong&gt;Protocol Buffers (ProtoBuf)&lt;/strong&gt; 作为其接口定义语言。ProtoBuf 中也有一个&lt;code&gt;oneof&lt;/code&gt;关键字，但其用途与 OpenAPI 中的略有不同。&lt;/p&gt;
&lt;h3 id=&quot;原因-2&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#原因-2&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;原因：&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;在 RPC 通信中，特别是在跨语言的场景下，有时需要表示一个值可以是多种数据类型中的一个。&lt;code&gt;oneof&lt;/code&gt;为此提供了一个优雅的解决方案。&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;好处-2&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#好处-2&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;好处：&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;它保证了在任何给定时间，&lt;code&gt;oneof&lt;/code&gt;内的字段只能设置一个，这有助于节省存储空间和序列化/反序列化时间。&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;强类型支持&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#强类型支持&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;强类型支持&lt;/h2&gt;
&lt;p&gt;强类型是 OpenAPI 和 gRPC 都强烈支持的一个核心概念。&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;：知道数据的确切类型可以优化存储和访问。&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;我们可以达到的是&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;错误检测&lt;/strong&gt;：可以在编译时（或验证时，对于 OpenAPI）捕获类型错误，而不是在运行时。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;代码清晰&lt;/strong&gt;：类型声明或注释为其他开发者提供了有关数据的清晰、明确的信息。&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;尽管 OpenAPI 和 gRPC 在处理&lt;code&gt;oneof&lt;/code&gt;和强类型时有所不同，但它们的目标是相同的：提供明确、一致和可靠的 API 描述。选择哪种技术取决于具体的应用场景，但了解这些技术如何处理这些关键概念可以帮助开发者做出明智的决策。&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>团队开发中对于代码仓库和镜像管理的标准统一</title>
    <link href="https://blog.whrss.com/posts/unified-standards-code-management-in-team-development"/>
    <id>https://blog.whrss.com/posts/unified-standards-code-management-in-team-development</id>
    <published>2023-10-25T01:01:39.000Z</published>
    <updated>2023-10-25T01:01:39.000Z</updated>
    <category term="技术"/>
    <category term="work"/>
    <category term="team-development"/>
    <category term="standard"/>
    <summary>随着现代软件开发的持续迭代，团队间的协作变得越来越重要。为了确保整个团队在编码、构建和部署过程中的效率和质量，引入一些特定的配置文件和标准工作流程显得尤为关键。以下就是一些在团队开发中常见而又重要的文件，我总结了它们的一些作用和优点。</summary>
    <content type="html">&lt;p&gt;随着现代软件开发的持续迭代，团队间的协作变得越来越重要。为了确保整个团队在编码、构建和部署过程中的效率和质量，引入一些特定的配置文件和标准工作流程显得尤为关键。以下就是一些在团队开发中常见而又重要的文件，我总结了它们的一些作用和优点。&lt;/p&gt;
&lt;h4 id=&quot;1-editorconfig&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#1-editorconfig&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;1. .editorconfig&lt;/h4&gt;
&lt;p&gt;&lt;strong&gt;作用&lt;/strong&gt;：&lt;code&gt;.editorconfig&lt;/code&gt; 是一种定义代码格式约定的文件，它用于统一不同编辑器和 IDE 的代码格式设置。&lt;/p&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;避免因为不同的代码风格导致的无意义的代码差异。&lt;/li&gt;
&lt;li&gt;提高代码的可读性和维护性。&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id=&quot;2-dockerignore&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#2-dockerignore&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;2. .dockerignore&lt;/h4&gt;
&lt;p&gt;&lt;strong&gt;作用&lt;/strong&gt;：定义哪些文件或目录应该被 Docker 忽略，不被包括在镜像构建中。&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;好处&lt;/strong&gt;：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;减少 Docker 镜像的大小。&lt;/li&gt;
&lt;li&gt;加快构建速度。&lt;/li&gt;
&lt;li&gt;避免将敏感或不必要的文件包含在 Docker 镜像中。&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id=&quot;3-gitignore&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#3-gitignore&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;3. .gitignore&lt;/h4&gt;
&lt;p&gt;&lt;strong&gt;作用&lt;/strong&gt;：指定哪些文件或目录应该被 Git 忽略，不被包括在版本控制中。&lt;/p&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;避免将编译产物、日志、临时文件等不必要的文件添加到 Git 中。&lt;/li&gt;
&lt;li&gt;防止敏感数据泄露。&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id=&quot;4-http-文件&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#4-http-文件&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;4. .http 文件&lt;/h4&gt;
&lt;p&gt;&lt;strong&gt;作用&lt;/strong&gt;：这是一个用于 API 测试的文件，可以在一些 IDE 如 Visual Studio Code、IDEA 中直接运行。&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;好处&lt;/strong&gt;：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;简化 API 测试流程。&lt;/li&gt;
&lt;li&gt;提供一个可共享和可版本化的 API 测试集合。&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id=&quot;5-dockerfile&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#5-dockerfile&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;5. Dockerfile&lt;/h4&gt;
&lt;p&gt;&lt;strong&gt;作用&lt;/strong&gt;：描述如何自动构建 Docker 镜像的指南。&lt;/p&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;简化和标准化部署流程。&lt;/li&gt;
&lt;li&gt;提供一个清晰的、版本化的构建描述。&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id=&quot;6-makefile&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#6-makefile&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;6. Makefile&lt;/h4&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;ul&gt;
&lt;li&gt;提高工作效率，简化复杂任务。&lt;/li&gt;
&lt;li&gt;为新成员提供了一个明确的指南。&lt;/li&gt;
&lt;li&gt;保证任务的一致性和可重复性。&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id=&quot;7-jenkinsfile&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#7-jenkinsfile&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;7. Jenkinsfile&lt;/h4&gt;
&lt;p&gt;&lt;strong&gt;作用&lt;/strong&gt;：描述如何在 Jenkins 上自动化构建、测试和部署流程。&lt;/p&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;提高代码质量，通过自动化测试减少错误。&lt;/li&gt;
&lt;li&gt;加速软件交付速度。&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;以上所列出的各种文件在整个 CI/CD 中都很重要。它们不仅可以帮助团队保持代码的一致性、高质量和安全性，还可以大大提高开发和部署的效率。如果你的团队中有哪个工具没有使用到，很开心可以分享给你，如果你觉得有什么同样重要的文件我没有提到，欢迎留言。&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>我的自行车</title>
    <link href="https://blog.whrss.com/posts/fnhon"/>
    <id>https://blog.whrss.com/posts/fnhon</id>
    <published>2023-10-20T02:40:33.000Z</published>
    <updated>2023-10-20T02:40:33.000Z</updated>
    <category term="生活和思考"/>
    <category term="fnhon"/>
    <category term="通勤"/>
    <category term="bicycle"/>
    <summary>在今年7月份左右，我开始关注自行车，出于便携性而言，我更倾向于购买一辆折叠车，之前在大街上也看到了很多骑得超快的折叠车，所以我对于折叠车的竞速性能也是满意的，于是我开始看各种折叠车的测评和论坛~</summary>
    <content type="html">&lt;p&gt;在今年7月份左右，我开始关注自行车，出于便携性而言，我更倾向于购买一辆折叠车，之前在大街上也看到了很多骑得超快的折叠车，所以我对于折叠车的竞速性能也是满意的，于是我开始看各种折叠车的测评和论坛。&lt;/p&gt;
&lt;p&gt;折叠车和山地、公里车相比，会更加复杂，零件会更多一些。同样的，有整车 有组装。但在折叠车的市场里，不想公路和山地，大多数购买整车，在折叠车这里，组装是主市场。&lt;/p&gt;
&lt;p&gt;组装，主要的零件就是车架，折叠车里最火的就是风行的车架。除了风行，另外就是大行、飞鱼 和 小布，大行是卖的最多的折叠车整车品牌，小布是一个很“高端豪华”设计很时尚的很贵的折叠车品牌。&lt;/p&gt;
&lt;p&gt;风行蚂蚁腿：&lt;br&gt;&lt;img src=&quot;https://pic.whrss.com/2023/10/1696909500.png&quot; alt=&quot;image.png&quot; loading=&quot;eager&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;大行P8:&lt;br&gt;&lt;img src=&quot;https://pic.whrss.com/2023/10/1696909590.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;小布折叠车：&lt;br&gt;&lt;img src=&quot;https://pic.whrss.com/2023/10/1696909723.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;因为风行折叠车的可选配、自定义方案足够多，所以我选择了从风行中寻找方案。风行的折叠车主要有四种车架，蚂蚁腿、Y架、K架、海豚架。&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;而我的出行并没有特别的需求，通勤短程使用，没有特别的需求，好看即可，而蚂蚁腿就是颜值这块儿的顶梁柱。&lt;/p&gt;
&lt;p&gt;然后我看了很多的方案，看到最后，给我审美整疲劳了，最后把之前觉得好看的发给了女朋友，让她来给我选，最后，她一眼就看中了非碳的最贵的一个。。。&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://pic.whrss.com/2023/10/1696910316.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://pic.whrss.com/2023/10/1696910322.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://pic.whrss.com/2023/10/1696910337.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://pic.whrss.com/2023/10/1696910361.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;这个车架的颜色非常漂亮，有风行的标，但不是风行的颜色。问过老板才知道，是他们家自己喷的，我再翻，就没有过第二家这么做的了。&lt;/p&gt;
&lt;p&gt;整车配置如下：&lt;br&gt;&lt;img src=&quot;https://pic.whrss.com/2023/10/1696910295.jpg&quot; alt=&quot;56101696910294_.pic.jpg&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;br&gt;车架大概是 1200 + 700 涂装&lt;br&gt;两个轱辘 加一起 1k多&lt;br&gt;碳前叉 1k&lt;br&gt;加上其他的零零散散碎碎 ¥5300&lt;/p&gt;
&lt;p&gt;看到这个价格，我当时确实是跪了。&lt;/p&gt;
&lt;p&gt;买车最开始嚷嚷着预算800， 后来看着看着 1600， 再看风行折叠车9速最低配也要2500，好家伙一层一层，最后终于超越了5k。。。&lt;br&gt;可能是价格的烘托，这车是越看越好看。&lt;br&gt;女朋友觉得我喜欢的东西，买就完了。想到自己今年要换工作，工资也涨了一点点，买！&lt;br&gt;随后我也是痛痛快快下单了。&lt;/p&gt;
&lt;p&gt;经过半个多月的漫长等待，商家终于想起我了，然后用了一天给我喷了漆，连夜顺丰，给我发过来了。&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;经过比较漫长的挑选和等待，我终于收到了心爱的车～&lt;/p&gt;
&lt;p&gt;开箱，店家送了一副鲜红色的脚踏板，我透，然后我和店家说颜色不合适呀，店家又给我发了一个。&lt;br&gt;&lt;img src=&quot;https://pic.whrss.com/2023/10/1696911029.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;就是上面两幅，黑的发来的是个坏的，左脚螺丝口对的有问题，装上骑也有异响。我忍不了等待了，自己花一百多买了一副。 然后就是把套，也是在上图，是一个海绵把套，骑了几公里后我发现手腕疼，赶紧换！ 海绵把套还贼难拆，直接刀子剌掉。&lt;br&gt;考虑过上弯把和牛角把，像这样的：&lt;br&gt;&lt;img src=&quot;https://pic.whrss.com/2023/10/1696911234.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;br&gt;但是发现，会影响折叠（特别是我的车头管是内折的）。所以最后选了一个大行的把套，感觉还是不错的。&lt;br&gt;&lt;img src=&quot;https://pic.whrss.com/2023/10/1696911351.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;关于折叠车，业界是标配不上脚撑子和挡泥板的，我装一下，我也不上！&lt;/p&gt;
&lt;p&gt;为了安全，买了车前灯和尾灯还有铃铛，买了自行车挎包 买了骑行护目镜，头盔目前还没有买。&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;至此，我的自行车相关配件也购买完毕。&lt;/p&gt;
&lt;p&gt;开始遇到一些问题：&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;骑行异响&lt;br&gt; 骑的时候，不是牙盘响，认真听 是车前面的部分。后来联系了商家，确认不会是别的问题，我就往前把的各种关节加了WD-40，解决！&lt;/li&gt;
&lt;li&gt;换挡不流畅&lt;br&gt; 5挡以下，换挡来回跳，后来问了下店家，说后面有一个档位的微调螺丝，调整下就好了，我就在车库调调骑骑，弄得差不多算流畅吧。&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;另外还有一个温馨提示，我这个车是碟刹嘛，刹车动作如果比较多，骑完车一定不要手贱去摸那个刹车片。&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;可以开始畅快地骑行了，然后，我发现，公司不让把自行车折叠带上楼！！！ 放楼下又怕刮蹭，毕竟这车架就小两千啦，还是心疼的。&lt;/p&gt;
&lt;p&gt;再往后两天，我又换了工作，离家17公里多，啊～ 骑不动了，不骑了&lt;br&gt;吃灰开始。&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>使用 rclone 命令行管理 Cloudflare R2 对象存储</title>
    <link href="https://blog.whrss.com/posts/r2-rclone"/>
    <id>https://blog.whrss.com/posts/r2-rclone</id>
    <published>2023-10-12T23:00:26.000Z</published>
    <updated>2023-10-12T23:00:26.000Z</updated>
    <category term="折腾"/>
    <category term="cloudflare"/>
    <category term="R2"/>
    <category term="S3"/>
    <category term="blog"/>
    <summary>Cloudflare R2 是一款高性能、低成本的对象存储服务。之前在使用 OSS 的时候，用惯了 OSS brewer， 在用 R2 时候发现，开始没有找到合适的 brewer 工具，而网页端上传会限制文件数量和大小，就尝试用命令行的 client 了哈哈， 使用之后发现，确实好用，相比使用网页管理对象存储，利用命令行工具可以大大提高管理效率，特别适合需要批量操作或脚本化的场景。</summary>
    <content type="html">&lt;p&gt;Cloudflare R2 是一款高性能、低成本的对象存储服务。之前在使用 OSS 的时候，用惯了 OSS brewer， 在用 R2 时候发现，开始没有找到合适的 brewer 工具，而网页端上传会限制文件数量和大小，就尝试用命令行的 client 了哈哈， 使用之后发现，确实好用，相比使用网页管理对象存储，利用命令行工具可以大大提高管理效率，特别适合需要批量操作或脚本化的场景。&lt;/p&gt;
&lt;p&gt;评论老哥分享了一个 client 工具: &lt;a href=&quot;https://cyberduck.io/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;https://cyberduck.io/&lt;/a&gt; 我尝试用下试试～&lt;/p&gt;
&lt;h2 id=&quot;安装-rclone&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#安装-rclone&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;安装 rclone&lt;/h2&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;sh&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-bash&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;sudo&lt;/span&gt; -v ; curl https://rclone.org/install.sh | &lt;span class=&quot;hljs-built_in&quot;&gt;sudo&lt;/span&gt; bash&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;查看 config 文件识别的地址&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;sh&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-bash&quot;&gt;rclone config file
&lt;span class=&quot;hljs-comment&quot;&gt;# Configuration file doesn&amp;#x27;t exist, but rclone will use this path:&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;# /Users/xxx/.config/rclone/rclone.conf&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;sh&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-bash&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;# 编辑文件配置&lt;/span&gt;
vi /Users/xxx/.config/rclone/rclone.conf&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;sh&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-bash&quot;&gt;[testConfig]
&lt;span class=&quot;hljs-built_in&quot;&gt;type&lt;/span&gt; = s3
provider = Cloudflare
access_key_id = abc123
secret_access_key = xyz456
endpoint = https://&amp;lt;accountid&amp;gt;.r2.cloudflarestorage.com
acl = private&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;这里我创建了一个名为 bucket 的桶&lt;br&gt;所需的 access_key_id 和 secret_access_key 需要另外申请：&lt;br&gt;&lt;img src=&quot;https://pic.whrss.com/2023/10/1697177622.png&quot; alt=&quot;image.png&quot; loading=&quot;eager&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;设置完成后，就可以对 cloudflare 的桶资源进行管理了。&lt;/p&gt;
&lt;h2 id=&quot;列出存储桶和对象&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#列出存储桶和对象&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;列出存储桶和对象&lt;/h2&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;sh&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-bash&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;# 列出所有存储桶:&lt;/span&gt;
rclone lsd testConfig:

&lt;span class=&quot;hljs-comment&quot;&gt;# 列出所有桶及内部目录文件&lt;/span&gt;
~ rclone tree testConfig:
  ...

&lt;span class=&quot;hljs-comment&quot;&gt;# 列出指定桶及内部目录文件&lt;/span&gt;
~ rclone tree testConfig:bucket
/
└── 2023
    ├── 08
    │   ├── 1690960360295.png
    │   └── 1692713312723.png
    ├── 09
    │   ├── 1693822893.jpg
    │   └── 1694588667.png
    └── 10
        └── 1696911351.png
        
&lt;span class=&quot;hljs-comment&quot;&gt;# 创建新桶: &lt;/span&gt;
rclone &lt;span class=&quot;hljs-built_in&quot;&gt;mkdir&lt;/span&gt; testConfig:bucket

&lt;span class=&quot;hljs-comment&quot;&gt;# 删除空桶:&lt;/span&gt;
rclone &lt;span class=&quot;hljs-built_in&quot;&gt;rmdir&lt;/span&gt; testConfig:bucket  

&lt;span class=&quot;hljs-comment&quot;&gt;# 列出对象列表:&lt;/span&gt;
rclone &lt;span class=&quot;hljs-built_in&quot;&gt;ls&lt;/span&gt; testConfig:path
&lt;span class=&quot;hljs-comment&quot;&gt;# 计算对象存储总量:&lt;/span&gt;
rclone size testConfig:path&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;h2 id=&quot;上传和检索对象&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#上传和检索对象&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;上传和检索对象&lt;/h2&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;sh&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-bash&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;# 上传本地文件或目录: &lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;# rclone copy [目录或者文件] test:桶名+路径&lt;/span&gt;
rclone copy helloworld testConfig:bucket

&lt;span class=&quot;hljs-comment&quot;&gt;# 查看&lt;/span&gt;
rclone tree testConfig:bucket

&lt;span class=&quot;hljs-comment&quot;&gt;# 下载对象到本地:&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;# rclone copy test:桶名+路径 本地目标路径&lt;/span&gt;
rclone copy testConfig:bucket/README.md .

&lt;span class=&quot;hljs-comment&quot;&gt;# 删除&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;# rclone delete test:桶名+路径&lt;/span&gt;
rclone delete testConfig:bucket/README.md

&lt;span class=&quot;hljs-comment&quot;&gt;# 更多&lt;/span&gt;
rclone --&lt;span class=&quot;hljs-built_in&quot;&gt;help&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
</content>
  </entry>
  <entry>
    <title>GORM 中 SQL、慢 SQL 打印日志传递 trace ID</title>
    <link href="https://blog.whrss.com/posts/gorm-trace-id"/>
    <id>https://blog.whrss.com/posts/gorm-trace-id</id>
    <published>2023-09-25T03:14:27.000Z</published>
    <updated>2023-09-25T03:14:27.000Z</updated>
    <category term="技术"/>
    <category term="go"/>
    <category term="gorm"/>
    <category term="trace"/>
    <category term="kratos"/>
    <summary>GORM 中SQL、慢SQL打印日志传递 trace ID， 重写GORM日志实现，SQL日志、慢日志请求追踪</summary>
    <content type="html">&lt;p&gt;实现 &lt;code&gt;gorm.io/gorm/logger&lt;/code&gt; 下的函数⬇️&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;// gorm 源码&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;type&lt;/span&gt; Interface &lt;span class=&quot;hljs-keyword&quot;&gt;interface&lt;/span&gt; {  
   LogMode(LogLevel) Interface  
   Info(context.Context, &lt;span class=&quot;hljs-type&quot;&gt;string&lt;/span&gt;, ...&lt;span class=&quot;hljs-keyword&quot;&gt;interface&lt;/span&gt;{})  
   Warn(context.Context, &lt;span class=&quot;hljs-type&quot;&gt;string&lt;/span&gt;, ...&lt;span class=&quot;hljs-keyword&quot;&gt;interface&lt;/span&gt;{})  
   Error(context.Context, &lt;span class=&quot;hljs-type&quot;&gt;string&lt;/span&gt;, ...&lt;span class=&quot;hljs-keyword&quot;&gt;interface&lt;/span&gt;{})  
   Trace(ctx context.Context, begin time.Time, fc &lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;()&lt;/span&gt;&lt;/span&gt; (sql &lt;span class=&quot;hljs-type&quot;&gt;string&lt;/span&gt;, rowsAffected &lt;span class=&quot;hljs-type&quot;&gt;int64&lt;/span&gt;), err &lt;span class=&quot;hljs-type&quot;&gt;error&lt;/span&gt;)  
}&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;以下为自定义的重写实现，主要函数是&lt;code&gt;Trace&lt;/code&gt;&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;package&lt;/span&gt; log  
  
&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; (  
   &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;context&amp;quot;&lt;/span&gt;  
   &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;time&amp;quot;&lt;/span&gt;  
   &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;github.com/go-kratos/kratos/v2/log&amp;quot;&lt;/span&gt;
   &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;gorm.io/gorm/logger&amp;quot;&lt;/span&gt;
)  
  
&lt;span class=&quot;hljs-keyword&quot;&gt;type&lt;/span&gt; GormLogger &lt;span class=&quot;hljs-keyword&quot;&gt;struct&lt;/span&gt; {  
   SlowThreshold time.Duration  
}  
  
&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;NewGormLogger&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;()&lt;/span&gt;&lt;/span&gt; *GormLogger {  
   &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; &amp;amp;GormLogger{  
      SlowThreshold: &lt;span class=&quot;hljs-number&quot;&gt;200&lt;/span&gt; * time.Millisecond, &lt;span class=&quot;hljs-comment&quot;&gt;// 一般超过200毫秒就算慢查所以不使用配置进行更改  &lt;/span&gt;
   }  
}  
  
&lt;span class=&quot;hljs-keyword&quot;&gt;var&lt;/span&gt; _ logger.Interface = (*GormLogger)(&lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt;)  
  
&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-params&quot;&gt;(l *GormLogger)&lt;/span&gt;&lt;/span&gt; LogMode(lev logger.LogLevel) logger.Interface {  
   &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; &amp;amp;GormLogger{}  
}  
&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-params&quot;&gt;(l *GormLogger)&lt;/span&gt;&lt;/span&gt; Info(ctx context.Context, msg &lt;span class=&quot;hljs-type&quot;&gt;string&lt;/span&gt;, data ...&lt;span class=&quot;hljs-keyword&quot;&gt;interface&lt;/span&gt;{}) {  
   log.Context(ctx).Infof(msg, data)  
}  
&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-params&quot;&gt;(l *GormLogger)&lt;/span&gt;&lt;/span&gt; Warn(ctx context.Context, msg &lt;span class=&quot;hljs-type&quot;&gt;string&lt;/span&gt;, data ...&lt;span class=&quot;hljs-keyword&quot;&gt;interface&lt;/span&gt;{}) {  
   log.Context(ctx).Errorf(msg, data)  
}  
&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-params&quot;&gt;(l *GormLogger)&lt;/span&gt;&lt;/span&gt; Error(ctx context.Context, msg &lt;span class=&quot;hljs-type&quot;&gt;string&lt;/span&gt;, data ...&lt;span class=&quot;hljs-keyword&quot;&gt;interface&lt;/span&gt;{}) {  
   log.Context(ctx).Errorf(msg, data)  
}  
&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-params&quot;&gt;(l *GormLogger)&lt;/span&gt;&lt;/span&gt; Trace(ctx context.Context, begin time.Time, fc &lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;()&lt;/span&gt;&lt;/span&gt; (sql &lt;span class=&quot;hljs-type&quot;&gt;string&lt;/span&gt;, rowsAffected &lt;span class=&quot;hljs-type&quot;&gt;int64&lt;/span&gt;), err &lt;span class=&quot;hljs-type&quot;&gt;error&lt;/span&gt;) {  
   &lt;span class=&quot;hljs-comment&quot;&gt;// 获取运行时间  &lt;/span&gt;
   elapsed := time.Since(begin)  
   &lt;span class=&quot;hljs-comment&quot;&gt;// 获取 SQL 语句和返回条数  &lt;/span&gt;
   sql, rows := fc()  
   &lt;span class=&quot;hljs-comment&quot;&gt;// Gorm 错误时打印&lt;/span&gt;
   &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; err != &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt; {  
      log.Context(ctx).Errorf(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;SQL ERROR, | sql=%v, rows=%v, elapsed=%v&amp;quot;&lt;/span&gt;, sql, rows, elapsed)  
   }  
   &lt;span class=&quot;hljs-comment&quot;&gt;// 慢查询日志  &lt;/span&gt;
   &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; l.SlowThreshold != &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt; &amp;amp;&amp;amp; elapsed &amp;gt; l.SlowThreshold {  
      log.Context(ctx).Warn(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;Database Slow Log, | sql=%v, rows=%v, elapsed=%v&amp;quot;&lt;/span&gt;, sql, rows, elapsed)  
   }  
  
}&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;blockquote&gt;
&lt;p&gt;这里我使用的log组件是kratos框架的log组件，设置好zap后注入为全局log&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;在&lt;code&gt;GORM&lt;/code&gt;创建连接的地方注入我们重写后的自定义Logger&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;db, err := gorm.Open(mysql.Open(cfg.Dsn()), &amp;amp;gorm.Config{  
   QueryFields: &lt;span class=&quot;hljs-literal&quot;&gt;true&lt;/span&gt;,    
   Logger: logdef.NewGormLogger(),  &lt;span class=&quot;hljs-comment&quot;&gt;// 注入&lt;/span&gt;
})&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;最后，在查询的地方，带上&lt;code&gt;withContext&lt;/code&gt;即可&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-params&quot;&gt;(ud *userDao)&lt;/span&gt;&lt;/span&gt; AddOne(c context.Context, user *model.User) (userId &lt;span class=&quot;hljs-type&quot;&gt;int64&lt;/span&gt;, err &lt;span class=&quot;hljs-type&quot;&gt;error&lt;/span&gt;) {  
   err = db.GetConn().WithContext(c).Create(user).Error  
   &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; err != &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt; {  
      log.Context(c).Errorf(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;AddOne fail|err=%+v&amp;quot;&lt;/span&gt;, err)  
      &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt;  
   }  
   &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; user.Id, &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt;  
}&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
</content>
  </entry>
  <entry>
    <title>更换博客图床，从 OSS 到 GitHub 再到 R2</title>
    <link href="https://blog.whrss.com/posts/pic-archive"/>
    <id>https://blog.whrss.com/posts/pic-archive</id>
    <published>2023-08-02T01:09:40.000Z</published>
    <updated>2023-08-02T01:09:40.000Z</updated>
    <category term="折腾"/>
    <category term="blog"/>
    <category term="图床"/>
    <summary>写博客一个很重要的东西就是图床， 如果没有一个合适的图床来安全稳定地存储数据，指不定哪天，你的文章就到处都是 ![真的找不到了.png](https://pic.whrss.com/1690960055739.png) 而对于一个曾经被ban过号，崩过盘(硬盘)的人来说，分外敏感。如果你的图片存储在任何一个带监管的平台，你的账号很可能由于一些不可抗力资源牵连，内容全部404。 于是我对自己的博客相关的资源都进行了“安全”的部署，图片资源这块儿一年多来，我一直使用的是github做图床的，但是github有几个问题...</summary>
    <content type="html">&lt;p&gt;写博客一个很重要的东西就是图床， 如果没有一个合适的图床来安全稳定地存储数据，指不定哪天，你的文章就到处都是&lt;br&gt;&lt;img src=&quot;https://pic.whrss.com/1690960055739.png&quot; alt=&quot;真的找不到了.png&quot; loading=&quot;eager&quot; decoding=&quot;async&quot;&gt;&lt;br&gt;而对于一个曾经被ban过号，崩过盘(硬盘)的人来说，分外敏感。如果你的图片存储在任何一个带监管的平台，你的账号很可能由于一些不可抗力资源牵连，内容全部404。&lt;br&gt;于是我对自己的博客相关的资源都进行了“安全”的部署，图片资源这块儿一年多来，我一直使用的是github做图床的，但是github有几个问题：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;一个仓库的存储大小限制1G，如果超过限制，很可能会被ban库的。&lt;/li&gt;
&lt;li&gt;GitHub 阻止大小超过 100 MB 的文件。&lt;/li&gt;
&lt;li&gt;GitHub 在国内网络下无法访问。&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;于是，几个月前把云资源全部迁到cloudflare的我，又有了白嫖的念头。&lt;/p&gt;
&lt;p&gt;能不能使用R2来做图床呢？之前用过阿里OSS做图床的我，本能地想到，一定是可以的！&lt;/p&gt;
&lt;p&gt;简单搜搜，R2图床～&lt;/p&gt;
&lt;p&gt;不出所料～哈哈哈哈简简单单&lt;br&gt;当然前提是你需要有一个cloud flare 账号哦&lt;/p&gt;
&lt;h4 id=&quot;一-cloud-flare操作&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#一-cloud-flare操作&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;一. cloud flare操作&lt;/h4&gt;
&lt;h5 id=&quot;1-到cloud-flare创建一个bucket&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#1-到cloud-flare创建一个bucket&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;1. 到cloud flare创建一个bucket&lt;/h5&gt;
&lt;p&gt;&lt;img src=&quot;https://pic.whrss.com/2023/08/1690960818028.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;h5 id=&quot;2-对bucket进行配置&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#2-对bucket进行配置&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;2. 对bucket进行配置&lt;/h5&gt;
&lt;p&gt;&lt;img src=&quot;https://pic.whrss.com/2023/08/1690961129504.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;h5 id=&quot;3-然后到r2的列表菜单申请一个secret&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#3-然后到r2的列表菜单申请一个secret&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;3. 然后到r2的列表菜单，申请一个secret&lt;/h5&gt;
&lt;p&gt;&lt;img src=&quot;https://pic.whrss.com/2023/08/1690961204965.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;br&gt;&lt;img src=&quot;https://pic.whrss.com/2023/08/1690961242519.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;h4 id=&quot;二-本地操作&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#二-本地操作&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;二. 本地操作&lt;/h4&gt;
&lt;p&gt;使用pic-go进行上传，如果没有，请安装一个&lt;/p&gt;
&lt;h5 id=&quot;1-在设置中的默认图床不包含cloud-flare-需要安装一下插件这里的插件需要安装的是aws的s3插件该插件兼容国外同s3类型的这些所有的对象存储&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#1-在设置中的默认图床不包含cloud-flare-需要安装一下插件这里的插件需要安装的是aws的s3插件该插件兼容国外同s3类型的这些所有的对象存储&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;1. 在设置中的默认图床不包含cloud flare ，需要安装一下插件，这里的插件需要安装的是aws的S3插件，该插件兼容国外同S3类型的这些所有的对象存储。&lt;/h5&gt;
&lt;p&gt;需要安装这两个插件，一个是功能，一个是展示。&lt;br&gt;&lt;img src=&quot;https://pic.whrss.com/2023/08/1690961428690.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;然后在设置处就会出来新的选项&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://pic.whrss.com/2023/08/1690961479806.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;h5 id=&quot;2-填写下刚才获取到的那些参数&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#2-填写下刚才获取到的那些参数&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;2. 填写下刚才获取到的那些参数&lt;/h5&gt;
&lt;p&gt;&lt;img src=&quot;https://pic.whrss.com/2023/08/1690961579898.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;最后效果如下：&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs&quot;&gt;![image.png](https://pic.whrss.com/2023/08/1690961579898.png)&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;完美～&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>如何在 Go 中实现程序的优雅退出，go-kratos 源码解析</title>
    <link href="https://blog.whrss.com/posts/go-grace-stop"/>
    <id>https://blog.whrss.com/posts/go-grace-stop</id>
    <published>2023-07-28T21:58:45.000Z</published>
    <updated>2023-07-28T21:58:45.000Z</updated>
    <category term="技术"/>
    <category term="go"/>
    <category term="kratos"/>
    <category term="grace-stop"/>
    <summary>使用kratos这个框架有近一年了，最近了解了一下kratos关于程序优雅退出的具体实现。</summary>
    <content type="html">&lt;p&gt;使用kratos这个框架有近一年了，最近了解了一下kratos关于程序优雅退出的具体实现。&lt;/p&gt;
&lt;p&gt;这部分逻辑在app.go文件中，在main中，找到app.Run方法，点进入就可以了&lt;/p&gt;
&lt;p&gt;它包含以下几个部分:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;p&gt;App结构体:包含应用程序的配置选项和运行时状态。&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;New函数:创建一个App实例。&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Run方法:启动应用程序。主要步骤包括:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;构建ServiceInstance注册实例&lt;/li&gt;
&lt;li&gt;启动Server&lt;/li&gt;
&lt;li&gt;注册实例到服务发现&lt;/li&gt;
&lt;li&gt;监听停止信号&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Stop方法:优雅停止应用程序。主要步骤包括:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;从服务发现中注销实例&lt;/li&gt;
&lt;li&gt;取消应用程序上下文&lt;/li&gt;
&lt;li&gt;停止Server&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;buildInstance方法:构建用于服务发现注册的实例。&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;NewContext和FromContext函数:给Context添加AppInfo,便于后续从Context获取。&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;核心的逻辑流程是:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;创建App实例&lt;/li&gt;
&lt;li&gt;在App.Run()里面启动Server,注册实例,监听信号&lt;/li&gt;
&lt;li&gt;接收到停止信号后会调用App.Stop()停止应用&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;我们先对Run方法进行一个源码进行查看&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;// Run executes all OnStart hooks registered with the application&amp;#x27;s Lifecycle.&lt;/span&gt;
&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-params&quot;&gt;(a *App)&lt;/span&gt;&lt;/span&gt; Run() &lt;span class=&quot;hljs-type&quot;&gt;error&lt;/span&gt; {

  &lt;span class=&quot;hljs-comment&quot;&gt;// 构建服务发现注册实例&lt;/span&gt;
  instance, err := a.buildInstance() 
  &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; err != &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt; {
    &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; err
  }

  &lt;span class=&quot;hljs-comment&quot;&gt;// 保存实例  &lt;/span&gt;
  a.mu.Lock()
  a.instance = instance
  a.mu.Unlock()

  &lt;span class=&quot;hljs-comment&quot;&gt;// 创建错误组&lt;/span&gt;
  eg, ctx := errgroup.WithContext(NewContext(a.ctx, a))

  &lt;span class=&quot;hljs-comment&quot;&gt;// 等待组,用于等待Server启动完成&lt;/span&gt;
  wg := sync.WaitGroup{}

  &lt;span class=&quot;hljs-comment&quot;&gt;// 启动每个Server&lt;/span&gt;
  &lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; _, srv := &lt;span class=&quot;hljs-keyword&quot;&gt;range&lt;/span&gt; a.opts.servers {
    srv := srv 
    eg.Go(&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;()&lt;/span&gt;&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;error&lt;/span&gt; {
      &lt;span class=&quot;hljs-comment&quot;&gt;// 等待停止信号&lt;/span&gt;
      &amp;lt;-ctx.Done()  
      &lt;span class=&quot;hljs-comment&quot;&gt;// 停止Server&lt;/span&gt;
      stopCtx, cancel := context.WithTimeout(a.opts.ctx, a.opts.stopTimeout)
      &lt;span class=&quot;hljs-keyword&quot;&gt;defer&lt;/span&gt; cancel()
      &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; srv.Stop(stopCtx)
    })

    wg.Add(&lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;)
    eg.Go(&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;()&lt;/span&gt;&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;error&lt;/span&gt; {
      &lt;span class=&quot;hljs-comment&quot;&gt;// Server启动完成&lt;/span&gt;
      wg.Done() 
      &lt;span class=&quot;hljs-comment&quot;&gt;// 启动Server  &lt;/span&gt;
      &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; srv.Start(NewContext(a.opts.ctx, a)) 
    })
  }

  &lt;span class=&quot;hljs-comment&quot;&gt;// 等待所有Server启动完成&lt;/span&gt;
  wg.Wait()

  &lt;span class=&quot;hljs-comment&quot;&gt;// 注册服务实例&lt;/span&gt;
  &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; a.opts.registrar != &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt; {
    rctx, rcancel := context.WithTimeout(ctx, a.opts.registrarTimeout)
    &lt;span class=&quot;hljs-keyword&quot;&gt;defer&lt;/span&gt; rcancel()
    &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; err := a.opts.registrar.Register(rctx, instance); err != &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt; {
      &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; err
    }
  }
  
  &lt;span class=&quot;hljs-comment&quot;&gt;// 监听停止信号&lt;/span&gt;
  c := &lt;span class=&quot;hljs-built_in&quot;&gt;make&lt;/span&gt;(&lt;span class=&quot;hljs-keyword&quot;&gt;chan&lt;/span&gt; os.Signal, &lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;)
  signal.Notify(c, a.opts.sigs...)
  eg.Go(&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;()&lt;/span&gt;&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;error&lt;/span&gt; {
    &lt;span class=&quot;hljs-keyword&quot;&gt;select&lt;/span&gt; {
    &lt;span class=&quot;hljs-keyword&quot;&gt;case&lt;/span&gt; &amp;lt;-ctx.Done():
      &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt;
    &lt;span class=&quot;hljs-keyword&quot;&gt;case&lt;/span&gt; &amp;lt;-c:
      &lt;span class=&quot;hljs-comment&quot;&gt;// 收到停止信号,停止应用------------- ⬅️注意此时&lt;/span&gt;
      &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; a.Stop() 
    }
  })

  &lt;span class=&quot;hljs-comment&quot;&gt;// 等待错误组执行完成&lt;/span&gt;
  &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; err := eg.Wait(); err != &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt; &amp;amp;&amp;amp; !errors.Is(err, context.Canceled) {
    &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; err
  }

  &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt;
}&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;核心逻辑就是这里⬇️，使用signal.Notify去监听操作系统给出的停止信号。&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;  &lt;span class=&quot;hljs-comment&quot;&gt;// 监听停止信号&lt;/span&gt;
  c := &lt;span class=&quot;hljs-built_in&quot;&gt;make&lt;/span&gt;(&lt;span class=&quot;hljs-keyword&quot;&gt;chan&lt;/span&gt; os.Signal, &lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;)
  signal.Notify(c, a.opts.sigs...)
  eg.Go(&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;()&lt;/span&gt;&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;error&lt;/span&gt; {
    &lt;span class=&quot;hljs-keyword&quot;&gt;select&lt;/span&gt; {
    &lt;span class=&quot;hljs-keyword&quot;&gt;case&lt;/span&gt; &amp;lt;-ctx.Done():
      &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt;
    &lt;span class=&quot;hljs-keyword&quot;&gt;case&lt;/span&gt; &amp;lt;-c:
      &lt;span class=&quot;hljs-comment&quot;&gt;// 收到停止信号,停止应用&lt;/span&gt;
      &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; a.Stop() 
    }
  })&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;然后调用了Stop方法，我们再看下Stop的源码&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;// Stop gracefully stops the application.&lt;/span&gt;
&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-params&quot;&gt;(a *App)&lt;/span&gt;&lt;/span&gt; Stop() &lt;span class=&quot;hljs-type&quot;&gt;error&lt;/span&gt; {

  &lt;span class=&quot;hljs-comment&quot;&gt;// 获取服务实例 &lt;/span&gt;
  a.mu.Lock()
  instance := a.instance
  a.mu.Unlock()

  &lt;span class=&quot;hljs-comment&quot;&gt;// 从服务发现注销实例&lt;/span&gt;
  &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; a.opts.registrar != &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt; &amp;amp;&amp;amp; instance != &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt; {
    ctx, cancel := context.WithTimeout(NewContext(a.ctx, a), a.opts.registrarTimeout)
    &lt;span class=&quot;hljs-keyword&quot;&gt;defer&lt;/span&gt; cancel()
    &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; err := a.opts.registrar.Deregister(ctx, instance); err != &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt; {
      &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; err
    }
  }

  &lt;span class=&quot;hljs-comment&quot;&gt;// 取消应用上下文&lt;/span&gt;
  &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; a.cancel != &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt; {
    a.cancel() 
  }

  &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt;
}&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;主要步骤是:&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs&quot;&gt;1. 获取已经保存的服务实例
2. 如果配置了服务发现,则从服务发现中注销该实例
3. 取消应用上下文来通知应用停止

在Run方法中,我们通过context.WithCancel创建的可取消的上下文Context，在这里通过调用cancel函数来取消该上下文，以通知应用停止。

取消上下文会导致在Run方法中启动的协程全部退出，从而优雅停止应用。

所以Stop方法比较简单，关键是利用了Context来控制应用生命周期。&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;我们可以注意到，在Run方法中，我们使用到了一个signal包下的Notify方法来对操作系统的关闭事件进行监听，这个是我们动作的核心，我把这部分单独整理在了&lt;a href=&quot;https://whrss.com/post/go-signal&quot;&gt;另一篇文章&lt;/a&gt;中。&lt;/p&gt;
&lt;p&gt;通过对操作系统事件的监听，我们就可以对一些必须完成的任务进行优雅地停止，如果有一些任务必须完成，我们可以在任务开始使用 wg := sync.WaitGroup{} 来对任务进行一个Add操作，当所有任务完成，监听到操作系统的关闭动作，我们需要使用wg.wait() 等待任务完成再进行退出。以实现一个优雅地启停。&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>os.signal golang 中的信号处理</title>
    <link href="https://blog.whrss.com/posts/go-signal"/>
    <id>https://blog.whrss.com/posts/go-signal</id>
    <published>2023-07-28T21:56:55.000Z</published>
    <updated>2023-07-28T21:56:55.000Z</updated>
    <category term="技术"/>
    <category term="go"/>
    <category term="signal"/>
    <category term="grace stop"/>
    <summary>在程序进行重启等操作时，我们需要让程序完成一些重要的任务之后，优雅地退出，Golang为我们提供了signal包，实现信号处理机制，允许Go 程序与传入的信号进行交互。</summary>
    <content type="html">&lt;p&gt;在程序进行重启等操作时，我们需要让程序完成一些重要的任务之后，优雅地退出，Golang为我们提供了signal包，实现信号处理机制，允许Go 程序与传入的信号进行交互。&lt;/p&gt;
&lt;p&gt;Go语言标准库中signal包的核心功能主要包含以下几个方面:&lt;/p&gt;
&lt;h5 id=&quot;1-signal处理的全局状态管理&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#1-signal处理的全局状态管理&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;1. signal处理的全局状态管理&lt;/h5&gt;
&lt;p&gt;通过handlers结构体跟踪每个signal的处理状态，包含信号与channel的映射关系,以及每个信号的引用计数。&lt;/p&gt;
&lt;h5 id=&quot;2-信号处理的注册与注销&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#2-信号处理的注册与注销&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;2. 信号处理的注册与注销&lt;/h5&gt;
&lt;p&gt;Notify函数用于向指定的channel注册信号处理，会更新handlers的状态。&lt;/p&gt;
&lt;p&gt;Stop函数用于注销指定channel的信号处理，将其从handlers中移除。&lt;/p&gt;
&lt;p&gt;Reset函数用于重置指定信号的处理为默认行为。&lt;/p&gt;
&lt;h5 id=&quot;3-信号的抓取与分发&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#3-信号的抓取与分发&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;3. 信号的抓取与分发&lt;/h5&gt;
&lt;p&gt;process函数在收到signal时，会把它分发给所有注册了该信号的channel。&lt;/p&gt;
&lt;h5 id=&quot;4-signal处理的恢复&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#4-signal处理的恢复&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;4. signal处理的恢复&lt;/h5&gt;
&lt;p&gt;通过cancel函数，可以恢复signal的默认行为或忽略。&lt;/p&gt;
&lt;h5 id=&quot;5-context信号通知支持&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#5-context信号通知支持&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;5. Context信号通知支持&lt;/h5&gt;
&lt;p&gt;NotifyContext函数会创建一个Context，在Context结束时自动注销signal处理。&lt;/p&gt;
&lt;h5 id=&quot;6-处理signal并发访问的同步&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#6-处理signal并发访问的同步&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;6. 处理signal并发访问的同步&lt;/h5&gt;
&lt;p&gt;通过handlers的锁保证对全局状态的线程安全访问。&lt;/p&gt;
&lt;h5 id=&quot;7-一些工具函数&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#7-一些工具函数&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;7. 一些工具函数&lt;/h5&gt;
&lt;p&gt;如handler的mask操作,判断signal是否在ignore列表中等。&lt;/p&gt;
&lt;p&gt;总的来说,该实现通过handlers跟踪signal与channel的关系,在收到signal时分发给感兴趣的channel,提供了flexible和高效的signal处理机制。&lt;/p&gt;
&lt;p&gt;在实际地使用中，我们需要创建一个接收信号量的channel，使用Notify将这个channel注册进去，当信号发生时，channel就可以接收到信号，后续的业务就可以针对性地进行处理。如下：&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;package&lt;/span&gt; main

&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; (
	&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;fmt&amp;quot;&lt;/span&gt;
	&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;os&amp;quot;&lt;/span&gt;
	&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;os/signal&amp;quot;&lt;/span&gt;
	&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;syscall&amp;quot;&lt;/span&gt;
)

&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;main&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;()&lt;/span&gt;&lt;/span&gt; {

	&lt;span class=&quot;hljs-comment&quot;&gt;// 创建一个channel来接收SIGINT信号&lt;/span&gt;
	c := &lt;span class=&quot;hljs-built_in&quot;&gt;make&lt;/span&gt;(&lt;span class=&quot;hljs-keyword&quot;&gt;chan&lt;/span&gt; os.Signal)

	&lt;span class=&quot;hljs-comment&quot;&gt;// 监听SIGINT信号并发送到c&lt;/span&gt;
	signal.Notify(c, syscall.SIGINT)

	&lt;span class=&quot;hljs-comment&quot;&gt;// 使用一个无限循环来响应SIGINT信号&lt;/span&gt;
	&lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; {
		fmt.Println(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;Waiting for SIGINT&amp;quot;&lt;/span&gt;)
		&amp;lt;-c
		fmt.Println(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;Got SIGINT. Breaking...&amp;quot;&lt;/span&gt;)
		&lt;span class=&quot;hljs-keyword&quot;&gt;break&lt;/span&gt;
	}
}&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;&lt;em&gt;共有32个信号量，相对应的枚举在syscall包下&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;常用的信号值包括：&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs&quot;&gt; SIGHUP 1 终端控制进程结束(终端连接断开)
 SIGINT 2 用户发送INTR字符(Ctrl+C)触发
 SIGQUIT 3 用户发送OUIT字符(Ctrl+/触发
 SIGKILL 9 无条件结束程序(不能被捕获、阻塞或忽略)
 SIGUSR1 10 用户保留
 SIGUSR2 12 用户保留
 SIGPIPE 13 消息管道损坏(FIFO/Socket通信时，管道未打开而进行写操作)
 SIGALRM 14 时钟定时信号
 SIGTERM 15 结束程序(可以被捕获、阻塞或忽略)&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;在go框架中，项目中实际使用到signal进行优雅退出见：&lt;a href=&quot;https://whrss.com/post/go-grace-stop&quot;&gt;如何在go中实现程序的优雅退出，go-kratos源码解析&lt;/a&gt;&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>探索 PlanetScale：划分分支的 MySQL Serverless 平台</title>
    <link href="https://blog.whrss.com/posts/planet-scale"/>
    <id>https://blog.whrss.com/posts/planet-scale</id>
    <published>2023-07-11T19:37:52.000Z</published>
    <updated>2023-07-11T19:37:52.000Z</updated>
    <category term="趣发现"/>
    <category term="serverless"/>
    <category term="blog"/>
    <category term="mysql"/>
    <category term="db"/>
    <summary>最近我发现了一个非常有趣的国外MySQL Serverless平台，它叫做PlanetScale。这个平台不仅仅是一个数据库，它能像代码一样轻松地创建开发和测试环境。你可以从主库中拉出一个与之完全相同结构的development或staging数据库，并在这个环境中进行开发和测试。所有的数据都是隔离的，不会相互干扰。
当你完成开发后，你可以创建一个deploy request，PlanetScale会自动比对并生成Schema diff，然后你可以仔细审查需要部署的内容。确认没问题，你就可以将这些变更部署到线上库中。整个部署过程不会导致停机时间，非常方便。</summary>
    <content type="html">&lt;p&gt;最近我发现了一个非常有趣的国外MySQL Serverless平台，它叫做&lt;a href=&quot;https://app.planetscale.com&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;PlanetScale&lt;/a&gt;。这个平台不仅仅是一个数据库，它能像代码一样轻松地创建开发和测试环境。你可以从主库中拉出一个与之完全相同结构的development或staging数据库，并在这个环境中进行开发和测试。所有的数据都是隔离的，不会相互干扰。&lt;/p&gt;
&lt;p&gt;当你完成开发后，你可以创建一个deploy request，PlanetScale会自动比对并生成Schema diff，然后你可以仔细审查需要部署的内容。确认没问题，你就可以将这些变更部署到线上库中。整个部署过程不会导致停机时间，非常方便。&lt;/p&gt;
&lt;p&gt;PlanetScale的入门使用是免费的，他们提供了以下免费套餐：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;5GB存储空间&lt;/li&gt;
&lt;li&gt;每月10亿行读取操作&lt;/li&gt;
&lt;li&gt;每月1000万行写入操作&lt;/li&gt;
&lt;li&gt;1个生产分支&lt;/li&gt;
&lt;li&gt;1个开发分支&lt;/li&gt;
&lt;li&gt;社区支持&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;如果超出了免费套餐的限制，他们会按照以下价格收费：每GB存储空间每月2.5美元，每10亿行读取操作每月1美元，每100万行写入操作每月1.5美元。对于我这样的个人使用者，真的太不错了。&lt;/p&gt;
&lt;p&gt;这个平台运行在云上，提供了一个Web管理界面和一个CLI工具。我试了一下他们的Web管理界面，但发现它并不是很好用，无法进行批量的SQL执行。于是我研究了一下CLI工具的使用，并做了一份小记录，现在和大家分享一下。&lt;/p&gt;
&lt;p&gt;以下是在 &lt;code&gt;Mac&lt;/code&gt; 中使用&lt;code&gt;PlanetScale CLI&lt;/code&gt;工具的步骤：&lt;br&gt;其他系统安装可见：&lt;a href=&quot;https://planetscale.com/docs/concepts/planetscale-environment-setup&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;官方文档&lt;/a&gt;&lt;/p&gt;
&lt;h4 id=&quot;1-安装pscale工具&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#1-安装pscale工具&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;1. 安装pscale工具&lt;/h4&gt;
&lt;p&gt;&lt;code&gt;brew install planetscale/tap/pscale&lt;/code&gt;&lt;/p&gt;
&lt;h4 id=&quot;2-更新brew和pscale确保使用的是最新版本&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#2-更新brew和pscale确保使用的是最新版本&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;2. 更新brew和pscale，确保使用的是最新版本&lt;/h4&gt;
&lt;p&gt;&lt;code&gt;brew update &amp;&amp; brew upgrade pscale&lt;/code&gt;&lt;/p&gt;
&lt;h4 id=&quot;3-进行认证&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#3-进行认证&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;3. 进行认证&lt;/h4&gt;
&lt;p&gt;&lt;code&gt;pscale auth login&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;这个命令会在浏览器中打开一个页面&lt;br&gt;&lt;img src=&quot;https://raw.githubusercontent.com/whrsss/pic-sync/master/img/20230712112110.png&quot; alt=&quot;image.png&quot; loading=&quot;eager&quot; decoding=&quot;async&quot;&gt;&lt;br&gt;如果你已经登录了PlanetScale账号，它会直接让你确认验证。验证成功后，你就可以开始使用CLI工具了。&lt;/p&gt;
&lt;p&gt;如果你走到这步的时候提示：&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;java&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-java&quot;&gt;Error: error decoding error response: invalid character &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;&amp;lt;&amp;#x27;&lt;/span&gt; looking &lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; beginning of value&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;你需要调整一下网络～ 目前是不给大陆用户IP使用的。&lt;/p&gt;
&lt;h4 id=&quot;4-连接到相应的数据库分支&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#4-连接到相应的数据库分支&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;4. 连接到相应的数据库分支&lt;/h4&gt;
&lt;p&gt;&lt;code&gt;pscale connect [数据库名] [分支名] # 例如： pscale connect blog main&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;连接成功后，你就可以通过本地的3306端口代理访问远程数据库了。&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs&quot;&gt;Secure connection to database whrss and branch main is established!.
Local address to connect your application: 127.0.0.1:3306 (press ctrl-c to quit)&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/whrsss/pic-sync/master/img/20230712111233.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;h4 id=&quot;5-本地连接&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#5-本地连接&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;5. 本地连接&lt;/h4&gt;
&lt;p&gt; 点击&lt;code&gt;Get connection strings&lt;/code&gt;，你就可以得到连接数据库所需的账号名和密码，然后可以在本地的数据库连接软件中直接连接数据库了。&lt;br&gt;    &lt;img src=&quot;https://raw.githubusercontent.com/whrsss/pic-sync/master/img/202307121100351.png&quot; alt=&quot;&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;ol start=&quot;6&quot;&gt;
&lt;li&gt;选择适合你的编程语言的连接串，这样你就可以在不同的程序中直接使用了。&lt;br&gt; &lt;img src=&quot;https://raw.githubusercontent.com/whrsss/pic-sync/master/img/20230712110227.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;通过这些简单的步骤，你就可以轻松地使用PlanetScale来管理和部署你的MySQL应用了。快来体验一下吧！&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>优化你的RSS订阅：一次全面改进的实践</title>
    <link href="https://blog.whrss.com/posts/feed-sub"/>
    <id>https://blog.whrss.com/posts/feed-sub</id>
    <published>2023-06-26T12:25:21.000Z</published>
    <updated>2023-06-26T12:25:21.000Z</updated>
    <category term="折腾"/>
    <category term="feed"/>
    <category term="blog"/>
    <summary>先前，我的 RSS 订阅功能过于简化，只提供了几个基本字段，而且不展示全文。我决定对订阅功能做一次全面的改进。</summary>
    <content type="html">&lt;p&gt;先前，我的 RSS 订阅功能过于简化，只提供了几个基本字段，而且不展示全文。简介后面，我添加了一个链接指向原文，如下所示：&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/whrsss/pic-sync/master/img/20230626202258.png&quot; alt=&quot;image.png&quot; loading=&quot;eager&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;过于简陋，无法直接在 RSS 阅读器软件上进行查看，另外，我临时用 Kotlin 编写的这个功能需要每次调用时重新生成，这点就对这个功能的简单和独立性产生了影响，这件事放了太久，最近进行一次全面的改进。&lt;/p&gt;
&lt;p&gt;原始的文章是用 Markdown 编写的。为了方便通过手机或电脑上的 RSS 阅读器查看，我需要将文章内容转换为 HTML 格式。在 Go 语言中，有一个成熟的组件：blackfriday。它能把每段文字用 p 标签标记，用 code 和 pre 标签标记代码块，以及用 h1234 标签标记不同层级的标题。&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;github.com/PuerkitoBio/goquery
github.com/russross/blackfriday/v2&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;经过一次生成并查看效果后，我发现有些地方需要改进。例如，图片和文字都是左对齐的，看起来并不美观。另外，非代码块的单引号也会被转化为代码块，导致原本可以在一行显示的内容被拆分为三行。于是我添加了一些附加功能：&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;Md2Html&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;(markdown []&lt;span class=&quot;hljs-type&quot;&gt;byte&lt;/span&gt;)&lt;/span&gt;&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;string&lt;/span&gt; {

	&lt;span class=&quot;hljs-comment&quot;&gt;// 1. Convert markdown to HTML&lt;/span&gt;
	html := blackfriday.Run(markdown)

	&lt;span class=&quot;hljs-comment&quot;&gt;// 2. Create a new document from the HTML string&lt;/span&gt;
	doc, err := goquery.NewDocumentFromReader(bytes.NewReader(html))
	&lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; err != &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt; {
	log.Fatal(err)
	}

	&lt;span class=&quot;hljs-comment&quot;&gt;// 3. Process all elements to have a max-width of 1300px and text alignment to left&lt;/span&gt;
	doc.Find(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;p, h1, h2, h3, h4, h5, h6, ul, ol, li, table, pre&amp;quot;&lt;/span&gt;).Each(&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;(i &lt;span class=&quot;hljs-type&quot;&gt;int&lt;/span&gt;, s *goquery.Selection)&lt;/span&gt;&lt;/span&gt; {
	s.SetAttr(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;style&amp;quot;&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;max-width: 1300px; display: block; margin-left: auto; margin-right: auto; text-align: left;&amp;quot;&lt;/span&gt;)
	})

	&lt;span class=&quot;hljs-comment&quot;&gt;// 4. Process the images to be centered and have a max size of 500x500&lt;/span&gt;
	doc.Find(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;img&amp;quot;&lt;/span&gt;).Each(&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;(i &lt;span class=&quot;hljs-type&quot;&gt;int&lt;/span&gt;, s *goquery.Selection)&lt;/span&gt;&lt;/span&gt; {
	s.SetAttr(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;style&amp;quot;&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;max-width: 500px; max-height: 500px; display: block; margin-left: auto; margin-right: auto;&amp;quot;&lt;/span&gt;)
	})

	&lt;span class=&quot;hljs-comment&quot;&gt;// 5. Process code blocks to be styled like in markdown, and inline code to be bold&lt;/span&gt;
	doc.Find(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;code&amp;quot;&lt;/span&gt;).Each(&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;(i &lt;span class=&quot;hljs-type&quot;&gt;int&lt;/span&gt;, s *goquery.Selection)&lt;/span&gt;&lt;/span&gt; {
	&lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; goquery.NodeName(s.Parent()) == &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;pre&amp;quot;&lt;/span&gt; {
	&lt;span class=&quot;hljs-comment&quot;&gt;// this is a code block, keep the markdown style&lt;/span&gt;
	s.SetAttr(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;style&amp;quot;&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;display: block; white-space: pre; border: 1px solid #ccc; padding: 6px 10px; color: #333; background-color: #f9f9f9; border-radius: 3px;&amp;quot;&lt;/span&gt;)
	} &lt;span class=&quot;hljs-keyword&quot;&gt;else&lt;/span&gt; {
	&lt;span class=&quot;hljs-comment&quot;&gt;// this is inline code, replace it with bold text&lt;/span&gt;
	s.ReplaceWithHtml(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;&amp;lt;b&amp;gt;&amp;quot;&lt;/span&gt; + s.Text() + &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;&amp;lt;/b&amp;gt;&amp;quot;&lt;/span&gt;)
	}
	})

	&lt;span class=&quot;hljs-comment&quot;&gt;// 6. Get the modified HTML&lt;/span&gt;
	modifiedHtml, err := doc.Html()
	&lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; err != &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt; {
	log.Fatal(err)
	}

	&lt;span class=&quot;hljs-comment&quot;&gt;// Replace self-closing tags&lt;/span&gt;
	modifiedHtml = strings.Replace(modifiedHtml, &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;/&amp;gt;&amp;quot;&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;&amp;gt;&amp;quot;&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;-1&lt;/span&gt;)

	&lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; modifiedHtml
}&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;修改之后，我把生成的 HTML 内容放入 RSS 的 XML 中。XML 内容的生成就是简单的字符串拼接，我写了一个 GenerateFeed 方法来完成：&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;type&lt;/span&gt; Article &lt;span class=&quot;hljs-keyword&quot;&gt;struct&lt;/span&gt; {
	Title &lt;span class=&quot;hljs-type&quot;&gt;string&lt;/span&gt;
	Link &lt;span class=&quot;hljs-type&quot;&gt;string&lt;/span&gt;
	Id &lt;span class=&quot;hljs-type&quot;&gt;string&lt;/span&gt;
	Published time.Time
	Updated time.Time
	Content &lt;span class=&quot;hljs-type&quot;&gt;string&lt;/span&gt;
	Summary &lt;span class=&quot;hljs-type&quot;&gt;string&lt;/span&gt;
}

&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;GenerateFeed&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;(articles []Article)&lt;/span&gt;&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;string&lt;/span&gt; {
	&lt;span class=&quot;hljs-comment&quot;&gt;// 对文章按发布日期排序&lt;/span&gt;
	sort.Slice(articles, &lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;(i, j &lt;span class=&quot;hljs-type&quot;&gt;int&lt;/span&gt;)&lt;/span&gt;&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;bool&lt;/span&gt; {
	&lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; articles[i].Published.After(articles[j].Published)
	})

	&lt;span class=&quot;hljs-comment&quot;&gt;// 生成Feed&lt;/span&gt;
	feed := &lt;span class=&quot;hljs-string&quot;&gt;`&amp;lt;feed xmlns=&amp;quot;http://www.w3.org/2005/Atom&amp;quot;&amp;gt;
	&amp;lt;title&amp;gt;了迹奇有没&amp;lt;/title&amp;gt;
	&amp;lt;link href=&amp;quot;/feed.xml&amp;quot; rel=&amp;quot;self&amp;quot;/&amp;gt;
	&amp;lt;link href=&amp;quot;https://whrss.com/&amp;quot;/&amp;gt;
	&amp;lt;updated&amp;gt;`&lt;/span&gt; + articles[&lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt;].Updated.Format(time.RFC3339Nano) + &lt;span class=&quot;hljs-string&quot;&gt;`&amp;lt;/updated&amp;gt;
	&amp;lt;id&amp;gt;https://whrss.com/&amp;lt;/id&amp;gt;
	&amp;lt;author&amp;gt;
	&amp;lt;name&amp;gt;whrss&amp;lt;/name&amp;gt;
	&amp;lt;/author&amp;gt;`&lt;/span&gt;

	&lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; _, article := &lt;span class=&quot;hljs-keyword&quot;&gt;range&lt;/span&gt; articles {
	feed += &lt;span class=&quot;hljs-string&quot;&gt;`
	&amp;lt;entry&amp;gt;
	&amp;lt;title&amp;gt;`&lt;/span&gt; + article.Title + &lt;span class=&quot;hljs-string&quot;&gt;`&amp;lt;/title&amp;gt;
	&amp;lt;link href=&amp;quot;`&lt;/span&gt; + article.Link + &lt;span class=&quot;hljs-string&quot;&gt;`&amp;quot;/&amp;gt;
	&amp;lt;id&amp;gt;`&lt;/span&gt; + article.Id + &lt;span class=&quot;hljs-string&quot;&gt;`&amp;lt;/id&amp;gt;
	&amp;lt;published&amp;gt;`&lt;/span&gt; + article.Published.Format(time.RFC3339) + &lt;span class=&quot;hljs-string&quot;&gt;`&amp;lt;/published&amp;gt;
	&amp;lt;updated&amp;gt;`&lt;/span&gt; + article.Updated.Format(time.RFC3339Nano) + &lt;span class=&quot;hljs-string&quot;&gt;`&amp;lt;/updated&amp;gt;
	&amp;lt;content type=&amp;quot;html&amp;quot;&amp;gt;&amp;lt;![CDATA[`&lt;/span&gt; + article.Content + &lt;span class=&quot;hljs-string&quot;&gt;`]]&amp;gt;&amp;lt;/content&amp;gt;
	&amp;lt;summary type=&amp;quot;html&amp;quot;&amp;gt;`&lt;/span&gt; + article.Summary + &lt;span class=&quot;hljs-string&quot;&gt;`&amp;lt;/summary&amp;gt;
	&amp;lt;/entry&amp;gt;`&lt;/span&gt;
	}

	feed += &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;\n&amp;lt;/feed&amp;gt;&amp;quot;&lt;/span&gt;
	&lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; feed
}&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;最后效果确实十分理想，手机上的观看效果不输我的原始站点，很不错～&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>最近在做的事：GitHub Action | GPT Plus | whisper | V2EX | GPT API | PMP</title>
    <link href="https://blog.whrss.com/posts/done-lately"/>
    <id>https://blog.whrss.com/posts/done-lately</id>
    <published>2023-06-25T07:49:29.000Z</published>
    <updated>2023-06-25T07:49:29.000Z</updated>
    <category term="生活和思考"/>
    <category term="GitHub Action"/>
    <category term="GPT Plus"/>
    <category term="whisper"/>
    <category term="V2EX"/>
    <category term="GPT API"/>
    <category term="PMP"/>
    <summary>运动数据使用GitHub Action自动更新｜ 开通体验了一下GPT Plus ｜ 买了一支录音笔，全天候录音，使用 whisper 录音转文字 ｜终于注册了 V2EX ｜GPT API续费问题曲线救国｜报名了PMP的培训班和考试</summary>
    <content type="html">&lt;h4 id=&quot;运动数据使用github-action自动更新&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#运动数据使用github-action自动更新&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;运动数据使用GitHub Action自动更新&lt;/h4&gt;
&lt;p&gt;看着每天的运动数据，满满的，还感觉有点充实😆️ 积少成多嘛&lt;/p&gt;
&lt;h4 id=&quot;开通体验了一下gpt-plus&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#开通体验了一下gpt-plus&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;开通体验了一下GPT Plus&lt;/h4&gt;
&lt;p&gt;太想体验下GPT4了，之前苦于充值门槛过高，上个月出了app充值后，我使用支付宝礼品卡充值体验了下，感觉还是不错的，但是个人使用确实还是按量更划算一点，但是充值门槛过高😲️&lt;/p&gt;
&lt;h4 id=&quot;买了一支录音笔全天候录音使用-whisper-录音转文字&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#买了一支录音笔全天候录音使用-whisper-录音转文字&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;买了一支录音笔，全天候录音，使用 whisper 录音转文字&lt;/h4&gt;
&lt;p&gt;之前全程吃瓜了刘能离婚案，后来受他种草，也买了索尼的tx660，全天候录音，之后再把录音源文件和转的文本保存起来，这样想检索也会很方便的。&lt;/p&gt;
&lt;h4 id=&quot;终于注册了-v2ex&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#终于注册了-v2ex&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;终于注册了 V2EX&lt;/h4&gt;
&lt;p&gt;这个社区知道很久了，一直是游客登录，看到别人发的别人社区啊推荐啊很不错，我说我也得养养号😜️&lt;/p&gt;
&lt;h4 id=&quot;gpt-api续费问题曲线救国&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#gpt-api续费问题曲线救国&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;GPT API续费问题曲线救国&lt;/h4&gt;
&lt;p&gt;续上面充值问题，最近充值门槛更高了，对网络要求也更高了，还动不动就给封号。那我怎么整，Api确实便宜又方便，而且不用管那么复杂的网络。这不刚注册了V2EX嘛，上去翻翻。&lt;br&gt;&lt;img src=&quot;https://raw.githubusercontent.com/whrsss/pic-sync/master/img/20230625153717.png&quot; alt=&quot;image.png&quot; loading=&quot;eager&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;然后我使用了这个-&amp;gt; &lt;a href=&quot;https://aiproxy.io/?i=whrsss&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;aiproxy&lt;/a&gt; ，咱这V站注册就开始实际生产力了哈哈哈。&lt;br&gt;感觉还可以，然后使用自建的客户端输入地址和key就可以用啦。&lt;br&gt;&lt;img src=&quot;https://raw.githubusercontent.com/whrsss/pic-sync/master/img/20230625154004.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;h4 id=&quot;报名了pmp的培训班和考试&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#报名了pmp的培训班和考试&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;报名了PMP的培训班和考试&lt;/h4&gt;
&lt;p&gt;6月中下旬决定报名8月份的PMP考试，一方面是我现在处于软考之后的一个学习的空窗期，一个原因是因为朋友刘某（一个年轻的项目经理）拉我，最重要的一个原因是，我确实很需要管理协调方面的工作技能，而且我刚好到了PMP的报名门槛😄️。&lt;br&gt;报名费是真滴贵呀～&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>一个游戏开发者的自我介绍</title>
    <link href="https://blog.whrss.com/posts/me"/>
    <id>https://blog.whrss.com/posts/me</id>
    <published>2023-06-08T14:22:30.000Z</published>
    <updated>2023-06-08T14:22:30.000Z</updated>
    <category term="生活和思考"/>
    <category term="about me"/>
    <summary>职业道路上的新旅程：一个游戏开发者的自我介绍</summary>
    <content type="html">&lt;p&gt;我写这篇博客的初衷并不是出于单纯的自我表达，而是为了那些可能会对我未来职业发展产生重要影响的人们。或许你是一个正在考虑我的简历的HR，或者是将来可能与我一起共事的团队成员。无论你是谁，我都希望通过这篇博客让你更深入地了解我。同时，写作的过程也让我有机会重新审视和整理我的技能和经历。😝️&lt;/p&gt;
&lt;p&gt;我目前就职于一家游戏公司，我们的团队虽然&lt;code&gt;小&lt;/code&gt;但十分&lt;code&gt;精悍&lt;/code&gt;✊️。我负责的任务非常多，目前核心是一个女性向AVG游戏的后端开发，这款游戏在TapTap上的评价和排名都&lt;code&gt;非&lt;/code&gt; &lt;code&gt;常&lt;/code&gt; &lt;code&gt;高&lt;/code&gt;，另外我也参与公共服务和核心业务模块的开发。&lt;/p&gt;
&lt;p&gt;除此之外，我还负责管理公司所有的服务器资源，并负责运维工作。这主要得益于我平时对很多技术的尝试和钻研，让我能够顺利应对上云带来的各种挑战。&lt;/p&gt;
&lt;p&gt;我在2021年3月加入这家公司，两个月后便开始接手核心项目。主要的技术栈包括&lt;code&gt;Kratos&lt;/code&gt; + &lt;code&gt;Go&lt;/code&gt;和&lt;code&gt;Spring Boot&lt;/code&gt; + &lt;code&gt;Kotlin&lt;/code&gt;。目前，我们正在将新项目统一使用Go这套技术栈，因为Go不仅满足了我们的需求，还非常易于维护。在数据库方面，我个人对SQL和分布式事务更熟悉，也能够在不同的业务场景中使用不同的数据库和工具。&lt;/p&gt;
&lt;p&gt;我加入公司之初，我们的服务和服务器都是单体和独立的，各种技术栈和老项目混乱无章，也恰逢人员交接之际。然而，随着新业务的展开，我们从零开始，大量地构建和改进，同时采用了K8S。如今，无论是&lt;code&gt;服务文档&lt;/code&gt;、&lt;code&gt;服务框架&lt;/code&gt;、&lt;code&gt;单元测试&lt;/code&gt;，还是&lt;code&gt;CI/CD&lt;/code&gt;，我们都已经运行得非常成熟，这也非常适合我们目前和未来一段时间的项目架构。&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;我始终认为技术人应该持续学习和进步。我觉得我已经做到了我能做到的事情，至于更多的东西，我知道我现在的知识储备可能有限，但我仍希望能更进一步。年轻的我没有太多负担，希望能够抓住机会，走得更远。这就是我正在寻找新机会的原因。我期待挑战，也期待更有趣的工作。我相信，无论结果如何，这个过程都会带给我宝贵的经验和成长。&lt;/strong&gt;&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>使用GitHub Action 同步运动数据并生成热力图</title>
    <link href="https://blog.whrss.com/posts/github-poster"/>
    <id>https://blog.whrss.com/posts/github-poster</id>
    <published>2023-06-04T13:14:48.000Z</published>
    <updated>2023-06-04T13:14:48.000Z</updated>
    <category term="折腾"/>
    <category term="GitHub Action"/>
    <category term="快捷指令"/>
    <summary>如果你想把你的运动数据和热力图同步到 GitHub，那么你来对地方了。在这篇文章中，我将详细解释如何使用 GitHub Actions 和 Python 自动同步和更新你的数据。
这个项目是在伊洪@yihong0618的GitHubPoster的基础上进行的所以在此表示感谢。他的另一个项目是IBeat （之前我对GitHub Action做了一次尝试），从这里我开始接触了快捷指令的触发。</summary>
    <content type="html">&lt;p&gt;如果你想把你的运动数据和热力图同步到 GitHub，那么你来对地方了。在这篇文章中，我将详细解释如何使用 GitHub Actions 和 Python 自动同步和更新你的数据。&lt;/p&gt;
&lt;p&gt;这个项目是在伊洪&lt;a href=&quot;https://github.com/yihong0618&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;@yihong0618&lt;/a&gt;的GitHubPoster的基础上进行的所以在此表示感谢。他的另一个项目是IBeat （之前我对GitHub Action&lt;a href=&quot;https://whrss.com/post/github-action&quot;&gt;做了一次尝试&lt;/a&gt;），从这里我开始接触了快捷指令的触发。&lt;/p&gt;
&lt;p&gt;最终效果如下：&lt;br&gt;&lt;img src=&quot;https://raw.githubusercontent.com/whrss9527/whrss9527/master/AppleHealthData.svg&quot; alt=&quot;我的运动数据&quot; loading=&quot;eager&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;h2 id=&quot;一-开始前的准备&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#一-开始前的准备&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;一. 开始前的准备&lt;/h2&gt;
&lt;p&gt;首先，你需要 fork @yihong0618的项目，并将其克隆到本地： &lt;a href=&quot;https://github.com/whrsss/GitHubPoster&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;https://github.com/whrsss/GitHubPoster&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;然后，安装项目的依赖项：&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;python&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-python&quot;&gt;pip3 install -r requirements.txt&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;h2 id=&quot;二-全量生成历史数据&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#二-全量生成历史数据&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;二. 全量生成历史数据&lt;/h2&gt;
&lt;p&gt;研究了一下，步骤是先全量生成历史数据（用全量模式backfill），再进行追加（incremental）。&lt;/p&gt;
&lt;p&gt;下面是如何导出每日运动量（卡路里）出来的例子。首先，将apple 运动中的数据导出，解压在IN_FOLDER文件夹中，然后在项目根目录运行：&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;python&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-python&quot;&gt;python3 -m github_poster apple_health --apple_health_mode backfill --year &lt;span class=&quot;hljs-number&quot;&gt;2020&lt;/span&gt;-&lt;span class=&quot;hljs-number&quot;&gt;2023&lt;/span&gt; --apple_health_record_type move --me &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;your name&amp;quot;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;这样在OUT_FOLDER目录下就会生成一份全量的数据，IN_FOLDER下也会生成对应的全量json文件，之后的增量，会加入到IN_FOLDER的json文件中。&lt;/p&gt;
&lt;h4 id=&quot;逻辑微调&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#逻辑微调&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;逻辑微调&lt;/h4&gt;
&lt;p&gt;由于我的目标是统计每日消耗的卡路里，在apple health导出的数据中，分成了两块儿， 分别是&lt;br&gt;type=”HKQuantityTypeIdentifierBasalEnergyBurned”和 type=”HKQuantityTypeIdentifierActiveEnergyBurned” ，每日基础消耗数据和每日运动活动数据。&lt;br&gt;（ps. Apple 运动记录中不同的运动类型&lt;a href=&quot;https://developer.apple.com/documentation/healthkit/data_types?language=objc&amp;amp;changes=latest_minor&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;在这里&lt;/a&gt;，想要自定义其他可以自取）&lt;/p&gt;
&lt;p&gt;而在GitHubPoster中支持的3种类型中，move、exercise、stand，对应的apple health数据都是单种类型，所以，需要将type修改为数组类型才能实现。&lt;br&gt;在 github_poster/loader/apple_health_loader.py 中修改其中的 RecordMetadata 的支持和使用。&lt;br&gt;首先需要将&lt;code&gt;type&lt;/code&gt;字段修改为一个列表或者集合。在定义&lt;code&gt;RecordMetadata&lt;/code&gt;时，将&lt;code&gt;type&lt;/code&gt;字段类型改为&lt;code&gt;List&lt;/code&gt;或&lt;code&gt;Set&lt;/code&gt;：&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;python&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-python&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; typing &lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;List&lt;/span&gt;

RecordMetadata = namedtuple(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;RecordMetadata&amp;quot;&lt;/span&gt;, [&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;types&amp;quot;&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;unit&amp;quot;&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;track_color&amp;quot;&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;func&amp;quot;&lt;/span&gt;])&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;然后在定义&lt;code&gt;HEALTH_RECORD_TYPES&lt;/code&gt;时，你就可以为每个键提供多个类型了：&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;python&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-python&quot;&gt;HEALTH_RECORD_TYPES = {
    &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;stand&amp;quot;&lt;/span&gt;: RecordMetadata(
        [&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;HKCategoryTypeIdentifierAppleStandHour&amp;quot;&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;AnotherType&amp;quot;&lt;/span&gt;, ...],
        &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;hours&amp;quot;&lt;/span&gt;,
        &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;#62F90B&amp;quot;&lt;/span&gt;,
        &lt;span class=&quot;hljs-keyword&quot;&gt;lambda&lt;/span&gt; x: &lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;HKCategoryValueAppleStandHourStood&amp;quot;&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt;,
    ),
    ...
}&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;接着，你需要在&lt;code&gt;AppleHealthLoader&lt;/code&gt;类的&lt;code&gt;backfill&lt;/code&gt;方法中，修改判断记录类型的逻辑。将原来的等于比较改为检查类型是否在&lt;code&gt;types&lt;/code&gt;列表中：&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;python&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-python&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;hljs-title function_&quot;&gt;backfill&lt;/span&gt;(&lt;span class=&quot;hljs-params&quot;&gt;self&lt;/span&gt;):
    from_export = defaultdict(&lt;span class=&quot;hljs-built_in&quot;&gt;int&lt;/span&gt;)

    in_target_section = &lt;span class=&quot;hljs-literal&quot;&gt;False&lt;/span&gt;
    &lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; _, elem &lt;span class=&quot;hljs-keyword&quot;&gt;in&lt;/span&gt; ET.iterparse(&lt;span class=&quot;hljs-variable language_&quot;&gt;self&lt;/span&gt;.apple_health_export_file, events=[&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;end&amp;quot;&lt;/span&gt;]):
        &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; elem.tag != &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;Record&amp;quot;&lt;/span&gt;:
            &lt;span class=&quot;hljs-keyword&quot;&gt;continue&lt;/span&gt;

        &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; elem.attrib[&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;type&amp;quot;&lt;/span&gt;] &lt;span class=&quot;hljs-keyword&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;hljs-variable language_&quot;&gt;self&lt;/span&gt;.record_metadata.types:
            ...&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;这样，每个&lt;code&gt;RecordMetadata&lt;/code&gt;就可以包含多个&lt;code&gt;type&lt;/code&gt;了，可以在&lt;code&gt;HEALTH_RECORD_TYPES&lt;/code&gt;中为每个键定义任意数量的类型。&lt;/p&gt;
&lt;p&gt;再次执行，即可生成想要的数据。&lt;/p&gt;
&lt;p&gt;到这里，如果你不需要每日更新，只发个朋友圈啥的，就够了。&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;三-设置-github-actions-进行数据的增量更新&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#三-设置-github-actions-进行数据的增量更新&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;三.  设置 GitHub Actions 进行数据的增量更新&lt;/h2&gt;
&lt;p&gt;要实现数据的每日更新，我们需要利用快捷指令和 GitHub Actions。具体的步骤如下：&lt;/p&gt;
&lt;h3 id=&quot;生成一个accesstoken&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#生成一个accesstoken&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;生成一个AccessToken&lt;/h3&gt;
&lt;p&gt;我们首先需要生成一个AccessToken，用来作为快捷指令post请求的凭证： &lt;img src=&quot;https://raw.githubusercontent.com/whrsss/pic-sync/master/img/20230531154301.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;h3 id=&quot;配置github仓库的权限&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#配置github仓库的权限&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;配置GitHub仓库的权限&lt;/h3&gt;
&lt;p&gt;接下来，我们需要打开GitHub action 的仓库读写权限，用来作为图片生成完成以及数据增量的仓库保存： &lt;img src=&quot;https://raw.githubusercontent.com/whrsss/pic-sync/master/img/20230531154150.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;h3 id=&quot;编写-github-actions-workflow-编写-github-actions-工作流程&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#编写-github-actions-workflow-编写-github-actions-工作流程&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;编写 GitHub Actions workflow 编写 GitHub Actions 工作流程&lt;/h3&gt;
&lt;p&gt;我们在.github/workflow目录下创建一个yml后缀的文件，比如叫sync_exercise.yml，下面是我的文件的内容：&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;yml&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-yaml&quot;&gt;&lt;span class=&quot;hljs-attr&quot;&gt;name:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;Run&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;Poster&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;Generate&lt;/span&gt;
&lt;span class=&quot;hljs-attr&quot;&gt;on:&lt;/span&gt;
  &lt;span class=&quot;hljs-attr&quot;&gt;workflow_dispatch:&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;inputs:&lt;/span&gt;
      &lt;span class=&quot;hljs-attr&quot;&gt;time:&lt;/span&gt;
        &lt;span class=&quot;hljs-attr&quot;&gt;description:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;time list&amp;#x27;&lt;/span&gt;
        &lt;span class=&quot;hljs-attr&quot;&gt;required:&lt;/span&gt; &lt;span class=&quot;hljs-literal&quot;&gt;false&lt;/span&gt;
      &lt;span class=&quot;hljs-attr&quot;&gt;value:&lt;/span&gt;
        &lt;span class=&quot;hljs-attr&quot;&gt;description:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;value list&amp;#x27;&lt;/span&gt;
        &lt;span class=&quot;hljs-attr&quot;&gt;required:&lt;/span&gt; &lt;span class=&quot;hljs-literal&quot;&gt;false&lt;/span&gt;
  &lt;span class=&quot;hljs-attr&quot;&gt;pull_request:&lt;/span&gt;
  
&lt;span class=&quot;hljs-attr&quot;&gt;env:&lt;/span&gt;
  &lt;span class=&quot;hljs-attr&quot;&gt;TYPE:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;apple_health&amp;quot;&lt;/span&gt; 
  &lt;span class=&quot;hljs-attr&quot;&gt;ME:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;whrsss&lt;/span&gt;
  &lt;span class=&quot;hljs-comment&quot;&gt;# change env here&lt;/span&gt;
  &lt;span class=&quot;hljs-attr&quot;&gt;GITHUB_NAME:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;whrsss&lt;/span&gt;
  &lt;span class=&quot;hljs-attr&quot;&gt;GITHUB_EMAIL:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;xxx@qq.com&lt;/span&gt;
&lt;span class=&quot;hljs-attr&quot;&gt;jobs:&lt;/span&gt;
  &lt;span class=&quot;hljs-attr&quot;&gt;sync:&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;name:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;Sync&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;runs-on:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;ubuntu-latest&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;steps:&lt;/span&gt;
      &lt;span class=&quot;hljs-bullet&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;hljs-attr&quot;&gt;name:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;Checkout&lt;/span&gt;
        &lt;span class=&quot;hljs-attr&quot;&gt;uses:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;actions/checkout@v3&lt;/span&gt;
      &lt;span class=&quot;hljs-bullet&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;hljs-attr&quot;&gt;name:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;Set&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;up&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;Python&lt;/span&gt;
        &lt;span class=&quot;hljs-attr&quot;&gt;uses:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;actions/setup-python@v4&lt;/span&gt;
        &lt;span class=&quot;hljs-attr&quot;&gt;with:&lt;/span&gt;
          &lt;span class=&quot;hljs-attr&quot;&gt;python-version:&lt;/span&gt; &lt;span class=&quot;hljs-number&quot;&gt;3.8&lt;/span&gt;

      &lt;span class=&quot;hljs-bullet&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;hljs-attr&quot;&gt;name:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;Install&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;dependencies&lt;/span&gt;
        &lt;span class=&quot;hljs-attr&quot;&gt;run:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;|
          python -m pip install --upgrade pip
          pip install -r requirements.txt
&lt;/span&gt;        &lt;span class=&quot;hljs-attr&quot;&gt;if:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;steps.pip-cache.outputs.cache-hit&lt;/span&gt; &lt;span class=&quot;hljs-type&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;true&amp;#x27;&lt;/span&gt;

      &lt;span class=&quot;hljs-bullet&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;hljs-attr&quot;&gt;name:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;Run&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;sync&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;apple_health&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;script&lt;/span&gt;
        &lt;span class=&quot;hljs-attr&quot;&gt;if:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;contains(env.TYPE,&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;apple_health&amp;#x27;&lt;/span&gt;&lt;span class=&quot;hljs-string&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;hljs-attr&quot;&gt;run:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;|
          python3 -m github_poster apple_health --apple_health_mode incremental --apple_health_date ${{ github.event.inputs.time }} --apple_health_value ${{ github.event.inputs.value }} --year 2020-2023 --apple_health_record_type move --me &amp;quot;whrsss&amp;quot;
&lt;/span&gt;
      &lt;span class=&quot;hljs-bullet&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;hljs-attr&quot;&gt;name:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;Push&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;poster&lt;/span&gt;
        &lt;span class=&quot;hljs-attr&quot;&gt;run:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;|
          git config --local user.email &amp;quot;${{ env.GITHUB_EMAIL }}&amp;quot;
          git config --local user.name &amp;quot;${{ env.GITHUB_NAME }}&amp;quot;
          git add .
          git commit -m &amp;#x27;update new poster&amp;#x27; || echo &amp;quot;nothing to commit&amp;quot;
          git push || echo &amp;quot;nothing to push&amp;quot;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;如果想要了解github action语法的同学可以google一下&lt;br&gt;上面的yaml的步骤分别是：&lt;br&gt;	1. 定义了一个名为 “Run Poster Generate” 的 Github Actions&lt;br&gt;	2. 指定了两种触发方式，一种是手动触发的 workflow_dispatch，另一种是当有新的 pull_request 时触发&lt;br&gt;	3. 指定了一些环境变量，包括 poster 生成所需的参数&lt;br&gt;	4. 定义了一个名为 “sync” 的 job，指定在 ubuntu-latest 操作系统上运行&lt;br&gt;	5. 包括了三个步骤：&lt;br&gt;	   - checkout：将代码仓库从 Github 上下载到本地&lt;br&gt;	   - set up python：安装 python 3.8 版本&lt;br&gt;	   - install dependencies：安装项目所需的所有依赖包&lt;br&gt;	6. 如果缓存中没有依赖，才会继续执行后续步骤&lt;br&gt;	7. 如果环境变量中的 TYPE 是 apple_health，则执行同步 Apple Health 数据的脚本&lt;br&gt;	8. 完成同步后，将生成的新 poster 推送到 Github 仓库中去。&lt;/p&gt;
&lt;h3 id=&quot;获取workflow-id-获取workflow-id&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#获取workflow-id-获取workflow-id&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;获取workflow id 获取workflow id&lt;/h3&gt;
&lt;p&gt;我们可以通过以下命令获取workflow id：&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;shell&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-bash&quot;&gt;curl https://api.github.com/repos/{用户名}/{仓库名}/actions/workflows -H &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;Authorization: token d8xxxxxxxxxx&amp;quot;&lt;/span&gt; &lt;span class=&quot;hljs-comment&quot;&gt;# change to your config&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;上面的token后的token就是第一步获取的token。&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/whrsss/pic-sync/master/img/20230531155227.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;h2 id=&quot;创建快捷指令&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#创建快捷指令&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;创建快捷指令&lt;/h2&gt;
&lt;p&gt;你可以下载大佬已经创建好的&lt;a href=&quot;https://www.icloud.com/shortcuts/6ab6047b459c41ad822ad6b94b1c03d4&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;快捷指令&lt;/a&gt;，然后修改以下部分即可：&lt;br&gt;&lt;img src=&quot;https://raw.githubusercontent.com/whrsss/pic-sync/master/img/20230603095830.png&quot; alt=&quot;&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;h2 id=&quot;设置自动化&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#设置自动化&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;设置自动化&lt;/h2&gt;
&lt;p&gt;最后，我们需要设置快捷指令的自动触发条件。我选择的是每天结束时进行同步： &lt;img src=&quot;https://raw.githubusercontent.com/whrsss/pic-sync/master/img/54781685519843_.pic.jpg&quot; alt=&quot;54781685519843_.pic.jpg&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;h2 id=&quot;结束语&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#结束语&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;结束语&lt;/h2&gt;
&lt;p&gt;希望这篇文章对你有所帮助。如果你试过这个项目，我很乐意听到你的反馈和经验。如果你有任何问题或建议，也欢迎在下面的评论中提出。&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>【Gorm】Save 方法更新踩坑记录</title>
    <link href="https://blog.whrss.com/posts/gorm-save-issue"/>
    <id>https://blog.whrss.com/posts/gorm-save-issue</id>
    <published>2023-06-03T08:53:55.000Z</published>
    <updated>2023-06-03T08:53:55.000Z</updated>
    <category term="技术"/>
    <category term="go"/>
    <category term="gorm"/>
    <summary>在我最近使用Gorm进行字段更新的过程中，我遇到了一个问题。当我尝试更新status字段时，即使该字段的值没有发生变化，Gorm还是提示我“Duplicate entry &#39;xxxx&#39; for key &#39;PRIMARY&#39;”。</summary>
    <content type="html">&lt;p&gt;在我最近使用Gorm进行字段更新的过程中，我遇到了一个问题。当我尝试更新status字段时，即使该字段的值没有发生变化，Gorm还是提示我“Duplicate entry ‘xxxx’ for key ‘PRIMARY’”。&lt;/p&gt;
&lt;p&gt;首先，让我们看看Gorm的官方文档对&lt;code&gt;Save&lt;/code&gt;方法的描述：&lt;/p&gt;
&lt;p&gt;&lt;code&gt;Save&lt;/code&gt;方法会保存所有的字段，即使字段是零值。&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;db.First(&amp;amp;user)  

user.Name = &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;jinzhu 2&amp;quot;&lt;/span&gt;  
user.Age = &lt;span class=&quot;hljs-number&quot;&gt;100&lt;/span&gt;  
db.Save(&amp;amp;user)  
&lt;span class=&quot;hljs-comment&quot;&gt;// UPDATE users SET name=&amp;#x27;jinzhu 2&amp;#x27;, age=100, birthday=&amp;#x27;2016-01-01&amp;#x27;, updated_at = &amp;#x27;2013-11-17 21:34:10&amp;#x27; WHERE id=111;  &lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;&lt;code&gt;Save&lt;/code&gt;方法是一个复合函数。如果保存的数据不包含主键，它将执行&lt;code&gt;Create&lt;/code&gt;。反之，如果保存的数据包含主键，它将执行&lt;code&gt;Update&lt;/code&gt;（带有所有字段）。&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;db.Save(&amp;amp;User{Name: &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;jinzhu&amp;quot;&lt;/span&gt;, Age: &lt;span class=&quot;hljs-number&quot;&gt;100&lt;/span&gt;})  
&lt;span class=&quot;hljs-comment&quot;&gt;// INSERT INTO `users` (`name`,`age`,`birthday`,`update_at`) VALUES (&amp;quot;jinzhu&amp;quot;,100,&amp;quot;0000-00-00 00:00:00&amp;quot;,&amp;quot;0000-00-00 00:00:00&amp;quot;)  &lt;/span&gt;

db.Save(&amp;amp;User{ID: &lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;, Name: &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;jinzhu&amp;quot;&lt;/span&gt;, Age: &lt;span class=&quot;hljs-number&quot;&gt;100&lt;/span&gt;})  
&lt;span class=&quot;hljs-comment&quot;&gt;// UPDATE `users` SET `name`=&amp;quot;jinzhu&amp;quot;,`age`=100,`birthday`=&amp;quot;0000-00-00 00:00:00&amp;quot;,`update_at`=&amp;quot;0000-00-00 00:00:00&amp;quot; WHERE `id` = 1  &lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;根据这个描述，我预期的行为应该是更新操作，因为我提供了ID字段。然而，实际发生的却是插入操作。这让我感到困惑。&lt;/p&gt;
&lt;p&gt;为了理解这个问题，我深入阅读了Gorm的源码：&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;// Save updates value in database. If value doesn&amp;#x27;t contain a matching primary key, value is inserted.func (db *DB) Save(value interface{}) (tx *DB) {  &lt;/span&gt;
tx = db.getInstance()  
tx.Statement.Dest = value  
  
reflectValue := reflect.Indirect(reflect.ValueOf(value))  
&lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; reflectValue.Kind() == reflect.Ptr || reflectValue.Kind() == reflect.Interface {  
reflectValue = reflect.Indirect(reflectValue)  
}  
  
&lt;span class=&quot;hljs-keyword&quot;&gt;switch&lt;/span&gt; reflectValue.Kind() {  
&lt;span class=&quot;hljs-keyword&quot;&gt;case&lt;/span&gt; reflect.Slice, reflect.Array:  
&lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; _, ok := tx.Statement.Clauses[&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;ON CONFLICT&amp;quot;&lt;/span&gt;]; !ok {  
tx = tx.Clauses(clause.OnConflict{UpdateAll: &lt;span class=&quot;hljs-literal&quot;&gt;true&lt;/span&gt;})  
}  
tx = tx.callbacks.Create().Execute(tx.Set(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;gorm:update_track_time&amp;quot;&lt;/span&gt;, &lt;span class=&quot;hljs-literal&quot;&gt;true&lt;/span&gt;))  
&lt;span class=&quot;hljs-keyword&quot;&gt;case&lt;/span&gt; reflect.Struct:  
&lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; err := tx.Statement.Parse(value); err == &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt; &amp;amp;&amp;amp; tx.Statement.Schema != &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt; {  
&lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; _, pf := &lt;span class=&quot;hljs-keyword&quot;&gt;range&lt;/span&gt; tx.Statement.Schema.PrimaryFields {  
&lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; _, isZero := pf.ValueOf(tx.Statement.Context, reflectValue); isZero {  
&lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; tx.callbacks.Create().Execute(tx)  
}  
}  
}  
  
&lt;span class=&quot;hljs-keyword&quot;&gt;fallthrough&lt;/span&gt;  
&lt;span class=&quot;hljs-keyword&quot;&gt;default&lt;/span&gt;:  
selectedUpdate := &lt;span class=&quot;hljs-built_in&quot;&gt;len&lt;/span&gt;(tx.Statement.Selects) != &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt;  
&lt;span class=&quot;hljs-comment&quot;&gt;// when updating, use all fields including those zero-value fields  &lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; !selectedUpdate {  
tx.Statement.Selects = &lt;span class=&quot;hljs-built_in&quot;&gt;append&lt;/span&gt;(tx.Statement.Selects, &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;*&amp;quot;&lt;/span&gt;)  
}  
  
updateTx := tx.callbacks.Update().Execute(tx.Session(&amp;amp;Session{Initialized: &lt;span class=&quot;hljs-literal&quot;&gt;true&lt;/span&gt;}))  
  
&lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; updateTx.Error == &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt; &amp;amp;&amp;amp; updateTx.RowsAffected == &lt;span class=&quot;hljs-number&quot;&gt;0&lt;/span&gt; &amp;amp;&amp;amp; !updateTx.DryRun &amp;amp;&amp;amp; !selectedUpdate {  
&lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; tx.Create(value)  
}  
  
&lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; updateTx  
}  
  
&lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt;  
}&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;源码的主要逻辑如下：&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;获取数据库实例并准备执行SQL语句。&lt;code&gt;value&lt;/code&gt;是要操作的数据。&lt;/li&gt;
&lt;li&gt;利用反射机制确定&lt;code&gt;value&lt;/code&gt;的类型。&lt;/li&gt;
&lt;li&gt;如果&lt;code&gt;value&lt;/code&gt;是Slice或Array，并且没有定义冲突解决策略（”ON CONFLICT”），那么设置更新所有冲突字段的冲突解决策略，并执行插入操作。&lt;/li&gt;
&lt;li&gt;如果&lt;code&gt;value&lt;/code&gt;是一个Struct，那么会尝试解析这个结构体，然后遍历它的主键字段。如果主键字段是零值，则执行插入操作。&lt;/li&gt;
&lt;li&gt;对于除Slice、Array、Struct以外的类型，将尝试执行更新操作。如果在更新操作后，没有任何行受到影响，并且没有选择特定的字段进行更新，则执行插入操作。&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;从这个函数我们可以看出，当传入的&lt;code&gt;value&lt;/code&gt;对应的数据库记录不存在时（根据主键判断），Gorm会尝试创建一个新的记录。如果更新操作不影响任何行，Gorm同样会尝试创建一个新的记录。&lt;/p&gt;
&lt;p&gt;这个行为与我们通常理解的“upsert”（update + insert）逻辑略有不同。在这种情况下，即使更新的数据与数据库中的数据完全相同，Gorm还是会尝试进行插入操作。这就是为什么我会看到&lt;code&gt;Duplicate entry &#39;xxxx&#39; for key &#39;PRIMARY&#39;&lt;/code&gt;的错误，因为这就是主键冲突的错误提示。&lt;/p&gt;
&lt;p&gt;对于Gorm的这种行为我感到困惑，同时我也对官方文档的描述感到失望，因为它并没有提供这部分的信息。&lt;/p&gt;
&lt;p&gt;如何解决这个问题呢？&lt;/p&gt;
&lt;p&gt;我们可以自己实现一个Save方法，利用GORM的Create方法和冲突解决策略：&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;// Update all columns to new value on conflict except primary keys and those columns having default values from sql func  &lt;/span&gt;
db.Clauses(clause.OnConflict{  
  UpdateAll: &lt;span class=&quot;hljs-literal&quot;&gt;true&lt;/span&gt;,  
}).Create(&amp;amp;users)  
&lt;span class=&quot;hljs-comment&quot;&gt;// INSERT INTO &amp;quot;users&amp;quot; *** ON CONFLICT (&amp;quot;id&amp;quot;) DO UPDATE SET &amp;quot;name&amp;quot;=&amp;quot;excluded&amp;quot;.&amp;quot;name&amp;quot;, &amp;quot;age&amp;quot;=&amp;quot;excluded&amp;quot;.&amp;quot;age&amp;quot;, ...;  &lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;// INSERT INTO `users` *** ON DUPLICATE KEY UPDATE `name`=VALUES(name),`age`=VALUES(age), ...; MySQL&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;在Gorm的Create方法的文档中，我们可以看到这种用法。如果提供了ID，它会更新其他所有的字段。如果没有提供ID，它会插入新的记录。&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;经热心老哥提醒，当使用 &lt;code&gt;INSERT ... ON DUPLICATE KEY UPDATE&lt;/code&gt; 语句时，如果插入的行因为唯一索引或主键冲突而失败，MySQL 会执行更新操作。这种情况下，会涉及到锁的问题，如果多个事务同时试图对同一行进行 &lt;code&gt;INSERT ... ON DUPLICATE KEY UPDATE&lt;/code&gt; 操作，可能会引起死锁，尤其是在复杂的查询和多表操作中。死锁发生时，MySQL 会自动检测并回滚其中一个事务来解决死锁。频繁使用这种语句在高并发场景下可能会对性能造成影响，因为每次冲突都需要进行额外的更新操作，并且涉及到锁的管理。&lt;/p&gt;
&lt;p&gt;所以，如果你的业务涉及复杂和并发的业务场景，可以尝试手动在应用层进行检测冲突，避免数据库的冲突和锁的竞争。&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>一次线上异常的追踪与处理</title>
    <link href="https://blog.whrss.com/posts/exception-tracking"/>
    <id>https://blog.whrss.com/posts/exception-tracking</id>
    <published>2023-06-02T11:24:29.000Z</published>
    <updated>2023-06-02T11:24:29.000Z</updated>
    <category term="技术"/>
    <category term="exception"/>
    <summary>5月31日晚，我们接到游戏玩家反馈，经常出现请求超时的提示。在我亲自登录游戏验证后，也出现了相同的错误，但游戏仍然可以正常运行，数据也没有任何问题。
经过客户端的错误检查，我们发现请求出现了`408 Request Timeout`的错误。该响应状态码意味着服务器打算关闭没有在使用的连接，即使客户端没有发送任何请求，一些服务器仍会在空闲连接上发送此信息。服务器决定关闭连接，而不是继续等待。</summary>
    <content type="html">&lt;h1 id=&quot;一次线上异常的追踪与处理&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#一次线上异常的追踪与处理&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;一次线上异常的追踪与处理&lt;/h1&gt;
&lt;p&gt;5月31日晚，我们接到游戏玩家反馈，经常出现请求超时的提示。在我亲自登录游戏验证后，也出现了相同的错误，但游戏仍然可以正常运行，数据也没有任何问题。&lt;/p&gt;
&lt;p&gt;经过客户端的错误检查，我们发现请求出现了&lt;code&gt;408 Request Timeout&lt;/code&gt;的错误。该响应状态码意味着服务器打算关闭没有在使用的连接，即使客户端没有发送任何请求，一些服务器仍会在空闲连接上发送此信息。服务器决定关闭连接，而不是继续等待。&lt;/p&gt;
&lt;h2 id=&quot;1-日志检查&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#1-日志检查&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;1. 日志检查&lt;/h2&gt;
&lt;p&gt;接下来，我查看了服务器的日志，发现后台的两个服务的日志都在正常运行，没有异常提示。当我进行pod查看时，发现有两个pod显示容器没有日志，这两个pod已经挂掉。&lt;/p&gt;
&lt;p&gt;为什么这两个pod会宕机呢？我开始回溯近1小时的日志，发现在晚上10点左右，出现了JDBC连接异常。&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;sh&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-bash&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;### Error querying database. Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is java.sql.SQLTransientConnectionException: HikariPool-1 - Connection is not available, request timed out after 31363ms.&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;通过Google查询，我了解到这种错误是由于Spring Boot的默认连接池HikariPool在连接排队阻塞，无法获取连接，最后导致超时。在数据库错误之后的一段时间内，出现了Java内存异常。&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;json&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-json&quot;&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;@timestamp&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;2023-05-31 22:18:24.382&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;level&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;ERROR&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;source&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;className&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;org.apache.juli.logging.DirectJDKLog&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;methodName&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;log&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;line&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;hljs-number&quot;&gt;175&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;message&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Handler dispatch failed; nested exception is java.lang.OutOfMemoryError: Java heap space] with root cause&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;error.type&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;java.lang.OutOfMemoryError&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;error.message&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;Java heap space&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;error.stack_trace&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;java.lang.OutOfMemoryError: Java heap space\n&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;由于我们没有设置连接池上限（默认最大为10），当获取连接阻塞后，请求排队，最终导致内存溢出。最后，由于内存溢出，pod触发&lt;code&gt;java.io.IOException: Broken pipe&lt;/code&gt;错误，即管道断开，服务宕机。&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;json&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-json&quot;&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;@timestamp&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;2023-05-31 22:18:24.393&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;level&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;WARN&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;source&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;className&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;methodName&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;logException&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;line&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;hljs-number&quot;&gt;199&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;hljs-attr&quot;&gt;&amp;quot;message&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;Resolved [org.springframework.web.util.NestedServletException: Handler dispatch failed; nested exception is java.lang.OutOfMemoryError: Java heap space]&amp;quot;&lt;/span&gt;&lt;span class=&quot;hljs-punctuation&quot;&gt;}&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;h2 id=&quot;2-增加连接池大小&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#2-增加连接池大小&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;2. 增加连接池大小&lt;/h2&gt;
&lt;p&gt;Hikari是Spring Boot自带的连接池，默认最大只有10个。因此，我的第一步解决方案是增加这个服务的连接池大小。在服务的yaml数据库连接配置中增加了一些参数。 &lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;yml&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-yaml&quot;&gt;  &lt;span class=&quot;hljs-attr&quot;&gt;datasource:&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;url:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;jdbc:mysql://rm-2xxxxxx&amp;#x27;&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;username:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;xx&amp;#x27;&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;password:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;xxx&amp;#x27;&lt;/span&gt;
    &lt;span class=&quot;hljs-comment&quot;&gt;# 下面这些????&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;type:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;com.zaxxer.hikari.HikariDataSource&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;driver-class-name:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;com.mysql.cj.jdbc.Driver&lt;/span&gt;
    &lt;span class=&quot;hljs-attr&quot;&gt;hikari:&lt;/span&gt;
      &lt;span class=&quot;hljs-comment&quot;&gt;#连接池名&lt;/span&gt;
      &lt;span class=&quot;hljs-attr&quot;&gt;pool-name:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;DateHikariCP&lt;/span&gt;
      &lt;span class=&quot;hljs-comment&quot;&gt;#最小空闲连接数&lt;/span&gt;
      &lt;span class=&quot;hljs-attr&quot;&gt;minimum-idle:&lt;/span&gt; &lt;span class=&quot;hljs-number&quot;&gt;10&lt;/span&gt;
      &lt;span class=&quot;hljs-comment&quot;&gt;# 空闲连接存活最大时间，默认600000（10分钟）&lt;/span&gt;
      &lt;span class=&quot;hljs-attr&quot;&gt;idle-timeout:&lt;/span&gt; &lt;span class=&quot;hljs-number&quot;&gt;180000&lt;/span&gt;
      &lt;span class=&quot;hljs-comment&quot;&gt;# 连接池最大连接数，默认是10&lt;/span&gt;
      &lt;span class=&quot;hljs-attr&quot;&gt;maximum-pool-size:&lt;/span&gt; &lt;span class=&quot;hljs-number&quot;&gt;100&lt;/span&gt;
      &lt;span class=&quot;hljs-comment&quot;&gt;# 此属性控制从池返回的连接的默认自动提交行为,默认值：true&lt;/span&gt;
      &lt;span class=&quot;hljs-attr&quot;&gt;auto-commit:&lt;/span&gt; &lt;span class=&quot;hljs-literal&quot;&gt;true&lt;/span&gt;
      &lt;span class=&quot;hljs-comment&quot;&gt;# 此属性控制池中连接的最长生命周期，值0表示无限生命周期，默认1800000即30分钟&lt;/span&gt;
      &lt;span class=&quot;hljs-attr&quot;&gt;max-lifetime:&lt;/span&gt; &lt;span class=&quot;hljs-number&quot;&gt;1800000&lt;/span&gt;
      &lt;span class=&quot;hljs-comment&quot;&gt;# 数据库连接超时时间,默认30秒，即30000&lt;/span&gt;
      &lt;span class=&quot;hljs-attr&quot;&gt;connection-timeout:&lt;/span&gt; &lt;span class=&quot;hljs-number&quot;&gt;30000&lt;/span&gt;
      &lt;span class=&quot;hljs-attr&quot;&gt;connection-test-query:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;SELECT&lt;/span&gt; &lt;span class=&quot;hljs-number&quot;&gt;1&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;h2 id=&quot;3-性能优化&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#3-性能优化&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;3. 性能优化&lt;/h2&gt;
&lt;p&gt;尽管从表面上看，问题是由于连接池数量太少，导致连接请求阻塞。但深层的原因是服务对数据库的请求处理过慢，最后导致阻塞。如果请求数量继续增加，即使扩大了连接池，同样会阻塞连接。这就像滴滴打车，碰到下雨天儿，队一旦开始排，后面就不知道要排多久了。&lt;/p&gt;
&lt;p&gt;这个数据库存储了大量的数据，其中聊天记录的存储主要占用了性能。我们在处理聊天记录时做了分表处理。但由于数据量过大，单表依然有近两千万的数据。这张大表有一个联合索引，索引数据量较大。每次更新都需要维护索引空间，每次单个玩家数据量到达限值，就会进行局部清理。&lt;/p&gt;
&lt;p&gt;这里的数据插入动作可能消耗时间较长。由于对消息的可靠性要求不高，我们可以使用异步进行，这样在等待插入的过程中可以省去大量的请求连接占用资源。&lt;/p&gt;
&lt;p&gt;我们优化了消息保存数量。以前，每个玩家保存900条消息，但一般只查询最近的300条。现在，每500条进行一次清理，清理至300条，以节省空间。&lt;/p&gt;
&lt;p&gt;即使数据量节省了很多，但由于业务价值相对成本比例因素，与业务部门进行沟通，将业务的容忍度定为定期3个月。&lt;/p&gt;
&lt;h2 id=&quot;4-空间优化&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#4-空间优化&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;4. 空间优化&lt;/h2&gt;
&lt;p&gt;查询表空间占用：&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;sql&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sql&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;-- 查询库中每个表的空间占用，分项列出 &lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;select&lt;/span&gt;   table_schema &lt;span class=&quot;hljs-keyword&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;数据库&amp;#x27;&lt;/span&gt;,   table_name &lt;span class=&quot;hljs-keyword&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;表名&amp;#x27;&lt;/span&gt;,   table_rows &lt;span class=&quot;hljs-keyword&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;记录数&amp;#x27;&lt;/span&gt;,   &lt;span class=&quot;hljs-keyword&quot;&gt;truncate&lt;/span&gt;(data_length&lt;span class=&quot;hljs-operator&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;hljs-number&quot;&gt;1024&lt;/span&gt;&lt;span class=&quot;hljs-operator&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;hljs-number&quot;&gt;1024&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;) &lt;span class=&quot;hljs-keyword&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;数据容量(MB)&amp;#x27;&lt;/span&gt;,   &lt;span class=&quot;hljs-keyword&quot;&gt;truncate&lt;/span&gt;(index_length&lt;span class=&quot;hljs-operator&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;hljs-number&quot;&gt;1024&lt;/span&gt;&lt;span class=&quot;hljs-operator&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;hljs-number&quot;&gt;1024&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;) &lt;span class=&quot;hljs-keyword&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;索引容量(MB)&amp;#x27;&lt;/span&gt;   
&lt;span class=&quot;hljs-keyword&quot;&gt;from&lt;/span&gt; information_schema.tables   
&lt;span class=&quot;hljs-keyword&quot;&gt;where&lt;/span&gt; table_schema&lt;span class=&quot;hljs-operator&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;表名&amp;#x27;&lt;/span&gt;   
&lt;span class=&quot;hljs-keyword&quot;&gt;order&lt;/span&gt; &lt;span class=&quot;hljs-keyword&quot;&gt;by&lt;/span&gt; data_length &lt;span class=&quot;hljs-keyword&quot;&gt;desc&lt;/span&gt;, index_length &lt;span class=&quot;hljs-keyword&quot;&gt;desc&lt;/span&gt;;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;对经常有删除操作的数据表进行碎片清理：&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;sql&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-sql&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;alter table&lt;/span&gt; 表名 engine&lt;span class=&quot;hljs-operator&quot;&gt;=&lt;/span&gt;innodb;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;经过清理，可以看到表空间占用缩小了40%左右。加上之前的业务修改，数据量又有了明显的缩减，使得数据库到了MySQL的舒适区，单表在500万左右。&lt;/p&gt;
&lt;h2 id=&quot;5-相关经验&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#5-相关经验&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;5. 相关经验&lt;/h2&gt;
&lt;p&gt;以前我们有一个Go服务有非常大的IO，偶尔会出现崩溃，日志也是提示:”write tcp IP: xxx-&amp;gt; IP:xxx write: broken pipe”。开始以为是服务器在上传到OSS的过程中出现的连接异常，后来和阿里确认了并非OSS的断开错误。经过多次排查，最后发现在上传文件前，对内容进行了json序列化，这个过程非常费性能。当请求过多时，就发生了阻塞，阻塞过多，内存占用过大，溢出，服务就会拒绝服务。此时，连接的管道就会强行断开。&lt;/p&gt;
&lt;p&gt;在很多业务场景中，都会出现这种情况：当计算资源不足时，请求就会阻塞堆积，最后最先崩溃的总是内存。&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Go 单元测试高效实践</title>
    <link href="https://blog.whrss.com/posts/go-test"/>
    <id>https://blog.whrss.com/posts/go-test</id>
    <published>2023-04-21T10:27:10.000Z</published>
    <updated>2023-04-21T10:27:10.000Z</updated>
    <category term="技术"/>
    <category term="Go"/>
    <category term="UnitTesting"/>
    <category term="SDM"/>
    <category term="XP"/>
    <summary>敏捷开发中有一个广为人知的开发方法就是 XP（极限编程），XP 提倡测试先行，为了将以后出现 bug 的几率降到最低，这一点与近些年流行的 TDD（测试驱动开发）有异曲同工之处。
在最开始做编程时，我总是忽略单元测试在代码中的作用，觉得编写单元测试的功夫都赶上甚至超越业务程序了。到后来，业务量越来越复杂，慢慢地，浮现一个问题，就是系统对于测试人员是一个黑盒，简单的测试无法保证系统所设计的东西都可以测试到。</summary>
    <content type="html">&lt;p&gt;敏捷开发中有一个广为人知的开发方法就是 XP（极限编程），XP 提倡测试先行，为了将以后出现 bug 的几率降到最低，这一点与近些年流行的 TDD（测试驱动开发）有异曲同工之处。&lt;/p&gt;
&lt;p&gt;在最开始做编程时，我总是忽略单元测试在代码中的作用，觉得编写单元测试的功夫都赶上甚至超越业务程序了。到后来，业务量越来越复杂，慢慢地，浮现一个问题，就是系统对于测试人员是一个黑盒，简单的测试无法保证系统所设计的东西都可以测试到⬇️&lt;br&gt;	举两个最简单的例子：&lt;br&gt;	系统设计的数据打点，是无法从功能业务上测试出来的，而对于测试人员，可能由于版本差异，用例未覆盖。&lt;br&gt;	如果一个表中有两个字段，新用户过来更新一个字段之后，测另一个字段的功能时就不再以一个新用户的身份操作了。&lt;br&gt;	在这样的情况下，如果开发人员没有对系统做完全的检查，就很可能出现问题。&lt;br&gt;就以上情况看，需要从开发人员的维度，对功能做一个“预期”测试，一个功能走过，应该输入什么，输出什么，哪些数据变动了，变动是否符合预期等等。&lt;/p&gt;
&lt;p&gt;最近，公司业务基本都转入了 Go 做开发，在 Go 的整个业务处理上也日渐完善，而 Go 的单元测试用起来也十分顺手，所以做个小的总结。&lt;/p&gt;
&lt;h2 id=&quot;一-mock-db&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#一-mock-db&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;一. Mock DB&lt;/h2&gt;
&lt;p&gt;在单元测试中，很重要的一项就是数据库的 Mock，数据库要在每次单元测试时作为一个干净的初始状态，并且每次运行速度不能太慢。&lt;/p&gt;
&lt;h4 id=&quot;1-mysql-的-mock&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#1-mysql-的-mock&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;1. Mysql 的 Mock&lt;/h4&gt;
&lt;p&gt;这里使用到的是 github.com/dolthub/go-mysql-server 借鉴了这位大哥的方法 &lt;a href=&quot;https://juejin.cn/post/7131661977310461965&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;如何针对 MySQL 进行 Fake 测试&lt;/a&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;h6 id=&quot;db-的初始化&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#db-的初始化&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;DB 的初始化&lt;/h6&gt;
在 db 目录下&lt;/li&gt;
&lt;/ul&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;type&lt;/span&gt; Config &lt;span class=&quot;hljs-keyword&quot;&gt;struct&lt;/span&gt; {
   DSN             &lt;span class=&quot;hljs-type&quot;&gt;string&lt;/span&gt; &lt;span class=&quot;hljs-comment&quot;&gt;// write data source name.&lt;/span&gt;
   MaxOpenConn     &lt;span class=&quot;hljs-type&quot;&gt;int&lt;/span&gt;    &lt;span class=&quot;hljs-comment&quot;&gt;// open pool&lt;/span&gt;
   MaxIdleConn     &lt;span class=&quot;hljs-type&quot;&gt;int&lt;/span&gt;    &lt;span class=&quot;hljs-comment&quot;&gt;// idle pool&lt;/span&gt;
   ConnMaxLifeTime &lt;span class=&quot;hljs-type&quot;&gt;int&lt;/span&gt;
}

&lt;span class=&quot;hljs-keyword&quot;&gt;var&lt;/span&gt; DB *gorm.DB

&lt;span class=&quot;hljs-comment&quot;&gt;// InitDbConfig 初始化Db&lt;/span&gt;
&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;InitDbConfig&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;(c *conf.Data)&lt;/span&gt;&lt;/span&gt; {
   log.Info(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;Initializing Mysql&amp;quot;&lt;/span&gt;)
   &lt;span class=&quot;hljs-keyword&quot;&gt;var&lt;/span&gt; err &lt;span class=&quot;hljs-type&quot;&gt;error&lt;/span&gt;
   dsn := c.Database.Dsn
   maxIdleConns := c.Database.MaxIdleConn
   maxOpenConns := c.Database.MaxOpenConn
   connMaxLifetime := c.Database.ConnMaxLifeTime
   &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; DB, err = gorm.Open(mysql.Open(dsn), &amp;amp;gorm.Config{
      QueryFields: &lt;span class=&quot;hljs-literal&quot;&gt;true&lt;/span&gt;,
      NamingStrategy: schema.NamingStrategy{
         &lt;span class=&quot;hljs-comment&quot;&gt;//TablePrefix:   &amp;quot;&amp;quot;,   // 表名前缀&lt;/span&gt;
         SingularTable: &lt;span class=&quot;hljs-literal&quot;&gt;true&lt;/span&gt;, &lt;span class=&quot;hljs-comment&quot;&gt;// 使用单数表名&lt;/span&gt;
      },
   }); err != &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt; {
      &lt;span class=&quot;hljs-built_in&quot;&gt;panic&lt;/span&gt;(fmt.Errorf(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;初始化数据库失败: %s \n&amp;quot;&lt;/span&gt;, err))
   }
   sqlDB, err := DB.DB()
   &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; sqlDB != &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt; {
      sqlDB.SetMaxIdleConns(&lt;span class=&quot;hljs-type&quot;&gt;int&lt;/span&gt;(maxIdleConns))                               &lt;span class=&quot;hljs-comment&quot;&gt;// 空闲连接数&lt;/span&gt;
      sqlDB.SetMaxOpenConns(&lt;span class=&quot;hljs-type&quot;&gt;int&lt;/span&gt;(maxOpenConns))                               &lt;span class=&quot;hljs-comment&quot;&gt;// 最大连接数&lt;/span&gt;
      sqlDB.SetConnMaxLifetime(time.Second * time.Duration(connMaxLifetime)) &lt;span class=&quot;hljs-comment&quot;&gt;// 单位：秒&lt;/span&gt;
   }
   log.Info(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;Mysql: initialization completed&amp;quot;&lt;/span&gt;)
}&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;ul&gt;
&lt;li&gt;&lt;h6 id=&quot;fake-mysql-的初始化和注入&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#fake-mysql-的初始化和注入&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;fake-mysql 的初始化和注入&lt;/h6&gt;
在 fake_mysql 目录下&lt;/li&gt;
&lt;/ul&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;var&lt;/span&gt; (
   dbName    = &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;mydb&amp;quot;&lt;/span&gt;
   tableName = &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;mytable&amp;quot;&lt;/span&gt;
   address   = &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;localhost&amp;quot;&lt;/span&gt;
   port      = &lt;span class=&quot;hljs-number&quot;&gt;3380&lt;/span&gt;
)

&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;InitFakeDb&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;()&lt;/span&gt;&lt;/span&gt; {
   &lt;span class=&quot;hljs-keyword&quot;&gt;go&lt;/span&gt; &lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;()&lt;/span&gt;&lt;/span&gt; {
      Start()
   }()
   db.InitDbConfig(&amp;amp;conf.Data{
      Database: &amp;amp;conf.Data_Database{
         Dsn:             &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;no_user:@tcp(localhost:3380)/mydb?timeout=2s&amp;amp;readTimeout=5s&amp;amp;writeTimeout=5s&amp;amp;parseTime=true&amp;amp;loc=Local&amp;amp;charset=utf8,utf8mb4&amp;quot;&lt;/span&gt;,
         ShowLog:         &lt;span class=&quot;hljs-literal&quot;&gt;true&lt;/span&gt;,
         MaxIdleConn:     &lt;span class=&quot;hljs-number&quot;&gt;10&lt;/span&gt;,
         MaxOpenConn:     &lt;span class=&quot;hljs-number&quot;&gt;60&lt;/span&gt;,
         ConnMaxLifeTime: &lt;span class=&quot;hljs-number&quot;&gt;4000&lt;/span&gt;,
      },
   })
   migrateTable()
}

&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;Start&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;()&lt;/span&gt;&lt;/span&gt; {
   engine := sqle.NewDefault(
      memory.NewMemoryDBProvider(
         createTestDatabase(),
         information_schema.NewInformationSchemaDatabase(),
      ))

   config := server.Config{
      Protocol: &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;tcp&amp;quot;&lt;/span&gt;,
      Address:  fmt.Sprintf(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;%s:%d&amp;quot;&lt;/span&gt;, address, port),
   }

   s, err := server.NewDefaultServer(config, engine)
   &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; err != &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt; {
      &lt;span class=&quot;hljs-built_in&quot;&gt;panic&lt;/span&gt;(err)
   }

   &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; err = s.Start(); err != &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt; {
      &lt;span class=&quot;hljs-built_in&quot;&gt;panic&lt;/span&gt;(err)
   }

}

&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;createTestDatabase&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;()&lt;/span&gt;&lt;/span&gt; *memory.Database {
   db := memory.NewDatabase(dbName)
   db.EnablePrimaryKeyIndexes()
   &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; db
}

&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;migrateTable&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;()&lt;/span&gt;&lt;/span&gt; {
&lt;span class=&quot;hljs-comment&quot;&gt;// 生成一个user表到fake mysql中&lt;/span&gt;
   err := db.DB.AutoMigrate(&amp;amp;model.User{})
   &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; err != &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt; {
      &lt;span class=&quot;hljs-built_in&quot;&gt;panic&lt;/span&gt;(err)
   }
}&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;在单元测试开始，调用  &lt;code&gt;InitFakeDb()&lt;/code&gt; 即可&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;setup&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;()&lt;/span&gt;&lt;/span&gt; {
   fake_mysql.InitFakeDb()
}&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;hr&gt;
&lt;h4 id=&quot;2-redis-的-mock&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#2-redis-的-mock&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;2. Redis 的 Mock&lt;/h4&gt;
&lt;p&gt;这里用到的是 &lt;a href=&quot;https://github.com/alicebob/miniredis&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;miniredis&lt;/a&gt; , 与之配套的Redis Client 是  &lt;code&gt;go-redis/redis/v8&lt;/code&gt; ，在这里调用 InitTestRedis() 注入即可&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;// RedisClient redis 客户端  &lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;var&lt;/span&gt; RedisClient *redis.Client  
  
&lt;span class=&quot;hljs-comment&quot;&gt;// ErrRedisNotFound not exist in redisconst ErrRedisNotFound = redis.Nil  &lt;/span&gt;
  
&lt;span class=&quot;hljs-comment&quot;&gt;// Config redis config&lt;/span&gt;
&lt;span class=&quot;hljs-keyword&quot;&gt;type&lt;/span&gt; Config &lt;span class=&quot;hljs-keyword&quot;&gt;struct&lt;/span&gt; {  
   Addr         &lt;span class=&quot;hljs-type&quot;&gt;string&lt;/span&gt;  
   Password     &lt;span class=&quot;hljs-type&quot;&gt;string&lt;/span&gt;  
   DB           &lt;span class=&quot;hljs-type&quot;&gt;int&lt;/span&gt;  
   MinIdleConn  &lt;span class=&quot;hljs-type&quot;&gt;int&lt;/span&gt;  
   DialTimeout  time.Duration  
   ReadTimeout  time.Duration  
   WriteTimeout time.Duration  
   PoolSize     &lt;span class=&quot;hljs-type&quot;&gt;int&lt;/span&gt;  
   PoolTimeout  time.Duration  
   &lt;span class=&quot;hljs-comment&quot;&gt;// tracing switch  &lt;/span&gt;
   EnableTrace &lt;span class=&quot;hljs-type&quot;&gt;bool&lt;/span&gt;  
}  
  
&lt;span class=&quot;hljs-comment&quot;&gt;// Init 实例化一个redis client  &lt;/span&gt;
&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;Init&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;(c *conf.Data)&lt;/span&gt;&lt;/span&gt; *redis.Client {  
   RedisClient = redis.NewClient(&amp;amp;redis.Options{  
      Addr:         c.Redis.Addr,  
      Password:     c.Redis.Password,  
      DB:           &lt;span class=&quot;hljs-type&quot;&gt;int&lt;/span&gt;(c.Redis.DB),  
      MinIdleConns: &lt;span class=&quot;hljs-type&quot;&gt;int&lt;/span&gt;(c.Redis.MinIdleConn),  
      DialTimeout:  c.Redis.DialTimeout.AsDuration(),  
      ReadTimeout:  c.Redis.ReadTimeout.AsDuration(),  
      WriteTimeout: c.Redis.WriteTimeout.AsDuration(),  
      PoolSize:     &lt;span class=&quot;hljs-type&quot;&gt;int&lt;/span&gt;(c.Redis.PoolSize),  
      PoolTimeout:  c.Redis.PoolTimeout.AsDuration(),  
   })  
  
   _, err := RedisClient.Ping(context.Background()).Result()  
   &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; err != &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt; {  
      &lt;span class=&quot;hljs-built_in&quot;&gt;panic&lt;/span&gt;(err)  
   }  
  
   &lt;span class=&quot;hljs-comment&quot;&gt;// hook tracing (using open telemetry)  &lt;/span&gt;
   &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; c.Redis.IsTrace {  
      RedisClient.AddHook(redisotel.NewTracingHook())  
   }  
  
   &lt;span class=&quot;hljs-keyword&quot;&gt;return&lt;/span&gt; RedisClient  
}  
  
&lt;span class=&quot;hljs-comment&quot;&gt;// InitTestRedis 实例化一个可以用于单元测试的redis  &lt;/span&gt;
&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;InitTestRedis&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;()&lt;/span&gt;&lt;/span&gt; {  
   mr, err := miniredis.Run()  
   &lt;span class=&quot;hljs-keyword&quot;&gt;if&lt;/span&gt; err != &lt;span class=&quot;hljs-literal&quot;&gt;nil&lt;/span&gt; {  
      &lt;span class=&quot;hljs-built_in&quot;&gt;panic&lt;/span&gt;(err)  
   }  
   &lt;span class=&quot;hljs-comment&quot;&gt;// 打开下面命令可以测试链接关闭的情况  &lt;/span&gt;
   &lt;span class=&quot;hljs-comment&quot;&gt;// defer mr.Close()  &lt;/span&gt;
  
   RedisClient = redis.NewClient(&amp;amp;redis.Options{  
      Addr: mr.Addr(),  
   })  
   fmt.Println(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;mini redis addr:&amp;quot;&lt;/span&gt;, mr.Addr())  
}&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;h2 id=&quot;二-单元测试&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#二-单元测试&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;二. 单元测试&lt;/h2&gt;
&lt;p&gt;经过对比，我选择了 &lt;a href=&quot;https://github.com/smartystreets/goconvey/wiki/Documentation&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;goconvey&lt;/a&gt; 这个单元测试框架&lt;br&gt;它比原生的go testing 好用很多。goconvey还提供了很多好用的功能：&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;li&gt;支持原生go test&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;使用&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;cmd&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-dos&quot;&gt;go get github.com/smartystreets/goconvey&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;TestLoverUsecase_DailyVisit&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;(t *testing.T)&lt;/span&gt;&lt;/span&gt; {  
   Convey(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;Test TestLoverUsecase_DailyVisit&amp;quot;&lt;/span&gt;, t, &lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;()&lt;/span&gt;&lt;/span&gt; {  
      &lt;span class=&quot;hljs-comment&quot;&gt;// clean  &lt;/span&gt;
      uc := NewLoverUsecase(log.DefaultLogger, &amp;amp;UsecaseManager{})  
  
      Convey(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;ok&amp;quot;&lt;/span&gt;, &lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;()&lt;/span&gt;&lt;/span&gt; {  
         &lt;span class=&quot;hljs-comment&quot;&gt;// execute  &lt;/span&gt;
         res1, err1 := uc.DailyVisit(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;user1&amp;quot;&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt;)  
         So(err1, ShouldBeNil)  
         So(res1, ShouldNotBeNil)  
         &lt;span class=&quot;hljs-comment&quot;&gt;// 第 n (&amp;gt;=2)次拜访，不应该有奖励，也不应该报错  &lt;/span&gt;
         res2, err2 := uc.DailyVisit(&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;user1&amp;quot;&lt;/span&gt;, &lt;span class=&quot;hljs-number&quot;&gt;3&lt;/span&gt;)  
         So(err2, ShouldBeNil)  
         So(res2, ShouldBeNil)  
      })  
   })  
}&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs&quot;&gt;可以看到，函数签名和 go 原生的 test 是一致的
测试中嵌套了两层 Convey，外层new了内层Convey所需的参数 
内层调用了函数，对返回值进行了断言&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;这里的断言也可以像这样对返回值进行比较 &lt;code&gt;So(x, ShouldEqual, 2)&lt;/code&gt;&lt;br&gt;或者判断长度等等 &lt;code&gt;So(len(resMap),ShouldEqual, 2)&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;Convey的嵌套也可以灵活多层，可以像一棵多叉树一样扩展，足够满足业务模拟。&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;三-testmain&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#三-testmain&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;三. TestMain&lt;/h2&gt;
&lt;p&gt;为所有的 case 加上一个 TestMain 作为统一入口&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;go&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-go&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;import&lt;/span&gt; (  
&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;os&amp;quot;&lt;/span&gt;  
&lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;testing&amp;quot;&lt;/span&gt;  
  
. &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;github.com/smartystreets/goconvey/convey&amp;quot;&lt;/span&gt;  
)  
  
&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;TestMain&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;(m *testing.M)&lt;/span&gt;&lt;/span&gt; {  
   setup()  
   code := m.Run()  
   teardown()  
   os.Exit(code)
}
&lt;span class=&quot;hljs-comment&quot;&gt;// 初始化fake db&lt;/span&gt;
&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;hljs-title&quot;&gt;setup&lt;/span&gt;&lt;span class=&quot;hljs-params&quot;&gt;()&lt;/span&gt;&lt;/span&gt; {  
   fake_mysql.InitFakeDb()  
   redis.InitTestRedis()
}&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
</content>
  </entry>
  <entry>
    <title>一个有趣且实用的开源项目，将网页打包成应用</title>
    <link href="https://blog.whrss.com/posts/pake"/>
    <id>https://blog.whrss.com/posts/pake</id>
    <published>2023-04-04T08:19:46.000Z</published>
    <updated>2023-04-04T08:19:46.000Z</updated>
    <category term="趣发现"/>
    <category term="github"/>
    <category term="开源项目"/>
    <summary>最近在GitHub上面发现了一个[很有趣的开源应用](https://github.com/tw93/Pake)，可以将网页打包成应用
底层使用了rust进行开发，支持 Mac、Windows 和 Linux。使用命令将网站直接打包成PC应用。</summary>
    <content type="html">&lt;p&gt;最近在GitHub上面发现了一个&lt;a href=&quot;https://github.com/tw93/Pake&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;很有趣的开源应用&lt;/a&gt;，可以将网页打包成应用：&lt;/p&gt;
&lt;p&gt;这里是&lt;a href=&quot;https://github.com/tw93/Pake/blob/master/bin/README_EN.md&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;它的使用文档&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;底层使用了rust进行开发，支持 Mac、Windows 和 Linux。使用命令将网站直接打包成应用。&lt;/p&gt;
&lt;p&gt;这里我以最近部署的一个私人 ChatGPT Next为例， 我的地址为 &lt;a href=&quot;https://gpt.whrss.com&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;https://gpt.whrss.com&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;需要本地先有一个node环境，能使用npm命令。&lt;/p&gt;
&lt;p&gt;然后npm全局安装这个工具&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;shell&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-bash&quot;&gt;npm install -g pake-cli&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;安装完之后，就可以使用&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;shell&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-bash&quot;&gt;pake url [OPTIONS]...&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;来生成桌面应用了，参数有很多，我先用了这些：&lt;br&gt;这是我的命令：&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;shell&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-bash&quot;&gt;pake https://gpt.whrss.com --name GPT  --icon /Users/wu/Downloads/gpt.icns --height 700 --width 900&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;blockquote&gt;
&lt;p&gt;这里我指定了网站的url : &lt;a href=&quot;https://gpt.whrss.com&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;https://gpt.whrss.com&lt;/a&gt;&lt;br&gt;指定了生成的应用包的名字：GPT&lt;br&gt;指定了应用的 icon&lt;br&gt;指定了应用打开初始化的高度和宽度&lt;/p&gt;
&lt;/blockquote&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs&quot;&gt;mac icon生成和获取的地方 ： https://macosicons.com/#/&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;然后我进行了运行，因为我的icon指定的目录是Downloads下面，所以它直接生成在了下面，默认是用户目录。&lt;br&gt;&lt;img src=&quot;https://raw.githubusercontent.com/whrsss/pic-sync/master/img/20230404161314.png&quot; alt=&quot;image.png&quot; loading=&quot;eager&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;如上图，生成的包体非常的小和轻量，只有不到3M。&lt;/p&gt;
&lt;p&gt;= 更新 =&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;sh&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-bash&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;# 查看npm安装的插件的版本&lt;/span&gt;
npm -g list
/usr/local/lib
├── xxx
├── npm@9.3.1
├── pake-cli@2.0.0-alpha7
├── xxxxxxx
└── xxxxxxx

&lt;span class=&quot;hljs-comment&quot;&gt;# 更新指定插件&lt;/span&gt;
npm -g update pake-cli 
&lt;span class=&quot;hljs-comment&quot;&gt;# 再次查看 &lt;/span&gt;
npm -g list&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;hr&gt;
&lt;p&gt;关于这个软件的应用，我想到的最多就是那些常用的，但没有pc客户端的应用，比如 Twitter、WeRead、Spotify 等等，我也是接触这个项目后第一时间就使用上了，体验很不错，比之前方便了不少。&lt;br&gt;&lt;img src=&quot;https://raw.githubusercontent.com/whrsss/pic-sync/master/img/20230404161605.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>GitHub Action 自动化部署简单尝试</title>
    <link href="https://blog.whrss.com/posts/github-action"/>
    <id>https://blog.whrss.com/posts/github-action</id>
    <published>2023-03-31T10:38:20.000Z</published>
    <updated>2023-03-31T10:38:20.000Z</updated>
    <category term="技术"/>
    <category term="CI/CD"/>
    <category term="workflow"/>
    <category term="健康"/>
    <summary>之前看到很多大佬的 Blog 是部署在 Github 上面的，但因为自己目前的博客是带后端的，所以就没有考虑。很久之前看到 @yihong 的心跳和跑步，感觉挺不错的，但因为自己没有跑步的习惯，就感觉不是很感冒 ???? 直到最近在听零机一动的时候，又听到了 yihong 的跑步， 我突然想到，我应该也可以把我的游泳 骑车 有氧也像 @yihong 的跑步数据一样上传过来。那么第一件事，我需要了解一下 GitHub Action 的机制，小小地尝试一下。</summary>
    <content type="html">&lt;p&gt;之前看到很多大佬的 Blog 是部署在 Github 上面的，但因为自己目前的博客是带后端的，所以就没有考虑。很久之前看到 @yihong 的心跳和跑步，感觉挺不错的，但因为自己没有跑步的习惯，就感觉不是很感冒 ???? 直到最近在听零机一动的时候，又听到了 yihong 的跑步， 我突然想到，我应该也可以把我的游泳 骑车 有氧也像 @yihong 的跑步数据一样上传过来。那么第一件事，我需要了解一下 GitHub Action 的机制，小小地尝试一下。&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;首先，先看下 github action 的基本功能，我是通过&lt;a href=&quot;https://www.ruanyifeng.com/blog/2019/09/getting-started-with-github-actions.html&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;阮一峰老师的文章&lt;/a&gt;了解的。&lt;/p&gt;
&lt;p&gt;GitHub Actions 是一种自动化工具，2019 年开始测试，同年 11 月上线。可以在 GitHub 上构建、测试和部署软件项目。它允许 Github 用户通过预定义或自定义的操作序列来自动化整个软件开发生命周期中的流程（过程很像 Dockerfile 或 Jenkinsfile 的构建），并且完全与 Github 集成。&lt;/p&gt;
&lt;p&gt;使用 GitHub Actions，你可以创建一个由事件触发或定期运行的工作流（workflow），其中包含一个或多个步骤（steps）。每个步骤都是一个特定任务的命令，例如编译代码、运行测试、打包发布版本等。你可以选择将这些步骤放在同一个工作流内，也可以将它们拆分为不同的工作流文件。&lt;/p&gt;
&lt;p&gt;此外，Github Action 还提供了各种操作 (actions)，可以让您轻松地执行常见的任务，如 Shell 脚本、推送 Docker 映像、调用 API 等等。 也有一些和捷径市场一样的分享社区，把自己编写的 action yml 分享给他人使用。&lt;/p&gt;
&lt;p&gt;GitHub Actions 使得整个开发过程变得更加高效方便，能够提升团队的交付速度。同时，近年来越来越多的开源社区也开始尝试在其上面构建 CI/CD 流水线。&lt;/p&gt;
&lt;p&gt;这里可能没有接触过的朋友可能会想，我是否可以在上面部署应用呢？&lt;br&gt;这里的 Action 的作用类似于 Jenkins，可以帮你打包编译，如果你是一个静态项目，那么作为静态仓库的 Github 仓库是可以直接部署的； 但是如果是动态的后端服务，需要 Cpu 的，就无法进行了。&lt;/p&gt;
&lt;hr&gt;
&lt;h4 id=&quot;第一步创建-github-token&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#第一步创建-github-token&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;第一步，创建 GitHub Token&lt;/h4&gt;
&lt;p&gt;头像 -&amp;gt; settings -&amp;gt; 左侧 Developer settings -&amp;gt; 左侧 Personal access tokens -&amp;gt; Tokens(classic)&lt;br&gt;-&amp;gt; Generate new token (classic)&lt;br&gt;赋予 workflow 的权限&lt;/p&gt;
&lt;h4 id=&quot;第二步-在目标仓库中创建-githubworkflows-目录&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#第二步-在目标仓库中创建-githubworkflows-目录&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;第二步： 在目标仓库中创建  &lt;code&gt;.github/workflows&lt;/code&gt;  目录&lt;/h4&gt;
&lt;p&gt;目录中创建一个 yml 文件 workflow-name.yml&lt;br&gt;按照 GitHub 文档进行 yml 编写，我这里先了解机制，所以直接 fork @yihong 的项目，&lt;/p&gt;
&lt;h4 id=&quot;第三步-action-设置&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#第三步-action-设置&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;第三步 Action 设置&lt;/h4&gt;
&lt;p&gt;在项目的 settings 中找到 actions 下的 general，向下划动&lt;br&gt;&lt;img src=&quot;https://raw.githubusercontent.com/whrsss/pic-sync/master/img/20230331160949.png&quot; alt=&quot;image.png&quot; loading=&quot;eager&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/whrsss/pic-sync/master/img/20230331161110.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;br&gt;找到工作流的读写权限，进行勾选。这样我们在触发 action 后，项目的 push 就有权限进行了。&lt;/p&gt;
&lt;h4 id=&quot;第四步触发这个-action&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#第四步触发这个-action&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;第四步，触发这个 Action&lt;/h4&gt;
&lt;p&gt;在手机上部署&lt;a href=&quot;https://www.icloud.com/shortcuts/6ab6047b459c41ad822ad6b94b1c03d4&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;这个捷径&lt;/a&gt;&lt;br&gt;Token 填写第一步获取到的Token&lt;br&gt;GitHub_Name 填写Github用户名&lt;br&gt;Action_ID 填写yml名字（workflow-name.yml就全部填上去）&lt;/p&gt;
&lt;p&gt;修改仓库名字和分支（图中的whrsss是我的仓库名字，master是我的分支名）&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/whrsss/pic-sync/master/img/20230331162133.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;修改完成后，点击快捷指令的运行。然后打开Github 仓库，点开 Action 栏，项目正在构建。点开可以查看构建日志。&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/whrsss/pic-sync/master/img/20230331162634.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>从零开始搭建家庭软路由系统（安装OpenWrt，并做为旁路由接入家庭网络）</title>
    <link href="https://blog.whrss.com/posts/soft-routes"/>
    <id>https://blog.whrss.com/posts/soft-routes</id>
    <published>2023-03-21T06:09:57.000Z</published>
    <updated>2023-03-21T06:09:57.000Z</updated>
    <category term="折腾"/>
    <category term="软路由"/>
    <category term="科学上网"/>
    <summary>之前刷推看到了不少人发软路由，最近又看到a姐发了一句：全推入手软路由了 开始我还觉得软路由对我的作用应该不大吧，随着从众心理的影响，我觉得我应该试试。 刚好我还有从笔记本上拆下的内存和固态，岂不是严丝合缝？</summary>
    <content type="html">&lt;p&gt;之前刷推看到了不少人发软路由，最近又看到a姐发了一句：全推入手软路由了&lt;br&gt;开始我还觉得软路由对我的作用应该不大吧，随着从众心理的影响，我觉得我应该试试。&lt;br&gt;刚好我还有从笔记本上拆下的内存和固态，岂不是严丝合缝？&lt;/p&gt;
&lt;p&gt;然后我就下单了一个&lt;img src=&quot;https://raw.githubusercontent.com/whrsss/pic-sync/master/img/50091679362219_.pic.jpg&quot; alt=&quot;50091679362219_.pic.jpg&quot; loading=&quot;eager&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;外观差不多是这个样子：&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/whrsss/pic-sync/master/img/50101679362338_.pic.jpg&quot; alt=&quot;50101679362338_.pic.jpg&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;br&gt;&lt;img src=&quot;https://raw.githubusercontent.com/whrsss/pic-sync/master/img/50111679362342_.pic.jpg&quot; alt=&quot;50111679362342_.pic.jpg&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;内部结构大概是这个样子：&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/whrsss/pic-sync/master/img/50121679362346_.pic.jpg&quot; alt=&quot;50121679362346_.pic.jpg&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;拥有5个网口、两个 USB 2.0 和两个 USB 3.0 口、HDMI、DP、存储卡位以及两个笔记本内存条槽位、一根 m.2 插槽和一个 SATA 接口，可以说五脏俱全。&lt;/p&gt;
&lt;p&gt;我买的是只带电源的，内存条和磁盘需要自己加。&lt;/p&gt;
&lt;h3 id=&quot;一第一步-组装机器&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#一第一步-组装机器&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;一、第一步 组装机器&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;打开机器背部的固定螺丝以及后盖，将内存条插入相应槽位&lt;/li&gt;
&lt;li&gt;接入 SATA 固态硬盘或 M.2 硬盘，不要装上后盖，以防有问题还需要再拆开。&lt;/li&gt;
&lt;li&gt;连接电源，此时路由器将自动开机&lt;/li&gt;
&lt;li&gt;开机后如果听到一声响，表示内存识别功能正常。如果听到三声响连续作响就表示出现了问题。我使用的两个内存条，分别在两个槽位上尝试，只有一根（金士顿的骇客神条2400）能在其中一个槽位上被识别。如果两个槽位都无法识别，就只能买同店的内存条了。&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/whrsss/pic-sync/master/img/50131679363062_.pic.jpg&quot; alt=&quot;50131679363062_.pic.jpg&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;接下来就是准备安装系统。&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;二-制作启动盘&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#二-制作启动盘&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;二、 制作启动盘&lt;/h3&gt;
&lt;p&gt;我选择的系统是 &lt;a href=&quot;https://openwrt.org/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;OpenWRT/LEDE&lt;/a&gt; 在国内的家庭软路由中有着非常高的占有率，拥有海量的软件，和非常强大的生态。同时，OpenWRT 的教程也很丰富详实。&lt;br&gt;这里我使用的是 &lt;a href=&quot;https://fw.koolcenter.com/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;KoolShare 固件&lt;/a&gt;，内置了非常强大的插件市场。&lt;/p&gt;
&lt;h5 id=&quot;1-下载efi&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#1-下载efi&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;1. 下载efi&lt;/h5&gt;
&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/whrsss/pic-sync/master/img/20230321095218.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;br&gt;&lt;img src=&quot;https://raw.githubusercontent.com/whrsss/pic-sync/master/img/20230321095327.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;找到最新版本进行下载。&lt;br&gt;&lt;img src=&quot;https://raw.githubusercontent.com/whrsss/pic-sync/master/img/20230321095417.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;h5 id=&quot;2-写盘&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#2-写盘&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;2. 写盘&lt;/h5&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs&quot;&gt;下载完成后，使用balenaetcher写盘工具进行写盘，
- 如果没有安装balenaEtcher，首先需要下载并安装。
- 插入你的U盘，并打开balenaEtcher。
- 点击“选择镜像”按钮，选择刚才下载的.gz文件。
- 点击“选择驱动器”按钮，选择你插入的U盘。
- 点击“写入”按钮，balenaEtcher将开始写入镜像文件到你的U盘。
- 等待写入过程完成，并在完成后安全地弹出。&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;h3 id=&quot;三-安装和设置&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#三-安装和设置&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;三、 安装和设置&lt;/h3&gt;
&lt;h5 id=&quot;1-安装&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#1-安装&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;1. 安装&lt;/h5&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs&quot;&gt;- 将写好的盘插入软路由，接一个显示器和一个键盘给软路由，接上电源，开机。按f11(不同机器不同快捷键)进入快速启动。一切自动执行到终端提示完成，回车，提示出OpenWrt图标。
- 输入quickstart，1 设置Lan口IP，2 安装OpenWrt，3 重置 
- 选择2安装操作系统。这时候会提示安装位置，如果识别磁盘没有问题，就会让你选择你内部的固态或者sata硬盘。如果提示没有找到硬盘，就是硬盘有问题或者接口接错了（我在使用sata协议的m.2接口固态硬盘时，提示了这个问题，固态硬盘需要选择nvme接口协议的） 
- 几秒后会提示你拔掉U盘，这时候就会自动重启进入系统。 
- 同样的 输入quickstart  选择1 设置lan口IP。可以设置为 192.168.2.6， 子网掩码设置为255.255.255.0（等下会说明用途）
- 接一根网线从软路由 lan 口到 PC 上，pc打开浏览器，访问 192.168.2.6 ，这时候会进入软路由后台，用户名root 默认密码 password 
到这里，安装基本完成，openWrt可以进入后台访问。&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;h5 id=&quot;2-设置旁路由&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#2-设置旁路由&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;2. 设置旁路由&lt;/h5&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs&quot;&gt;旁路由就是将软路由接入在普通硬路由下，做数据处理。&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/whrsss/pic-sync/master/img/20230321101330.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;在硬路由器控制台上禁用 DHCP 功能，然后记录下其 LAN 口 IP 地址（例如，我的是 192.168.2.5）&lt;/li&gt;
&lt;li&gt;在软路由面板的“网络”下，选择“接口”并设置 LAN 口，将 LAN 口 IP 设置为硬路由器 IP 同一网段（也就是192.168.2.6），将网关地址和 DNS 解析地址都设置为硬路由器 LAN 口地址 192.168.2.5 点击保存并应用。&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;拔下PC网线，将软路由Lan口与硬路由Lan口相连。&lt;br&gt;电脑连接原先的硬路由wifi网络， 浏览器输入192.168.2.6，正确访问到软路由后台。再登录软路由后台系统，检查网络状况，已连通。&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Clash 设置国内国外自动分流访问</title>
    <link href="https://blog.whrss.com/posts/clash-auto-triage"/>
    <id>https://blog.whrss.com/posts/clash-auto-triage</id>
    <published>2023-03-10T09:15:55.000Z</published>
    <updated>2023-03-10T09:15:55.000Z</updated>
    <category term="折腾"/>
    <category term="VPN"/>
    <category term="Clash"/>
    <category term="科学上网"/>
    <summary>Clash 是一款开源的网络代理工具，可以帮助用户实现对网络流量的控制和管理。我使用了很久，但苦于每次访问国内外网络需要手动开关代理，于是我就问了下GPT， 还真就解决了。</summary>
    <content type="html">&lt;p&gt;Clash 是一款开源的网络代理工具，可以帮助用户实现对网络流量的控制和管理。我使用了很久，但苦于每次访问国内外网络需要手动开关代理，于是我就问了下GPT， 还真就解决了。&lt;/p&gt;
&lt;p&gt;如果你也需要设置 Clash 区分国内和国外流量，可以按照以下步骤进行操作：&lt;/p&gt;
&lt;h4 id=&quot;1-打开配置文件windows在右下角&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#1-打开配置文件windows在右下角&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;1. 打开配置文件(windows在右下角)：&lt;/h4&gt;
&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/whrsss/pic-sync/master/img/20230310170129.png&quot; alt=&quot;image.png&quot; loading=&quot;eager&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/whrsss/pic-sync/master/img/20230310170252.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;使用 Visual Studio Code 打开 config.yaml&lt;br&gt;内容是这样的：&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;yml&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-yaml&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;#---------------------------------------------------#&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;## 配置文件需要放置在 $HOME/.config/clash/*.yaml&lt;/span&gt;

&lt;span class=&quot;hljs-comment&quot;&gt;## 这份文件是clashX的基础配置文件，请尽量新建配置文件进行修改。&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;## ！！！只有这份文件的端口设置会随ClashX启动生效&lt;/span&gt;

&lt;span class=&quot;hljs-comment&quot;&gt;## 如果您不知道如何操作，请参阅 官方Github文档 https://github.com/Dreamacro/clash/blob/dev/README.md&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;#---------------------------------------------------#&lt;/span&gt;

&lt;span class=&quot;hljs-comment&quot;&gt;# (HTTP and SOCKS5 in one port)&lt;/span&gt;
&lt;span class=&quot;hljs-attr&quot;&gt;mixed-port:&lt;/span&gt; &lt;span class=&quot;hljs-number&quot;&gt;7890&lt;/span&gt;
&lt;span class=&quot;hljs-comment&quot;&gt;# RESTful API for clash&lt;/span&gt;
&lt;span class=&quot;hljs-attr&quot;&gt;external-controller:&lt;/span&gt; &lt;span class=&quot;hljs-number&quot;&gt;127.0&lt;/span&gt;&lt;span class=&quot;hljs-number&quot;&gt;.0&lt;/span&gt;&lt;span class=&quot;hljs-number&quot;&gt;.1&lt;/span&gt;&lt;span class=&quot;hljs-string&quot;&gt;:9090&lt;/span&gt;
&lt;span class=&quot;hljs-attr&quot;&gt;allow-lan:&lt;/span&gt; &lt;span class=&quot;hljs-literal&quot;&gt;false&lt;/span&gt;
&lt;span class=&quot;hljs-attr&quot;&gt;mode:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;rule&lt;/span&gt;
&lt;span class=&quot;hljs-attr&quot;&gt;log-level:&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;warning&lt;/span&gt;

&lt;span class=&quot;hljs-attr&quot;&gt;proxies:&lt;/span&gt; 

&lt;span class=&quot;hljs-attr&quot;&gt;proxy-groups:&lt;/span&gt;

&lt;span class=&quot;hljs-attr&quot;&gt;rules:&lt;/span&gt;
&lt;span class=&quot;hljs-bullet&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;DOMAIN-SUFFIX,google.com,DIRECT&lt;/span&gt;
&lt;span class=&quot;hljs-bullet&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;DOMAIN-KEYWORD,google,DIRECT&lt;/span&gt;
&lt;span class=&quot;hljs-bullet&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;DOMAIN,google.com,DIRECT&lt;/span&gt;
&lt;span class=&quot;hljs-bullet&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;DOMAIN-SUFFIX,ad.com,REJECT&lt;/span&gt;
&lt;span class=&quot;hljs-bullet&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;GEOIP,CN,DIRECT&lt;/span&gt;
&lt;span class=&quot;hljs-bullet&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;MATCH,DIRECT&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;h4 id=&quot;2-在-clash-配置文件中添加以下规则&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#2-在-clash-配置文件中添加以下规则&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;2. 在 Clash 配置文件中添加以下规则：&lt;/h4&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;yaml&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-yaml&quot;&gt;&lt;span class=&quot;hljs-comment&quot;&gt;# 添加下面的, 跟在后面&lt;/span&gt;
&lt;span class=&quot;hljs-attr&quot;&gt;payload:&lt;/span&gt;
&lt;span class=&quot;hljs-bullet&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;DOMAIN-SUFFIX,cn,Direct&lt;/span&gt;
&lt;span class=&quot;hljs-bullet&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;DOMAIN-KEYWORD,geosite,Proxy&lt;/span&gt;
&lt;span class=&quot;hljs-bullet&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;IP-CIDR,10.0.0.0/8,Direct&lt;/span&gt;
&lt;span class=&quot;hljs-bullet&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;IP-CIDR,172.16.0.0/12,Direct&lt;/span&gt;
&lt;span class=&quot;hljs-bullet&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;IP-CIDR,192.168.0.0/16,Direct&lt;/span&gt;
&lt;span class=&quot;hljs-bullet&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;IP-CIDR,127.0.0.0/8,Direct&lt;/span&gt;
&lt;span class=&quot;hljs-bullet&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;IP-CIDR,224.0.0.0/4,Direct&lt;/span&gt;
&lt;span class=&quot;hljs-bullet&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;IP-CIDR,240.0.0.0/4,Direct&lt;/span&gt;
&lt;span class=&quot;hljs-bullet&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;hljs-string&quot;&gt;MATCH,Final&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;h4 id=&quot;3-每个配置段的作用&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#3-每个配置段的作用&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;3. 每个配置段的作用&lt;/h4&gt;
&lt;p&gt;然后我问了一下 gpt 这些配置的作用：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;DOMAIN-SUFFIX,cn,Direct 表示所有以 “.cn” 结尾的域名都直接连接（不通过代理）。&lt;/li&gt;
&lt;li&gt;DOMAIN-KEYWORD,geosite,Proxy 表示包含关键词 “geosite” 的域名（比如 “&lt;a href=&quot;http://www.geosite.xn--com%22%29-7b5ky65m8h8a714d7hau1aj3h./&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;www.geosite.com”）都通过代理连接。&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;IP-CIDR,10.0.0.0/8,Direct 表示 IP 地址在 10.0.0.0 - 10.255.255.255 范围内的都直接连接。&lt;/li&gt;
&lt;li&gt;IP-CIDR,172.16.0.0/12,Direct 表示 IP 地址在 172.16.0.0 - 172.31.255.255 范围内的都直接连接。&lt;/li&gt;
&lt;li&gt;IP-CIDR,192.168.0.0/16,Direct 表示 IP 地址在 192.168.0.0 - 192.168.255.255 范围内的都直接连接。&lt;/li&gt;
&lt;li&gt;IP-CIDR,127.0.0.0/8,Direct 表示本地回环地址都直接连接（通常是 127.0.0.1）。&lt;/li&gt;
&lt;li&gt;IP-CIDR,224.0.0.0/4,Direct 和 IP-CIDR,240.0.0.0/4,Direct 表示多播地址都直接连接。&lt;/li&gt;
&lt;li&gt;MATCH,Final 表示匹配到这条规则后，后面的规则不会再被匹配，可以理解为中断匹配流程，即该规则为终结规则（Final Rule）。&lt;/li&gt;
&lt;/ul&gt;
</content>
  </entry>
  <entry>
    <title>将本地服务通过 SSH 代理给外部访问</title>
    <link href="https://blog.whrss.com/posts/ssh-proxy-conn"/>
    <id>https://blog.whrss.com/posts/ssh-proxy-conn</id>
    <published>2023-03-09T08:08:49.000Z</published>
    <updated>2023-03-09T08:08:49.000Z</updated>
    <category term="技术"/>
    <category term="ssh"/>
    <category term="proxy"/>
    <category term="linux"/>
    <summary>如何使用 ssh 将本地服务代理给外部访问并保持 SSH 会话的连接性</summary>
    <content type="html">&lt;p&gt;如何使用 ssh 将本地服务代理给外部访问并保持 SSH 会话的连接性&lt;/p&gt;
&lt;h3 id=&quot;1-外部服务器-nginx-配置&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#1-外部服务器-nginx-配置&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;1. 外部服务器 nginx 配置&lt;/h3&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;shell&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-bash&quot;&gt;server {
    listen     localhost:80;
    server_name  _;
    root         /usr/share/nginx/html;

    &lt;span class=&quot;hljs-comment&quot;&gt;# 重要：将请求转发到本地服务&lt;/span&gt;
    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        proxy_pass http://127.0.0.1:10412;
        proxy_set_header Host &lt;span class=&quot;hljs-variable&quot;&gt;$host&lt;/span&gt;:80;
        proxy_set_header X-Real-IP &lt;span class=&quot;hljs-variable&quot;&gt;$remote_addr&lt;/span&gt;;
        proxy_set_header X-Forwarded-For &lt;span class=&quot;hljs-variable&quot;&gt;$proxy_add_x_forwarded_for&lt;/span&gt;;
        proxy_set_header Via &lt;span class=&quot;hljs-string&quot;&gt;&amp;quot;nginx&amp;quot;&lt;/span&gt;;
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;h3 id=&quot;2-权限认证&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#2-权限认证&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;2. 权限认证&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;在外网服务器上运行以下命令以生成公钥：&lt;code&gt;ssh-keygen -o&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;将公钥复制到内网服务器上，并添加到 &lt;code&gt;~/.ssh/authorized_keys&lt;/code&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 id=&quot;3-目标内网服务器-ssh-连接&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#3-目标内网服务器-ssh-连接&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;3. 目标内网服务器 ssh 连接&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;在本地启动服务并将其监听在端口 8088&lt;/li&gt;
&lt;li&gt;将外网访问的端口 10412 转发到本地端口 8088&lt;/li&gt;
&lt;/ol&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;shell&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-bash&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;nohup&lt;/span&gt; ssh -N -v -R 10412:127.0.0.1:8088 root@{外部服务器的外网IP} 2&amp;gt;&amp;amp;1 &amp;amp;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;h3 id=&quot;4-保持会话&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#4-保持会话&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;4. 保持会话&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;在保持 SSH 会话中，加入以下命令来保持连接&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;ServerAliveInterval&lt;/strong&gt; 是指定服务器发送保持连接的数据包的时间（单位：秒）&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;ServerAliveCountMax&lt;/strong&gt; 是指定尝试与服务器保持连接的最大次数&lt;/li&gt;
&lt;/ol&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;shell&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-bash&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;nohup&lt;/span&gt; ssh -N -v -o ServerAliveInterval=10 -o ServerAliveCountMax=1000 -R 10412:127.0.0.1:8088 root@{外部服务器的外网IP} 2&amp;gt;&amp;amp;1 &amp;amp;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
</content>
  </entry>
  <entry>
    <title>惊喜又焦虑，AI 技术的发展</title>
    <link href="https://blog.whrss.com/posts/the-ai-challenge"/>
    <id>https://blog.whrss.com/posts/the-ai-challenge</id>
    <published>2023-03-04T07:48:36.000Z</published>
    <updated>2023-03-04T07:48:36.000Z</updated>
    <category term="生活和思考"/>
    <category term="ai"/>
    <category term="chatgpt"/>
    <category term="openai"/>
    <summary>最近，我接触了很多关于AI技术的东西。例如ChatGPT、NewBing、ChatGPT更快的API、stable diffusion、AI语音识别等等。这些技术让我惊喜，也让我感到焦虑。</summary>
    <content type="html">&lt;p&gt;最近，我接触了很多关于AI技术的东西。例如ChatGPT、NewBing、ChatGPT更快的API、stable diffusion、AI语音识别等等。这些技术让我惊喜，也让我感到焦虑。&lt;/p&gt;
&lt;p&gt;AI应用日新月异，我的想象力甚至赶不上技术的发展。它们不仅代表了技术的进步，也牵动着就业市场的变革。&lt;/p&gt;
&lt;p&gt;我又陷入了意义的怪圈。作为一个软件开发者，我的学习和工作是否还有意义和价值？我的未来会是怎样？如果AI技术可以替代我的工作 ，那么我还能做什么？&lt;/p&gt;
&lt;p&gt;如果AI技术只是用于娱乐和教育等领域 ，我或许会感到比较放心，因为我可以成为一个普通的使用者，享受这些技术带来的便利和乐趣，而不必担心它们对我的生活产生过大的影响。&lt;/p&gt;
&lt;p&gt;但事实是，AI技术已经渗透到包括软件开发在内各个行业和领域 。AI可以提高软件开发人员的效率和质量 ，也可以拓展软件开发人员的知识和技能 。但同时 ，它们也给软件开发人员带来了更大的竞争压力和更高的要求 。&lt;/p&gt;
&lt;p&gt;当然 ，我并不否定AI技术 。它们也有很多优点和潜力 。但是 ，我不能忽视它们带来 的改变和挑战。不知道哪一天，我真的会被AI取代。&lt;/p&gt;
&lt;p&gt;后来，我在medium上面看到一篇文章：&lt;a href=&quot;https://javascript.plainenglish.io/coding-wont-exist-in-5-years-this-is-why-6da748ba676c&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;coding-wont-exist-in-5-years-this-is-why&lt;/a&gt; 让我对未来的看法变得理性客观了很多。&lt;/p&gt;
&lt;p&gt;AI 驱动的工具将取代人类“编码员”。这些工具将能够比人类更快、更高效地编写和调试代码，而且 成本更低。&lt;br&gt;如果你所能做的就是写代码，那么你就不是“Engineer”，而是“coder”，你一定会被AI取代。&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;“幸存下来的不是最强壮的物种，也不是最聪明的物种——它**是最能适应变化的物种。”&lt;br&gt;																														*- 查尔斯·达尔文&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;有了chatGPT这样的工具写代码，只会写代码的人是没有用的。正如工匠能够适应和学习新技能以保持竞争力一样，编码人员将能够通过更多地了解如何使用这些工具来发挥自己的优势来做到这一点。&lt;/p&gt;
&lt;p&gt;&lt;em&gt;只有渴望成为房间里最聪明的人，才会担心周围的一切都变得比他聪明。&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;适应新的方式是痛苦的，但只有活着的人才能感受到这种痛苦——死者甚至感受不到火葬的火光。能利用它的人——将前进，而那些不适应的人将不复存在——&lt;strong&gt;&lt;em&gt;it is simple as that.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;h1 id=&quot;they-are-coming-for-you&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#they-are-coming-for-you&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;They Are Coming for You !&lt;/h1&gt;
</content>
  </entry>
  <entry>
    <title>体验 New Bing：一个比 ChatGPT 更强大、更幽默、更有用的搜索引擎聊天机器人</title>
    <link href="https://blog.whrss.com/posts/newbing-vs-chatgpt"/>
    <id>https://blog.whrss.com/posts/newbing-vs-chatgpt</id>
    <published>2023-03-02T07:43:16.000Z</published>
    <updated>2023-03-02T07:43:16.000Z</updated>
    <category term="趣发现"/>
    <category term="newbing"/>
    <category term="chatgpt"/>
    <category term="ai"/>
    <category term="openai"/>
    <summary>最近在推特上看到很多人在谈论New Bing申请的事情，我也收到了试用通过的邮件。于是我马上打开Edge浏览器体验了一下。</summary>
    <content type="html">&lt;p&gt;最近在推特上看到很多人在谈论New Bing申请的事情，我也收到了试用通过的邮件。于是我马上打开Edge浏览器体验了一下。&lt;/p&gt;
&lt;p&gt;&lt;em&gt;注意：如果你也收到了邀请，但是无法进入聊天页面，请参考这篇文章：&lt;a href=&quot;https://zhuanlan.zhihu.com/p/605970396&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;https://zhuanlan.zhihu.com/p/605970396&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;New Bing是一个基于人工智能的搜索引擎聊天机器人。它可以回答各种问题，并且提供相关的链接和信息。它还可以跟你聊天，并且很有幽默感。&lt;/p&gt;
&lt;p&gt;我在搜索框输入了一些问题，并且看到了右侧New Bing的回复。我还向上滑动鼠标进入了聊天窗口，在那里我跟New Bing进行了一些对话。其中包括一些荒谬的问题：&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/whrsss/pic-sync/master/img/6091677668780_.pic_hd.jpg&quot; alt=&quot;6091677668780_.pic_hd.jpg&quot; loading=&quot;eager&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;为了对比New Bing的能力，我还用同样的问题向ChatGPT问了一下。&lt;img src=&quot;https://raw.githubusercontent.com/whrsss/pic-sync/master/img/6081677668773_.pic_hd.jpg&quot; alt=&quot;6081677668773_.pic_hd.jpg&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;从这个问题中可以看出，两个机器人都给出了相对正确的答案。但是New Bing却显得更像一个懂得幽默的人，并且每个专业名词都有引用来源。&lt;/p&gt;
&lt;p&gt;以前我曾经问过ChatGPT关于滕王阁序的问题。它告诉我滕王阁序是李白、苏轼、白居易写的。每次问都是不同的答案，但都是错的。今天我又问了同样的问题，它给出了这样的回答：&lt;br&gt;&lt;img src=&quot;https://raw.githubusercontent.com/whrsss/pic-sync/master/img/20230302095203.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;br&gt;现在，它的作者是正确的，但是它的地址、内容描述等等都还是错误的。&lt;/p&gt;
&lt;p&gt;同样的问题，bing是怎么回复的呢？&lt;br&gt;&lt;img src=&quot;https://raw.githubusercontent.com/whrsss/pic-sync/master/img/20230302095332.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;bing的回复没有任何问题，并且对滕王阁 王勃 骈文  对仗的出处都有标出链接引用。它是从这些答案中汇总得出的。&lt;br&gt;然后我继续问了几个问题：&lt;br&gt;&lt;img src=&quot;https://raw.githubusercontent.com/whrsss/pic-sync/master/img/20230302100030.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;在问到一些想法的问题时，bing的表现明显没有最初好，它在没有引用时，杜撰的内容也是不可信的，比如它说这是滕王阁序的最后一句。&lt;/p&gt;
&lt;p&gt;二者 相比，chatGPT的聊天确实是一个Demo级别的产品，而NewBing是一个测试级别的产品。&lt;br&gt;并且二者在训练的层次和模型版本，应该也有先后之别。&lt;br&gt;对于普通用户来说，new bing未来应该是更加受欢迎的，加上与Edge的融合，产品体验上应该可以完胜单独的浏览器或者AI Chat。&lt;/p&gt;
&lt;p&gt;今天我还听到一个消息，就是GPT的API从3.0升级到了3.5，回复快了数倍，而且还更加便宜。看到hongyi直接拿来接了小爱同学，这两天有时间我也去搞一下子。&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Interesting &amp; Useful 的开源项目</title>
    <link href="https://blog.whrss.com/posts/open-source-projects"/>
    <id>https://blog.whrss.com/posts/open-source-projects</id>
    <published>2023-02-28T07:53:37.000Z</published>
    <updated>2023-02-28T07:53:37.000Z</updated>
    <category term="技术"/>
    <category term="GitHub"/>
    <category term="OpenSource"/>
    <summary>分享一些平时遇到的有趣的开源项目</summary>
    <content type="html">&lt;div class=&quot;table-wrap&quot;&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;地址&lt;/th&gt;
&lt;th&gt;描述&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;https://github.com/lmarzen/esp32-weather-epd&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;https://github.com/lmarzen/esp32-weather-epd&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;一个天气显示的墨水瓶项目&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;https://github.com/AUTOMATIC1111/stable-diffusion-webui&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;https://github.com/AUTOMATIC1111/stable-diffusion-webui&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;Stable Diffusion 模型的 WebUI 界面。这是一个实现在浏览器上使用的 Stable Diffusion 模型的项目，支持通过文本/图片生成图片、嵌入文本、调整图片大小等功能。&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;https://github.com/gildas-lormeau/SingleFile&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;https://github.com/gildas-lormeau/SingleFile&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;一键下载网页，能够将网页上的文字、图片等内容，完整地整合到单个 HTML 文件里，支持 Chrome、Firefox、Safari、Microsoft Edge 等主流浏览器。&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;https://github.com/espanso/espanso&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;https://github.com/espanso/espanso&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;快捷输入工具&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;https://github.com/tw93/Pake&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;https://github.com/tw93/Pake&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;将网页打包成桌面应用，支持Mac Windows Linux&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;/div&gt;
</content>
  </entry>
  <entry>
    <title>聊天记录存储实践</title>
    <link href="https://blog.whrss.com/posts/chat-message-store"/>
    <id>https://blog.whrss.com/posts/chat-message-store</id>
    <published>2023-02-27T05:53:20.000Z</published>
    <updated>2023-02-27T05:53:20.000Z</updated>
    <category term="技术"/>
    <category term="db"/>
    <summary>公司的某款游戏在1月初接入微软小冰AI聊天功能。为了保存聊天记录并为后续的统计功能做好准备，决定将聊天记录存放在服务端。</summary>
    <content type="html">&lt;p&gt;公司的某款游戏在1月初接入微软小冰AI聊天功能。为了保存聊天记录并为后续的统计功能做好准备，决定将聊天记录存放在服务端。最初并不清楚聊天数据量的大小以及玩家对聊天功能的使用情况，所以采用了价格和性能相对宽容的MySQL作为存储介质。&lt;/p&gt;
&lt;p&gt;经过大约一个月的运营后，聊天记录表中的数据量已经达到了两千万条。反馈给策划部门后，为控制数据量，决定对聊天记录数量进行限制。每个玩家的每个角色最多只保存200条记录，每个玩家最多可保存3个角色的记录，即每个玩家最多只保存900条聊天记录。服务端的处理逻辑随即修改为每存储300条记录后就清理一次，以确保数据量控制在一定范围内。&lt;/p&gt;
&lt;p&gt;根据游戏的新增和玩家留存数据，假设每个玩家平均游戏时间为10天，新增的玩家数在2000至3000之间。因此，每10天会有20000至30000个新的玩家数据，按最高值计算，每10天可能会产生最高2700万条数据，每月最多可能达到5000万条数据。这样计算下来，在一个月后，MySQL可能会无法支持数据的频繁读写操作，需要对聊天记录的存储进行调整。&lt;/p&gt;
&lt;p&gt;针对游戏的AVG属性，玩家的生命周期相对较短，因此可以根据玩家的注册时间对其进行划分，从而对玩家数据进行分表存储。具体来说，可以按照玩家注册时间的月份对数据进行划分，并使用相应的表进行数据的存储和查询。这样，每个月份可以相对均匀地承载玩家数据，原本可能达到千万级别的数据量，现在可以控制在百万级别，完全可以解决目前的问题（聊天数据量与新增数据正相关，新增相对稳定）。&lt;/p&gt;
&lt;p&gt;接下来需要考虑的是，当一个玩家的生命周期结束后，其数据仍然会一直存储在数据库中。而当新的一年开始，新注册的玩家会继续存储，这样对玩家数据的切片就只是一个临时的措施。解决这个问题的方法是分析玩家在主生命周期结束后的行为，发现这些玩家长时间不会再次登录并进行聊天。因此，可以将这些不活跃的玩家数据迁移到便宜的分布式文件存储中，并且记录迁移标志，删除掉原数据库表中的记录。采用定时任务的方式，这样可以减少对业务的影响。&lt;/p&gt;
&lt;p&gt;以上的删除操作，都要注意一点，mysql delete删除操作不会释放表空间。这里需要对表空间进行手动释放。手动释放大表空间是一个比较耗费性能的操作，还会对表数据进行锁定。所以释放操作是需要对实际情况进行设计的。在上面的情况中，我们对数据进行按月操作，可以在一个月后，对上月的数据进行清理。比如 3月初清理1月份的表，因为3月份活跃的玩家大多可能是2月份注册的。可以定在凌晨进行定时删除，对业务影响降到最低。&lt;/p&gt;
&lt;p&gt;在2月份，新增了对聊天记录进行标记的操作需求，以进行定期反馈和AI调教。这里我们将标记操作的聊天记录独立出来存储，这样可以方便后续的统计和分析。这样也可以避免将标记操作分散在不同的表中，增加数据处理的复杂性。同时，由于标记操作的数据量不会很大，也可以考虑采用NoSQL数据库或者其他内存型数据库来存储这些数据，以提高查询速度和减少存储成本。&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>在 Google 设置静态页面 CDN 加速</title>
    <link href="https://blog.whrss.com/posts/google-static-cdn"/>
    <id>https://blog.whrss.com/posts/google-static-cdn</id>
    <published>2023-02-15T08:52:35.000Z</published>
    <updated>2023-02-15T08:52:35.000Z</updated>
    <category term="技术"/>
    <category term="google"/>
    <category term="建站"/>
    <category term="cdn"/>
    <summary>在google设置静态页面 CDN加速</summary>
    <content type="html">&lt;p&gt;在google设置静态页面 CDN加速&lt;/p&gt;
&lt;h3 id=&quot;一-创建bucket设置bucket&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#一-创建bucket设置bucket&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;一、 创建bucket，设置bucket&lt;/h3&gt;
&lt;p&gt;&lt;a href=&quot;https://console.cloud.google.com/storage/browser&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;https://console.cloud.google.com/storage/browser&lt;/a&gt; &lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;h5 id=&quot;创建bucket&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#创建bucket&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;创建bucket&lt;/h5&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/whrsss/pic-sync/master/img/20230214111414.png&quot; alt=&quot;image.png&quot; loading=&quot;eager&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;h5 id=&quot;设置bucket公开访问&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#设置bucket公开访问&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;设置bucket公开访问&lt;/h5&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;ol&gt;
&lt;li&gt;&lt;p&gt;在bucket列表中，进入刚创建的bucket。&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;选择页面顶部附近的&lt;strong&gt;权限&lt;/strong&gt;标签。&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;在&lt;strong&gt;权限&lt;/strong&gt;部分中，点击 person_add &lt;strong&gt;授予访问权限&lt;/strong&gt;按钮。&lt;/p&gt;
&lt;p&gt;此时将显示“授予访问权限”对话框。&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;在&lt;strong&gt;新的主帐号&lt;/strong&gt;字段中，输入 &lt;code&gt;allUsers&lt;/code&gt;。&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;在&lt;strong&gt;选择角色&lt;/strong&gt;下拉列表的过滤条件框中输入 &lt;strong&gt;Storage Object Viewer&lt;/strong&gt;，然后从过滤后的结果中选择 &lt;strong&gt;Storage Object Viewer&lt;/strong&gt;。&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;点击&lt;strong&gt;保存&lt;/strong&gt;。&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;点击&lt;strong&gt;允许公开访问&lt;/strong&gt;。&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 id=&quot;二设置cdn&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#二设置cdn&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;二、设置CDN&lt;/h3&gt;
&lt;p&gt;&lt;a href=&quot;https://console.cloud.google.com/net-services/cdn/list&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;https://console.cloud.google.com/net-services/cdn/list&lt;/a&gt;&lt;br&gt;添加来源，创建时可能会附带创建好负载均衡，用来做DNS解析使用&lt;br&gt;&lt;img src=&quot;https://raw.githubusercontent.com/whrsss/pic-sync/master/img/20230214111757.png&quot; alt=&quot;image.png&quot; loading=&quot;lazy&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;p&gt;指向刚才新创建的bucket&lt;/p&gt;
&lt;p&gt;在host and path rules设置地址规则。&lt;/p&gt;
&lt;h3 id=&quot;三dns解析&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#三dns解析&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;三、DNS解析&lt;/h3&gt;
&lt;p&gt;进入负载均衡控制台&lt;br&gt;&lt;a href=&quot;https://console.cloud.google.com/net-services/loadbalancing/list/loadBalancers&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;https://console.cloud.google.com/net-services/loadbalancing/list/loadBalancers&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;选择创建好的负载均衡，点进去，拿到公网IP，到DNS控制台进行解析即可。&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>发现优质 Newsletter 和 Blog</title>
    <link href="https://blog.whrss.com/posts/find-newsletter"/>
    <id>https://blog.whrss.com/posts/find-newsletter</id>
    <published>2023-02-05T11:47:18.000Z</published>
    <updated>2023-02-05T11:47:18.000Z</updated>
    <category term="生活和思考"/>
    <category term="知识源"/>
    <summary>我平时一直都在发现很多优质的资源，但都没有整理。一直增加，单独一个页面可能开始会有些乱，就先开一篇放在这里。</summary>
    <content type="html">&lt;p&gt;我平时一直都在发现很多优质的资源，但都没有整理。一直增加，单独一个页面可能开始会有些乱，就先开一篇放在这里。&lt;/p&gt;
&lt;div class=&quot;table-wrap&quot;&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;名称&lt;/th&gt;
&lt;th&gt;简介&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;https://xinquji.com/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;新趣集&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;发现有趣的新产品&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;https://alleyread.com/discover&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;AlleyRead&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;发现国内外优质内容&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;https://meta.appinn.net/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;小众软件 - 发现&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;寻找应用、软件&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;https://support.qq.com/products/57688/link-jump?jump=https://v2ex.com/go/share&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;v2ex - 发现&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;分享好玩的，并获取灵感 (须自强)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;https://www.v1tx.com/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;v1tx&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;分享实用工具与解决问题&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;https://chao.fun/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;炒饭&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;发现有趣的内容｜&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;https://creatorsdaily.com/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;创造者日报&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;每天发现有趣的产品｜&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;https://www.producthunt.com/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;producthunt&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;每天发现有趣的新产品 (国外产品)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;https://zhaodao.ai/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;找到 AI&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;找到你喜爱的作品&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;https://www.52pojie.cn/forum-2-1.html&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;52 破解&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;找到你想要的软件&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;https://alleyread.com/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;发现优质 Newsletter&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;授人予鱼 不如授人予渔， 这是一个newsletter的推荐网站&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;hr&gt;
&lt;p&gt;Copy By yihong Blog , 都是非常好的博客⬇️&lt;/p&gt;
&lt;h4 id=&quot;yihong0618-收藏的博客&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#yihong0618-收藏的博客&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;@yihong0618 收藏的博客&lt;/h4&gt;
&lt;div class=&quot;table-wrap&quot;&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;博客名称&lt;/th&gt;
&lt;th&gt;添加日期&lt;/th&gt;
&lt;th&gt;type&lt;/th&gt;
&lt;th&gt;备注&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;https://niyue.com/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;niyue&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;2022.01.20&lt;/td&gt;
&lt;td&gt;第一个&lt;/td&gt;
&lt;td&gt;写 20 年博客的前辈&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;http://baotiao.github.io/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;baotiao&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;2022.01.31&lt;/td&gt;
&lt;td&gt;数据库&lt;/td&gt;
&lt;td&gt;做有积累的事情&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;http://javabin.cn/archives/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;javabin&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;2022.02.03&lt;/td&gt;
&lt;td&gt;hacker&lt;/td&gt;
&lt;td&gt;好 cool 的人&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;https://soulteary.com/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;soulteary&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;2022.02.07&lt;/td&gt;
&lt;td&gt;DIY 神&lt;/td&gt;
&lt;td&gt;向往&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;https://7dot9.com/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;7dot9&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;2022.02.26&lt;/td&gt;
&lt;td&gt;前辈&lt;/td&gt;
&lt;td&gt;梦在这里可以飞翔&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;a href=&quot;https://chrisdown.name/archive.html&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;chrisdown&lt;/a&gt;&lt;/td&gt;
&lt;td&gt;2022.03.05&lt;/td&gt;
&lt;td&gt;SRE&lt;/td&gt;
&lt;td&gt;Linux&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;/div&gt;
</content>
  </entry>
  <entry>
    <title>Nginx 代理静态网站 CSS 解析异常</title>
    <link href="https://blog.whrss.com/posts/nginx-website"/>
    <id>https://blog.whrss.com/posts/nginx-website</id>
    <published>2023-01-31T13:55:01.000Z</published>
    <updated>2023-01-31T13:55:01.000Z</updated>
    <category term="技术"/>
    <category term="nginx"/>
    <summary>今天在使用ecs进行部署网页时，出现了一个问题。使用nginx代理到页面index.html路径下，同路径的资源都可以加载到，但是却无法正确加载到页面样式。打开f12，网络和控制台都没有资源异常，但页面乱成了一锅粥。 本地打开是正常的，上到服务器却不行？</summary>
    <content type="html">&lt;p&gt;今天在使用ecs进行部署网页时，出现了一个问题。使用nginx代理到页面index.html路径下，同路径的资源都可以加载到，但是却无法正确加载到页面样式。打开f12，网络和控制台都没有资源异常，但页面乱成了一锅粥。&lt;br&gt;本地打开是正常的，上到服务器却不行？&lt;br&gt;之前使用nginx时，并没有这个问题，于是我猜测是不是nginx新的版本对配置参数进行了修改？&lt;br&gt;但我翻看了nginx的文档，却没有找到。于是我跟着症状开始在网上翻文，终于：&lt;/p&gt;
&lt;h2 id=&quot;解决方法&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#解决方法&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;解决方法&lt;/h2&gt;
&lt;p&gt;若不对于css文件解析进行配置，nginx默认文件都是&lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Learn/Server-side/Configuring_server_MIME_types&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;&lt;code&gt;text/plain&lt;/code&gt;&lt;/a&gt;类型进行解析，为此我们需要对此进行简单配置。将下面这段代码放入到&lt;code&gt;location&lt;/code&gt;模块下面，然后重启nginx。&lt;strong&gt;记住一定要清理浏览器的缓存&lt;/strong&gt;。&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;sh&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-bash&quot;&gt;include mime.types;  
default_type application/octet-stream;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;完整如下：&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;sh&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-bash&quot;&gt;location / {
              include mime.types;
              default_type application/octet-stream;
              &lt;span class=&quot;hljs-built_in&quot;&gt;alias&lt;/span&gt; /opt/website/;
              autoindex on;
         }
&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
</content>
  </entry>
  <entry>
    <title>macOS 12 Monterey + Windows11 我的生产力答案</title>
    <link href="https://blog.whrss.com/posts/hackintosh"/>
    <id>https://blog.whrss.com/posts/hackintosh</id>
    <published>2022-12-25T13:14:27.000Z</published>
    <updated>2022-12-25T13:14:27.000Z</updated>
    <category term="技术"/>
    <category term="黑苹果"/>
    <category term="攒机"/>
    <summary>大学毕业以后，买了一台乞丐版的13寸的macbook pro（8 + 128 这个配置可能还不如现在的安卓手机），今年年中，我开始把工作用的macbook pro（18款 15寸 16 + 256）往家里带，勉强够用。到了今年下半年，我渐渐感觉，这俩电脑，一个能打的都没有，真顶不住了。</summary>
    <content type="html">&lt;p&gt;大学毕业后，我买了一台乞丐版的 13 寸 MacBook Pro，这台电脑配置比现在的安卓手机还低。今年年中，我开始把用于工作的 MacBook Pro（18 款 15 寸 16+256）带回家使用，虽然勉强能用，但是我渐渐地发现这两台电脑都不能满足我的需求。&lt;/p&gt;
&lt;p&gt;从 2020 年开始，我就计划安装一台黑苹果，我把很多零件加入购物车，但是当时显卡实在太贵，所以一直没有开始。后来以太坊价格直线上涨，矿卡价格也水涨船高，苹果公司也开始全面转向 ARM 平台，这使我更加渴望拥有一台强大的“生产力”工具，赶上黑苹果的尾巴。&lt;/p&gt;
&lt;p&gt;在我看来，相比苹果设备，黑苹果有以下几个优点：&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;价格便宜。&lt;/li&gt;
&lt;li&gt;可以自定义硬件配置，不需要精准的安装技能。&lt;/li&gt;
&lt;li&gt;可以安装 x86 平台的 Windows 系统，可以用于娱乐和生产力。&lt;/li&gt;
&lt;li&gt;探索的过程也是一种快乐。&lt;/li&gt;
&lt;/ol&gt;
&lt;blockquote&gt;
&lt;p&gt;价格方面，只需要 1000 元左右就可以购买 32GB DDR5 内存，500多块可以买到2TB 固态硬盘等等。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;hr&gt;
&lt;blockquote&gt;
&lt;p&gt;自定义硬件方面，我可以先买一个 32GB 的内存条，然后等到有钱了再买一个（众所都周知，苹果的内存条是金子做的，真买不起）。&lt;br&gt;同样的道理，我也可以先买一个 5600XT 显卡(甚至是矿卡)，然后再换成 6600XT 等更强的显卡。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;hr&gt;
&lt;blockquote&gt;
&lt;p&gt;安装 Windows 是很有必要的，因为无论是娱乐还是工作，Windows 都是必不可少的。&lt;br&gt;如果你觉得双系统切换麻烦，这个工具了解一下👇&lt;br&gt;&lt;img src=&quot;https://raw.githubusercontent.com/whrsss/pic-sync/master/img/20230219112401.png&quot; alt=&quot;image.png&quot; loading=&quot;eager&quot; decoding=&quot;async&quot;&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;hr&gt;
&lt;p&gt;几个劣势：&lt;/p&gt;
&lt;ol&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;li&gt;需要花费一些时间。&lt;/li&gt;
&lt;/ol&gt;
&lt;blockquote&gt;
&lt;p&gt;在体积上，再怎么取舍，也会远远超过mac stdio的完美集成。我使用的机箱是联立A4 H2O，是比较经典的A4机箱，也要11L的空间。但我这里可以装下一个240水冷，更大的体积也会带来更好的散热。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;blockquote&gt;
&lt;p&gt;兼容性的话，在装机时候，需要很多的设置，扒帖，去定制更适配的EFI。&lt;/p&gt;
&lt;/blockquote&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;blockquote&gt;
&lt;p&gt;花费时间是可以取舍的，如果想要尽量快，就去尽量找别人准备好的，可能会花费几块钱；如果喜欢折腾，就去扒帖，学习设置。白果只有物流时间。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;hr&gt;
&lt;p&gt;然后，我进行了一些性能测试。总体来说，我的黑苹果系统表现不错，性能比我之前的MacBook Pro要好得多。我可以运行Adobe Creative Suite和Final Cut Pro等专业软件，没有出现任何问题。&lt;/p&gt;
&lt;p&gt;此外，我也可以在我的黑苹果上安装Windows系统，这样我就可以玩一些Windows平台上的游戏了。这是Mac OS系统所不能提供的，这也是我决定装黑苹果的原因之一。&lt;/p&gt;
&lt;p&gt;当然，黑苹果也有一些劣势，比如兼容性和稳定性相对较差，可能需要花费一些时间来解决问题。但是，对于我这种喜欢折腾的人来说，这些问题并不是什么大问题。我可以通过网上的资源和社区来解决这些问题。&lt;/p&gt;
&lt;p&gt;总的来说，装黑苹果是一项有趣的尝试。虽然过程可能会有些繁琐，但是如果你是一个喜欢尝试新事物和折腾的人，那么我认为你可以尝试一下。😃️&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;然后就是我的整个装机历程了：&lt;/p&gt;
&lt;p&gt;零件：&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs&quot;&gt;1. 机箱 联立A4 H2O 900RMB
2. 电源 长城tf750 729RMB
3. 主板 ROG B660itx 1250RMB
4. 内存 海盗船DDR5 5200MHZ 1000RMB
5. CPU i512490F盒装 1050RMB
6. 显卡 蓝宝石5600XT 白金版 6G 628RMB
7. 固态 七彩虹2TB 569RMB
8. 水冷 利民冰封幻境240 RGB 300RMB
共： 6426RMB&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;win11固态出厂预装&lt;/p&gt;
&lt;p&gt;在网上找到B660I 主板设置好的EFI文件&lt;/p&gt;
&lt;p&gt;下载和这个EFI文件适配的带引导的dmg系统镜像，直接写盘，更换EFI，重启安装。&lt;/p&gt;
&lt;p&gt;之后我会把相对应的教程和文件贴一下，如果有同学看到了，感兴趣，着急的可以直接留言，我会尽快整理的。 😘️&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>最新版 Let’s Encrypt 免费证书申请步骤，保姆级教程</title>
    <link href="https://blog.whrss.com/posts/lets-encrypt"/>
    <id>https://blog.whrss.com/posts/lets-encrypt</id>
    <published>2022-12-02T11:17:50.000Z</published>
    <updated>2022-12-02T11:17:50.000Z</updated>
    <category term="技术"/>
    <category term="建站"/>
    <summary>最近将域名迁到了google domain，就研究了一下Let’s Encrypt的域名证书配置。发现网上找到的教程在官方说明中已经废弃，所以自己写一个流程记录一下。</summary>
    <content type="html">&lt;p&gt;最近将域名迁到了google domain，就研究了一下Let’s Encrypt的域名证书配置。发现网上找到的教程在官方说明中已经废弃，所以自己写一个流程记录一下。&lt;/p&gt;
&lt;p&gt;步骤方法官方文档见：&lt;a href=&quot;https://eff-certbot.readthedocs.io/en/stable/install.html#installation&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;https://eff-certbot.readthedocs.io/en/stable/install.html#installation&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;snapd官方文档见：&lt;a href=&quot;https://certbot.eff.org/instructions&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;https://certbot.eff.org/instructions&lt;/a&gt;&lt;/p&gt;
&lt;h4 id=&quot;1-安装snapd这里我使用的是centos系统&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#1-安装snapd这里我使用的是centos系统&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;1. 安装snapd（这里我使用的是centos系统）&lt;/h4&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;shell&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-bash&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;sudo&lt;/span&gt; yum install snapd
&lt;span class=&quot;hljs-built_in&quot;&gt;sudo&lt;/span&gt; systemctl &lt;span class=&quot;hljs-built_in&quot;&gt;enable&lt;/span&gt; --now snapd.socket
&lt;span class=&quot;hljs-built_in&quot;&gt;sudo&lt;/span&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;ln&lt;/span&gt; -s /var/lib/snapd/snap /snap&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;h4 id=&quot;2-使用snapd安装certbot&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#2-使用snapd安装certbot&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;2. 使用snapd安装certbot&lt;/h4&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;shell&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-bash&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;sudo&lt;/span&gt; snap install --classic certbot
&lt;span class=&quot;hljs-built_in&quot;&gt;sudo&lt;/span&gt; &lt;span class=&quot;hljs-built_in&quot;&gt;ln&lt;/span&gt; -s /snap/bin/certbot /usr/bin/certbot&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;####3. 生成证书（需要指定nginx）&lt;br&gt;▶️ &lt;a href=&quot;https://blog.csdn.net/w_monster/article/details/126352529&quot; title=&quot;手动安装nginx&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;手动安装nginx&lt;/a&gt;&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;shell&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-bash&quot;&gt;certbot certonly --nginx --nginx-ctl /usr/local/nginx/sbin/nginx --nginx-server-root /usr/local/nginx/conf&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;这里的certonly就是只下载对应文件，不进行配置nginx，适用于自己配置或者更新使用。去掉则会帮你进行配置nginx（我没有试用）。&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;可能出现的问题：&lt;/p&gt;
&lt;p&gt;The error was: PluginError(‘Nginx build is missing SSL module (—with-http_ssl_module).’)&lt;/p&gt;
&lt;p&gt;提示这个错误是因为目前nginx缺少–with-http_ssl_module这个模块，我们要添加这个模块。重新编译nginx&lt;/p&gt;
&lt;p&gt;进入nginx下载的目录&lt;/p&gt;
&lt;p&gt;./configure —prefix=/usr/local/nginx —with-http_ssl_module&lt;/p&gt;
&lt;p&gt;编译完成后&lt;/p&gt;
&lt;p&gt;make&lt;/p&gt;
&lt;p&gt;make install&lt;/p&gt;
&lt;p&gt;/usr/local/nginx/sbin/nginx -s stop&lt;/p&gt;
&lt;p&gt;/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;   使用 /usr/local/nginx/sbin/nginx -V 查看是否生效&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;shell&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-bash&quot;&gt;[root]# /usr/local/nginx/sbin/nginx -V
nginx version: nginx/1.23.2
built by gcc 10.2.1 20200825 (Alibaba 10.2.1-3 2.32) (GCC) 
built with OpenSSL 1.1.1k  FIPS 25 Mar 2021
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --with-http_ssl_module&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;blockquote&gt;
&lt;p&gt;生效，重新执行上面的命令即可。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h4 id=&quot;4-生成证书&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#4-生成证书&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;4. 生成证书&lt;/h4&gt;
&lt;p&gt;   执行上面的命令后，程序会让你确认你的邮箱和你的域名，确认完成后会将证书文件生成在指定目录中。&lt;/p&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;shell&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs language-bash&quot;&gt;certbot certonly --nginx --nginx-ctl /usr/local/nginx/sbin/nginx --nginx-server-root /usr/local/nginx/conf
Saving debug &lt;span class=&quot;hljs-built_in&quot;&gt;log&lt;/span&gt; to /var/log/letsencrypt/letsencrypt.log
Enter email address (used &lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; urgent renewal and security notices)
 (Enter &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;c&amp;#x27;&lt;/span&gt; to cancel): [这里输入你的邮箱]

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Please &lt;span class=&quot;hljs-built_in&quot;&gt;read&lt;/span&gt; the Terms of Service at
https://letsencrypt.org/documents/LE-SA-v1.3-September-21-2022.pdf. You must
agree &lt;span class=&quot;hljs-keyword&quot;&gt;in&lt;/span&gt; order to register with the ACME server. Do you agree?
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: Y

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Would you be willing, once your first certificate is successfully issued, to
share your email address with the Electronic Frontier Foundation, a founding
partner of the Let&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;s Encrypt project and the non-profit organization that
develops Certbot? We&amp;#x27;&lt;/span&gt;d like to send you email about our work encrypting the web,
EFF news, campaigns, and ways to support digital freedom.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: Y [选Y 继续]
Account registered.

Which names would you like to activate HTTPS &lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt;?
We recommend selecting either all domains, or all domains &lt;span class=&quot;hljs-keyword&quot;&gt;in&lt;/span&gt; a VirtualHost/server block.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1: whrss.com
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Select the appropriate numbers separated by commas and/or spaces, or leave input
blank to &lt;span class=&quot;hljs-keyword&quot;&gt;select&lt;/span&gt; all options shown (Enter &lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;c&amp;#x27;&lt;/span&gt; to cancel):  [这里不需要输入，回车选所有]
Requesting a certificate &lt;span class=&quot;hljs-keyword&quot;&gt;for&lt;/span&gt; whrss.com

Successfully received certificate.
Certificate is saved at: 
&lt;span class=&quot;hljs-comment&quot;&gt;# [这里告诉我们生成的文件路径和有效期]&lt;/span&gt;
/etc/letsencrypt/live/whrss.com/fullchain.pem
Key is saved at:         /etc/letsencrypt/live/whrss.com/privkey.pem
This certificate expires on 2023-03-02.
These files will be updated when the certificate renews.
Certbot has &lt;span class=&quot;hljs-built_in&quot;&gt;set&lt;/span&gt; up a scheduled task to automatically renew this certificate &lt;span class=&quot;hljs-keyword&quot;&gt;in&lt;/span&gt; the background.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
If you like Certbot, please consider supporting our work by:
 * Donating to ISRG / Let&lt;span class=&quot;hljs-string&quot;&gt;&amp;#x27;s Encrypt:   https://letsencrypt.org/donate
 * Donating to EFF:                    https://eff.org/donate-le
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;h4 id=&quot;5-nginxconf的配置&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#5-nginxconf的配置&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;5. Nginx.conf的配置&lt;/h4&gt;
&lt;figure class=&quot;code&quot; data-lang=&quot;&quot;&gt;&lt;pre&gt;&lt;code class=&quot;hljs&quot;&gt;server{
        #监听443端口
        listen 443 ssl;
        #对应的域名，空格分隔域名就可以了
        server_name whrss.com; 
        #第一个域名的文件
        ssl_certificate /etc/letsencrypt/live/whrss.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/whrss.com/privkey.pem;
        # 其他配置
        ssl_session_timeout 5m;
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
        ssl_prefer_server_ciphers on;
        #这是我的主页访问地址，因为使用的是静态的html网页，所以直接使用location就可以完成了。
        location / {
            root   /;
            index  /;
            proxy_pass http://127.0.0.1:9091;
            proxy_set_header Host $host:443;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Via &amp;quot;nginx&amp;quot;;
        }
}&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;以上！！&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>五人墓碑记</title>
    <link href="https://blog.whrss.com/posts/tombstone-of-the-five"/>
    <id>https://blog.whrss.com/posts/tombstone-of-the-five</id>
    <published>2022-11-28T02:02:25.000Z</published>
    <updated>2022-11-28T02:02:25.000Z</updated>
    <category term="生活和思考"/>
    <category term="right"/>
    <summary>五人墓碑记 明 张溥　 卒以吾辈之发愤一击，不敢复有株治。</summary>
    <content type="html">&lt;h5 id=&quot;作者张溥-明&quot;&gt;&lt;a class=&quot;anchor&quot; href=&quot;#作者张溥-明&quot; aria-hidden=&quot;true&quot; tabindex=&quot;-1&quot;&gt;#&lt;/a&gt;作者：张溥　明&lt;/h5&gt;
&lt;hr&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;
</content>
  </entry>
  <entry>
    <title>随想—生活效能</title>
    <link href="https://blog.whrss.com/posts/effectiveness"/>
    <id>https://blog.whrss.com/posts/effectiveness</id>
    <published>2022-11-27T07:34:45.000Z</published>
    <updated>2022-11-27T07:34:45.000Z</updated>
    <category term="生活和思考"/>
    <category term="随想"/>
    <summary>效能，效就是结果，能就是取效所做的功。</summary>
    <content type="html">&lt;p&gt;之前我有写过一篇文章，是关于边际效益的思考的，但很不幸，我没有备份，一并被阿里云ban掉了。&lt;br&gt;那篇文章是基于李永乐老师的一个视频——996的那个，来讨论的。最近，我发现在生活中，我有不少关于效益的习惯和思考，记录一下。&lt;/p&gt;
&lt;p&gt;最近，我意识到自己对于效益的思考和行为有不少习惯，其中一个例子是洗衣服。由于我租住的房子没有洗衣机，而我个人穿着简单，衣服也很少，所以我通常都是手洗。刚开始，我只是随便洗一下，因为感觉这样能省事，但是随着时间的推移，我开始思考这个过程中的效益和成本，并且逐渐调整了我的洗衣方式。&lt;/p&gt;
&lt;p&gt;首先，我从心理层面分析了这个问题。我从洗衣液问世时就开始使用它，因为它能轻松地溶解脏污，尤其是一些不易清洗的面料。这种想法让我认为只要用洗衣液泡一下，就能够解决70%左右的污渍。对于日常穿着，这种简单的清洗方式足以满足需求。但是对于有些衣服，比如容易掉色的棉制外裤，洗得太狠会影响寿命，这也是我使用简单方法洗衣服的原因之一。此外，冬天水太冷，而且洗衣机所需的衣服数量太多，所以我不得不简化洗衣的流程。&lt;/p&gt;
&lt;p&gt;接着，我开始考虑“边际效益”。我想到了洗衣过程中从“干净”到“脏”的过渡，这个过程需要进行比较，比如，当衣服开始散发出汗味时，就需要清洗。我需要洗衣服来保证我的整体干净程度。在控制洗衣液和水温等变量条件下，衣服的干净程度和所需要付出的劳动基本上可以看作一个效益曲线。这个曲线上有一个最佳点，也就是衣服的干净程度和所付出的劳动量之间的比例最佳。在这个点上，我们付出的劳动和晾晒的时间等等，可以最大程度地轻松达到一个干净的程度。如果要让衣服更加干净，所需付出的劳动就会越来越大。&lt;/p&gt;
&lt;p&gt;因此，我选择了一种简单而有效的洗衣方式：浸泡、揉搓、涮净、拧干和晾晒。这个过程几乎不需要花费多少时间和经历，在让衣服变得干净的同时，也会大大延长衣物的寿命。&lt;/p&gt;
&lt;p&gt;效能，效就是结果，能就是取效所做的功。在实现目标的过程中，所需付出的劳动与产生的效果之间存在一种平衡点，我们需要找到这个点，以达到最大化效益的目的。&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>测试一下功能吧</title>
    <link href="https://blog.whrss.com/posts/test-function"/>
    <id>https://blog.whrss.com/posts/test-function</id>
    <published>2022-11-24T13:11:52.000Z</published>
    <updated>2022-11-24T13:11:52.000Z</updated>
    <category term="技术"/>
    <category term="闲谈"/>
    <summary>阿里服务器被ban了，数据全没了</summary>
    <content type="html">&lt;p&gt;阿里服务器被ban了，数据全没了，测试一下重新组织博客能否正常工作吧&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;全部组件都使用了国外免费的平台。&lt;/p&gt;
</content>
  </entry>
</feed>
