diff --git a/2014/12/30/Clone-Graph-Part-I/index.html b/2014/12/30/Clone-Graph-Part-I/index.html index 70d2e80877..56bddd2e12 100644 --- a/2014/12/30/Clone-Graph-Part-I/index.html +++ b/2014/12/30/Clone-Graph-Part-I/index.html @@ -1,4 +1,4 @@ -Clone Graph Part I | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Clone Graph Part I

problem

Clone a graph. Input is a Node pointer. Return the Node pointer of the cloned graph.
+Clone Graph Part I | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Clone Graph Part I

problem

Clone a graph. Input is a Node pointer. Return the Node pointer of the cloned graph.
 
 A graph is defined below:
 struct Node {
@@ -34,4 +34,4 @@ Node *clone(Node *graph) {
     }
  
     return graphCopy;
-}

anlysis

using the Breadth-first traversal
and use a map to save the neighbors not to be duplicated.

0%
\ No newline at end of file +}

anlysis

using the Breadth-first traversal
and use a map to save the neighbors not to be duplicated.

0%
\ No newline at end of file diff --git a/2019/12/07/JVM-G1-Part-1/index.html b/2019/12/07/JVM-G1-Part-1/index.html index 55f40e4bb7..ab756282e5 100644 --- a/2019/12/07/JVM-G1-Part-1/index.html +++ b/2019/12/07/JVM-G1-Part-1/index.html @@ -1,4 +1,4 @@ -JVM源码分析之G1垃圾收集器分析一 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

JVM源码分析之G1垃圾收集器分析一

对 Java 的 gc 实现比较感兴趣,原先一般都是看周志明的书,但其实并没有讲具体的 gc 源码,而是把整个思路和流程讲解了一下
特别是 G1 的具体实现
一般对 G1 的理解其实就是把原先整块的新生代老年代分成了以 region 为单位的小块内存,简而言之,就是原先对新生代老年代的收集会涉及到整个代的堆内存空间,而G1 把它变成了更细致的小块内存
这带来了一个很明显的好处和一个很明显的坏处,好处是内存收集可以更灵活,耗时会变短,但整个收集的处理复杂度就变高了
目前看了一点点关于 G1 收集的预期时间相关的代码

HeapWord* G1CollectedHeap::do_collection_pause(size_t word_size,
+JVM源码分析之G1垃圾收集器分析一 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

JVM源码分析之G1垃圾收集器分析一

对 Java 的 gc 实现比较感兴趣,原先一般都是看周志明的书,但其实并没有讲具体的 gc 源码,而是把整个思路和流程讲解了一下
特别是 G1 的具体实现
一般对 G1 的理解其实就是把原先整块的新生代老年代分成了以 region 为单位的小块内存,简而言之,就是原先对新生代老年代的收集会涉及到整个代的堆内存空间,而G1 把它变成了更细致的小块内存
这带来了一个很明显的好处和一个很明显的坏处,好处是内存收集可以更灵活,耗时会变短,但整个收集的处理复杂度就变高了
目前看了一点点关于 G1 收集的预期时间相关的代码

HeapWord* G1CollectedHeap::do_collection_pause(size_t word_size,
                                                uint gc_count_before,
                                                bool* succeeded,
                                                GCCause::Cause gc_cause) {
@@ -575,4 +575,4 @@
   phase_times()->record_non_young_cset_choice_time_ms((non_young_end_time_sec - non_young_start_time_sec) * 1000.0);
 
   QuickSort::sort(_collection_set_regions, _collection_set_cur_length, compare_region_idx, true);
-}

上面第三行是个判断,当前是否是 mixed 回收阶段,如果不是的话其实是没有老年代什么事的,所以可以看到代码基本是从这个 if 判断
if (collector_state()->in_mixed_phase()) {开始往下走的
先写到这,偏向于做笔记用,有错轻拍

0%
\ No newline at end of file +}

上面第三行是个判断,当前是否是 mixed 回收阶段,如果不是的话其实是没有老年代什么事的,所以可以看到代码基本是从这个 if 判断
if (collector_state()->in_mixed_phase()) {开始往下走的
先写到这,偏向于做笔记用,有错轻拍

0%
\ No newline at end of file diff --git a/2019/12/18/1Q84读后感/index.html b/2019/12/18/1Q84读后感/index.html index f4b3bd4c16..9e521d4911 100644 --- a/2019/12/18/1Q84读后感/index.html +++ b/2019/12/18/1Q84读后感/index.html @@ -1 +1 @@ -村上春树《1Q84》读后感 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

村上春树《1Q84》读后感

看完了村上春树的《1Q84》,这应该是第五本看的他的书了,继 跑步,挪威的森林,刺杀骑士团长,海边的卡夫卡之后,不是其中最长的,好像是海边的卡夫卡还是刺杀骑士团长比较长一点,都是在微信读书上看的,比较方便,最开始在上面看的是高晓松的《鱼羊野史》,不知道为啥取这个名字,但是还是满吸引我的,不过由于去年的种种,没有很多心思把它看完,而且本身的组织形式就是比较松散的,看到哪算哪,其实一些野史部分是我比较喜欢,有些谈到人物的就不太有兴趣,而且类似于大祥哥吃的东西,反正都是哇,怎么这么好吃,嗯,太爱(niu)你(bi)了,高晓松就是这个人是我最喜欢的 xxx 家,我也没去细究过他有没有说重复过,反正是不太爱,后来因为这书还一度对战争史有了浓厚的兴趣,然而事实告诉我,大部头的战争史,其实正史我是真的啃不下去,我可能只对其中 10%的内容感兴趣,不过终于也在今年把它看完了,好像高晓松的晓说也最终季了,貌似其中讲朝鲜战争的还被和谐了,看样子是说出了一些故事(truth)。

本来只是想把 《1Q84》的读后感写下,现在觉得还是把这篇当成我今年的读书总结吧,不过先从《1Q84》说起。

严格来讲,这不是很书面化的读后感,可能我想写的也只是像聊天一样的说下我读过的书,包括的技术博客其实也是类似的,以后或许会转变,但是目前水平如此吧,写多了可能会变好,也可能不会。

开始正文吧,这书有点类似于海边的卡夫卡,一开始是通过两条故事线,穿插着叙述,一条是青豆的,不算是个职业杀手的女杀手,要去解决一个经常家暴的斯文败类,穿着描述得比较性感吧,杀人方式是通过比较长的细针,从脖子后面一个精巧的位置插入,可以造成是未知原因死亡的假象,可能会推断成心梗之类的,这里有个前置的细节,就是青豆是乘坐一辆很高级的出租车,内饰什么的都非常有质感,有点不像一辆出租车,然后车里放了一首比较小众的歌,雅纳切克的《小交响曲》,但是青豆知道它,这跟后面的情节也有些许关系,这是女主人公青豆的出场;相应的男主的出场印象不是太深刻,男主叫天吾,是个不知名的作家,跟一个叫小松的编辑有比较好的关系,虽然天吾还没有拿到比较有分量的奖项,但是小松很看好他,也让他帮忙审校一个新作家奖的投稿文章,虽然天吾自身还没获得过这个奖,天吾还有个正式工作,是当数学老师,天吾在学生时代是个数学天才,但后面有对文学产生了兴趣,文学还不足以养活自己,靠着教课还是能保持温饱;

接下来是正式故事的起点了,就是小松收到了一部小说投稿,名叫《空气蛹》,是个叫深绘里的女孩子投的稿,小松对他赋予了很高的评价,这里好像记岔了,好像是天吾对这部小说很有好感,但是小松比较怀疑,然后小松看了之后也有了浓厚的兴趣,这里就是开端了,小松想让天吾来重写润色这部《空气蛹》,因为故事本身很有分量,但是描写手法叙事方式等都很拙劣,而天吾正好擅长这个,小松对天吾的评价是,描写技巧无可挑剔,就是故事主体的火花还没际遇迸发,需要一个导火索,这个就可以类比我们程序员,很多比较初中级的程序员主要擅长在原来的代码上修修改改或者给他分配个小功能,比较高级的程序员就需要能做一些项目的架构设计,核心的技术方案设计,以前我也觉得写文档这个比较无聊,但是当一个项目真的比较庞大,复杂的时候,整体和核心部分的架构设计和方案还是需要有文档沉淀的,不然别人不知道没法接受,自己过段时间也会忘记。

对于小松的这个建议,他的初衷是想搅一搅这个死气沉沉套路颇深的文坛,因为本身《空气蛹》这部小说的内容很吸引人,小松想通过天吾的润色补充让这部小说冲击新人奖,有种恶作剧的意图,天吾对此表示很多担心和顾虑,小松的这个建议其实也是一种文学作假,有两方面的担心,一方面是原作者深绘里是否同意如此操作,一方面是外界如果发现了这个事实会有什么样的后果,但是小松表示不用担心,前一步由小松牵线,让天吾跟原作者深绘里当面沟通这个代写是否被允许,结果当然是被允许了,这里有了对深绘里的初步描写,按我的理解是比较仙的感觉,然后语言沟通有些吃力,或者说有她自己的特色,当面沟通时貌似是让深绘里回去再考虑下,然后后面再由天吾去深绘里寄宿的戎野老师家沟通具体的细节。

2019年12月18日23:37:19 更新
去到戎野老师家之后,天吾知道了关于深绘里的一些事情,深绘里的父亲与戎野老师应该是老友,深绘里的父亲在当初成立了一个叫”先驱”的公社,一个独立运行的社会组织,以运营农场作为物资来源,追求更为松散的共同体,即不过分激进地公有制,进行松散的共同生活,承认私有财产,简而言之就是这样一个能稳定存活下来的独立社会组织,但是随着稳定运行,内部的激进派和稳健派开始出现分歧,不可磨合,后来两派就分裂了,深绘里的父亲,深田保留在了稳健派,但是此时其实深田保内心是矛盾的,以为一开始其实是他倡导的独立革命才组织起了这群人,然而现在他又认清了现实社会已经不太相信能通过革命来独立的可能性,后来激进派便开始越加封闭,而且进行军事训练和思想教育,而后这个先驱的激进派别便有了新的名字”黎明”,深绘里也是在此时从先驱逃离来投靠戎野老师
暂时先写到这,未完待续~

0%
\ No newline at end of file +村上春树《1Q84》读后感 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

村上春树《1Q84》读后感

看完了村上春树的《1Q84》,这应该是第五本看的他的书了,继 跑步,挪威的森林,刺杀骑士团长,海边的卡夫卡之后,不是其中最长的,好像是海边的卡夫卡还是刺杀骑士团长比较长一点,都是在微信读书上看的,比较方便,最开始在上面看的是高晓松的《鱼羊野史》,不知道为啥取这个名字,但是还是满吸引我的,不过由于去年的种种,没有很多心思把它看完,而且本身的组织形式就是比较松散的,看到哪算哪,其实一些野史部分是我比较喜欢,有些谈到人物的就不太有兴趣,而且类似于大祥哥吃的东西,反正都是哇,怎么这么好吃,嗯,太爱(niu)你(bi)了,高晓松就是这个人是我最喜欢的 xxx 家,我也没去细究过他有没有说重复过,反正是不太爱,后来因为这书还一度对战争史有了浓厚的兴趣,然而事实告诉我,大部头的战争史,其实正史我是真的啃不下去,我可能只对其中 10%的内容感兴趣,不过终于也在今年把它看完了,好像高晓松的晓说也最终季了,貌似其中讲朝鲜战争的还被和谐了,看样子是说出了一些故事(truth)。

本来只是想把 《1Q84》的读后感写下,现在觉得还是把这篇当成我今年的读书总结吧,不过先从《1Q84》说起。

严格来讲,这不是很书面化的读后感,可能我想写的也只是像聊天一样的说下我读过的书,包括的技术博客其实也是类似的,以后或许会转变,但是目前水平如此吧,写多了可能会变好,也可能不会。

开始正文吧,这书有点类似于海边的卡夫卡,一开始是通过两条故事线,穿插着叙述,一条是青豆的,不算是个职业杀手的女杀手,要去解决一个经常家暴的斯文败类,穿着描述得比较性感吧,杀人方式是通过比较长的细针,从脖子后面一个精巧的位置插入,可以造成是未知原因死亡的假象,可能会推断成心梗之类的,这里有个前置的细节,就是青豆是乘坐一辆很高级的出租车,内饰什么的都非常有质感,有点不像一辆出租车,然后车里放了一首比较小众的歌,雅纳切克的《小交响曲》,但是青豆知道它,这跟后面的情节也有些许关系,这是女主人公青豆的出场;相应的男主的出场印象不是太深刻,男主叫天吾,是个不知名的作家,跟一个叫小松的编辑有比较好的关系,虽然天吾还没有拿到比较有分量的奖项,但是小松很看好他,也让他帮忙审校一个新作家奖的投稿文章,虽然天吾自身还没获得过这个奖,天吾还有个正式工作,是当数学老师,天吾在学生时代是个数学天才,但后面有对文学产生了兴趣,文学还不足以养活自己,靠着教课还是能保持温饱;

接下来是正式故事的起点了,就是小松收到了一部小说投稿,名叫《空气蛹》,是个叫深绘里的女孩子投的稿,小松对他赋予了很高的评价,这里好像记岔了,好像是天吾对这部小说很有好感,但是小松比较怀疑,然后小松看了之后也有了浓厚的兴趣,这里就是开端了,小松想让天吾来重写润色这部《空气蛹》,因为故事本身很有分量,但是描写手法叙事方式等都很拙劣,而天吾正好擅长这个,小松对天吾的评价是,描写技巧无可挑剔,就是故事主体的火花还没际遇迸发,需要一个导火索,这个就可以类比我们程序员,很多比较初中级的程序员主要擅长在原来的代码上修修改改或者给他分配个小功能,比较高级的程序员就需要能做一些项目的架构设计,核心的技术方案设计,以前我也觉得写文档这个比较无聊,但是当一个项目真的比较庞大,复杂的时候,整体和核心部分的架构设计和方案还是需要有文档沉淀的,不然别人不知道没法接受,自己过段时间也会忘记。

对于小松的这个建议,他的初衷是想搅一搅这个死气沉沉套路颇深的文坛,因为本身《空气蛹》这部小说的内容很吸引人,小松想通过天吾的润色补充让这部小说冲击新人奖,有种恶作剧的意图,天吾对此表示很多担心和顾虑,小松的这个建议其实也是一种文学作假,有两方面的担心,一方面是原作者深绘里是否同意如此操作,一方面是外界如果发现了这个事实会有什么样的后果,但是小松表示不用担心,前一步由小松牵线,让天吾跟原作者深绘里当面沟通这个代写是否被允许,结果当然是被允许了,这里有了对深绘里的初步描写,按我的理解是比较仙的感觉,然后语言沟通有些吃力,或者说有她自己的特色,当面沟通时貌似是让深绘里回去再考虑下,然后后面再由天吾去深绘里寄宿的戎野老师家沟通具体的细节。

2019年12月18日23:37:19 更新
去到戎野老师家之后,天吾知道了关于深绘里的一些事情,深绘里的父亲与戎野老师应该是老友,深绘里的父亲在当初成立了一个叫”先驱”的公社,一个独立运行的社会组织,以运营农场作为物资来源,追求更为松散的共同体,即不过分激进地公有制,进行松散的共同生活,承认私有财产,简而言之就是这样一个能稳定存活下来的独立社会组织,但是随着稳定运行,内部的激进派和稳健派开始出现分歧,不可磨合,后来两派就分裂了,深绘里的父亲,深田保留在了稳健派,但是此时其实深田保内心是矛盾的,以为一开始其实是他倡导的独立革命才组织起了这群人,然而现在他又认清了现实社会已经不太相信能通过革命来独立的可能性,后来激进派便开始越加封闭,而且进行军事训练和思想教育,而后这个先驱的激进派别便有了新的名字”黎明”,深绘里也是在此时从先驱逃离来投靠戎野老师
暂时先写到这,未完待续~

0%
\ No newline at end of file diff --git a/2020/02/09/G1收集器概述/index.html b/2020/02/09/G1收集器概述/index.html index da2b643a1f..efdd132f72 100644 --- a/2020/02/09/G1收集器概述/index.html +++ b/2020/02/09/G1收集器概述/index.html @@ -1,4 +1,4 @@ -G1收集器概述 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

G1收集器概述

G1: The Garbage-First Collector, 垃圾回收优先的垃圾回收器,目标是用户多核 cpu 和大内存的机器,最大的特点就是可预测的停顿时间,官方给出的介绍是提供一个用户在大的堆内存情况下一个低延迟表现的解决方案,通常是 6GB 及以上的堆大小,有低于 0.5 秒稳定的可预测的停顿时间。

这里主要介绍这个比较新的垃圾回收器,在 G1 之前的垃圾回收器都是基于如下图的内存结构分布,有新生代,老年代和永久代(jdk8 之前),然后G1 往前的那些垃圾回收器都有个分代,比如 serial,parallel 等,一般有个应用的组合,最初的 serial 和 serial old,因为新生代和老年代的收集方式不太一样,新生代主要是标记复制,所以有 eden 跟两个 survival区,老年代一般用标记整理方式,而 G1 对这个不太一样。

看一下 G1 的内存分布

可以看到这有很大的不同,G1 通过将内存分成大小相等的 region,每个region是存在于一个连续的虚拟内存范围,对于某个 region 来说其角色是类似于原来的收集器的Eden、Survivor、Old Generation,这个具体在代码层面

// We encode the value of the heap region type so the generation can be
+G1收集器概述 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

G1收集器概述

G1: The Garbage-First Collector, 垃圾回收优先的垃圾回收器,目标是用户多核 cpu 和大内存的机器,最大的特点就是可预测的停顿时间,官方给出的介绍是提供一个用户在大的堆内存情况下一个低延迟表现的解决方案,通常是 6GB 及以上的堆大小,有低于 0.5 秒稳定的可预测的停顿时间。

这里主要介绍这个比较新的垃圾回收器,在 G1 之前的垃圾回收器都是基于如下图的内存结构分布,有新生代,老年代和永久代(jdk8 之前),然后G1 往前的那些垃圾回收器都有个分代,比如 serial,parallel 等,一般有个应用的组合,最初的 serial 和 serial old,因为新生代和老年代的收集方式不太一样,新生代主要是标记复制,所以有 eden 跟两个 survival区,老年代一般用标记整理方式,而 G1 对这个不太一样。

看一下 G1 的内存分布

可以看到这有很大的不同,G1 通过将内存分成大小相等的 region,每个region是存在于一个连续的虚拟内存范围,对于某个 region 来说其角色是类似于原来的收集器的Eden、Survivor、Old Generation,这个具体在代码层面

// We encode the value of the heap region type so the generation can be
  // determined quickly. The tag is split into two parts:
  //
  //   major type (young, old, humongous, archive)           : top N-1 bits
@@ -52,4 +52,4 @@
    ArchiveMask           = 32,
    OpenArchiveTag        = ArchiveMask | PinnedMask | OldMask,
    ClosedArchiveTag      = ArchiveMask | PinnedMask | OldMask + 1
- } Tag;

hotspot/share/gc/g1/heapRegionType.hpp

当执行垃圾收集时,G1以类似于CMS收集器的方式运行。 G1执行并发全局标记阶段,以确定整个堆中对象的存活性。标记阶段完成后,G1知道哪些region是基本空的。它首先收集这些region,通常会产生大量的可用空间。这就是为什么这种垃圾收集方法称为“垃圾优先”的原因。顾名思义,G1将其收集和压缩活动集中在可能充满可回收对象(即垃圾)的堆区域。 G1使用暂停预测模型来满足用户定义的暂停时间目标,并根据指定的暂停时间目标选择要收集的区域数。

由G1标识为可回收的区域是使用撤离的方式(Evacuation)。 G1将对象从堆的一个或多个区域复制到堆上的单个区域,并在此过程中压缩并释放内存。撤离是在多处理器上并行执行的,以减少暂停时间并增加吞吐量。因此,对于每次垃圾收集,G1都在用户定义的暂停时间内连续工作以减少碎片。这是优于前面两种方法的。 CMS(并发标记扫描)垃圾收集器不进行压缩。 ParallelOld垃圾回收仅执行整个堆压缩,这导致相当长的暂停时间。

需要重点注意的是,G1不是实时收集器。它很有可能达到设定的暂停时间目标,但并非绝对确定。 G1根据先前收集的数据,估算在用户指定的目标时间内可以收集多少个区域。因此,收集器具有收集区域成本的合理准确的模型,并且收集器使用此模型来确定要收集哪些和多少个区域,同时保持在暂停时间目标之内。

注意:G1同时具有并发(与应用程序线程一起运行,例如优化,标记,清理)和并行(多线程,例如stw)阶段。Full GC仍然是单线程的,但是如果正确调优,您的应用程序应该可以避免Full GC。

在前面那篇中在代码层面简单的了解了这个可预测时间的过程,这也是 G1 的一大特点。

0%
\ No newline at end of file + } Tag;

hotspot/share/gc/g1/heapRegionType.hpp

当执行垃圾收集时,G1以类似于CMS收集器的方式运行。 G1执行并发全局标记阶段,以确定整个堆中对象的存活性。标记阶段完成后,G1知道哪些region是基本空的。它首先收集这些region,通常会产生大量的可用空间。这就是为什么这种垃圾收集方法称为“垃圾优先”的原因。顾名思义,G1将其收集和压缩活动集中在可能充满可回收对象(即垃圾)的堆区域。 G1使用暂停预测模型来满足用户定义的暂停时间目标,并根据指定的暂停时间目标选择要收集的区域数。

由G1标识为可回收的区域是使用撤离的方式(Evacuation)。 G1将对象从堆的一个或多个区域复制到堆上的单个区域,并在此过程中压缩并释放内存。撤离是在多处理器上并行执行的,以减少暂停时间并增加吞吐量。因此,对于每次垃圾收集,G1都在用户定义的暂停时间内连续工作以减少碎片。这是优于前面两种方法的。 CMS(并发标记扫描)垃圾收集器不进行压缩。 ParallelOld垃圾回收仅执行整个堆压缩,这导致相当长的暂停时间。

需要重点注意的是,G1不是实时收集器。它很有可能达到设定的暂停时间目标,但并非绝对确定。 G1根据先前收集的数据,估算在用户指定的目标时间内可以收集多少个区域。因此,收集器具有收集区域成本的合理准确的模型,并且收集器使用此模型来确定要收集哪些和多少个区域,同时保持在暂停时间目标之内。

注意:G1同时具有并发(与应用程序线程一起运行,例如优化,标记,清理)和并行(多线程,例如stw)阶段。Full GC仍然是单线程的,但是如果正确调优,您的应用程序应该可以避免Full GC。

在前面那篇中在代码层面简单的了解了这个可预测时间的过程,这也是 G1 的一大特点。

0%
\ No newline at end of file diff --git a/2020/05/31/聊聊-Dubbo-的-SPI/index.html b/2020/05/31/聊聊-Dubbo-的-SPI/index.html index 7dea78fd0c..2059975577 100644 --- a/2020/05/31/聊聊-Dubbo-的-SPI/index.html +++ b/2020/05/31/聊聊-Dubbo-的-SPI/index.html @@ -1,4 +1,4 @@ -聊聊 Dubbo 的 SPI | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

聊聊 Dubbo 的 SPI

SPI全称是Service Provider Interface,咋眼看跟api是不是有点相似,api是application interface,这两个其实在某些方面有类似的地方,也有蛮大的区别,比如我们基于 dubbo 的微服务,一般我们可以提供服务,然后非泛化调用的话,我们可以把 api 包提供给应用调用方,他们根据接口签名传对应参数并配置好对应的服务发现如 zk 等就可以调用我们的服务了,然后 spi 会有点类似但是是反过来的关系,相当于是一种规范,比如我约定完成这个功能需要两个有两个接口,一个是连接的,一个是断开的,其实就可以用 jdbc 的驱动举例,比较老套了,然后各个厂家去做具体的实现吧,到时候根据我接口的全限定名的文件来加载实际的实现类,然后运行的时候调用对应实现类的方法就完了

3sKdpg

看上面的图,java.sql.Driver就是 spi,对应在classpath 的 META-INF/services 目录下的这个文件,里边的内容就是具体的实现类

1590735097909

简单介绍了 Java的 SPI,再来说说 dubbo 的,dubbo 中为啥要用 SPI 呢,主要是为了框架的可扩展性和性能方面的考虑,比如协议层 dubbo 默认使用 dubbo 协议,同时也支持很多其他协议,也支持用户自己实现协议,那么跟 Java 的 SPI 会有什么区别呢,我们也来看个文件

bqxWMp

是不是看着很想,又有点不一样,在 Java 的 SPI 配置文件里每一行只有一个实现类的全限定名,在 Dubbo的 SPI配置文件中是 key=value 的形式,我们只需要对应的 key 就能加载对应的实现,

/**
+聊聊 Dubbo 的 SPI | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

聊聊 Dubbo 的 SPI

SPI全称是Service Provider Interface,咋眼看跟api是不是有点相似,api是application interface,这两个其实在某些方面有类似的地方,也有蛮大的区别,比如我们基于 dubbo 的微服务,一般我们可以提供服务,然后非泛化调用的话,我们可以把 api 包提供给应用调用方,他们根据接口签名传对应参数并配置好对应的服务发现如 zk 等就可以调用我们的服务了,然后 spi 会有点类似但是是反过来的关系,相当于是一种规范,比如我约定完成这个功能需要两个有两个接口,一个是连接的,一个是断开的,其实就可以用 jdbc 的驱动举例,比较老套了,然后各个厂家去做具体的实现吧,到时候根据我接口的全限定名的文件来加载实际的实现类,然后运行的时候调用对应实现类的方法就完了

3sKdpg

看上面的图,java.sql.Driver就是 spi,对应在classpath 的 META-INF/services 目录下的这个文件,里边的内容就是具体的实现类

1590735097909

简单介绍了 Java的 SPI,再来说说 dubbo 的,dubbo 中为啥要用 SPI 呢,主要是为了框架的可扩展性和性能方面的考虑,比如协议层 dubbo 默认使用 dubbo 协议,同时也支持很多其他协议,也支持用户自己实现协议,那么跟 Java 的 SPI 会有什么区别呢,我们也来看个文件

bqxWMp

是不是看着很想,又有点不一样,在 Java 的 SPI 配置文件里每一行只有一个实现类的全限定名,在 Dubbo的 SPI配置文件中是 key=value 的形式,我们只需要对应的 key 就能加载对应的实现,

/**
      * 返回指定名字的扩展。如果指定名字的扩展不存在,则抛异常 {@link IllegalStateException}.
      *
      * @param name
diff --git a/2020/06/06/聊聊-Dubbo-的-SPI-续之自适应拓展/index.html b/2020/06/06/聊聊-Dubbo-的-SPI-续之自适应拓展/index.html
index 29c42b3501..c913dd2743 100644
--- a/2020/06/06/聊聊-Dubbo-的-SPI-续之自适应拓展/index.html
+++ b/2020/06/06/聊聊-Dubbo-的-SPI-续之自适应拓展/index.html
@@ -1,4 +1,4 @@
-聊聊 Dubbo 的 SPI 续之自适应拓展 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

聊聊 Dubbo 的 SPI 续之自适应拓展

Adaptive

这个应该是 Dubbo SPI 里最玄妙的东西了,一开始没懂,自适应扩展点加载,
dubbo://123.123.123.123:1234/com.nicksxs.demo.service.HelloWorldService?anyhost=true&application=demo&default.loadbalance=random&default.service.filter=LoggerFilter&dubbo=2.5.3&interface=com.nicksxs.demo.service.HelloWorldService&logger=slf4j&methods=method1,method2,method3,method4&pid=4292&retries=0&side=provider&threadpool=fixed&threads=200&timeout=2000&timestamp=1590647155886
那我从比较能理解的角度或者说思路去讲讲我的理解,因为直接将原理如果脱离了使用,对于我这样的理解能力比较差的可能会比较吃力,从使用场景开始讲可能会比较舒服了,这里可以看到参数里有蛮多的,举个例子,比如这个 threadpool = fixed,说明线程池使用的是 fixed 对应的实现,也就是下图的这个

这样子似乎没啥问题了,反正就是用dubbo 的 spi 加载嘛,好像没啥问题,其实问题还是存在的,或者说不太优雅,比如要先判断我这个 fixed 对应的实现类是哪个,这里可能就有个 if-else 判断了,但是 dubbo 的开发人员似乎不太想这么做这个事情,

譬如我们在引用一个服务时,在ReferenceConfig 中的

private static final Protocol refprotocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();

就获取了自适应拓展,

public T getAdaptiveExtension() {
+聊聊 Dubbo 的 SPI 续之自适应拓展 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

聊聊 Dubbo 的 SPI 续之自适应拓展

Adaptive

这个应该是 Dubbo SPI 里最玄妙的东西了,一开始没懂,自适应扩展点加载,
dubbo://123.123.123.123:1234/com.nicksxs.demo.service.HelloWorldService?anyhost=true&application=demo&default.loadbalance=random&default.service.filter=LoggerFilter&dubbo=2.5.3&interface=com.nicksxs.demo.service.HelloWorldService&logger=slf4j&methods=method1,method2,method3,method4&pid=4292&retries=0&side=provider&threadpool=fixed&threads=200&timeout=2000&timestamp=1590647155886
那我从比较能理解的角度或者说思路去讲讲我的理解,因为直接将原理如果脱离了使用,对于我这样的理解能力比较差的可能会比较吃力,从使用场景开始讲可能会比较舒服了,这里可以看到参数里有蛮多的,举个例子,比如这个 threadpool = fixed,说明线程池使用的是 fixed 对应的实现,也就是下图的这个

这样子似乎没啥问题了,反正就是用dubbo 的 spi 加载嘛,好像没啥问题,其实问题还是存在的,或者说不太优雅,比如要先判断我这个 fixed 对应的实现类是哪个,这里可能就有个 if-else 判断了,但是 dubbo 的开发人员似乎不太想这么做这个事情,

譬如我们在引用一个服务时,在ReferenceConfig 中的

private static final Protocol refprotocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();

就获取了自适应拓展,

public T getAdaptiveExtension() {
         Object instance = cachedAdaptiveInstance.get();
         if (instance == null) {
             if (createAdaptiveInstanceError == null) {
diff --git a/2020/09/06/mybatis-的-和-是有啥区别/index.html b/2020/09/06/mybatis-的-和-是有啥区别/index.html
index 61a4b7df7b..eda6b9e7a6 100644
--- a/2020/09/06/mybatis-的-和-是有啥区别/index.html
+++ b/2020/09/06/mybatis-的-和-是有啥区别/index.html
@@ -1,4 +1,4 @@
-mybatis 的 $ 和 # 是有啥区别 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

mybatis 的 $ 和 # 是有啥区别

这个问题也是面试中常被问到的,就抽空来了解下这个,跳过一大段前面初始化的逻辑,
对于一条select * from t1 where id = #{id}这样的 sql,在初始化扫描 mapper 的xml文件的时候会根据是否是 dynamic 来判断生成 DynamicSqlSource 还是 RawSqlSource,这里它是一条 RawSqlSource,
在这里做了替换,将#{}替换成了?

前面说的是否 dynamic 就是在这里进行判断

// org.apache.ibatis.scripting.xmltags.XMLScriptBuilder#parseScriptNode
+mybatis 的 $ 和 # 是有啥区别 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

mybatis 的 $ 和 # 是有啥区别

这个问题也是面试中常被问到的,就抽空来了解下这个,跳过一大段前面初始化的逻辑,
对于一条select * from t1 where id = #{id}这样的 sql,在初始化扫描 mapper 的xml文件的时候会根据是否是 dynamic 来判断生成 DynamicSqlSource 还是 RawSqlSource,这里它是一条 RawSqlSource,
在这里做了替换,将#{}替换成了?

前面说的是否 dynamic 就是在这里进行判断

// org.apache.ibatis.scripting.xmltags.XMLScriptBuilder#parseScriptNode
 public SqlSource parseScriptNode() {
     MixedSqlNode rootSqlNode = parseDynamicTags(context);
     SqlSource sqlSource;
diff --git a/2020/09/20/Leetcode-3-Longest-Substring-Without-Repeating-Characters-题解分析/index.html b/2020/09/20/Leetcode-3-Longest-Substring-Without-Repeating-Characters-题解分析/index.html
index 34257b9f6e..072018ac84 100644
--- a/2020/09/20/Leetcode-3-Longest-Substring-Without-Repeating-Characters-题解分析/index.html
+++ b/2020/09/20/Leetcode-3-Longest-Substring-Without-Repeating-Characters-题解分析/index.html
@@ -1,4 +1,4 @@
-Leetcode 3 Longest Substring Without Repeating Characters 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 3 Longest Substring Without Repeating Characters 题解分析

又做了个题,看记录是以前用 C++写过的,现在捋一捋思路,用 Java 再写了一下,思路还是比较清晰的,但是边界细节处理得比较差

简要介绍

Given a string s, find the length of the longest substring without repeating characters.

样例

Example 1:

Input: s = "abcabcbb"
+Leetcode 3 Longest Substring Without Repeating Characters 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 3 Longest Substring Without Repeating Characters 题解分析

又做了个题,看记录是以前用 C++写过的,现在捋一捋思路,用 Java 再写了一下,思路还是比较清晰的,但是边界细节处理得比较差

简要介绍

Given a string s, find the length of the longest substring without repeating characters.

样例

Example 1:

Input: s = "abcabcbb"
 Output: 3
 Explanation: The answer is "abc", with the length of 3.

Example 2:

Input: s = "bbbbb"
 Output: 1
@@ -38,4 +38,4 @@ Output: 0

注释应该写的比较清楚了。

0%
\ No newline at end of file +}

注释应该写的比较清楚了。

0%
\ No newline at end of file diff --git a/2020/10/03/mybatis-的缓存是怎么回事/index.html b/2020/10/03/mybatis-的缓存是怎么回事/index.html index f24dfeff3a..6e24373007 100644 --- a/2020/10/03/mybatis-的缓存是怎么回事/index.html +++ b/2020/10/03/mybatis-的缓存是怎么回事/index.html @@ -1,4 +1,4 @@ -mybatis 的缓存是怎么回事 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

mybatis 的缓存是怎么回事

Java 真的是任何一个中间件,比较常用的那种,都有很多内容值得深挖,比如这个缓存,慢慢有过一些感悟,比如如何提升性能,缓存无疑是一大重要手段,最底层开始 CPU 就有缓存,而且又小又贵,再往上一点内存一般作为硬盘存储在运行时的存储,一般在代码里也会用内存作为一些本地缓存,譬如数据库,像 mysql 这种也是有innodb_buffer_pool来提升查询效率,本质上理解就是用更快的存储作为相对慢存储的缓存,减少查询直接访问较慢的存储,并且这个都是相对的,比起 cpu 的缓存,那内存也是渣,但是与普通机械硬盘相比,那也是两个次元的水平。

闲扯这么多来说说 mybatis 的缓存,mybatis 一般作为一个轻量级的 orm 使用,相对应的就是比较重量级的 hibernate,不过不在这次讨论范围,上一次是主要讲了 mybatis 在解析 sql 过程中,对于两种占位符的不同替换实现策略,这次主要聊下 mybatis 的缓存,前面其实得了解下前置的东西,比如 sqlsession,先当做我们知道 sqlsession 是个什么玩意,可能或多或少的知道 mybatis 是有两级缓存,

一级缓存

第一级的缓存是在 BaseExecutor 中的 PerpetualCache,它是个最基本的缓存实现类,使用了 HashMap 实现缓存功能,代码其实没几十行

public class PerpetualCache implements Cache {
+mybatis 的缓存是怎么回事 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

mybatis 的缓存是怎么回事

Java 真的是任何一个中间件,比较常用的那种,都有很多内容值得深挖,比如这个缓存,慢慢有过一些感悟,比如如何提升性能,缓存无疑是一大重要手段,最底层开始 CPU 就有缓存,而且又小又贵,再往上一点内存一般作为硬盘存储在运行时的存储,一般在代码里也会用内存作为一些本地缓存,譬如数据库,像 mysql 这种也是有innodb_buffer_pool来提升查询效率,本质上理解就是用更快的存储作为相对慢存储的缓存,减少查询直接访问较慢的存储,并且这个都是相对的,比起 cpu 的缓存,那内存也是渣,但是与普通机械硬盘相比,那也是两个次元的水平。

闲扯这么多来说说 mybatis 的缓存,mybatis 一般作为一个轻量级的 orm 使用,相对应的就是比较重量级的 hibernate,不过不在这次讨论范围,上一次是主要讲了 mybatis 在解析 sql 过程中,对于两种占位符的不同替换实现策略,这次主要聊下 mybatis 的缓存,前面其实得了解下前置的东西,比如 sqlsession,先当做我们知道 sqlsession 是个什么玩意,可能或多或少的知道 mybatis 是有两级缓存,

一级缓存

第一级的缓存是在 BaseExecutor 中的 PerpetualCache,它是个最基本的缓存实现类,使用了 HashMap 实现缓存功能,代码其实没几十行

public class PerpetualCache implements Cache {
 
   private final String id;
 
diff --git a/2020/10/11/Leetcode-2-Add-Two-Numbers-题解分析/index.html b/2020/10/11/Leetcode-2-Add-Two-Numbers-题解分析/index.html
index 1eecb8818f..2844686734 100644
--- a/2020/10/11/Leetcode-2-Add-Two-Numbers-题解分析/index.html
+++ b/2020/10/11/Leetcode-2-Add-Two-Numbers-题解分析/index.html
@@ -1,4 +1,4 @@
-Leetcode 2 Add Two Numbers 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 2 Add Two Numbers 题解分析

又 roll 到了一个以前做过的题,不过现在用 Java 也来写一下,是 easy 级别的,所以就简单说下

简要介绍

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.
就是给了两个链表,用来表示两个非负的整数,在链表中倒序放着,每个节点包含一位的数字,把他们加起来以后也按照原来的链表结构输出

样例

example 1

Input: l1 = [2,4,3], l2 = [5,6,4]
+Leetcode 2 Add Two Numbers 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 2 Add Two Numbers 题解分析

又 roll 到了一个以前做过的题,不过现在用 Java 也来写一下,是 easy 级别的,所以就简单说下

简要介绍

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.
就是给了两个链表,用来表示两个非负的整数,在链表中倒序放着,每个节点包含一位的数字,把他们加起来以后也按照原来的链表结构输出

样例

example 1

Input: l1 = [2,4,3], l2 = [5,6,4]
 Output: [7,0,8]
 Explanation: 342 + 465 = 807.

example 2

Input: l1 = [0], l2 = [0]
 Output: [0]

example 3

Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
@@ -30,4 +30,4 @@ Output: [8,9,9,9,0,0,0,1]

这里唯二需要注意的就是两个点,一个是循环条件需要包含进位值还存在的情况,还有一个是最后一个节点,如果是空的了,就不要在 new 一个出来了,写的比较挫

0%
\ No newline at end of file + }

这里唯二需要注意的就是两个点,一个是循环条件需要包含进位值还存在的情况,还有一个是最后一个节点,如果是空的了,就不要在 new 一个出来了,写的比较挫

0%
\ No newline at end of file diff --git a/2020/10/25/Leetcode-104-二叉树的最大深度-Maximum-Depth-of-Binary-Tree-题解分析/index.html b/2020/10/25/Leetcode-104-二叉树的最大深度-Maximum-Depth-of-Binary-Tree-题解分析/index.html index 18b0cbd570..9343760e60 100644 --- a/2020/10/25/Leetcode-104-二叉树的最大深度-Maximum-Depth-of-Binary-Tree-题解分析/index.html +++ b/2020/10/25/Leetcode-104-二叉树的最大深度-Maximum-Depth-of-Binary-Tree-题解分析/index.html @@ -1,4 +1,4 @@ -Leetcode 104 二叉树的最大深度(Maximum Depth of Binary Tree) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 104 二叉树的最大深度(Maximum Depth of Binary Tree) 题解分析

题目介绍

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

示例:
给定二叉树 [3,9,20,null,null,15,7],

  3
+Leetcode 104 二叉树的最大深度(Maximum Depth of Binary Tree) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 104 二叉树的最大深度(Maximum Depth of Binary Tree) 题解分析

题目介绍

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

示例:
给定二叉树 [3,9,20,null,null,15,7],

  3
  / \
 9  20
   /  \
@@ -20,4 +20,4 @@
     }
     // 前面返回后,左右取大者
     return Math.max(left + 1, right + 1);
-}

分析

其实对于树这类题,一般是以递归形式比较方便,只是要注意退出条件

0%
\ No newline at end of file +}

分析

其实对于树这类题,一般是以递归形式比较方便,只是要注意退出条件

0%
\ No newline at end of file diff --git a/2020/11/15/Leetcode-234-回文联表-Palindrome-Linked-List-题解分析/index.html b/2020/11/15/Leetcode-234-回文联表-Palindrome-Linked-List-题解分析/index.html index 02ebe3f38d..16eeae0951 100644 --- a/2020/11/15/Leetcode-234-回文联表-Palindrome-Linked-List-题解分析/index.html +++ b/2020/11/15/Leetcode-234-回文联表-Palindrome-Linked-List-题解分析/index.html @@ -1,4 +1,4 @@ -Leetcode 234 回文链表(Palindrome Linked List) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 234 回文链表(Palindrome Linked List) 题解分析

题目介绍

Given a singly linked list, determine if it is a palindrome.
给定一个单向链表,判断是否是回文链表

例一 Example 1:

Input: 1->2
Output: false

例二 Example 2:

Input: 1->2->2->1
Output: true

挑战下自己

Follow up:
Could you do it in O(n) time and O(1) space?

简要分析

首先这是个单向链表,如果是双向的就可以一个从头到尾,一个从尾到头,显然那样就没啥意思了,然后想过要不找到中点,然后用一个栈,把前一半塞进栈里,但是这种其实也比较麻烦,比如长度是奇偶数,然后如何找到中点,这倒是可以借助于双指针,还是比较麻烦,再想一想,回文链表,就跟最开始的一样,链表只有单向的,我用个栈不就可以逆向了么,先把链表整个塞进栈里,然后在一个个 pop 出来跟链表从头开始比较,全对上了就是回文了

/**
+Leetcode 234 回文链表(Palindrome Linked List) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 234 回文链表(Palindrome Linked List) 题解分析

题目介绍

Given a singly linked list, determine if it is a palindrome.
给定一个单向链表,判断是否是回文链表

例一 Example 1:

Input: 1->2
Output: false

例二 Example 2:

Input: 1->2->2->1
Output: true

挑战下自己

Follow up:
Could you do it in O(n) time and O(1) space?

简要分析

首先这是个单向链表,如果是双向的就可以一个从头到尾,一个从尾到头,显然那样就没啥意思了,然后想过要不找到中点,然后用一个栈,把前一半塞进栈里,但是这种其实也比较麻烦,比如长度是奇偶数,然后如何找到中点,这倒是可以借助于双指针,还是比较麻烦,再想一想,回文链表,就跟最开始的一样,链表只有单向的,我用个栈不就可以逆向了么,先把链表整个塞进栈里,然后在一个个 pop 出来跟链表从头开始比较,全对上了就是回文了

/**
  * Definition for singly-linked list.
  * public class ListNode {
  *     int val;
@@ -31,4 +31,4 @@
         }
         return true;
     }
-}
0%
\ No newline at end of file +}
0%
\ No newline at end of file diff --git a/2020/12/06/Leetcode-155-最小栈-Min-Stack-题解分析/index.html b/2020/12/06/Leetcode-155-最小栈-Min-Stack-题解分析/index.html index 203af8d88a..1c21d85c8a 100644 --- a/2020/12/06/Leetcode-155-最小栈-Min-Stack-题解分析/index.html +++ b/2020/12/06/Leetcode-155-最小栈-Min-Stack-题解分析/index.html @@ -1,4 +1,4 @@ -Leetcode 155 最小栈(Min Stack) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 155 最小栈(Min Stack) 题解分析

题目介绍

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
设计一个栈,支持压栈,出站,获取栈顶元素,通过常数级复杂度获取栈中的最小元素

  • push(x) – Push element x onto stack.
  • pop() – Removes the element on top of the stack.
  • top() – Get the top element.
  • getMin() – Retrieve the minimum element in the stack.

示例

Example 1:

Input
+Leetcode 155 最小栈(Min Stack) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 155 最小栈(Min Stack) 题解分析

题目介绍

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
设计一个栈,支持压栈,出站,获取栈顶元素,通过常数级复杂度获取栈中的最小元素

  • push(x) – Push element x onto stack.
  • pop() – Removes the element on top of the stack.
  • top() – Get the top element.
  • getMin() – Retrieve the minimum element in the stack.

示例

Example 1:

Input
 ["MinStack","push","push","push","getMin","pop","top","getMin"]
 [[],[-2],[0],[-3],[],[],[],[]]
 
@@ -51,4 +51,4 @@ minStack.getMin(); // return -2
             return s2.peek();
         }
-    }
0%
\ No newline at end of file + }
0%
\ No newline at end of file diff --git a/2020/12/13/Leetcode-105-从前序与中序遍历序列构造二叉树-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal-题解分析/index.html b/2020/12/13/Leetcode-105-从前序与中序遍历序列构造二叉树-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal-题解分析/index.html index bf537b3a87..1a05384332 100644 --- a/2020/12/13/Leetcode-105-从前序与中序遍历序列构造二叉树-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal-题解分析/index.html +++ b/2020/12/13/Leetcode-105-从前序与中序遍历序列构造二叉树-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal-题解分析/index.html @@ -1,4 +1,4 @@ -Leetcode 105 从前序与中序遍历序列构造二叉树(Construct Binary Tree from Preorder and Inorder Traversal) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 105 从前序与中序遍历序列构造二叉树(Construct Binary Tree from Preorder and Inorder Traversal) 题解分析

题目介绍

Given preorder and inorder traversal of a tree, construct the binary tree.
给定一棵树的前序和中序遍历,构造出一棵二叉树

注意

You may assume that duplicates do not exist in the tree.
你可以假设树中没有重复的元素。(PS: 不然就没法做了呀)

例子:

preorder = [3,9,20,15,7]
+Leetcode 105 从前序与中序遍历序列构造二叉树(Construct Binary Tree from Preorder and Inorder Traversal) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 105 从前序与中序遍历序列构造二叉树(Construct Binary Tree from Preorder and Inorder Traversal) 题解分析

题目介绍

Given preorder and inorder traversal of a tree, construct the binary tree.
给定一棵树的前序和中序遍历,构造出一棵二叉树

注意

You may assume that duplicates do not exist in the tree.
你可以假设树中没有重复的元素。(PS: 不然就没法做了呀)

例子:

preorder = [3,9,20,15,7]
 inorder = [9,3,15,20,7]

返回的二叉树

  3
  / \
 9  20
@@ -32,4 +32,4 @@ inorder = [9,3,15,20,7]
0%
\ No newline at end of file +}
0%
\ No newline at end of file diff --git a/2021/01/10/Leetcode-160-相交链表-intersection-of-two-linked-lists-题解分析/index.html b/2021/01/10/Leetcode-160-相交链表-intersection-of-two-linked-lists-题解分析/index.html index d58001f4c8..cdbd807694 100644 --- a/2021/01/10/Leetcode-160-相交链表-intersection-of-two-linked-lists-题解分析/index.html +++ b/2021/01/10/Leetcode-160-相交链表-intersection-of-two-linked-lists-题解分析/index.html @@ -1,4 +1,4 @@ -Leetcode 160 相交链表(intersection-of-two-linked-lists) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 160 相交链表(intersection-of-two-linked-lists) 题解分析

题目介绍

写一个程序找出两个单向链表的交叉起始点,可能是我英语不好,图里画的其实还有一点是交叉以后所有节点都是相同的
Write a program to find the node at which the intersection of two singly linked lists begins.

For example, the following two linked lists:

begin to intersect at node c1.

Example 1:

Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3
+Leetcode 160 相交链表(intersection-of-two-linked-lists) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 160 相交链表(intersection-of-two-linked-lists) 题解分析

题目介绍

写一个程序找出两个单向链表的交叉起始点,可能是我英语不好,图里画的其实还有一点是交叉以后所有节点都是相同的
Write a program to find the node at which the intersection of two singly linked lists begins.

For example, the following two linked lists:

begin to intersect at node c1.

Example 1:

Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3
 Output: Reference of the node with value = 8
 Input Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.

分析题解

一开始没什么头绪,感觉只能最原始的遍历,后来看了一些文章,发现比较简单的方式就是先找两个链表的长度差,因为从相交点开始肯定是长度一致的,这是个很好的解题突破口,找到长度差以后就是先跳过长链表的较长部分,然后开始同步遍历比较 A,B 链表;

代码

public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
         if (headA == null || headB == null) {
@@ -42,4 +42,4 @@ Input Explanation: The intersected node's value is 8 (note that this must not be
             }
         }
         return null;
-    }

总结

可能缺少这种思维,做的还是比较少,所以没法一下子反应过来,需要锻炼,我的第一反应是两重遍历,不过那样复杂度就高了,这里应该是只有 O(N) 的复杂度。

0%
\ No newline at end of file + }

总结

可能缺少这种思维,做的还是比较少,所以没法一下子反应过来,需要锻炼,我的第一反应是两重遍历,不过那样复杂度就高了,这里应该是只有 O(N) 的复杂度。

0%
\ No newline at end of file diff --git a/2021/01/24/Leetcode-124-二叉树中的最大路径和-Binary-Tree-Maximum-Path-Sum-题解分析/index.html b/2021/01/24/Leetcode-124-二叉树中的最大路径和-Binary-Tree-Maximum-Path-Sum-题解分析/index.html index 30cb6f1406..cc826665f4 100644 --- a/2021/01/24/Leetcode-124-二叉树中的最大路径和-Binary-Tree-Maximum-Path-Sum-题解分析/index.html +++ b/2021/01/24/Leetcode-124-二叉树中的最大路径和-Binary-Tree-Maximum-Path-Sum-题解分析/index.html @@ -1,4 +1,4 @@ -Leetcode 124 二叉树中的最大路径和(Binary Tree Maximum Path Sum) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 124 二叉树中的最大路径和(Binary Tree Maximum Path Sum) 题解分析

题目介绍

A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.

The path sum of a path is the sum of the node’s values in the path.

Given the root of a binary tree, return the maximum path sum of any path.

路径 被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。该路径 至少包含一个 节点,且不一定经过根节点。

路径和 是路径中各节点值的总和。

给你一个二叉树的根节点 root ,返回其 最大路径和

简要分析

其实这个题目会被误解成比较简单,左子树最大的,或者右子树最大的,或者两边加一下,仔细想想都不对,其实有可能是产生于左子树中,或者右子树中,这两个都是指跟左子树根还有右子树根没关系的,这么说感觉不太容易理解,画个图

可以看到图里,其实最长路径和是左边这个子树组成的,跟根节点还有右子树完全没关系,然后再想一种情况,如果是整棵树就是图中的左子树,那么这个最长路径和就是左子树加右子树加根节点了,所以不是我一开始想得那么简单,在代码实现中也需要一些技巧

代码

int ansNew = Integer.MIN_VALUE;
+Leetcode 124 二叉树中的最大路径和(Binary Tree Maximum Path Sum) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 124 二叉树中的最大路径和(Binary Tree Maximum Path Sum) 题解分析

题目介绍

A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.

The path sum of a path is the sum of the node’s values in the path.

Given the root of a binary tree, return the maximum path sum of any path.

路径 被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。该路径 至少包含一个 节点,且不一定经过根节点。

路径和 是路径中各节点值的总和。

给你一个二叉树的根节点 root ,返回其 最大路径和

简要分析

其实这个题目会被误解成比较简单,左子树最大的,或者右子树最大的,或者两边加一下,仔细想想都不对,其实有可能是产生于左子树中,或者右子树中,这两个都是指跟左子树根还有右子树根没关系的,这么说感觉不太容易理解,画个图

可以看到图里,其实最长路径和是左边这个子树组成的,跟根节点还有右子树完全没关系,然后再想一种情况,如果是整棵树就是图中的左子树,那么这个最长路径和就是左子树加右子树加根节点了,所以不是我一开始想得那么简单,在代码实现中也需要一些技巧

代码

int ansNew = Integer.MIN_VALUE;
 public int maxPathSum(TreeNode root) {
         maxSumNew(root);
         return ansNew;
@@ -21,4 +21,4 @@
     int res = Math.max(left + right + root.val, currentSum);
     ans = Math.max(res, ans);
     return currentSum;
-}

这里非常重要的就是 ansNew 是最后的一个结果,而对于 maxSumNew 这个函数的返回值其实是需要包含了一个连续结果,因为要返回继续去算路径和,所以返回的是 currentSum,最终结果是 ansNew

结果图

难得有个 100%,贴个图哈哈

0%
\ No newline at end of file +}

这里非常重要的就是 ansNew 是最后的一个结果,而对于 maxSumNew 这个函数的返回值其实是需要包含了一个连续结果,因为要返回继续去算路径和,所以返回的是 currentSum,最终结果是 ansNew

结果图

难得有个 100%,贴个图哈哈

0%
\ No newline at end of file diff --git a/2021/02/07/关于读书打卡与分享/index.html b/2021/02/07/关于读书打卡与分享/index.html index aed31b053c..d760504b85 100644 --- a/2021/02/07/关于读书打卡与分享/index.html +++ b/2021/02/07/关于读书打卡与分享/index.html @@ -1 +1 @@ -关于读书打卡与分享 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

关于读书打卡与分享

最近群里大佬发起了一个读书打卡活动,需要每天读一会书,在群里打卡分享感悟,争取一个月能读完一本书,说实话一天十分钟的读书时间倒是问题不大,不过每天都要打卡,而且一个月要读完一本书,其实难度还是有点大的,不过也想试试看。
之前某某老大给自己立了个 flag,说要读一百本书,这对我来说挺难实现的,一则我也不喜欢书只读一小半,二则感觉对于喜欢看的内容范围还是比较有限制,可能也算是比较矫情,不爱追热门的各类东西,因为往往会有一些跟大众不一致的观点看法,显得格格不入。所以还是这个打卡活动可能会比较适合我,书是人类进步的阶梯。
到现在是打卡了三天了,读的主要是白岩松的《幸福了吗》,对于白岩松,我们这一代人是比较熟悉,并且整体印象比较不错的一个央视主持人,从《焦点访谈》开始,到疫情期间的各类一线节目,可能对我来说是个三观比较正,敢于说一些真话的主持人,这中间其实是有个空档期,没怎么看电视,也不太关注了,只是在疫情期间的节目,还是一如既往地给人一种可靠的感觉,正好有一次偶然微信读书推荐了白岩松的这本书,就看了一部分,正好这次继续往下看,因为相对来讲不会很晦涩,并且从这位知名央视主持人的角度分享他的过往和想法看法,还是比较有意思的。
从对汶川地震,08 年奥运等往事的回忆和一些细节的呈现,也让我了解比较多当时所不知道的,特别是汶川地震,那时的我还在读高中,真的是看着电视,作为“猛男”都忍不住泪目了,共和国之殇,多难兴邦,但是这对于当事人来说,都是一场醒不过来的噩梦。
然后是对于足球的热爱,其实光这个就能掰扯很多,因为我不爱足球,只爱篮球,其中原因有的没的也挺多可以说的,但是看了他的书,才能比较深入的了解一个足球迷,对足球,对中国足球,对世界杯,对阿根廷的感情。
接下去还是想能继续坚持下去,加油!

0%
\ No newline at end of file +关于读书打卡与分享 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

关于读书打卡与分享

最近群里大佬发起了一个读书打卡活动,需要每天读一会书,在群里打卡分享感悟,争取一个月能读完一本书,说实话一天十分钟的读书时间倒是问题不大,不过每天都要打卡,而且一个月要读完一本书,其实难度还是有点大的,不过也想试试看。
之前某某老大给自己立了个 flag,说要读一百本书,这对我来说挺难实现的,一则我也不喜欢书只读一小半,二则感觉对于喜欢看的内容范围还是比较有限制,可能也算是比较矫情,不爱追热门的各类东西,因为往往会有一些跟大众不一致的观点看法,显得格格不入。所以还是这个打卡活动可能会比较适合我,书是人类进步的阶梯。
到现在是打卡了三天了,读的主要是白岩松的《幸福了吗》,对于白岩松,我们这一代人是比较熟悉,并且整体印象比较不错的一个央视主持人,从《焦点访谈》开始,到疫情期间的各类一线节目,可能对我来说是个三观比较正,敢于说一些真话的主持人,这中间其实是有个空档期,没怎么看电视,也不太关注了,只是在疫情期间的节目,还是一如既往地给人一种可靠的感觉,正好有一次偶然微信读书推荐了白岩松的这本书,就看了一部分,正好这次继续往下看,因为相对来讲不会很晦涩,并且从这位知名央视主持人的角度分享他的过往和想法看法,还是比较有意思的。
从对汶川地震,08 年奥运等往事的回忆和一些细节的呈现,也让我了解比较多当时所不知道的,特别是汶川地震,那时的我还在读高中,真的是看着电视,作为“猛男”都忍不住泪目了,共和国之殇,多难兴邦,但是这对于当事人来说,都是一场醒不过来的噩梦。
然后是对于足球的热爱,其实光这个就能掰扯很多,因为我不爱足球,只爱篮球,其中原因有的没的也挺多可以说的,但是看了他的书,才能比较深入的了解一个足球迷,对足球,对中国足球,对世界杯,对阿根廷的感情。
接下去还是想能继续坚持下去,加油!

0%
\ No newline at end of file diff --git a/2021/03/14/Leetcode-121-买卖股票的最佳时机-Best-Time-to-Buy-and-Sell-Stock-题解分析/index.html b/2021/03/14/Leetcode-121-买卖股票的最佳时机-Best-Time-to-Buy-and-Sell-Stock-题解分析/index.html index 01906dfa21..0ecb531136 100644 --- a/2021/03/14/Leetcode-121-买卖股票的最佳时机-Best-Time-to-Buy-and-Sell-Stock-题解分析/index.html +++ b/2021/03/14/Leetcode-121-买卖股票的最佳时机-Best-Time-to-Buy-and-Sell-Stock-题解分析/index.html @@ -1,4 +1,4 @@ -Leetcode 121 买卖股票的最佳时机(Best Time to Buy and Sell Stock) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 121 买卖股票的最佳时机(Best Time to Buy and Sell Stock) 题解分析

题目介绍

You are given an array prices where prices[i] is the price of a given stock on the ith day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。

你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。

返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0

简单分析

其实这个跟二叉树的最长路径和有点类似,需要找到整体的最大收益,但是在迭代过程中需要一个当前的值

int maxSofar = 0;
+Leetcode 121 买卖股票的最佳时机(Best Time to Buy and Sell Stock) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 121 买卖股票的最佳时机(Best Time to Buy and Sell Stock) 题解分析

题目介绍

You are given an array prices where prices[i] is the price of a given stock on the ith day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。

你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。

返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0

简单分析

其实这个跟二叉树的最长路径和有点类似,需要找到整体的最大收益,但是在迭代过程中需要一个当前的值

int maxSofar = 0;
 public int maxProfit(int[] prices) {
     if (prices.length <= 1) {
         return 0;
@@ -19,4 +19,4 @@
         }
     }
     return maxSofar;
-}

总结下

一开始看到 easy 就觉得是很简单,就没有 maxSofar ,但是一提交就出现问题了
对于[2, 4, 1]这种就会变成 0,所以还是需要一个历史值来存放历史最大值,这题有点动态规划的意思

0%
\ No newline at end of file +}

总结下

一开始看到 easy 就觉得是很简单,就没有 maxSofar ,但是一提交就出现问题了
对于[2, 4, 1]这种就会变成 0,所以还是需要一个历史值来存放历史最大值,这题有点动态规划的意思

0%
\ No newline at end of file diff --git a/2021/05/01/Leetcode-48-旋转图像-Rotate-Image-题解分析/index.html b/2021/05/01/Leetcode-48-旋转图像-Rotate-Image-题解分析/index.html index da5b6582dc..1031a338df 100644 --- a/2021/05/01/Leetcode-48-旋转图像-Rotate-Image-题解分析/index.html +++ b/2021/05/01/Leetcode-48-旋转图像-Rotate-Image-题解分析/index.html @@ -1,4 +1,4 @@ -Leetcode 48 旋转图像(Rotate Image) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 48 旋转图像(Rotate Image) 题解分析

题目介绍

You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).

You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

如图,这道题以前做过,其实一看有点蒙,好像规则很容易描述,但是代码很难写,因为要类似于贪吃蛇那样,后来想着应该会有一些特殊的技巧,比如翻转等

代码

直接上码

public void rotate(int[][] matrix) {
+Leetcode 48 旋转图像(Rotate Image) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 48 旋转图像(Rotate Image) 题解分析

题目介绍

You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).

You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

如图,这道题以前做过,其实一看有点蒙,好像规则很容易描述,但是代码很难写,因为要类似于贪吃蛇那样,后来想着应该会有一些特殊的技巧,比如翻转等

代码

直接上码

public void rotate(int[][] matrix) {
         // 这里真的傻了,长宽应该是一致的,所以取一次就够了
         int lengthX = matrix[0].length;
         int lengthY = matrix.length;
@@ -34,4 +34,4 @@
                 matrix[j][i] = temp;
             }
         }
-    }

还没到可以直接归纳题目类型的水平,主要是几年前做过,可能有那么点模糊的记忆,当然应该也有直接转的方法

0%
\ No newline at end of file + }

还没到可以直接归纳题目类型的水平,主要是几年前做过,可能有那么点模糊的记忆,当然应该也有直接转的方法

0%
\ No newline at end of file diff --git a/2021/05/23/Leetcode-236-二叉树的最近公共祖先-Lowest-Common-Ancestor-of-a-Binary-Tree-题解分析/index.html b/2021/05/23/Leetcode-236-二叉树的最近公共祖先-Lowest-Common-Ancestor-of-a-Binary-Tree-题解分析/index.html index e4da65ff7b..90e90980ed 100644 --- a/2021/05/23/Leetcode-236-二叉树的最近公共祖先-Lowest-Common-Ancestor-of-a-Binary-Tree-题解分析/index.html +++ b/2021/05/23/Leetcode-236-二叉树的最近公共祖先-Lowest-Common-Ancestor-of-a-Binary-Tree-题解分析/index.html @@ -1,4 +1,4 @@ -Leetcode 236 二叉树的最近公共祖先(Lowest Common Ancestor of a Binary Tree) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 236 二叉树的最近公共祖先(Lowest Common Ancestor of a Binary Tree) 题解分析

题目介绍

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 pq,最近公共祖先表示为一个节点 x,满足 xpq 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”

代码

public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
+Leetcode 236 二叉树的最近公共祖先(Lowest Common Ancestor of a Binary Tree) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 236 二叉树的最近公共祖先(Lowest Common Ancestor of a Binary Tree) 题解分析

题目介绍

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 pq,最近公共祖先表示为一个节点 x,满足 xpq 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”

代码

public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
         // 如果当前节点就是 p 或者是 q 的时候,就直接返回了
         // 当没找到,即 root == null 的时候也会返回 null,这是个重要的点
         if (root == null || root == p || root == q) return root;
@@ -25,4 +25,4 @@
 //            return root;
 //        }
 //        return left == null ? right : right == null ? left : root;
-    }
0%
\ No newline at end of file + }
0%
\ No newline at end of file diff --git a/2021/07/04/Leetcode-42-接雨水-Trapping-Rain-Water-题解分析/index.html b/2021/07/04/Leetcode-42-接雨水-Trapping-Rain-Water-题解分析/index.html index 268465e98b..2ac15779e1 100644 --- a/2021/07/04/Leetcode-42-接雨水-Trapping-Rain-Water-题解分析/index.html +++ b/2021/07/04/Leetcode-42-接雨水-Trapping-Rain-Water-题解分析/index.html @@ -1,4 +1,4 @@ -Leetcode 42 接雨水 (Trapping Rain Water) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 42 接雨水 (Trapping Rain Water) 题解分析

题目介绍

给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。

示例


输入:height = [0,1,0,2,1,0,1,3,2,1,2,1]
输出:6
解释:上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。

简单分析

其实最开始的想法是从左到右扫区间,就是示例中的第一个水槽跟第二个水槽都可以用这个办法解决

前面这种是属于右侧比左侧高的情况,对于左侧高右侧低的就不行了,(写这篇的时候想起来可以再反着扫一遍可能可以)

所以这个方案不好,贴一下这个方案的代码

public int trap(int[] height) {
+Leetcode 42 接雨水 (Trapping Rain Water) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 42 接雨水 (Trapping Rain Water) 题解分析

题目介绍

给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。

示例


输入:height = [0,1,0,2,1,0,1,3,2,1,2,1]
输出:6
解释:上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。

简单分析

其实最开始的想法是从左到右扫区间,就是示例中的第一个水槽跟第二个水槽都可以用这个办法解决

前面这种是属于右侧比左侧高的情况,对于左侧高右侧低的就不行了,(写这篇的时候想起来可以再反着扫一遍可能可以)

所以这个方案不好,贴一下这个方案的代码

public int trap(int[] height) {
     int lastLeft = -1;
     int sum = 0;
     int tempSum = 0;
@@ -48,4 +48,4 @@ maxR[n -+= tempSum;
     }
 }
-return sum;
0%
\ No newline at end of file +return sum;
0%
\ No newline at end of file diff --git a/2021/07/18/2021-年中总结/index.html b/2021/07/18/2021-年中总结/index.html index 5363ba021d..3830215eef 100644 --- a/2021/07/18/2021-年中总结/index.html +++ b/2021/07/18/2021-年中总结/index.html @@ -1 +1 @@ -2021 年中总结 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

2021 年中总结

又到半年总结时,第一次写总结类型的文章感觉挺好写的,但是后面总觉得这过去的一段时间所做的事情,能力上的成长低于预期,但是是需要总结下,找找问题,顺便展望下未来。

这一年做的最让自己满意的应该就是看了一些书,由折腾群洋总发起的读书打卡活动,到目前为止已经读完了这几本书,《cUrl 必知必会》,《古董局中局 1》,《古董局中局 2》,《算法图解》,《每天 5 分钟玩转 Kubernetes》《幸福了吗?》《高可用可伸缩微服务架构:基于 Dubbo、Spring Cloud和 Service Mesh》《Rust 权威指南》后面可以写个专题说说看的这些书,虽然每天打卡如果时间安排不好,并且看的书像 rust 这样比较难的话还是会有点小焦虑,不过也是个调整过程,一方面可以在白天就抽空看一会,然后也不必要每次都看很大一章,注重吸收。

技术上的成长的话,有一些比较小的长进吧,对于一些之前忽视的 synchronized,ThreadLocal 和 AQS 等知识点做了下查漏补缺了,然后多了解了一些 Java 垃圾回收的内容,但是在实操上还是比较欠缺,成型的技术方案,架构上所谓的优化也比较少,一些想法也还有考虑不周全的地方,还需要多花时间和心思去学习加强,特别是在目前已经有的基础上如何做系统深层次的优化,既不要是鸡毛蒜皮的,也不能出现一些不可接受的问题和故障,这是个很重要的课题,需要好好学习,后面考虑定一些周期性目标,两个月左右能有一些成果和总结。

另外一部分是自己的服务,因为 ucloud 的机器太贵就没续费了,所以都迁移到腾讯云的小机器上了,顺便折腾了一点点 traefik,但是还很不熟练,不太习惯这一套,一方面是 docker 还不习惯,这也加重了对这套环境的不适应,还是习惯裸机部署,另一方面就是 k8s 了,家里的机器还没虚拟化,没有很好的条件可以做实验,这也是读书打卡的一个没做好的点,整体的学习效果受限于深度和实操,后面是看都是用 traefik,也找到了一篇文章可以 traefik 转发到裸机应用,因为主仓库用的是裸机的 gogs。

还有就是运动减肥上,唉,这又是很大的一个痛点,基本没效果,只是还算稳定,昨天看到一个视频说还需要力量训练来增肌,以此可以提升基础代谢,打算往这个方向尝试下,因为今天没有疫情限制了,在 6 月底完成了 200 公里的跑步小目标,只是有些膝盖跟大腿根外侧不适,抽空得去看下医生,后面打算每天也能做点卷腹跟俯卧撑。

下半年还希望能继续多看看书,比很多网上各种乱七八糟的文章会好很多,结合豆瓣评分,找一些评价高一些的文章,但也不是说分稍低点的就不行,有些也看人是不是适合,一般 6 分以上评价比较多的就可以试试。

0%
\ No newline at end of file +2021 年中总结 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

2021 年中总结

又到半年总结时,第一次写总结类型的文章感觉挺好写的,但是后面总觉得这过去的一段时间所做的事情,能力上的成长低于预期,但是是需要总结下,找找问题,顺便展望下未来。

这一年做的最让自己满意的应该就是看了一些书,由折腾群洋总发起的读书打卡活动,到目前为止已经读完了这几本书,《cUrl 必知必会》,《古董局中局 1》,《古董局中局 2》,《算法图解》,《每天 5 分钟玩转 Kubernetes》《幸福了吗?》《高可用可伸缩微服务架构:基于 Dubbo、Spring Cloud和 Service Mesh》《Rust 权威指南》后面可以写个专题说说看的这些书,虽然每天打卡如果时间安排不好,并且看的书像 rust 这样比较难的话还是会有点小焦虑,不过也是个调整过程,一方面可以在白天就抽空看一会,然后也不必要每次都看很大一章,注重吸收。

技术上的成长的话,有一些比较小的长进吧,对于一些之前忽视的 synchronized,ThreadLocal 和 AQS 等知识点做了下查漏补缺了,然后多了解了一些 Java 垃圾回收的内容,但是在实操上还是比较欠缺,成型的技术方案,架构上所谓的优化也比较少,一些想法也还有考虑不周全的地方,还需要多花时间和心思去学习加强,特别是在目前已经有的基础上如何做系统深层次的优化,既不要是鸡毛蒜皮的,也不能出现一些不可接受的问题和故障,这是个很重要的课题,需要好好学习,后面考虑定一些周期性目标,两个月左右能有一些成果和总结。

另外一部分是自己的服务,因为 ucloud 的机器太贵就没续费了,所以都迁移到腾讯云的小机器上了,顺便折腾了一点点 traefik,但是还很不熟练,不太习惯这一套,一方面是 docker 还不习惯,这也加重了对这套环境的不适应,还是习惯裸机部署,另一方面就是 k8s 了,家里的机器还没虚拟化,没有很好的条件可以做实验,这也是读书打卡的一个没做好的点,整体的学习效果受限于深度和实操,后面是看都是用 traefik,也找到了一篇文章可以 traefik 转发到裸机应用,因为主仓库用的是裸机的 gogs。

还有就是运动减肥上,唉,这又是很大的一个痛点,基本没效果,只是还算稳定,昨天看到一个视频说还需要力量训练来增肌,以此可以提升基础代谢,打算往这个方向尝试下,因为今天没有疫情限制了,在 6 月底完成了 200 公里的跑步小目标,只是有些膝盖跟大腿根外侧不适,抽空得去看下医生,后面打算每天也能做点卷腹跟俯卧撑。

下半年还希望能继续多看看书,比很多网上各种乱七八糟的文章会好很多,结合豆瓣评分,找一些评价高一些的文章,但也不是说分稍低点的就不行,有些也看人是不是适合,一般 6 分以上评价比较多的就可以试试。

0%
\ No newline at end of file diff --git a/2021/10/07/Leetcode-021-合并两个有序链表-Merge-Two-Sorted-Lists-题解分析/index.html b/2021/10/07/Leetcode-021-合并两个有序链表-Merge-Two-Sorted-Lists-题解分析/index.html index 63b37d1838..5f4823c58b 100644 --- a/2021/10/07/Leetcode-021-合并两个有序链表-Merge-Two-Sorted-Lists-题解分析/index.html +++ b/2021/10/07/Leetcode-021-合并两个有序链表-Merge-Two-Sorted-Lists-题解分析/index.html @@ -1,4 +1,4 @@ -Leetcode 021 合并两个有序链表 ( Merge Two Sorted Lists ) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 021 合并两个有序链表 ( Merge Two Sorted Lists ) 题解分析

题目介绍

Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.

将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

示例 1

输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]

示例 2

输入: l1 = [], l2 = []
输出: []

示例 3

输入: l1 = [], l2 = [0]
输出: [0]

简要分析

这题是 Easy 的,看着也挺简单,两个链表进行合并,就是比较下大小,可能将就点的话最好就在两个链表中原地合并

题解代码

public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
+Leetcode 021 合并两个有序链表 ( Merge Two Sorted Lists ) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 021 合并两个有序链表 ( Merge Two Sorted Lists ) 题解分析

题目介绍

Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.

将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

示例 1

输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]

示例 2

输入: l1 = [], l2 = []
输出: []

示例 3

输入: l1 = [], l2 = [0]
输出: [0]

简要分析

这题是 Easy 的,看着也挺简单,两个链表进行合并,就是比较下大小,可能将就点的话最好就在两个链表中原地合并

题解代码

public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
         // 下面两个if判断了入参的边界,如果其一为null,直接返回另一个就可以了
         if (l1 == null) {
             return l2;
@@ -40,4 +40,4 @@
         current = null;
         // 返回这个头结点
         return merged;
-    }

结果

0%
\ No newline at end of file + }

结果

0%
\ No newline at end of file diff --git a/2021/10/31/Leetcode-028-实现-strStr-Implement-strStr-题解分析/index.html b/2021/10/31/Leetcode-028-实现-strStr-Implement-strStr-题解分析/index.html index 2fed6e6d16..5c0d4f4157 100644 --- a/2021/10/31/Leetcode-028-实现-strStr-Implement-strStr-题解分析/index.html +++ b/2021/10/31/Leetcode-028-实现-strStr-Implement-strStr-题解分析/index.html @@ -1,4 +1,4 @@ -Leetcode 028 实现 strStr() ( Implement strStr() ) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 028 实现 strStr() ( Implement strStr() ) 题解分析

题目介绍

Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C’s strstr() and Java’s indexOf().

示例

Example 1:

Input: haystack = "hello", needle = "ll"
+Leetcode 028 实现 strStr() ( Implement strStr() ) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 028 实现 strStr() ( Implement strStr() ) 题解分析

题目介绍

Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C’s strstr() and Java’s indexOf().

示例

Example 1:

Input: haystack = "hello", needle = "ll"
 Output: 2

Example 2:

Input: haystack = "aaaaa", needle = "bba"
 Output: -1

Example 3:

Input: haystack = "", needle = ""
 Output: 0

题解

字符串比较其实是写代码里永恒的主题,底层的编译器等处理肯定需要字符串对比,像 kmp 算法也是很厉害

code

public int strStr(String haystack, String needle) {
@@ -47,4 +47,4 @@ Output: 0
0%
\ No newline at end of file + }
0%
\ No newline at end of file diff --git a/2021/11/28/Leetcode-053-最大子序和-Maximum-Subarray-题解分析/index.html b/2021/11/28/Leetcode-053-最大子序和-Maximum-Subarray-题解分析/index.html index 6cba68ac65..af7bba9111 100644 --- a/2021/11/28/Leetcode-053-最大子序和-Maximum-Subarray-题解分析/index.html +++ b/2021/11/28/Leetcode-053-最大子序和-Maximum-Subarray-题解分析/index.html @@ -1,4 +1,4 @@ -Leetcode 053 最大子序和 ( Maximum Subarray ) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 053 最大子序和 ( Maximum Subarray ) 题解分析

题目介绍

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

A subarray is a contiguous part of an array.

示例

Example 1:

Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.

Example 2:

Input: nums = [1]
Output: 1

Example 3:

Input: nums = [5,4,-1,7,8]
Output: 23

说起来这个题其实非常有渊源,大学数据结构的第一个题就是这个,而最佳的算法就是传说中的 online 算法,就是遍历一次就完了,最基本的做法就是记下来所有的连续子数组,然后求出最大的那个。

代码

public int maxSubArray(int[] nums) {
+Leetcode 053 最大子序和 ( Maximum Subarray ) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 053 最大子序和 ( Maximum Subarray ) 题解分析

题目介绍

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

A subarray is a contiguous part of an array.

示例

Example 1:

Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.

Example 2:

Input: nums = [1]
Output: 1

Example 3:

Input: nums = [5,4,-1,7,8]
Output: 23

说起来这个题其实非常有渊源,大学数据结构的第一个题就是这个,而最佳的算法就是传说中的 online 算法,就是遍历一次就完了,最基本的做法就是记下来所有的连续子数组,然后求出最大的那个。

代码

public int maxSubArray(int[] nums) {
         int max = nums[0];
         int sum = nums[0];
         for (int i = 1; i < nums.length; i++) {
@@ -8,4 +8,4 @@
             max = Math.max(max, sum);
         }
         return max;
-    }
0%
\ No newline at end of file + }
0%
\ No newline at end of file diff --git a/2022/03/07/Leetcode-349-两个数组的交集-Intersection-of-Two-Arrays-Easy-题解分析/index.html b/2022/03/07/Leetcode-349-两个数组的交集-Intersection-of-Two-Arrays-Easy-题解分析/index.html index 73b86456ed..cf09f2dc10 100644 --- a/2022/03/07/Leetcode-349-两个数组的交集-Intersection-of-Two-Arrays-Easy-题解分析/index.html +++ b/2022/03/07/Leetcode-349-两个数组的交集-Intersection-of-Two-Arrays-Easy-题解分析/index.html @@ -1,4 +1,4 @@ -Leetcode 349 两个数组的交集 ( Intersection of Two Arrays *Easy* ) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 349 两个数组的交集 ( Intersection of Two Arrays *Easy* ) 题解分析

题目介绍

给定两个数组 nums1 和 nums2 ,返回 它们的交集 。输出结果中的每个元素一定是 唯一 的。我们可以 不考虑输出结果的顺序

 

示例

示例 1:

输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2]

示例 2:

输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出:[9,4]
解释:[4,9] 也是可通过的  

提示:

  • 1 <= nums1.length, nums2.length <= 1000
  • 0 <= nums1[i], nums2[i] <= 1000

分析与题解

两个数组的交集,最简单就是两层循环了把两个都存在的找出来,不过还有个要去重的问题,稍微思考下可以使用集合 set 来处理,先把一个数组全丢进去,再对比另外一个,如果出现在第一个集合里就丢进一个新的集合,最后转换成数组,这次我稍微取了个巧,因为看到了提示里的条件,两个数组中的元素都是不大于 1000 的,所以就搞了个 1000 长度的数组,如果在第一个数组出现,就在对应的下标设置成 1,如果在第二个数组也出现了就加 1,

code

public int[] intersection(int[] nums1, int[] nums2) {
+Leetcode 349 两个数组的交集 ( Intersection of Two Arrays *Easy* ) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 349 两个数组的交集 ( Intersection of Two Arrays *Easy* ) 题解分析

题目介绍

给定两个数组 nums1 和 nums2 ,返回 它们的交集 。输出结果中的每个元素一定是 唯一 的。我们可以 不考虑输出结果的顺序

 

示例

示例 1:

输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2]

示例 2:

输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出:[9,4]
解释:[4,9] 也是可通过的  

提示:

  • 1 <= nums1.length, nums2.length <= 1000
  • 0 <= nums1[i], nums2[i] <= 1000

分析与题解

两个数组的交集,最简单就是两层循环了把两个都存在的找出来,不过还有个要去重的问题,稍微思考下可以使用集合 set 来处理,先把一个数组全丢进去,再对比另外一个,如果出现在第一个集合里就丢进一个新的集合,最后转换成数组,这次我稍微取了个巧,因为看到了提示里的条件,两个数组中的元素都是不大于 1000 的,所以就搞了个 1000 长度的数组,如果在第一个数组出现,就在对应的下标设置成 1,如果在第二个数组也出现了就加 1,

code

public int[] intersection(int[] nums1, int[] nums2) {
     // 大小是 1000 的数组,如果没有提示的条件就没法这么做
     // define a array which size is 1000, and can not be done like this without the condition in notice
         int[] inter = new int[1000];
@@ -33,4 +33,4 @@
             }
         }
         return outer;
-    }
0%
\ No newline at end of file + }
0%
\ No newline at end of file diff --git a/2022/03/13/Leetcode-83-删除排序链表中的重复元素-Remove-Duplicates-from-Sorted-List-Easy-题解分析/index.html b/2022/03/13/Leetcode-83-删除排序链表中的重复元素-Remove-Duplicates-from-Sorted-List-Easy-题解分析/index.html index ccac97eed5..5560c5566b 100644 --- a/2022/03/13/Leetcode-83-删除排序链表中的重复元素-Remove-Duplicates-from-Sorted-List-Easy-题解分析/index.html +++ b/2022/03/13/Leetcode-83-删除排序链表中的重复元素-Remove-Duplicates-from-Sorted-List-Easy-题解分析/index.html @@ -1,4 +1,4 @@ -Leetcode 83 删除排序链表中的重复元素 ( Remove Duplicates from Sorted List *Easy* ) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 83 删除排序链表中的重复元素 ( Remove Duplicates from Sorted List *Easy* ) 题解分析

题目介绍

给定一个已排序的链表的头 head , 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。
PS:注意已排序,还有返回也要已排序

示例 1:

输入:head = [1,1,2]
输出:[1,2]

示例 2:

输入:head = [1,1,2,3,3]
输出:[1,2,3]

提示:

  • 链表中节点数目在范围 [0, 300]
  • -100 <= Node.val <= 100
  • 题目数据保证链表已经按 升序 排列

分析与题解

这题其实是比较正常的 easy 级别的题目,链表已经排好序了,如果还带一个排序就更复杂一点,
只需要前后项做个对比,如果一致则移除后项,因为可能存在多个重复项,所以只有在前后项不同
时才会更新被比较项

code

public ListNode deleteDuplicates(ListNode head) {
+Leetcode 83 删除排序链表中的重复元素 ( Remove Duplicates from Sorted List *Easy* ) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 83 删除排序链表中的重复元素 ( Remove Duplicates from Sorted List *Easy* ) 题解分析

题目介绍

给定一个已排序的链表的头 head , 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。
PS:注意已排序,还有返回也要已排序

示例 1:

输入:head = [1,1,2]
输出:[1,2]

示例 2:

输入:head = [1,1,2,3,3]
输出:[1,2,3]

提示:

  • 链表中节点数目在范围 [0, 300]
  • -100 <= Node.val <= 100
  • 题目数据保证链表已经按 升序 排列

分析与题解

这题其实是比较正常的 easy 级别的题目,链表已经排好序了,如果还带一个排序就更复杂一点,
只需要前后项做个对比,如果一致则移除后项,因为可能存在多个重复项,所以只有在前后项不同
时才会更新被比较项

code

public ListNode deleteDuplicates(ListNode head) {
     // 链表头是空的或者只有一个头结点,就不用处理了
     if (head == null || head.next == null) {
         return head;
@@ -18,4 +18,4 @@
     }
     // 最后返回头结点
     return head;
-}

链表应该是个需要反复的训练的数据结构,因为涉及到前后指针,然后更新操作,判空等,
我在这块也是掌握的不太好,需要多练习。

0%
\ No newline at end of file +}

链表应该是个需要反复的训练的数据结构,因为涉及到前后指针,然后更新操作,判空等,
我在这块也是掌握的不太好,需要多练习。

0%
\ No newline at end of file diff --git a/2022/03/27/Leetcode-4-寻找两个正序数组的中位数-Median-of-Two-Sorted-Arrays-Hard-题解分析/index.html b/2022/03/27/Leetcode-4-寻找两个正序数组的中位数-Median-of-Two-Sorted-Arrays-Hard-题解分析/index.html index bb00780ef7..0509e236ca 100644 --- a/2022/03/27/Leetcode-4-寻找两个正序数组的中位数-Median-of-Two-Sorted-Arrays-Hard-题解分析/index.html +++ b/2022/03/27/Leetcode-4-寻找两个正序数组的中位数-Median-of-Two-Sorted-Arrays-Hard-题解分析/index.html @@ -1,4 +1,4 @@ -Leetcode 4 寻找两个正序数组的中位数 ( Median of Two Sorted Arrays *Hard* ) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 4 寻找两个正序数组的中位数 ( Median of Two Sorted Arrays *Hard* ) 题解分析

题目介绍

给定两个大小分别为 mn 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的 中位数

算法的时间复杂度应该为 O(log (m+n))

示例 1:

输入:nums1 = [1,3], nums2 = [2]
输出:2.00000
解释:合并数组 = [1,2,3] ,中位数 2

示例 2:

输入:nums1 = [1,2], nums2 = [3,4]
输出:2.50000
解释:合并数组 = [1,2,3,4] ,中位数 (2 + 3) / 2 = 2.5

分析与题解

这个题也是我随机出来的,之前都是随机到 easy 的,而且是序号这么靠前的,然后翻一下,之前应该是用 C++做过的,具体的方法其实可以从他的算法时间复杂度要求看出来,大概率是要二分法这种,后面就结合代码来讲了

public double findMedianSortedArrays(int[] nums1, int[] nums2) {
+Leetcode 4 寻找两个正序数组的中位数 ( Median of Two Sorted Arrays *Hard* ) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 4 寻找两个正序数组的中位数 ( Median of Two Sorted Arrays *Hard* ) 题解分析

题目介绍

给定两个大小分别为 mn 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的 中位数

算法的时间复杂度应该为 O(log (m+n))

示例 1:

输入:nums1 = [1,3], nums2 = [2]
输出:2.00000
解释:合并数组 = [1,2,3] ,中位数 2

示例 2:

输入:nums1 = [1,2], nums2 = [3,4]
输出:2.50000
解释:合并数组 = [1,2,3,4] ,中位数 (2 + 3) / 2 = 2.5

分析与题解

这个题也是我随机出来的,之前都是随机到 easy 的,而且是序号这么靠前的,然后翻一下,之前应该是用 C++做过的,具体的方法其实可以从他的算法时间复杂度要求看出来,大概率是要二分法这种,后面就结合代码来讲了

public double findMedianSortedArrays(int[] nums1, int[] nums2) {
         int n1 = nums1.length;
         int n2 = nums2.length;
         if (n1 > n2) {
@@ -43,4 +43,4 @@
         // 如果是偶数个,那还要取两个数组后面的较小者,然后求平均值
         int c2 = Math.min(m1 >= n1 ? Integer.MAX_VALUE : nums1[m1], m2 >= n2 ? Integer.MAX_VALUE : nums2[m2]);
         return (c1 + c2) / 2.0;
-    }

前面考虑的方法还是比较繁琐,考虑了两个数组的各种交叉情况,后面这个参考了一些网上的解法,代码比较简洁,但是可能不容易一下子就搞明白,所以配合了比较多的注释。

0%
\ No newline at end of file + }

前面考虑的方法还是比较繁琐,考虑了两个数组的各种交叉情况,后面这个参考了一些网上的解法,代码比较简洁,但是可能不容易一下子就搞明白,所以配合了比较多的注释。

0%
\ No newline at end of file diff --git a/2022/05/01/Leetcode-1115-交替打印-FooBar-Print-FooBar-Alternately-Medium-题解分析/index.html b/2022/05/01/Leetcode-1115-交替打印-FooBar-Print-FooBar-Alternately-Medium-题解分析/index.html index 53f37f9f88..5a17e48a6c 100644 --- a/2022/05/01/Leetcode-1115-交替打印-FooBar-Print-FooBar-Alternately-Medium-题解分析/index.html +++ b/2022/05/01/Leetcode-1115-交替打印-FooBar-Print-FooBar-Alternately-Medium-题解分析/index.html @@ -1,4 +1,4 @@ -Leetcode 1115 交替打印 FooBar ( Print FooBar Alternately *Medium* ) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 1115 交替打印 FooBar ( Print FooBar Alternately *Medium* ) 题解分析

无聊想去 roll 一题就看到了有并发题,就找到了这题,其实一眼看我的想法也是用信号量,但是用 condition 应该也是可以处理的,不过这类问题好像本地有点难调,因为它好像是抽取代码执行的,跟直观的逻辑比较不一样
Suppose you are given the following code:

class FooBar {
+Leetcode 1115 交替打印 FooBar ( Print FooBar Alternately *Medium* ) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 1115 交替打印 FooBar ( Print FooBar Alternately *Medium* ) 题解分析

无聊想去 roll 一题就看到了有并发题,就找到了这题,其实一眼看我的想法也是用信号量,但是用 condition 应该也是可以处理的,不过这类问题好像本地有点难调,因为它好像是抽取代码执行的,跟直观的逻辑比较不一样
Suppose you are given the following code:

class FooBar {
   public void foo() {
     for (int i = 0; i < n; i++) {
       print("foo");
@@ -39,4 +39,4 @@
             foo.release();
         }
     }
-}
0%
\ No newline at end of file +}
0%
\ No newline at end of file diff --git a/2022/06/19/Leetcode-698-划分为k个相等的子集-Partition-to-K-Equal-Sum-Subsets-Medium-题解分析/index.html b/2022/06/19/Leetcode-698-划分为k个相等的子集-Partition-to-K-Equal-Sum-Subsets-Medium-题解分析/index.html index cda6b7f079..f679ca22fd 100644 --- a/2022/06/19/Leetcode-698-划分为k个相等的子集-Partition-to-K-Equal-Sum-Subsets-Medium-题解分析/index.html +++ b/2022/06/19/Leetcode-698-划分为k个相等的子集-Partition-to-K-Equal-Sum-Subsets-Medium-题解分析/index.html @@ -1,4 +1,4 @@ -Leetcode 698 划分为k个相等的子集 ( Partition to K Equal Sum Subsets *Medium* ) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 698 划分为k个相等的子集 ( Partition to K Equal Sum Subsets *Medium* ) 题解分析

题目介绍

Given an integer array nums and an integer k, return true if it is possible to divide this array into k non-empty subsets whose sums are all equal.

示例

Example 1:

Input: nums = [4,3,2,3,5,2,1], k = 4
Output: true
Explanation: It is possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.

Example 2:

Input: nums = [1,2,3,4], k = 3
Output: false

Constraints:

  • 1 <= k <= nums.length <= 16
  • 1 <= nums[i] <= 10^4
  • The frequency of each element is in the range [1, 4].

解析

看到这个题一开始以为挺简单,但是仔细想想问题还是挺多的,首先是分成 k 组,但是数量不限,应该需要用到回溯的方式,同时对于时间和空间复杂度也有要求,一开始这个代码是超时的,我也试了下 leetcode 上 discussion 里 vote 最高的提交也是超时的,不过看 discussion 里的帖子,貌似是后面加了一些条件,可以帮忙提高执行效率,第三条提示不太清楚意图,具体可以看下代码

代码

public boolean canPartitionKSubsets(int[] nums, int k) {
+Leetcode 698 划分为k个相等的子集 ( Partition to K Equal Sum Subsets *Medium* ) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 698 划分为k个相等的子集 ( Partition to K Equal Sum Subsets *Medium* ) 题解分析

题目介绍

Given an integer array nums and an integer k, return true if it is possible to divide this array into k non-empty subsets whose sums are all equal.

示例

Example 1:

Input: nums = [4,3,2,3,5,2,1], k = 4
Output: true
Explanation: It is possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.

Example 2:

Input: nums = [1,2,3,4], k = 3
Output: false

Constraints:

  • 1 <= k <= nums.length <= 16
  • 1 <= nums[i] <= 10^4
  • The frequency of each element is in the range [1, 4].

解析

看到这个题一开始以为挺简单,但是仔细想想问题还是挺多的,首先是分成 k 组,但是数量不限,应该需要用到回溯的方式,同时对于时间和空间复杂度也有要求,一开始这个代码是超时的,我也试了下 leetcode 上 discussion 里 vote 最高的提交也是超时的,不过看 discussion 里的帖子,貌似是后面加了一些条件,可以帮忙提高执行效率,第三条提示不太清楚意图,具体可以看下代码

代码

public boolean canPartitionKSubsets(int[] nums, int k) {
     if (k == 1) {
         return true;
     }
@@ -64,4 +64,4 @@
         }
     }
     return false;
-}

最后贴个图

0%
\ No newline at end of file +}

最后贴个图

0%
\ No newline at end of file diff --git a/2022/07/02/Leetcode-20-有效的括号-Valid-Parentheses-Easy-题解分析/index.html b/2022/07/02/Leetcode-20-有效的括号-Valid-Parentheses-Easy-题解分析/index.html index ced657d77c..6c855e842e 100644 --- a/2022/07/02/Leetcode-20-有效的括号-Valid-Parentheses-Easy-题解分析/index.html +++ b/2022/07/02/Leetcode-20-有效的括号-Valid-Parentheses-Easy-题解分析/index.html @@ -1,4 +1,4 @@ -Leetcode 20 有效的括号 ( Valid Parentheses *Easy* ) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 20 有效的括号 ( Valid Parentheses *Easy* ) 题解分析

题目介绍

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

示例

Example 1:

Input: s = “()”
Output: true

Example 2:

Input: s = “()[]{}”
Output: true

Example 3:

Input: s = “(]”
Output: false

Constraints:

  • 1 <= s.length <= 10^4
  • s consists of parentheses only '()[]{}'.

解析

easy题,并且看起来也是比较简单的,三种括号按对匹配,直接用栈来做,栈里面存的是括号的类型,如果是左括号,就放入栈中,如果是右括号,就把栈顶的元素弹出,如果弹出的元素不是左括号,就返回false,如果弹出的元素是左括号,就继续往下走,如果遍历完了,如果栈里面还有元素,就返回false,如果遍历完了,如果栈里面没有元素,就返回true

代码

class Solution {
+Leetcode 20 有效的括号 ( Valid Parentheses *Easy* ) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 20 有效的括号 ( Valid Parentheses *Easy* ) 题解分析

题目介绍

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

示例

Example 1:

Input: s = “()”
Output: true

Example 2:

Input: s = “()[]{}”
Output: true

Example 3:

Input: s = “(]”
Output: false

Constraints:

  • 1 <= s.length <= 10^4
  • s consists of parentheses only '()[]{}'.

解析

easy题,并且看起来也是比较简单的,三种括号按对匹配,直接用栈来做,栈里面存的是括号的类型,如果是左括号,就放入栈中,如果是右括号,就把栈顶的元素弹出,如果弹出的元素不是左括号,就返回false,如果弹出的元素是左括号,就继续往下走,如果遍历完了,如果栈里面还有元素,就返回false,如果遍历完了,如果栈里面没有元素,就返回true

代码

class Solution {
     public boolean isValid(String s) {
 
         if (s.length() % 2 != 0) {
@@ -50,4 +50,4 @@
         }
         return stk.size() == 0;
     }
-}
0%
\ No newline at end of file +}
0%
\ No newline at end of file diff --git a/2022/07/17/《长安的荔枝》读后感/index.html b/2022/07/17/《长安的荔枝》读后感/index.html index 308cabd505..0875b5a516 100644 --- a/2022/07/17/《长安的荔枝》读后感/index.html +++ b/2022/07/17/《长安的荔枝》读后感/index.html @@ -1 +1 @@ -《长安的荔枝》读后感 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

《长安的荔枝》读后感

断断续续地看完了马伯庸老师的《长安的荔枝》,一开始是看这本书在排行榜排得很高,又是马伯庸的,之前看过他的《古董局中局》,还是很有意思的,而且正好是比较短的,不过前后也拖了蛮久才看完,看完后读了下马老师自己写的后记,就特别有感触。
整个故事是围绕一个上林署监事李善德被委任一项给贵妃送荔枝的差事展开,“长安回望绣成堆,山顶千门次第开,一骑红尘妃子笑,无人知是荔枝来”,以前没细究过这个送荔枝的过程,但是以以前的运输速度和保鲜条件,感觉也不是太现实,所以主人公一开始就以为只是像以往一样是送荔枝干这种,能比较方便运输,不容易变质的,结果发现其实是同僚在坑他,这次是要在贵妃生辰的时候给贵妃送来新鲜的岭南荔枝,用比较时兴的词来说,这就是个送命题啊,鲜荔枝一日色变,两日香变,三日味变,同僚的还有杜甫跟韩承,都觉得老李可以直接写休书了,保全家人,不然就是全家送命,李善德也觉得基本算是判刑了,而且其实是这事被转了几次,最后到老李所在的上林署,主管为了骗他接下这个活还特意在文书上把荔枝鲜的“鲜”字贴住,那会叫做“贴黄”,变成了荔枝“煎”,所以说官场险恶,大家都想把这烫手山芋丢出去,结果丢到了我们老实的老李头上,但是从接到这个通知到贵妃的生辰六月初一还有挺长的时间,其实这个活虽然送命,但是在前期这个“荔枝使”也基本就是类似带着尚方宝剑,御赐黄马褂的职位,随便申请经费,不必像常规的部门费用需要定预算,申请后再层层审批,而是特事特批特办的耍赖做法,所以在这段时间是能够潇洒挥霍一下的。其实可以好好地捞一波给妻女,然后写下和离,在自己死后能让她们过的好一些,但最后还是在杜甫的一番劝导下做出了尝试一番的决定,因为也没其他办法,既是退无可退,何不向前拼死一搏,其实说到这,我觉得看这本书感觉有所收获的第一点,有时候总觉得事情没戏了,想躺平放弃了,但是这样其实这个结果是不会变好的,尝试努力,拼尽全力搏一搏,说不定会有所改观,至少不会变更坏了。

0%
\ No newline at end of file +《长安的荔枝》读后感 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

《长安的荔枝》读后感

断断续续地看完了马伯庸老师的《长安的荔枝》,一开始是看这本书在排行榜排得很高,又是马伯庸的,之前看过他的《古董局中局》,还是很有意思的,而且正好是比较短的,不过前后也拖了蛮久才看完,看完后读了下马老师自己写的后记,就特别有感触。
整个故事是围绕一个上林署监事李善德被委任一项给贵妃送荔枝的差事展开,“长安回望绣成堆,山顶千门次第开,一骑红尘妃子笑,无人知是荔枝来”,以前没细究过这个送荔枝的过程,但是以以前的运输速度和保鲜条件,感觉也不是太现实,所以主人公一开始就以为只是像以往一样是送荔枝干这种,能比较方便运输,不容易变质的,结果发现其实是同僚在坑他,这次是要在贵妃生辰的时候给贵妃送来新鲜的岭南荔枝,用比较时兴的词来说,这就是个送命题啊,鲜荔枝一日色变,两日香变,三日味变,同僚的还有杜甫跟韩承,都觉得老李可以直接写休书了,保全家人,不然就是全家送命,李善德也觉得基本算是判刑了,而且其实是这事被转了几次,最后到老李所在的上林署,主管为了骗他接下这个活还特意在文书上把荔枝鲜的“鲜”字贴住,那会叫做“贴黄”,变成了荔枝“煎”,所以说官场险恶,大家都想把这烫手山芋丢出去,结果丢到了我们老实的老李头上,但是从接到这个通知到贵妃的生辰六月初一还有挺长的时间,其实这个活虽然送命,但是在前期这个“荔枝使”也基本就是类似带着尚方宝剑,御赐黄马褂的职位,随便申请经费,不必像常规的部门费用需要定预算,申请后再层层审批,而是特事特批特办的耍赖做法,所以在这段时间是能够潇洒挥霍一下的。其实可以好好地捞一波给妻女,然后写下和离,在自己死后能让她们过的好一些,但最后还是在杜甫的一番劝导下做出了尝试一番的决定,因为也没其他办法,既是退无可退,何不向前拼死一搏,其实说到这,我觉得看这本书感觉有所收获的第一点,有时候总觉得事情没戏了,想躺平放弃了,但是这样其实这个结果是不会变好的,尝试努力,拼尽全力搏一搏,说不定会有所改观,至少不会变更坏了。

0%
\ No newline at end of file diff --git a/2022/07/22/Leetcode-1260-二维网格迁移-Shift-2D-Grid-Easy-题解分析/index.html b/2022/07/22/Leetcode-1260-二维网格迁移-Shift-2D-Grid-Easy-题解分析/index.html index 464dad7bdf..8f5c72ed12 100644 --- a/2022/07/22/Leetcode-1260-二维网格迁移-Shift-2D-Grid-Easy-题解分析/index.html +++ b/2022/07/22/Leetcode-1260-二维网格迁移-Shift-2D-Grid-Easy-题解分析/index.html @@ -1,4 +1,4 @@ -Leetcode 1260 二维网格迁移 ( Shift 2D Grid *Easy* ) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 1260 二维网格迁移 ( Shift 2D Grid *Easy* ) 题解分析

题目介绍

Given a 2D grid of size m x n and an integer k. You need to shift the grid k times.

In one shift operation:

Element at grid[i][j] moves to grid[i][j + 1].
Element at grid[i][n - 1] moves to grid[i + 1][0].
Element at grid[m - 1][n - 1] moves to grid[0][0].
Return the 2D grid after applying shift operation k times.

示例

Example 1:

Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 1
Output: [[9,1,2],[3,4,5],[6,7,8]]

Example 2:

Input: grid = [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4
Output: [[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]

Example 3:

Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 9
Output: [[1,2,3],[4,5,6],[7,8,9]]

提示

  • m == grid.length
  • n == grid[i].length
  • 1 <= m <= 50
  • 1 <= n <= 50
  • -1000 <= grid[i][j] <= 1000
  • 0 <= k <= 100

解析

这个题主要是矩阵或者说数组的操作,并且题目要返回的是个 List,所以也不用原地操作,只需要找对位置就可以了,k 是多少就相当于让这个二维数组头尾衔接移动 k 个元素

代码

public List<List<Integer>> shiftGrid(int[][] grid, int k) {
+Leetcode 1260 二维网格迁移 ( Shift 2D Grid *Easy* ) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 1260 二维网格迁移 ( Shift 2D Grid *Easy* ) 题解分析

题目介绍

Given a 2D grid of size m x n and an integer k. You need to shift the grid k times.

In one shift operation:

Element at grid[i][j] moves to grid[i][j + 1].
Element at grid[i][n - 1] moves to grid[i + 1][0].
Element at grid[m - 1][n - 1] moves to grid[0][0].
Return the 2D grid after applying shift operation k times.

示例

Example 1:

Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 1
Output: [[9,1,2],[3,4,5],[6,7,8]]

Example 2:

Input: grid = [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4
Output: [[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]

Example 3:

Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 9
Output: [[1,2,3],[4,5,6],[7,8,9]]

提示

  • m == grid.length
  • n == grid[i].length
  • 1 <= m <= 50
  • 1 <= n <= 50
  • -1000 <= grid[i][j] <= 1000
  • 0 <= k <= 100

解析

这个题主要是矩阵或者说数组的操作,并且题目要返回的是个 List,所以也不用原地操作,只需要找对位置就可以了,k 是多少就相当于让这个二维数组头尾衔接移动 k 个元素

代码

public List<List<Integer>> shiftGrid(int[][] grid, int k) {
         // 行数
         int m = grid.length;
         // 列数
@@ -38,4 +38,4 @@
             matrix.add(line);
         }
         return matrix;
-    }

结果数据


比较慢

0%
\ No newline at end of file + }

结果数据


比较慢

0%
\ No newline at end of file diff --git a/2022/08/06/Leetcode-16-最接近的三数之和-3Sum-Closest-Medium-题解分析/index.html b/2022/08/06/Leetcode-16-最接近的三数之和-3Sum-Closest-Medium-题解分析/index.html index e60794d142..8e788f5570 100644 --- a/2022/08/06/Leetcode-16-最接近的三数之和-3Sum-Closest-Medium-题解分析/index.html +++ b/2022/08/06/Leetcode-16-最接近的三数之和-3Sum-Closest-Medium-题解分析/index.html @@ -1,4 +1,4 @@ -Leetcode 16 最接近的三数之和 ( 3Sum Closest *Medium* ) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 16 最接近的三数之和 ( 3Sum Closest *Medium* ) 题解分析

题目介绍

Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target.

Return the sum of the three integers.

You may assume that each input would have exactly one solution.

简单解释下就是之前是要三数之和等于目标值,现在是找到最接近的三数之和。

示例

Example 1:

Input: nums = [-1,2,1,-4], target = 1
Output: 2
Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

Example 2:

Input: nums = [0,0,0], target = 1
Output: 0

Constraints:

  • 3 <= nums.length <= 1000
  • -1000 <= nums[i] <= 1000
  • -10^4 <= target <= 10^4

简单解析

这个题思路上来讲不难,也是用原来三数之和的方式去做,利用”双指针法”或者其它描述法,但是需要简化逻辑

code

public int threeSumClosest(int[] nums, int target) {
+Leetcode 16 最接近的三数之和 ( 3Sum Closest *Medium* ) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 16 最接近的三数之和 ( 3Sum Closest *Medium* ) 题解分析

题目介绍

Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target.

Return the sum of the three integers.

You may assume that each input would have exactly one solution.

简单解释下就是之前是要三数之和等于目标值,现在是找到最接近的三数之和。

示例

Example 1:

Input: nums = [-1,2,1,-4], target = 1
Output: 2
Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

Example 2:

Input: nums = [0,0,0], target = 1
Output: 0

Constraints:

  • 3 <= nums.length <= 1000
  • -1000 <= nums[i] <= 1000
  • -10^4 <= target <= 10^4

简单解析

这个题思路上来讲不难,也是用原来三数之和的方式去做,利用”双指针法”或者其它描述法,但是需要简化逻辑

code

public int threeSumClosest(int[] nums, int target) {
         Arrays.sort(nums);
         // 当前最近的和
         int closestSum = nums[0] + nums[1] + nums[nums.length - 1];
@@ -33,4 +33,4 @@
             }
         }
         return closestSum;
-    }

结果

0%
\ No newline at end of file + }

结果

0%
\ No newline at end of file diff --git a/2022/08/14/Leetcode-278-第一个错误的版本-First-Bad-Version-Easy-题解分析/index.html b/2022/08/14/Leetcode-278-第一个错误的版本-First-Bad-Version-Easy-题解分析/index.html index c170fd0507..67bc689460 100644 --- a/2022/08/14/Leetcode-278-第一个错误的版本-First-Bad-Version-Easy-题解分析/index.html +++ b/2022/08/14/Leetcode-278-第一个错误的版本-First-Bad-Version-Easy-题解分析/index.html @@ -1,4 +1,4 @@ -Leetcode 278 第一个错误的版本 ( First Bad Version *Easy* ) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 278 第一个错误的版本 ( First Bad Version *Easy* ) 题解分析

题目介绍

You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.

Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad.

You are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.

示例

Example 1:

Input: n = 5, bad = 4
Output: 4
Explanation:
call isBadVersion(3) -> false
call isBadVersion(5) -> true
call isBadVersion(4) -> true
Then 4 is the first bad version.

Example 2:

Input: n = 1, bad = 1
Output: 1

简析

简单来说就是一个二分查找,但是这个问题其实处理起来还是需要搞清楚一些边界问题

代码

public int firstBadVersion(int n) {
+Leetcode 278 第一个错误的版本 ( First Bad Version *Easy* ) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 278 第一个错误的版本 ( First Bad Version *Easy* ) 题解分析

题目介绍

You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.

Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad.

You are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.

示例

Example 1:

Input: n = 5, bad = 4
Output: 4
Explanation:
call isBadVersion(3) -> false
call isBadVersion(5) -> true
call isBadVersion(4) -> true
Then 4 is the first bad version.

Example 2:

Input: n = 1, bad = 1
Output: 1

简析

简单来说就是一个二分查找,但是这个问题其实处理起来还是需要搞清楚一些边界问题

代码

public int firstBadVersion(int n) {
     // 类似于双指针法
     int left = 1, right = n, mid;
     while (left < right) {
@@ -16,4 +16,4 @@
     // 然后 left = mid + 1 就会等于 right,循环条件就跳出了,此时 left 就是那个起始的错误点了
     // 其实这两个是同一个值
     return left;
-}

往右移动示例

往左移动示例

结果

0%
\ No newline at end of file +}

往右移动示例

往左移动示例

结果

0%
\ No newline at end of file diff --git a/2022/08/23/Leetcode-885-螺旋矩阵-III-Spiral-Matrix-III-Medium-题解分析/index.html b/2022/08/23/Leetcode-885-螺旋矩阵-III-Spiral-Matrix-III-Medium-题解分析/index.html index 85eea124f5..bcd971f5ba 100644 --- a/2022/08/23/Leetcode-885-螺旋矩阵-III-Spiral-Matrix-III-Medium-题解分析/index.html +++ b/2022/08/23/Leetcode-885-螺旋矩阵-III-Spiral-Matrix-III-Medium-题解分析/index.html @@ -1,4 +1,4 @@ -Leetcode 885 螺旋矩阵 III ( Spiral Matrix III *Medium* ) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 885 螺旋矩阵 III ( Spiral Matrix III *Medium* ) 题解分析

题目介绍

You start at the cell (rStart, cStart) of an rows x cols grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column.

You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid’s boundary, we continue our walk outside the grid (but may return to the grid boundary later.). Eventually, we reach all rows * cols spaces of the grid.

Return an array of coordinates representing the positions of the grid in the order you visited them.

Example 1:

Input: rows = 1, cols = 4, rStart = 0, cStart = 0
Output: [[0,0],[0,1],[0,2],[0,3]]

Example 2:

Input: rows = 5, cols = 6, rStart = 1, cStart = 4
Output: [[1,4],[1,5],[2,5],[2,4],[2,3],[1,3],[0,3],[0,4],[0,5],[3,5],[3,4],[3,3],[3,2],[2,2],[1,2],[0,2],[4,5],[4,4],[4,3],[4,2],[4,1],[3,1],[2,1],[1,1],[0,1],[4,0],[3,0],[2,0],[1,0],[0,0]]

Constraints:

  • 1 <= rows, cols <= 100
  • 0 <= rStart < rows
  • 0 <= cStart < cols

简析

这个题主要是要相同螺旋矩阵的转变方向的边界判断,已经相同步长会行进两次这个规律,写代码倒不复杂

代码

public int[][] spiralMatrixIII(int rows, int cols, int rStart, int cStart) {
+Leetcode 885 螺旋矩阵 III ( Spiral Matrix III *Medium* ) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 885 螺旋矩阵 III ( Spiral Matrix III *Medium* ) 题解分析

题目介绍

You start at the cell (rStart, cStart) of an rows x cols grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column.

You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid’s boundary, we continue our walk outside the grid (but may return to the grid boundary later.). Eventually, we reach all rows * cols spaces of the grid.

Return an array of coordinates representing the positions of the grid in the order you visited them.

Example 1:

Input: rows = 1, cols = 4, rStart = 0, cStart = 0
Output: [[0,0],[0,1],[0,2],[0,3]]

Example 2:

Input: rows = 5, cols = 6, rStart = 1, cStart = 4
Output: [[1,4],[1,5],[2,5],[2,4],[2,3],[1,3],[0,3],[0,4],[0,5],[3,5],[3,4],[3,3],[3,2],[2,2],[1,2],[0,2],[4,5],[4,4],[4,3],[4,2],[4,1],[3,1],[2,1],[1,1],[0,1],[4,0],[3,0],[2,0],[1,0],[0,0]]

Constraints:

  • 1 <= rows, cols <= 100
  • 0 <= rStart < rows
  • 0 <= cStart < cols

简析

这个题主要是要相同螺旋矩阵的转变方向的边界判断,已经相同步长会行进两次这个规律,写代码倒不复杂

代码

public int[][] spiralMatrixIII(int rows, int cols, int rStart, int cStart) {
         int size = rows * cols;
         int x = rStart, y = cStart;
         // 返回的二维矩阵
@@ -39,4 +39,4 @@
             a++;
         }
         return matrix;
-    }

结果

0%
\ No newline at end of file + }

结果

0%
\ No newline at end of file diff --git a/2022/09/11/Leetcode-1862-向下取整数对和-Sum-of-Floored-Pairs-Hard-题解分析/index.html b/2022/09/11/Leetcode-1862-向下取整数对和-Sum-of-Floored-Pairs-Hard-题解分析/index.html index 803a7facbc..1ba000f138 100644 --- a/2022/09/11/Leetcode-1862-向下取整数对和-Sum-of-Floored-Pairs-Hard-题解分析/index.html +++ b/2022/09/11/Leetcode-1862-向下取整数对和-Sum-of-Floored-Pairs-Hard-题解分析/index.html @@ -1,4 +1,4 @@ -Leetcode 1862 向下取整数对和 ( Sum of Floored Pairs *Hard* ) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 1862 向下取整数对和 ( Sum of Floored Pairs *Hard* ) 题解分析

题目介绍

Given an integer array nums, return the sum of floor(nums[i] / nums[j]) for all pairs of indices 0 <= i, j < nums.length in the array. Since the answer may be too large, return it modulo 10^9 + 7.

The floor() function returns the integer part of the division.

对应中文
给你一个整数数组 nums ,请你返回所有下标对 0 <= i, j < nums.length 的 floor(nums[i] / nums[j]) 结果之和。由于答案可能会很大,请你返回答案对10^9 + 7 取余 的结果。

函数 floor() 返回输入数字的整数部分。

示例

Example 1:

Input: nums = [2,5,9]
Output: 10
Explanation:
floor(2 / 5) = floor(2 / 9) = floor(5 / 9) = 0
floor(2 / 2) = floor(5 / 5) = floor(9 / 9) = 1
floor(5 / 2) = 2
floor(9 / 2) = 4
floor(9 / 5) = 1
We calculate the floor of the division for every pair of indices in the array then sum them up.

Example 2:

Input: nums = [7,7,7,7,7,7,7]
Output: 49

Constraints:

  • 1 <= nums.length <= 10^5
  • 1 <= nums[i] <= 10^5

简析

这题不愧是 hard,要不是看了讨论区的一个大神的解答感觉从头做得想好久,
主要是两点,对于任何一个在里面的数,随便举个例子是 k,最简单的就是循环所有数对 k 除一下,
这样效率会很低,那么对于 k 有什么规律呢,就是对于所有小于 k 的数,往下取整都是 0,所以不用考虑,
对于所有大于 k 的数我们可以分成一个个的区间,[k,2k-1),[2k,3k-1),[3k,4k-1)……对于这些区间的
除了 k 往下取整,每个区间内的都是一样的,所以可以简化为对于任意一个 k,我只要知道与k 相同的有多少个,然后比 k 大的各个区间各有多少个数就可以了

代码

static final int MAXE5 = 100_000;
+Leetcode 1862 向下取整数对和 ( Sum of Floored Pairs *Hard* ) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 1862 向下取整数对和 ( Sum of Floored Pairs *Hard* ) 题解分析

题目介绍

Given an integer array nums, return the sum of floor(nums[i] / nums[j]) for all pairs of indices 0 <= i, j < nums.length in the array. Since the answer may be too large, return it modulo 10^9 + 7.

The floor() function returns the integer part of the division.

对应中文
给你一个整数数组 nums ,请你返回所有下标对 0 <= i, j < nums.length 的 floor(nums[i] / nums[j]) 结果之和。由于答案可能会很大,请你返回答案对10^9 + 7 取余 的结果。

函数 floor() 返回输入数字的整数部分。

示例

Example 1:

Input: nums = [2,5,9]
Output: 10
Explanation:
floor(2 / 5) = floor(2 / 9) = floor(5 / 9) = 0
floor(2 / 2) = floor(5 / 5) = floor(9 / 9) = 1
floor(5 / 2) = 2
floor(9 / 2) = 4
floor(9 / 5) = 1
We calculate the floor of the division for every pair of indices in the array then sum them up.

Example 2:

Input: nums = [7,7,7,7,7,7,7]
Output: 49

Constraints:

  • 1 <= nums.length <= 10^5
  • 1 <= nums[i] <= 10^5

简析

这题不愧是 hard,要不是看了讨论区的一个大神的解答感觉从头做得想好久,
主要是两点,对于任何一个在里面的数,随便举个例子是 k,最简单的就是循环所有数对 k 除一下,
这样效率会很低,那么对于 k 有什么规律呢,就是对于所有小于 k 的数,往下取整都是 0,所以不用考虑,
对于所有大于 k 的数我们可以分成一个个的区间,[k,2k-1),[2k,3k-1),[3k,4k-1)……对于这些区间的
除了 k 往下取整,每个区间内的都是一样的,所以可以简化为对于任意一个 k,我只要知道与k 相同的有多少个,然后比 k 大的各个区间各有多少个数就可以了

代码

static final int MAXE5 = 100_000;
 
 static final int MODULUSE9 = 1_000_000_000 + 7;
 
@@ -27,4 +27,4 @@
         total = (total + (sum % MODULUSE9  ) * (counts[i] - counts[i-1])) % MODULUSE9;
     }
     return (int)total;
-}

贴出来大神的解析,解析

结果

0%
\ No newline at end of file +}

贴出来大神的解析,解析

结果

0%
\ No newline at end of file diff --git a/2022/10/02/Leetcode-747-至少是其他数字两倍的最大数-Largest-Number-At-Least-Twice-of-Others-Easy-题解分析/index.html b/2022/10/02/Leetcode-747-至少是其他数字两倍的最大数-Largest-Number-At-Least-Twice-of-Others-Easy-题解分析/index.html index 4d32d1ae3f..c297a4fda7 100644 --- a/2022/10/02/Leetcode-747-至少是其他数字两倍的最大数-Largest-Number-At-Least-Twice-of-Others-Easy-题解分析/index.html +++ b/2022/10/02/Leetcode-747-至少是其他数字两倍的最大数-Largest-Number-At-Least-Twice-of-Others-Easy-题解分析/index.html @@ -1,4 +1,4 @@ -Leetcode 747 至少是其他数字两倍的最大数 ( Largest Number At Least Twice of Others *Easy* ) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 747 至少是其他数字两倍的最大数 ( Largest Number At Least Twice of Others *Easy* ) 题解分析

题目介绍

You are given an integer array nums where the largest integer is unique.

Determine whether the largest element in the array is at least twice as much as every other number in the array. If it is, return the index of the largest element, or return -1 otherwise.
确认在数组中的最大数是否是其余任意数的两倍大及以上,如果是返回索引,如果不是返回-1

示例

Example 1:

Input: nums = [3,6,1,0]
Output: 1
Explanation: 6 is the largest integer.
For every other number in the array x, 6 is at least twice as big as x.
The index of value 6 is 1, so we return 1.

Example 2:

Input: nums = [1,2,3,4]
Output: -1
Explanation: 4 is less than twice the value of 3, so we return -1.

提示:

  • 2 <= nums.length <= 50
  • 0 <= nums[i] <= 100
  • The largest element in nums is unique.

简要解析

这个题easy是题意也比较简单,找最大值,并且最大值是其他任意值的两倍及以上,其实就是找最大值跟次大值,比较下就好了

代码

public int dominantIndex(int[] nums) {
+Leetcode 747 至少是其他数字两倍的最大数 ( Largest Number At Least Twice of Others *Easy* ) 题解分析 | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Leetcode 747 至少是其他数字两倍的最大数 ( Largest Number At Least Twice of Others *Easy* ) 题解分析

题目介绍

You are given an integer array nums where the largest integer is unique.

Determine whether the largest element in the array is at least twice as much as every other number in the array. If it is, return the index of the largest element, or return -1 otherwise.
确认在数组中的最大数是否是其余任意数的两倍大及以上,如果是返回索引,如果不是返回-1

示例

Example 1:

Input: nums = [3,6,1,0]
Output: 1
Explanation: 6 is the largest integer.
For every other number in the array x, 6 is at least twice as big as x.
The index of value 6 is 1, so we return 1.

Example 2:

Input: nums = [1,2,3,4]
Output: -1
Explanation: 4 is less than twice the value of 3, so we return -1.

提示:

  • 2 <= nums.length <= 50
  • 0 <= nums[i] <= 100
  • The largest element in nums is unique.

简要解析

这个题easy是题意也比较简单,找最大值,并且最大值是其他任意值的两倍及以上,其实就是找最大值跟次大值,比较下就好了

代码

public int dominantIndex(int[] nums) {
     int largest = Integer.MIN_VALUE;
     int second = Integer.MIN_VALUE;
     int largestIndex = -1;
@@ -20,4 +20,4 @@
     } else {
         return -1;
     }
-}

通过图

第一次错了是把第二大的情况只考虑第一种,也有可能最大值完全没经过替换就变成最大值了

0%
\ No newline at end of file +}

通过图

第一次错了是把第二大的情况只考虑第一种,也有可能最大值完全没经过替换就变成最大值了

0%
\ No newline at end of file diff --git a/2023/09/10/Tomcat-系列篇一-介绍下-connector/index.html b/2023/09/10/Tomcat-系列篇一-介绍下-connector/index.html index 12eb85b274..1b77f1297c 100644 --- a/2023/09/10/Tomcat-系列篇一-介绍下-connector/index.html +++ b/2023/09/10/Tomcat-系列篇一-介绍下-connector/index.html @@ -1,4 +1,4 @@ -Tomcat 系列篇一-介绍下 connector | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Tomcat 系列篇一-介绍下 connector

tomcat的主体架构里,connector 作为核心的连接器

这也是个架构的优化,将连接跟请求处理分开,可以适配各种连接协议
连接器的初始化逻辑,是在初始化 WebServer 的时候调用
org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory#getWebServer

public WebServer getWebServer(ServletContextInitializer... initializers) {
+Tomcat 系列篇一-介绍下 connector | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

Tomcat 系列篇一-介绍下 connector

tomcat的主体架构里,connector 作为核心的连接器

这也是个架构的优化,将连接跟请求处理分开,可以适配各种连接协议
连接器的初始化逻辑,是在初始化 WebServer 的时候调用
org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory#getWebServer

public WebServer getWebServer(ServletContextInitializer... initializers) {
         if (this.disableMBeanRegistry) {
             Registry.disableRegistry();
         }
@@ -30,7 +30,7 @@
         }
         // Default for Connector depends on this system property
         setThrowOnFailure(Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE"));
-    }

这里就调用了
org.apache.coyote.ProtocolHandler#create
根据协议来生成对应的,我们这里默认就是
org.apache.coyote.http11.Http11NioProtocol

public static ProtocolHandler create(String protocol, boolean apr)
+    }

这里就调用了
org.apache.coyote.ProtocolHandler#create
根据协议来生成对应的,我们这里默认就是
org.apache.coyote.http11.Http11NioProtocol

public static ProtocolHandler create(String protocol, boolean apr)
             throws ClassNotFoundException, InstantiationException, IllegalAccessException,
             IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
         if (protocol == null || "HTTP/1.1".equals(protocol)
@@ -376,7 +376,7 @@
             stopLatch.countDown();
         }
         state = AcceptorState.ENDED;
-    }

这行socket = endpoint.serverSocketAccept();是 accept 等待线程进来,进来以后调用
``

@Override
+    }

这行socket = endpoint.serverSocketAccept();是 accept 等待线程进来,进来以后调用

@Override
     protected boolean setSocketOptions(SocketChannel socket) {
         NioSocketWrapper socketWrapper = null;
         try {
diff --git a/atom.xml b/atom.xml
index c6977dc156..b037deba63 100644
--- a/atom.xml
+++ b/atom.xml
@@ -6,7 +6,7 @@
   
   
   
-  2023-09-10T13:30:22.262Z
+  2023-09-11T00:15:24.644Z
   https://nicksxs.me/
   
   
@@ -21,7 +21,7 @@
     
     https://nicksxs.me/2023/09/10/Tomcat-%E7%B3%BB%E5%88%97%E7%AF%87%E4%B8%80-%E4%BB%8B%E7%BB%8D%E4%B8%8B-connector/
     2023-09-10T13:30:22.000Z
-    2023-09-10T13:30:22.262Z
+    2023-09-11T00:15:24.644Z
     
     
       
diff --git a/baidusitemap.xml b/baidusitemap.xml
index ef96aed56a..951f7e77ee 100644
--- a/baidusitemap.xml
+++ b/baidusitemap.xml
@@ -2,7 +2,7 @@
 
   
     https://nicksxs.me/2023/09/10/Tomcat-%E7%B3%BB%E5%88%97%E7%AF%87%E4%B8%80-%E4%BB%8B%E7%BB%8D%E4%B8%8B-connector/
-    2023-09-10
+    2023-09-11
   
   
     https://nicksxs.me/2023/08/20/springboot-web-server-%E5%90%AF%E5%8A%A8%E9%80%BB%E8%BE%91/
@@ -284,20 +284,16 @@
     https://nicksxs.me/2021/03/31/2020-%E5%B9%B4%E7%BB%88%E6%80%BB%E7%BB%93/
     2022-06-11
   
-  
-    https://nicksxs.me/2021/02/21/AQS-%E4%B9%8B-Condition-%E6%B5%85%E6%9E%90%E7%AC%94%E8%AE%B0/
-    2022-06-11
-  
   
     https://nicksxs.me/2022/02/13/Disruptor-%E7%B3%BB%E5%88%97%E4%B8%80/
     2022-06-11
   
   
-    https://nicksxs.me/2020/08/22/Filter-Intercepter-Aop-%E5%95%A5-%E5%95%A5-%E5%95%A5-%E8%BF%99%E4%BA%9B%E9%83%BD%E6%98%AF%E5%95%A5/
+    https://nicksxs.me/2022/02/27/Disruptor-%E7%B3%BB%E5%88%97%E4%BA%8C/
     2022-06-11
   
   
-    https://nicksxs.me/2022/02/27/Disruptor-%E7%B3%BB%E5%88%97%E4%BA%8C/
+    https://nicksxs.me/2020/08/22/Filter-Intercepter-Aop-%E5%95%A5-%E5%95%A5-%E5%95%A5-%E8%BF%99%E4%BA%9B%E9%83%BD%E6%98%AF%E5%95%A5/
     2022-06-11
   
   
@@ -309,11 +305,11 @@
     2022-06-11
   
   
-    https://nicksxs.me/2021/05/01/Leetcode-48-%E6%97%8B%E8%BD%AC%E5%9B%BE%E5%83%8F-Rotate-Image-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/
+    https://nicksxs.me/2021/07/04/Leetcode-42-%E6%8E%A5%E9%9B%A8%E6%B0%B4-Trapping-Rain-Water-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/
     2022-06-11
   
   
-    https://nicksxs.me/2021/07/04/Leetcode-42-%E6%8E%A5%E9%9B%A8%E6%B0%B4-Trapping-Rain-Water-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/
+    https://nicksxs.me/2021/05/01/Leetcode-48-%E6%97%8B%E8%BD%AC%E5%9B%BE%E5%83%8F-Rotate-Image-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/
     2022-06-11
   
   
@@ -324,12 +320,16 @@
     https://nicksxs.me/2020/08/06/Linux-%E4%B8%8B-grep-%E5%91%BD%E4%BB%A4%E7%9A%84%E4%B8%80%E7%82%B9%E5%B0%8F%E6%8A%80%E5%B7%A7/
     2022-06-11
   
+  
+    https://nicksxs.me/2021/02/21/AQS-%E4%B9%8B-Condition-%E6%B5%85%E6%9E%90%E7%AC%94%E8%AE%B0/
+    2022-06-11
+  
   
     https://nicksxs.me/2020/09/06/mybatis-%E7%9A%84-%E5%92%8C-%E6%98%AF%E6%9C%89%E5%95%A5%E5%8C%BA%E5%88%AB/
     2022-06-11
   
   
-    https://nicksxs.me/2021/04/18/rust%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0-%E6%89%80%E6%9C%89%E6%9D%83%E4%BA%8C/
+    https://nicksxs.me/2021/04/18/rust%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/
     2022-06-11
   
   
@@ -337,15 +337,15 @@
     2022-06-11
   
   
-    https://nicksxs.me/2021/04/18/rust%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/
+    https://nicksxs.me/2021/04/18/rust%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0-%E6%89%80%E6%9C%89%E6%9D%83%E4%BA%8C/
     2022-06-11
   
   
-    https://nicksxs.me/2021/03/07/%E3%80%8A%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6%E7%AE%97%E6%B3%95%E6%89%8B%E5%86%8C%E8%AF%BB%E4%B9%A6%E3%80%8B%E7%AC%94%E8%AE%B0%E4%B9%8B%E6%95%B4%E7%90%86%E7%AE%97%E6%B3%95/
+    https://nicksxs.me/2021/12/05/wordpress-%E5%BF%98%E8%AE%B0%E5%AF%86%E7%A0%81%E7%9A%84%E4%B8%80%E7%A7%8D%E8%A7%A3%E5%86%B3%E6%96%B9%E6%B3%95/
     2022-06-11
   
   
-    https://nicksxs.me/2021/12/05/wordpress-%E5%BF%98%E8%AE%B0%E5%AF%86%E7%A0%81%E7%9A%84%E4%B8%80%E7%A7%8D%E8%A7%A3%E5%86%B3%E6%96%B9%E6%B3%95/
+    https://nicksxs.me/2021/03/07/%E3%80%8A%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6%E7%AE%97%E6%B3%95%E6%89%8B%E5%86%8C%E8%AF%BB%E4%B9%A6%E3%80%8B%E7%AC%94%E8%AE%B0%E4%B9%8B%E6%95%B4%E7%90%86%E7%AE%97%E6%B3%95/
     2022-06-11
   
   
@@ -360,20 +360,16 @@
     https://nicksxs.me/2022/02/06/%E5%88%86%E4%BA%AB%E8%AE%B0%E5%BD%95%E4%B8%80%E4%B8%8B%E4%B8%80%E4%B8%AA-git-%E6%93%8D%E4%BD%9C%E6%96%B9%E6%B3%95/
     2022-06-11
   
-  
-    https://nicksxs.me/2021/09/04/%E8%81%8A%E4%B8%80%E4%B8%8B-RocketMQ-%E7%9A%84%E6%B6%88%E6%81%AF%E5%AD%98%E5%82%A8/
-    2022-06-11
-  
   
     https://nicksxs.me/2021/10/03/%E8%81%8A%E4%B8%80%E4%B8%8B-RocketMQ-%E7%9A%84%E6%B6%88%E6%81%AF%E5%AD%98%E5%82%A8%E4%B8%89/
     2022-06-11
   
   
-    https://nicksxs.me/2021/09/12/%E8%81%8A%E4%B8%80%E4%B8%8B-RocketMQ-%E7%9A%84%E6%B6%88%E6%81%AF%E5%AD%98%E5%82%A8%E4%BA%8C/
+    https://nicksxs.me/2021/09/04/%E8%81%8A%E4%B8%80%E4%B8%8B-RocketMQ-%E7%9A%84%E6%B6%88%E6%81%AF%E5%AD%98%E5%82%A8/
     2022-06-11
   
   
-    https://nicksxs.me/2021/10/17/%E8%81%8A%E4%B8%80%E4%B8%8B-RocketMQ-%E7%9A%84%E6%B6%88%E6%81%AF%E5%AD%98%E5%82%A8%E5%9B%9B/
+    https://nicksxs.me/2021/09/12/%E8%81%8A%E4%B8%80%E4%B8%8B-RocketMQ-%E7%9A%84%E6%B6%88%E6%81%AF%E5%AD%98%E5%82%A8%E4%BA%8C/
     2022-06-11
   
   
@@ -385,7 +381,7 @@
     2022-06-11
   
   
-    https://nicksxs.me/2020/11/22/%E8%81%8A%E8%81%8A-Dubbo-%E7%9A%84%E5%AE%B9%E9%94%99%E6%9C%BA%E5%88%B6/
+    https://nicksxs.me/2021/10/17/%E8%81%8A%E4%B8%80%E4%B8%8B-RocketMQ-%E7%9A%84%E6%B6%88%E6%81%AF%E5%AD%98%E5%82%A8%E5%9B%9B/
     2022-06-11
   
   
@@ -393,19 +389,19 @@
     2022-06-11
   
   
-    https://nicksxs.me/2021/06/13/%E8%81%8A%E8%81%8A-Java-%E7%9A%84%E7%B1%BB%E5%8A%A0%E8%BD%BD%E6%9C%BA%E5%88%B6%E4%BA%8C/
+    https://nicksxs.me/2020/11/22/%E8%81%8A%E8%81%8A-Dubbo-%E7%9A%84%E5%AE%B9%E9%94%99%E6%9C%BA%E5%88%B6/
     2022-06-11
   
   
-    https://nicksxs.me/2020/08/02/%E8%81%8A%E8%81%8A-Java-%E8%87%AA%E5%B8%A6%E7%9A%84%E9%82%A3%E4%BA%9B%E9%80%86%E5%A4%A9%E5%B7%A5%E5%85%B7/
+    https://nicksxs.me/2021/06/13/%E8%81%8A%E8%81%8A-Java-%E7%9A%84%E7%B1%BB%E5%8A%A0%E8%BD%BD%E6%9C%BA%E5%88%B6%E4%BA%8C/
     2022-06-11
   
   
-    https://nicksxs.me/2021/03/28/%E8%81%8A%E8%81%8A-Linux-%E4%B8%8B%E7%9A%84-top-%E5%91%BD%E4%BB%A4/
+    https://nicksxs.me/2020/08/02/%E8%81%8A%E8%81%8A-Java-%E8%87%AA%E5%B8%A6%E7%9A%84%E9%82%A3%E4%BA%9B%E9%80%86%E5%A4%A9%E5%B7%A5%E5%85%B7/
     2022-06-11
   
   
-    https://nicksxs.me/2021/12/26/%E8%81%8A%E8%81%8A-Sharding-Jdbc-%E7%9A%84%E7%AE%80%E5%8D%95%E5%8E%9F%E7%90%86%E5%88%9D%E7%AF%87/
+    https://nicksxs.me/2021/03/28/%E8%81%8A%E8%81%8A-Linux-%E4%B8%8B%E7%9A%84-top-%E5%91%BD%E4%BB%A4/
     2022-06-11
   
   
@@ -420,6 +416,10 @@
     https://nicksxs.me/2021/04/04/%E8%81%8A%E8%81%8A-dubbo-%E7%9A%84%E7%BA%BF%E7%A8%8B%E6%B1%A0/
     2022-06-11
   
+  
+    https://nicksxs.me/2021/12/26/%E8%81%8A%E8%81%8A-Sharding-Jdbc-%E7%9A%84%E7%AE%80%E5%8D%95%E5%8E%9F%E7%90%86%E5%88%9D%E7%AF%87/
+    2022-06-11
+  
   
     https://nicksxs.me/2020/12/27/%E8%81%8A%E8%81%8A-mysql-%E7%B4%A2%E5%BC%95%E7%9A%84%E4%B8%80%E4%BA%9B%E7%BB%86%E8%8A%82/
     2022-06-11
@@ -796,10 +796,6 @@
     https://nicksxs.me/2015/04/14/Add-Two-Number/
     2020-01-12
   
-  
-    https://nicksxs.me/2016/08/14/34-Search-for-a-Range/
-    2020-01-12
-  
   
     https://nicksxs.me/2014/12/24/MFC%20%E6%A8%A1%E6%80%81%E5%AF%B9%E8%AF%9D%E6%A1%86/
     2020-01-12
@@ -813,11 +809,11 @@
     2020-01-12
   
   
-    https://nicksxs.me/2015/01/14/Two-Sum/
+    https://nicksxs.me/2015/03/13/Reverse-Integer/
     2020-01-12
   
   
-    https://nicksxs.me/2015/03/13/Reverse-Integer/
+    https://nicksxs.me/2017/05/09/ambari-summary/
     2020-01-12
   
   
@@ -825,11 +821,15 @@
     2020-01-12
   
   
-    https://nicksxs.me/2017/05/09/ambari-summary/
+    https://nicksxs.me/2016/08/14/docker-mysql-cluster/
     2020-01-12
   
   
-    https://nicksxs.me/2016/08/14/docker-mysql-cluster/
+    https://nicksxs.me/2015/01/14/Two-Sum/
+    2020-01-12
+  
+  
+    https://nicksxs.me/2016/08/14/34-Search-for-a-Range/
     2020-01-12
   
   
@@ -869,11 +869,11 @@
     2020-01-12
   
   
-    https://nicksxs.me/2015/01/04/Path-Sum/
+    https://nicksxs.me/2015/03/11/Number-Of-1-Bits/
     2020-01-12
   
   
-    https://nicksxs.me/2015/03/11/Number-Of-1-Bits/
+    https://nicksxs.me/2015/01/04/Path-Sum/
     2020-01-12
   
   
diff --git a/categories/Java/page/2/index.html b/categories/Java/page/2/index.html
index 81d4ddd502..731d48da4f 100644
--- a/categories/Java/page/2/index.html
+++ b/categories/Java/page/2/index.html
@@ -1 +1 @@
-分类: java | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

0%
\ No newline at end of file +分类: Java | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

0%
\ No newline at end of file diff --git a/categories/docker/index.html b/categories/docker/index.html index c8de94bd8b..59a7a1ef7b 100644 --- a/categories/docker/index.html +++ b/categories/docker/index.html @@ -1 +1 @@ -分类: docker | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

docker 分类

2016
0%
t> \ No newline at end of file +分类: Docker | Nicksxs's Blog

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

0%
\ No newline at end of file diff --git a/index.html b/index.html index b9a0ca17c5..3bd796721e 100644 --- a/index.html +++ b/index.html @@ -1,4 +1,4 @@ -Nicksxs's Blog - What hurts more, the pain of hard work or the pain of regret?

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

tomcat的主体架构里,connector 作为核心的连接器

这也是个架构的优化,将连接跟请求处理分开,可以适配各种连接协议
连接器的初始化逻辑,是在初始化 WebServer 的时候调用
org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory#getWebServer

public WebServer getWebServer(ServletContextInitializer... initializers) {
+Nicksxs's Blog - What hurts more, the pain of hard work or the pain of regret?

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

tomcat的主体架构里,connector 作为核心的连接器

这也是个架构的优化,将连接跟请求处理分开,可以适配各种连接协议
连接器的初始化逻辑,是在初始化 WebServer 的时候调用
org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory#getWebServer

public WebServer getWebServer(ServletContextInitializer... initializers) {
         if (this.disableMBeanRegistry) {
             Registry.disableRegistry();
         }
@@ -30,7 +30,7 @@
         }
         // Default for Connector depends on this system property
         setThrowOnFailure(Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE"));
-    }

这里就调用了
org.apache.coyote.ProtocolHandler#create
根据协议来生成对应的,我们这里默认就是
org.apache.coyote.http11.Http11NioProtocol

public static ProtocolHandler create(String protocol, boolean apr)
+    }

这里就调用了
org.apache.coyote.ProtocolHandler#create
根据协议来生成对应的,我们这里默认就是
org.apache.coyote.http11.Http11NioProtocol

public static ProtocolHandler create(String protocol, boolean apr)
             throws ClassNotFoundException, InstantiationException, IllegalAccessException,
             IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
         if (protocol == null || "HTTP/1.1".equals(protocol)
@@ -376,7 +376,7 @@
             stopLatch.countDown();
         }
         state = AcceptorState.ENDED;
-    }

这行socket = endpoint.serverSocketAccept();是 accept 等待线程进来,进来以后调用
``

@Override
+    }

这行socket = endpoint.serverSocketAccept();是 accept 等待线程进来,进来以后调用

@Override
     protected boolean setSocketOptions(SocketChannel socket) {
         NioSocketWrapper socketWrapper = null;
         try {
diff --git a/leancloud.memo b/leancloud.memo
index 0f6541e031..75cd5fe020 100644
--- a/leancloud.memo
+++ b/leancloud.memo
@@ -232,4 +232,5 @@
 {"title":"springboot web server 启动逻辑","url":"/2023/08/20/springboot-web-server-启动逻辑/"},
 {"title":"springboot 请求响应处理流程","url":"/2023/08/27/springboot-请求响应处理流程/"},
 {"title":"springboot 处理请求的小分支-跳转 & cookie","url":"/2023/09/03/springboot-处理请求的小分支-跳转-cookie/"},
+{"title":"Tomcat 系列篇一-介绍下 connector","url":"/2023/09/10/Tomcat-系列篇一-介绍下-connector/"},
 ]
\ No newline at end of file
diff --git a/leancloud_counter_security_urls.json b/leancloud_counter_security_urls.json
index d3f7922465..20e61d1e8e 100644
--- a/leancloud_counter_security_urls.json
+++ b/leancloud_counter_security_urls.json
@@ -1 +1 @@
-[{"title":"村上春树《1Q84》读后感","url":"/2019/12/18/1Q84读后感/"},{"title":"2021 年中总结","url":"/2021/07/18/2021-年中总结/"},{"title":"2020 年终总结","url":"/2021/03/31/2020-年终总结/"},{"title":"2019年终总结","url":"/2020/02/01/2019年终总结/"},{"title":"2021 年终总结","url":"/2022/01/22/2021-年终总结/"},{"title":"AQS篇二 之 Condition 浅析笔记","url":"/2021/02/21/AQS-之-Condition-浅析笔记/"},{"title":"2020年中总结","url":"/2020/07/11/2020年中总结/"},{"title":"AbstractQueuedSynchronizer","url":"/2019/09/23/AbstractQueuedSynchronizer/"},{"title":"add-two-number","url":"/2015/04/14/Add-Two-Number/"},{"title":"AQS篇一","url":"/2021/02/14/AQS篇一/"},{"title":"Apollo 如何获取当前环境","url":"/2022/09/04/Apollo-如何获取当前环境/"},{"title":"Apollo 客户端启动过程分析","url":"/2022/09/18/Apollo-客户端启动过程分析/"},{"title":"Apollo 的 value 注解是怎么自动更新的","url":"/2020/11/01/Apollo-的-value-注解是怎么自动更新的/"},{"title":"Comparator使用小记","url":"/2020/04/05/Comparator使用小记/"},{"title":"Clone Graph Part I","url":"/2014/12/30/Clone-Graph-Part-I/"},{"title":"2022 年终总结","url":"/2023/01/15/2022-年终总结/"},{"title":"Dubbo 使用的几个记忆点","url":"/2022/04/02/Dubbo-使用的几个记忆点/"},{"title":"Disruptor 系列一","url":"/2022/02/13/Disruptor-系列一/"},{"title":"Filter, Interceptor, Aop, 啥, 啥, 啥? 这些都是啥?","url":"/2020/08/22/Filter-Intercepter-Aop-啥-啥-啥-这些都是啥/"},{"title":"G1收集器概述","url":"/2020/02/09/G1收集器概述/"},{"title":"JVM源码分析之G1垃圾收集器分析一","url":"/2019/12/07/JVM-G1-Part-1/"},{"title":"Leetcode 028 实现 strStr() ( Implement strStr() ) 题解分析","url":"/2021/10/31/Leetcode-028-实现-strStr-Implement-strStr-题解分析/"},{"title":"Leetcode 053 最大子序和 ( Maximum Subarray ) 题解分析","url":"/2021/11/28/Leetcode-053-最大子序和-Maximum-Subarray-题解分析/"},{"title":"Disruptor 系列二","url":"/2022/02/27/Disruptor-系列二/"},{"title":"34_Search_for_a_Range","url":"/2016/08/14/34-Search-for-a-Range/"},{"title":"Leetcode 104 二叉树的最大深度(Maximum Depth of Binary Tree) 题解分析","url":"/2020/10/25/Leetcode-104-二叉树的最大深度-Maximum-Depth-of-Binary-Tree-题解分析/"},{"title":"Leetcode 021 合并两个有序链表 ( Merge Two Sorted Lists ) 题解分析","url":"/2021/10/07/Leetcode-021-合并两个有序链表-Merge-Two-Sorted-Lists-题解分析/"},{"title":"Disruptor 系列三","url":"/2022/09/25/Disruptor-系列三/"},{"title":"Leetcode 1115 交替打印 FooBar ( Print FooBar Alternately *Medium* ) 题解分析","url":"/2022/05/01/Leetcode-1115-交替打印-FooBar-Print-FooBar-Alternately-Medium-题解分析/"},{"title":"Leetcode 121 买卖股票的最佳时机(Best Time to Buy and Sell Stock) 题解分析","url":"/2021/03/14/Leetcode-121-买卖股票的最佳时机-Best-Time-to-Buy-and-Sell-Stock-题解分析/"},{"title":"Leetcode 1260 二维网格迁移 ( Shift 2D Grid *Easy* ) 题解分析","url":"/2022/07/22/Leetcode-1260-二维网格迁移-Shift-2D-Grid-Easy-题解分析/"},{"title":"Leetcode 105 从前序与中序遍历序列构造二叉树(Construct Binary Tree from Preorder and Inorder Traversal) 题解分析","url":"/2020/12/13/Leetcode-105-从前序与中序遍历序列构造二叉树-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal-题解分析/"},{"title":"Leetcode 155 最小栈(Min Stack) 题解分析","url":"/2020/12/06/Leetcode-155-最小栈-Min-Stack-题解分析/"},{"title":"Leetcode 124 二叉树中的最大路径和(Binary Tree Maximum Path Sum) 题解分析","url":"/2021/01/24/Leetcode-124-二叉树中的最大路径和-Binary-Tree-Maximum-Path-Sum-题解分析/"},{"title":"Leetcode 160 相交链表(intersection-of-two-linked-lists) 题解分析","url":"/2021/01/10/Leetcode-160-相交链表-intersection-of-two-linked-lists-题解分析/"},{"title":"Leetcode 1862 向下取整数对和 ( Sum of Floored Pairs *Hard* ) 题解分析","url":"/2022/09/11/Leetcode-1862-向下取整数对和-Sum-of-Floored-Pairs-Hard-题解分析/"},{"title":"Leetcode 16 最接近的三数之和 ( 3Sum Closest *Medium* ) 题解分析","url":"/2022/08/06/Leetcode-16-最接近的三数之和-3Sum-Closest-Medium-题解分析/"},{"title":"Leetcode 2 Add Two Numbers 题解分析","url":"/2020/10/11/Leetcode-2-Add-Two-Numbers-题解分析/"},{"title":"Leetcode 234 回文链表(Palindrome Linked List) 题解分析","url":"/2020/11/15/Leetcode-234-回文联表-Palindrome-Linked-List-题解分析/"},{"title":"Leetcode 20 有效的括号 ( Valid Parentheses *Easy* ) 题解分析","url":"/2022/07/02/Leetcode-20-有效的括号-Valid-Parentheses-Easy-题解分析/"},{"title":"Leetcode 236 二叉树的最近公共祖先(Lowest Common Ancestor of a Binary Tree) 题解分析","url":"/2021/05/23/Leetcode-236-二叉树的最近公共祖先-Lowest-Common-Ancestor-of-a-Binary-Tree-题解分析/"},{"title":"Leetcode 278 第一个错误的版本 ( First Bad Version *Easy* ) 题解分析","url":"/2022/08/14/Leetcode-278-第一个错误的版本-First-Bad-Version-Easy-题解分析/"},{"title":"Leetcode 3 Longest Substring Without Repeating Characters 题解分析","url":"/2020/09/20/Leetcode-3-Longest-Substring-Without-Repeating-Characters-题解分析/"},{"title":"Headscale初体验以及踩坑记","url":"/2023/01/22/Headscale初体验以及踩坑记/"},{"title":"Leetcode 48 旋转图像(Rotate Image) 题解分析","url":"/2021/05/01/Leetcode-48-旋转图像-Rotate-Image-题解分析/"},{"title":"Leetcode 4 寻找两个正序数组的中位数 ( Median of Two Sorted Arrays *Hard* ) 题解分析","url":"/2022/03/27/Leetcode-4-寻找两个正序数组的中位数-Median-of-Two-Sorted-Arrays-Hard-题解分析/"},{"title":"Leetcode 42 接雨水 (Trapping Rain Water) 题解分析","url":"/2021/07/04/Leetcode-42-接雨水-Trapping-Rain-Water-题解分析/"},{"title":"Leetcode 349 两个数组的交集 ( Intersection of Two Arrays *Easy* ) 题解分析","url":"/2022/03/07/Leetcode-349-两个数组的交集-Intersection-of-Two-Arrays-Easy-题解分析/"},{"title":"Leetcode 885 螺旋矩阵 III ( Spiral Matrix III *Medium* ) 题解分析","url":"/2022/08/23/Leetcode-885-螺旋矩阵-III-Spiral-Matrix-III-Medium-题解分析/"},{"title":"Leetcode 83 删除排序链表中的重复元素 ( Remove Duplicates from Sorted List *Easy* ) 题解分析","url":"/2022/03/13/Leetcode-83-删除排序链表中的重复元素-Remove-Duplicates-from-Sorted-List-Easy-题解分析/"},{"title":"Leetcode 698 划分为k个相等的子集 ( Partition to K Equal Sum Subsets *Medium* ) 题解分析","url":"/2022/06/19/Leetcode-698-划分为k个相等的子集-Partition-to-K-Equal-Sum-Subsets-Medium-题解分析/"},{"title":"Linux 下 grep 命令的一点小技巧","url":"/2020/08/06/Linux-下-grep-命令的一点小技巧/"},{"title":"Maven实用小技巧","url":"/2020/02/16/Maven实用小技巧/"},{"title":"MFC 模态对话框","url":"/2014/12/24/MFC 模态对话框/"},{"title":"leetcode no.3","url":"/2015/04/15/Leetcode-No-3/"},{"title":"Path Sum","url":"/2015/01/04/Path-Sum/"},{"title":"Number of 1 Bits","url":"/2015/03/11/Number-Of-1-Bits/"},{"title":"Redis_分布式锁","url":"/2019/12/10/Redis-Part-1/"},{"title":"Reverse Bits","url":"/2015/03/11/Reverse-Bits/"},{"title":"Tomcat 系列篇一-介绍下 connector","url":"/2023/09/10/Tomcat-系列篇一-介绍下-connector/"},{"title":"two sum","url":"/2015/01/14/Two-Sum/"},{"title":"Reverse Integer","url":"/2015/03/13/Reverse-Integer/"},{"title":"binary-watch","url":"/2016/09/29/binary-watch/"},{"title":"ambari-summary","url":"/2017/05/09/ambari-summary/"},{"title":"docker比一般多一点的初学者介绍","url":"/2020/03/08/docker比一般多一点的初学者介绍/"},{"title":"docker比一般多一点的初学者介绍三","url":"/2020/03/21/docker比一般多一点的初学者介绍三/"},{"title":"docker-mysql-cluster","url":"/2016/08/14/docker-mysql-cluster/"},{"title":"dubbo 客户端配置的一个重要知识点","url":"/2022/06/11/dubbo-客户端配置的一个重要知识点/"},{"title":"docker比一般多一点的初学者介绍四","url":"/2022/12/25/docker比一般多一点的初学者介绍四/"},{"title":"docker比一般多一点的初学者介绍二","url":"/2020/03/15/docker比一般多一点的初学者介绍二/"},{"title":"docker使用中发现的echo命令的一个小技巧及其他","url":"/2020/03/29/echo命令的一个小技巧/"},{"title":"headscale 添加节点","url":"/2023/07/09/headscale-添加节点/"},{"title":"gogs使用webhook部署react单页应用","url":"/2020/02/22/gogs使用webhook部署react单页应用/"},{"title":"Leetcode 747 至少是其他数字两倍的最大数 ( Largest Number At Least Twice of Others *Easy* ) 题解分析","url":"/2022/10/02/Leetcode-747-至少是其他数字两倍的最大数-Largest-Number-At-Least-Twice-of-Others-Easy-题解分析/"},{"title":"invert-binary-tree","url":"/2015/06/22/invert-binary-tree/"},{"title":"C++ 指针使用中的一个小问题","url":"/2014/12/23/my-new-post/"},{"title":"dnsmasq的一个使用注意点","url":"/2023/04/16/dnsmasq的一个使用注意点/"},{"title":"mybatis 的 foreach 使用的注意点","url":"/2022/07/09/mybatis-的-foreach-使用的注意点/"},{"title":"java 中发起 http 请求时证书问题解决记录","url":"/2023/07/29/java-中发起-http-请求时证书问题解决记录/"},{"title":"mybatis 的缓存是怎么回事","url":"/2020/10/03/mybatis-的缓存是怎么回事/"},{"title":"mybatis系列-mybatis是如何初始化mapper的","url":"/2022/12/04/mybatis是如何初始化mapper的/"},{"title":"hexo 配置系列-接入Algolia搜索","url":"/2023/04/02/hexo-配置系列-接入Algolia搜索/"},{"title":"mybatis系列-connection连接池解析","url":"/2023/02/19/mybatis系列-connection连接池解析/"},{"title":"github 小技巧-更新 github host key","url":"/2023/03/28/github-小技巧-更新-github-host-key/"},{"title":"mybatis 的 $ 和 # 是有啥区别","url":"/2020/09/06/mybatis-的-和-是有啥区别/"},{"title":"mybatis系列-dataSource解析","url":"/2023/01/08/mybatis系列-dataSource解析/"},{"title":"nginx 日志小记","url":"/2022/04/17/nginx-日志小记/"},{"title":"mybatis系列-sql 类的简单使用","url":"/2023/03/12/mybatis系列-sql-类的简单使用/"},{"title":"mybatis系列-typeAliases系统","url":"/2023/01/01/mybatis系列-typeAliases系统/"},{"title":"minimum-size-subarray-sum-209","url":"/2016/10/11/minimum-size-subarray-sum-209/"},{"title":"mybatis系列-第一条sql的更多细节","url":"/2022/12/18/mybatis系列-第一条sql的更多细节/"},{"title":"pcre-intro-and-a-simple-package","url":"/2015/01/16/pcre-intro-and-a-simple-package/"},{"title":"openresty","url":"/2019/06/18/openresty/"},{"title":"mybatis系列-foreach 解析","url":"/2023/06/11/mybatis系列-foreach-解析/"},{"title":"mybatis系列-第一条sql的细节","url":"/2022/12/11/mybatis系列-第一条sql的细节/"},{"title":"php-abstract-class-and-interface","url":"/2016/11/10/php-abstract-class-and-interface/"},{"title":"mybatis系列-sql 类的简要分析","url":"/2023/03/19/mybatis系列-sql-类的简要分析/"},{"title":"rabbitmq-tips","url":"/2017/04/25/rabbitmq-tips/"},{"title":"redis数据结构介绍-第一部分 SDS,链表,字典","url":"/2019/12/26/redis数据结构介绍/"},{"title":"redis 的 rdb 和 COW 介绍","url":"/2021/08/15/redis-的-rdb-和-COW-介绍/"},{"title":"redis数据结构介绍三-第三部分 整数集合","url":"/2020/01/10/redis数据结构介绍三/"},{"title":"redis数据结构介绍二-第二部分 跳表","url":"/2020/01/04/redis数据结构介绍二/"},{"title":"mybatis系列-入门篇","url":"/2022/11/27/mybatis系列-入门篇/"},{"title":"redis数据结构介绍五-第五部分 对象","url":"/2020/01/20/redis数据结构介绍五/"},{"title":"redis淘汰策略复习","url":"/2021/08/01/redis淘汰策略复习/"},{"title":"redis数据结构介绍六 快表","url":"/2020/01/22/redis数据结构介绍六/"},{"title":"redis数据结构介绍四-第四部分 压缩表","url":"/2020/01/19/redis数据结构介绍四/"},{"title":"redis系列介绍七-过期策略","url":"/2020/04/12/redis系列介绍七/"},{"title":"redis系列介绍八-淘汰策略","url":"/2020/04/18/redis系列介绍八/"},{"title":"redis过期策略复习","url":"/2021/07/25/redis过期策略复习/"},{"title":"rust学习笔记-所有权二","url":"/2021/04/18/rust学习笔记-所有权二/"},{"title":"spark-little-tips","url":"/2017/03/28/spark-little-tips/"},{"title":"rust学习笔记-所有权三之切片","url":"/2021/05/16/rust学习笔记-所有权三之切片/"},{"title":"spring event 介绍","url":"/2022/01/30/spring-event-介绍/"},{"title":"powershell 初体验二","url":"/2022/11/20/powershell-初体验二/"},{"title":"rust学习笔记-所有权一","url":"/2021/04/18/rust学习笔记/"},{"title":"powershell 初体验","url":"/2022/11/13/powershell-初体验/"},{"title":"springboot mappings 注册逻辑","url":"/2023/08/13/springboot-mappings-注册逻辑/"},{"title":"springboot 请求响应处理流程","url":"/2023/08/27/springboot-请求响应处理流程/"},{"title":"summary-ranges-228","url":"/2016/10/12/summary-ranges-228/"},{"title":"spring boot中的 http 接口返回 json 形式的小注意点","url":"/2023/06/25/spring-boot中的-http-接口返回-json-形式的小注意点/"},{"title":"springboot web server 启动逻辑","url":"/2023/08/20/springboot-web-server-启动逻辑/"},{"title":"springboot 处理请求的小分支-跳转 & cookie","url":"/2023/09/03/springboot-处理请求的小分支-跳转-cookie/"},{"title":"《垃圾回收算法手册读书》笔记之整理算法","url":"/2021/03/07/《垃圾回收算法手册读书》笔记之整理算法/"},{"title":"swoole-websocket-test","url":"/2016/07/13/swoole-websocket-test/"},{"title":"ssh 小技巧-端口转发","url":"/2023/03/26/ssh-小技巧-端口转发/"},{"title":"《长安的荔枝》读后感","url":"/2022/07/17/《长安的荔枝》读后感/"},{"title":"一个 nginx 的简单记忆点","url":"/2022/08/21/一个-nginx-的简单记忆点/"},{"title":"上次的其他 外行聊国足","url":"/2022/03/06/上次的其他-外行聊国足/"},{"title":"wordpress 忘记密码的一种解决方法","url":"/2021/12/05/wordpress-忘记密码的一种解决方法/"},{"title":"介绍下最近比较实用的端口转发","url":"/2021/11/14/介绍下最近比较实用的端口转发/"},{"title":"springboot 获取 web 应用中所有的接口 url","url":"/2023/08/06/springboot-获取-web-应用中所有的接口-url/"},{"title":"win 下 vmware 虚拟机搭建黑裙 nas 的小思路","url":"/2023/06/04/win-下-vmware-虚拟机搭建黑裙-nas-的小思路/"},{"title":"介绍一下 RocketMQ","url":"/2020/06/21/介绍一下-RocketMQ/"},{"title":"从丁仲礼被美国制裁聊点啥","url":"/2020/12/20/从丁仲礼被美国制裁聊点啥/"},{"title":"nas 中使用 tmm 刮削视频","url":"/2023/07/02/使用-tmm-刮削视频/"},{"title":"关于读书打卡与分享","url":"/2021/02/07/关于读书打卡与分享/"},{"title":"从清华美院学姐聊聊我们身边的恶人","url":"/2020/11/29/从清华美院学姐聊聊我们身边的恶人/"},{"title":"关于 npe 的一个小记忆点","url":"/2023/07/16/关于-npe-的一个小记忆点/"},{"title":"分享一次比较诡异的 Windows 下 U盘无法退出的经历","url":"/2023/01/29/分享一次比较诡异的-Windows-下-U盘无法退出的经历/"},{"title":"《寻羊历险记》读后感","url":"/2023/07/23/《寻羊历险记》读后感/"},{"title":"分享记录一下一个 git 操作方法","url":"/2022/02/06/分享记录一下一个-git-操作方法/"},{"title":"关于公共交通再吐个槽","url":"/2021/03/21/关于公共交通再吐个槽/"},{"title":"周末我在老丈人家打了天小工","url":"/2020/08/16/周末我在老丈人家打了天小工/"},{"title":"分享记录一下一个 scp 操作方法","url":"/2022/02/06/分享记录一下一个-scp-操作方法/"},{"title":"分享一次折腾老旧笔记本的体验-续续篇","url":"/2023/02/26/分享一次折腾老旧笔记本的体验-续续篇/"},{"title":"在老丈人家的小工记三","url":"/2020/09/13/在老丈人家的小工记三/"},{"title":"在老丈人家的小工记四","url":"/2020/09/26/在老丈人家的小工记四/"},{"title":"分享一次折腾老旧笔记本的体验-续篇","url":"/2023/02/12/分享一次折腾老旧笔记本的体验-续篇/"},{"title":"在老丈人家的小工记五","url":"/2020/10/18/在老丈人家的小工记五/"},{"title":"分享一次折腾老旧笔记本的体验","url":"/2023/02/05/分享一次折腾老旧笔记本的体验/"},{"title":"在 wsl 2 中开启 ssh 连接","url":"/2023/04/23/在-wsl-2-中开启-ssh-连接/"},{"title":"寄生虫观后感","url":"/2020/03/01/寄生虫观后感/"},{"title":"屯菜惊魂记","url":"/2022/04/24/屯菜惊魂记/"},{"title":"搬运两个 StackOverflow 上的 Mysql 编码相关的问题解答","url":"/2022/01/16/搬运两个-StackOverflow-上的-Mysql-编码相关的问题解答/"},{"title":"看完了扫黑风暴,聊聊感想","url":"/2021/10/24/看完了扫黑风暴-聊聊感想/"},{"title":"是何原因竟让两人深夜奔袭十公里","url":"/2022/06/05/是何原因竟让两人深夜奔袭十公里/"},{"title":"聊一下 RocketMQ 的 NameServer 源码","url":"/2020/07/05/聊一下-RocketMQ-的-NameServer-源码/"},{"title":"给小电驴上牌","url":"/2022/03/20/给小电驴上牌/"},{"title":"聊一下 RocketMQ 的 DefaultMQPushConsumer 源码","url":"/2020/06/26/聊一下-RocketMQ-的-Consumer/"},{"title":"我是如何走上跑步这条不归路的","url":"/2020/07/26/我是如何走上跑步这条不归路的/"},{"title":"聊一下 RocketMQ 的消息存储之 MMAP","url":"/2021/09/04/聊一下-RocketMQ-的消息存储/"},{"title":"聊一下 RocketMQ 的消息存储三","url":"/2021/10/03/聊一下-RocketMQ-的消息存储三/"},{"title":"深度学习入门初认识","url":"/2023/04/30/深度学习入门初认识/"},{"title":"小工周记一","url":"/2023/03/05/小工周记一/"},{"title":"聊一下 RocketMQ 的消息存储二","url":"/2021/09/12/聊一下-RocketMQ-的消息存储二/"},{"title":"聊一下 RocketMQ 的消息存储四","url":"/2021/10/17/聊一下-RocketMQ-的消息存储四/"},{"title":"聊一下 RocketMQ 的顺序消息","url":"/2021/08/29/聊一下-RocketMQ-的顺序消息/"},{"title":"聊一下 SpringBoot 中使用的 cglib 作为动态代理中的一个注意点","url":"/2021/09/19/聊一下-SpringBoot-中使用的-cglib-作为动态代理中的一个注意点/"},{"title":"聊在东京奥运会闭幕式这天-二","url":"/2021/08/19/聊在东京奥运会闭幕式这天-二/"},{"title":"聊一下 SpringBoot 设置非 web 应用的方法","url":"/2022/07/31/聊一下-SpringBoot-设置非-web-应用的方法/"},{"title":"聊一下 SpringBoot 中动态切换数据源的方法","url":"/2021/09/26/聊一下-SpringBoot-中动态切换数据源的方法/"},{"title":"聊在东京奥运会闭幕式这天","url":"/2021/08/08/聊在东京奥运会闭幕式这天/"},{"title":"聊聊 Dubbo 的容错机制","url":"/2020/11/22/聊聊-Dubbo-的容错机制/"},{"title":"聊聊 Dubbo 的 SPI 续之自适应拓展","url":"/2020/06/06/聊聊-Dubbo-的-SPI-续之自适应拓展/"},{"title":"聊聊 Java 中绕不开的 Synchronized 关键字-二","url":"/2021/06/27/聊聊-Java-中绕不开的-Synchronized-关键字-二/"},{"title":"聊聊 Java 中绕不开的 Synchronized 关键字","url":"/2021/06/20/聊聊-Java-中绕不开的-Synchronized-关键字/"},{"title":"聊聊 Java 的类加载机制一","url":"/2020/11/08/聊聊-Java-的类加载机制/"},{"title":"聊聊 Java 的 equals 和 hashCode 方法","url":"/2021/01/03/聊聊-Java-的-equals-和-hashCode-方法/"},{"title":"聊聊 Dubbo 的 SPI","url":"/2020/05/31/聊聊-Dubbo-的-SPI/"},{"title":"聊聊 Java 的类加载机制二","url":"/2021/06/13/聊聊-Java-的类加载机制二/"},{"title":"聊聊 Java 自带的那些*逆天*工具","url":"/2020/08/02/聊聊-Java-自带的那些逆天工具/"},{"title":"聊一下关于怎么陪伴学习","url":"/2022/11/06/聊一下关于怎么陪伴学习/"},{"title":"聊聊 Linux 下的 top 命令","url":"/2021/03/28/聊聊-Linux-下的-top-命令/"},{"title":"聊聊 RocketMQ 的 Broker 源码","url":"/2020/07/19/聊聊-RocketMQ-的-Broker-源码/"},{"title":"聊聊 Sharding-Jdbc 的简单原理初篇","url":"/2021/12/26/聊聊-Sharding-Jdbc-的简单原理初篇/"},{"title":"聊聊 Sharding-Jdbc 分库分表下的分页方案","url":"/2022/01/09/聊聊-Sharding-Jdbc-分库分表下的分页方案/"},{"title":"聊聊 Sharding-Jdbc 的简单使用","url":"/2021/12/12/聊聊-Sharding-Jdbc-的简单使用/"},{"title":"聊聊 dubbo 的线程池","url":"/2021/04/04/聊聊-dubbo-的线程池/"},{"title":"聊聊 mysql 的 MVCC 续篇","url":"/2020/05/02/聊聊-mysql-的-MVCC-续篇/"},{"title":"聊聊 mysql 的 MVCC 续续篇之锁分析","url":"/2020/05/10/聊聊-mysql-的-MVCC-续续篇之加锁分析/"},{"title":"聊聊 mysql 索引的一些细节","url":"/2020/12/27/聊聊-mysql-索引的一些细节/"},{"title":"聊聊 mysql 的 MVCC","url":"/2020/04/26/聊聊-mysql-的-MVCC/"},{"title":"聊聊Java中的单例模式","url":"/2019/12/21/聊聊Java中的单例模式/"},{"title":"聊聊 redis 缓存的应用问题","url":"/2021/01/31/聊聊-redis-缓存的应用问题/"},{"title":"聊聊 SpringBoot 自动装配","url":"/2021/07/11/聊聊SpringBoot-自动装配/"},{"title":"聊聊传说中的 ThreadLocal","url":"/2021/05/30/聊聊传说中的-ThreadLocal/"},{"title":"聊聊一次 brew update 引发的血案","url":"/2020/06/13/聊聊一次-brew-update-引发的血案/"},{"title":"聊聊我刚学会的应用诊断方法","url":"/2020/05/22/聊聊我刚学会的应用诊断方法/"},{"title":"聊聊厦门旅游的好与不好","url":"/2021/04/11/聊聊厦门旅游的好与不好/"},{"title":"聊聊如何识别和意识到日常生活中的各类危险","url":"/2021/06/06/聊聊如何识别和意识到日常生活中的各类危险/"},{"title":"聊聊我的远程工作体验","url":"/2022/06/26/聊聊我的远程工作体验/"},{"title":"聊聊我理解的分布式事务","url":"/2020/05/17/聊聊我理解的分布式事务/"},{"title":"聊聊最近平淡的生活之又聊通勤","url":"/2021/11/07/聊聊最近平淡的生活/"},{"title":"聊聊最近平淡的生活之看看老剧","url":"/2021/11/21/聊聊最近平淡的生活之看看老剧/"},{"title":"聊聊最近平淡的生活之《花束般的恋爱》观后感","url":"/2021/12/31/聊聊最近平淡的生活之《花束般的恋爱》观后感/"},{"title":"聊聊这次换车牌及其他","url":"/2022/02/20/聊聊这次换车牌及其他/"},{"title":"聊聊最近平淡的生活之看《神探狄仁杰》","url":"/2021/12/19/聊聊最近平淡的生活之看《神探狄仁杰》/"},{"title":"聊聊给亲戚朋友的老电脑重装系统那些事儿","url":"/2021/05/09/聊聊给亲戚朋友的老电脑重装系统那些事儿/"},{"title":"聊聊部分公交车的设计bug","url":"/2021/12/05/聊聊部分公交车的设计bug/"},{"title":"聊聊那些加塞狗","url":"/2021/01/17/聊聊那些加塞狗/"},{"title":"记录一次折腾自组 nas 的失败经历-续续篇","url":"/2023/05/28/记录一次折腾自组-nas-的失败经历-续续篇/"},{"title":"记一个容器中 dubbo 注册的小知识点","url":"/2022/10/09/记一个容器中-dubbo-注册的小知识点/"},{"title":"记录下 Java Stream 的一些高效操作","url":"/2022/05/15/记录下-Java-Lambda-的一些高效操作/"},{"title":"记录一次折腾自组 nas 的失败经历-续续续篇","url":"/2023/06/18/记录一次折腾自组-nas-的失败经历-续续续篇/"},{"title":"记录一次折腾自组 nas 的失败经历-续篇","url":"/2023/05/14/记录一次折腾自组-nas-的失败经历-续篇/"},{"title":"记录下 phpunit 的入门使用方法之setUp和tearDown","url":"/2022/10/23/记录下-phpunit-的入门使用方法之setUp和tearDown/"},{"title":"记录一次折腾自组 nas 的失败经历","url":"/2023/05/07/记录一次折腾自组-nas-的失败经历/"},{"title":"记录下 zookeeper 集群迁移和易错点","url":"/2022/05/29/记录下-zookeeper-集群迁移/"},{"title":"解决 网络文件夹目前是以其他用户名和密码进行映射的 问题","url":"/2023/04/09/解决-网络文件夹目前是以其他用户名和密码进行映射的/"},{"title":"重看了下《蛮荒记》说说感受","url":"/2021/10/10/重看了下《蛮荒记》说说感受/"},{"title":"这周末我又在老丈人家打了天小工","url":"/2020/08/30/这周末我又在老丈人家打了天小工/"},{"title":"闲聊下乘公交的用户体验","url":"/2021/02/28/闲聊下乘公交的用户体验/"},{"title":"记录下 redis 的一些使用方法","url":"/2022/10/30/记录下-redis-的一些使用方法/"},{"title":"闲话篇-也算碰到了为老不尊和坏人变老了的典型案例","url":"/2022/05/22/闲话篇-也算碰到了为老不尊和坏人变老了的典型案例/"},{"title":"记录下 phpunit 的入门使用方法","url":"/2022/10/16/记录下-phpunit-的入门使用方法/"},{"title":"记录下把小米路由器 4A 千兆版刷成 openwrt 的过程","url":"/2023/05/21/记录下把小米路由器-4A-千兆版刷成-openwrt-的过程/"},{"title":"闲话篇-路遇神逻辑骑车带娃爹","url":"/2022/05/08/闲话篇-路遇神逻辑骑车带娃爹/"},{"title":"难得的大扫除","url":"/2022/04/10/难得的大扫除/"}]
\ No newline at end of file
+[{"title":"村上春树《1Q84》读后感","url":"/2019/12/18/1Q84读后感/"},{"title":"2019年终总结","url":"/2020/02/01/2019年终总结/"},{"title":"2020 年终总结","url":"/2021/03/31/2020-年终总结/"},{"title":"2020年中总结","url":"/2020/07/11/2020年中总结/"},{"title":"2021 年中总结","url":"/2021/07/18/2021-年中总结/"},{"title":"2021 年终总结","url":"/2022/01/22/2021-年终总结/"},{"title":"2022 年终总结","url":"/2023/01/15/2022-年终总结/"},{"title":"AQS篇一","url":"/2021/02/14/AQS篇一/"},{"title":"AbstractQueuedSynchronizer","url":"/2019/09/23/AbstractQueuedSynchronizer/"},{"title":"add-two-number","url":"/2015/04/14/Add-Two-Number/"},{"title":"Apollo 如何获取当前环境","url":"/2022/09/04/Apollo-如何获取当前环境/"},{"title":"Apollo 客户端启动过程分析","url":"/2022/09/18/Apollo-客户端启动过程分析/"},{"title":"Apollo 的 value 注解是怎么自动更新的","url":"/2020/11/01/Apollo-的-value-注解是怎么自动更新的/"},{"title":"Clone Graph Part I","url":"/2014/12/30/Clone-Graph-Part-I/"},{"title":"Comparator使用小记","url":"/2020/04/05/Comparator使用小记/"},{"title":"Disruptor 系列一","url":"/2022/02/13/Disruptor-系列一/"},{"title":"Disruptor 系列二","url":"/2022/02/27/Disruptor-系列二/"},{"title":"Disruptor 系列三","url":"/2022/09/25/Disruptor-系列三/"},{"title":"Dubbo 使用的几个记忆点","url":"/2022/04/02/Dubbo-使用的几个记忆点/"},{"title":"Filter, Interceptor, Aop, 啥, 啥, 啥? 这些都是啥?","url":"/2020/08/22/Filter-Intercepter-Aop-啥-啥-啥-这些都是啥/"},{"title":"G1收集器概述","url":"/2020/02/09/G1收集器概述/"},{"title":"Headscale初体验以及踩坑记","url":"/2023/01/22/Headscale初体验以及踩坑记/"},{"title":"JVM源码分析之G1垃圾收集器分析一","url":"/2019/12/07/JVM-G1-Part-1/"},{"title":"Leetcode 021 合并两个有序链表 ( Merge Two Sorted Lists ) 题解分析","url":"/2021/10/07/Leetcode-021-合并两个有序链表-Merge-Two-Sorted-Lists-题解分析/"},{"title":"Leetcode 028 实现 strStr() ( Implement strStr() ) 题解分析","url":"/2021/10/31/Leetcode-028-实现-strStr-Implement-strStr-题解分析/"},{"title":"Leetcode 053 最大子序和 ( Maximum Subarray ) 题解分析","url":"/2021/11/28/Leetcode-053-最大子序和-Maximum-Subarray-题解分析/"},{"title":"Leetcode 104 二叉树的最大深度(Maximum Depth of Binary Tree) 题解分析","url":"/2020/10/25/Leetcode-104-二叉树的最大深度-Maximum-Depth-of-Binary-Tree-题解分析/"},{"title":"Leetcode 105 从前序与中序遍历序列构造二叉树(Construct Binary Tree from Preorder and Inorder Traversal) 题解分析","url":"/2020/12/13/Leetcode-105-从前序与中序遍历序列构造二叉树-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal-题解分析/"},{"title":"Leetcode 1115 交替打印 FooBar ( Print FooBar Alternately *Medium* ) 题解分析","url":"/2022/05/01/Leetcode-1115-交替打印-FooBar-Print-FooBar-Alternately-Medium-题解分析/"},{"title":"Leetcode 121 买卖股票的最佳时机(Best Time to Buy and Sell Stock) 题解分析","url":"/2021/03/14/Leetcode-121-买卖股票的最佳时机-Best-Time-to-Buy-and-Sell-Stock-题解分析/"},{"title":"Leetcode 124 二叉树中的最大路径和(Binary Tree Maximum Path Sum) 题解分析","url":"/2021/01/24/Leetcode-124-二叉树中的最大路径和-Binary-Tree-Maximum-Path-Sum-题解分析/"},{"title":"Leetcode 1260 二维网格迁移 ( Shift 2D Grid *Easy* ) 题解分析","url":"/2022/07/22/Leetcode-1260-二维网格迁移-Shift-2D-Grid-Easy-题解分析/"},{"title":"Leetcode 155 最小栈(Min Stack) 题解分析","url":"/2020/12/06/Leetcode-155-最小栈-Min-Stack-题解分析/"},{"title":"Leetcode 16 最接近的三数之和 ( 3Sum Closest *Medium* ) 题解分析","url":"/2022/08/06/Leetcode-16-最接近的三数之和-3Sum-Closest-Medium-题解分析/"},{"title":"Leetcode 160 相交链表(intersection-of-two-linked-lists) 题解分析","url":"/2021/01/10/Leetcode-160-相交链表-intersection-of-two-linked-lists-题解分析/"},{"title":"Leetcode 1862 向下取整数对和 ( Sum of Floored Pairs *Hard* ) 题解分析","url":"/2022/09/11/Leetcode-1862-向下取整数对和-Sum-of-Floored-Pairs-Hard-题解分析/"},{"title":"Leetcode 20 有效的括号 ( Valid Parentheses *Easy* ) 题解分析","url":"/2022/07/02/Leetcode-20-有效的括号-Valid-Parentheses-Easy-题解分析/"},{"title":"Leetcode 2 Add Two Numbers 题解分析","url":"/2020/10/11/Leetcode-2-Add-Two-Numbers-题解分析/"},{"title":"Leetcode 234 回文链表(Palindrome Linked List) 题解分析","url":"/2020/11/15/Leetcode-234-回文联表-Palindrome-Linked-List-题解分析/"},{"title":"Leetcode 236 二叉树的最近公共祖先(Lowest Common Ancestor of a Binary Tree) 题解分析","url":"/2021/05/23/Leetcode-236-二叉树的最近公共祖先-Lowest-Common-Ancestor-of-a-Binary-Tree-题解分析/"},{"title":"Leetcode 278 第一个错误的版本 ( First Bad Version *Easy* ) 题解分析","url":"/2022/08/14/Leetcode-278-第一个错误的版本-First-Bad-Version-Easy-题解分析/"},{"title":"Leetcode 3 Longest Substring Without Repeating Characters 题解分析","url":"/2020/09/20/Leetcode-3-Longest-Substring-Without-Repeating-Characters-题解分析/"},{"title":"Leetcode 349 两个数组的交集 ( Intersection of Two Arrays *Easy* ) 题解分析","url":"/2022/03/07/Leetcode-349-两个数组的交集-Intersection-of-Two-Arrays-Easy-题解分析/"},{"title":"Leetcode 4 寻找两个正序数组的中位数 ( Median of Two Sorted Arrays *Hard* ) 题解分析","url":"/2022/03/27/Leetcode-4-寻找两个正序数组的中位数-Median-of-Two-Sorted-Arrays-Hard-题解分析/"},{"title":"Leetcode 42 接雨水 (Trapping Rain Water) 题解分析","url":"/2021/07/04/Leetcode-42-接雨水-Trapping-Rain-Water-题解分析/"},{"title":"Leetcode 48 旋转图像(Rotate Image) 题解分析","url":"/2021/05/01/Leetcode-48-旋转图像-Rotate-Image-题解分析/"},{"title":"Leetcode 698 划分为k个相等的子集 ( Partition to K Equal Sum Subsets *Medium* ) 题解分析","url":"/2022/06/19/Leetcode-698-划分为k个相等的子集-Partition-to-K-Equal-Sum-Subsets-Medium-题解分析/"},{"title":"Leetcode 747 至少是其他数字两倍的最大数 ( Largest Number At Least Twice of Others *Easy* ) 题解分析","url":"/2022/10/02/Leetcode-747-至少是其他数字两倍的最大数-Largest-Number-At-Least-Twice-of-Others-Easy-题解分析/"},{"title":"Leetcode 83 删除排序链表中的重复元素 ( Remove Duplicates from Sorted List *Easy* ) 题解分析","url":"/2022/03/13/Leetcode-83-删除排序链表中的重复元素-Remove-Duplicates-from-Sorted-List-Easy-题解分析/"},{"title":"Leetcode 885 螺旋矩阵 III ( Spiral Matrix III *Medium* ) 题解分析","url":"/2022/08/23/Leetcode-885-螺旋矩阵-III-Spiral-Matrix-III-Medium-题解分析/"},{"title":"leetcode no.3","url":"/2015/04/15/Leetcode-No-3/"},{"title":"Linux 下 grep 命令的一点小技巧","url":"/2020/08/06/Linux-下-grep-命令的一点小技巧/"},{"title":"MFC 模态对话框","url":"/2014/12/24/MFC 模态对话框/"},{"title":"Maven实用小技巧","url":"/2020/02/16/Maven实用小技巧/"},{"title":"Number of 1 Bits","url":"/2015/03/11/Number-Of-1-Bits/"},{"title":"Path Sum","url":"/2015/01/04/Path-Sum/"},{"title":"Redis_分布式锁","url":"/2019/12/10/Redis-Part-1/"},{"title":"Reverse Bits","url":"/2015/03/11/Reverse-Bits/"},{"title":"Reverse Integer","url":"/2015/03/13/Reverse-Integer/"},{"title":"Tomcat 系列篇一-介绍下 connector","url":"/2023/09/10/Tomcat-系列篇一-介绍下-connector/"},{"title":"ambari-summary","url":"/2017/05/09/ambari-summary/"},{"title":"AQS篇二 之 Condition 浅析笔记","url":"/2021/02/21/AQS-之-Condition-浅析笔记/"},{"title":"binary-watch","url":"/2016/09/29/binary-watch/"},{"title":"docker-mysql-cluster","url":"/2016/08/14/docker-mysql-cluster/"},{"title":"docker比一般多一点的初学者介绍","url":"/2020/03/08/docker比一般多一点的初学者介绍/"},{"title":"docker比一般多一点的初学者介绍三","url":"/2020/03/21/docker比一般多一点的初学者介绍三/"},{"title":"docker比一般多一点的初学者介绍二","url":"/2020/03/15/docker比一般多一点的初学者介绍二/"},{"title":"two sum","url":"/2015/01/14/Two-Sum/"},{"title":"docker使用中发现的echo命令的一个小技巧及其他","url":"/2020/03/29/echo命令的一个小技巧/"},{"title":"github 小技巧-更新 github host key","url":"/2023/03/28/github-小技巧-更新-github-host-key/"},{"title":"docker比一般多一点的初学者介绍四","url":"/2022/12/25/docker比一般多一点的初学者介绍四/"},{"title":"gogs使用webhook部署react单页应用","url":"/2020/02/22/gogs使用webhook部署react单页应用/"},{"title":"headscale 添加节点","url":"/2023/07/09/headscale-添加节点/"},{"title":"dnsmasq的一个使用注意点","url":"/2023/04/16/dnsmasq的一个使用注意点/"},{"title":"invert-binary-tree","url":"/2015/06/22/invert-binary-tree/"},{"title":"java 中发起 http 请求时证书问题解决记录","url":"/2023/07/29/java-中发起-http-请求时证书问题解决记录/"},{"title":"34_Search_for_a_Range","url":"/2016/08/14/34-Search-for-a-Range/"},{"title":"minimum-size-subarray-sum-209","url":"/2016/10/11/minimum-size-subarray-sum-209/"},{"title":"C++ 指针使用中的一个小问题","url":"/2014/12/23/my-new-post/"},{"title":"mybatis 的 foreach 使用的注意点","url":"/2022/07/09/mybatis-的-foreach-使用的注意点/"},{"title":"hexo 配置系列-接入Algolia搜索","url":"/2023/04/02/hexo-配置系列-接入Algolia搜索/"},{"title":"mybatis 的 $ 和 # 是有啥区别","url":"/2020/09/06/mybatis-的-和-是有啥区别/"},{"title":"mybatis 的缓存是怎么回事","url":"/2020/10/03/mybatis-的缓存是怎么回事/"},{"title":"mybatis系列-dataSource解析","url":"/2023/01/08/mybatis系列-dataSource解析/"},{"title":"mybatis系列-mybatis是如何初始化mapper的","url":"/2022/12/04/mybatis是如何初始化mapper的/"},{"title":"mybatis系列-connection连接池解析","url":"/2023/02/19/mybatis系列-connection连接池解析/"},{"title":"mybatis系列-foreach 解析","url":"/2023/06/11/mybatis系列-foreach-解析/"},{"title":"mybatis系列-sql 类的简要分析","url":"/2023/03/19/mybatis系列-sql-类的简要分析/"},{"title":"mybatis系列-typeAliases系统","url":"/2023/01/01/mybatis系列-typeAliases系统/"},{"title":"mybatis系列-第一条sql的更多细节","url":"/2022/12/18/mybatis系列-第一条sql的更多细节/"},{"title":"nginx 日志小记","url":"/2022/04/17/nginx-日志小记/"},{"title":"mybatis系列-入门篇","url":"/2022/11/27/mybatis系列-入门篇/"},{"title":"openresty","url":"/2019/06/18/openresty/"},{"title":"pcre-intro-and-a-simple-package","url":"/2015/01/16/pcre-intro-and-a-simple-package/"},{"title":"php-abstract-class-and-interface","url":"/2016/11/10/php-abstract-class-and-interface/"},{"title":"powershell 初体验","url":"/2022/11/13/powershell-初体验/"},{"title":"rabbitmq-tips","url":"/2017/04/25/rabbitmq-tips/"},{"title":"redis数据结构介绍-第一部分 SDS,链表,字典","url":"/2019/12/26/redis数据结构介绍/"},{"title":"redis 的 rdb 和 COW 介绍","url":"/2021/08/15/redis-的-rdb-和-COW-介绍/"},{"title":"redis数据结构介绍三-第三部分 整数集合","url":"/2020/01/10/redis数据结构介绍三/"},{"title":"redis数据结构介绍二-第二部分 跳表","url":"/2020/01/04/redis数据结构介绍二/"},{"title":"redis数据结构介绍五-第五部分 对象","url":"/2020/01/20/redis数据结构介绍五/"},{"title":"redis数据结构介绍六 快表","url":"/2020/01/22/redis数据结构介绍六/"},{"title":"redis数据结构介绍四-第四部分 压缩表","url":"/2020/01/19/redis数据结构介绍四/"},{"title":"redis淘汰策略复习","url":"/2021/08/01/redis淘汰策略复习/"},{"title":"powershell 初体验二","url":"/2022/11/20/powershell-初体验二/"},{"title":"redis系列介绍七-过期策略","url":"/2020/04/12/redis系列介绍七/"},{"title":"redis系列介绍八-淘汰策略","url":"/2020/04/18/redis系列介绍八/"},{"title":"redis过期策略复习","url":"/2021/07/25/redis过期策略复习/"},{"title":"rust学习笔记-所有权三之切片","url":"/2021/05/16/rust学习笔记-所有权三之切片/"},{"title":"rust学习笔记-所有权一","url":"/2021/04/18/rust学习笔记/"},{"title":"mybatis系列-第一条sql的细节","url":"/2022/12/11/mybatis系列-第一条sql的细节/"},{"title":"mybatis系列-sql 类的简单使用","url":"/2023/03/12/mybatis系列-sql-类的简单使用/"},{"title":"spring boot中的 http 接口返回 json 形式的小注意点","url":"/2023/06/25/spring-boot中的-http-接口返回-json-形式的小注意点/"},{"title":"spring event 介绍","url":"/2022/01/30/spring-event-介绍/"},{"title":"rust学习笔记-所有权二","url":"/2021/04/18/rust学习笔记-所有权二/"},{"title":"springboot 处理请求的小分支-跳转 & cookie","url":"/2023/09/03/springboot-处理请求的小分支-跳转-cookie/"},{"title":"springboot 获取 web 应用中所有的接口 url","url":"/2023/08/06/springboot-获取-web-应用中所有的接口-url/"},{"title":"spark-little-tips","url":"/2017/03/28/spark-little-tips/"},{"title":"springboot mappings 注册逻辑","url":"/2023/08/13/springboot-mappings-注册逻辑/"},{"title":"springboot web server 启动逻辑","url":"/2023/08/20/springboot-web-server-启动逻辑/"},{"title":"summary-ranges-228","url":"/2016/10/12/summary-ranges-228/"},{"title":"swoole-websocket-test","url":"/2016/07/13/swoole-websocket-test/"},{"title":"wordpress 忘记密码的一种解决方法","url":"/2021/12/05/wordpress-忘记密码的一种解决方法/"},{"title":"《垃圾回收算法手册读书》笔记之整理算法","url":"/2021/03/07/《垃圾回收算法手册读书》笔记之整理算法/"},{"title":"《长安的荔枝》读后感","url":"/2022/07/17/《长安的荔枝》读后感/"},{"title":"《寻羊历险记》读后感","url":"/2023/07/23/《寻羊历险记》读后感/"},{"title":"ssh 小技巧-端口转发","url":"/2023/03/26/ssh-小技巧-端口转发/"},{"title":"一个 nginx 的简单记忆点","url":"/2022/08/21/一个-nginx-的简单记忆点/"},{"title":"上次的其他 外行聊国足","url":"/2022/03/06/上次的其他-外行聊国足/"},{"title":"介绍一下 RocketMQ","url":"/2020/06/21/介绍一下-RocketMQ/"},{"title":"介绍下最近比较实用的端口转发","url":"/2021/11/14/介绍下最近比较实用的端口转发/"},{"title":"win 下 vmware 虚拟机搭建黑裙 nas 的小思路","url":"/2023/06/04/win-下-vmware-虚拟机搭建黑裙-nas-的小思路/"},{"title":"从丁仲礼被美国制裁聊点啥","url":"/2020/12/20/从丁仲礼被美国制裁聊点啥/"},{"title":"从清华美院学姐聊聊我们身边的恶人","url":"/2020/11/29/从清华美院学姐聊聊我们身边的恶人/"},{"title":"关于公共交通再吐个槽","url":"/2021/03/21/关于公共交通再吐个槽/"},{"title":"nas 中使用 tmm 刮削视频","url":"/2023/07/02/使用-tmm-刮削视频/"},{"title":"关于读书打卡与分享","url":"/2021/02/07/关于读书打卡与分享/"},{"title":"关于 npe 的一个小记忆点","url":"/2023/07/16/关于-npe-的一个小记忆点/"},{"title":"分享一次折腾老旧笔记本的体验-续续篇","url":"/2023/02/26/分享一次折腾老旧笔记本的体验-续续篇/"},{"title":"分享一次折腾老旧笔记本的体验","url":"/2023/02/05/分享一次折腾老旧笔记本的体验/"},{"title":"分享一次折腾老旧笔记本的体验-续篇","url":"/2023/02/12/分享一次折腾老旧笔记本的体验-续篇/"},{"title":"分享记录一下一个 git 操作方法","url":"/2022/02/06/分享记录一下一个-git-操作方法/"},{"title":"分享记录一下一个 scp 操作方法","url":"/2022/02/06/分享记录一下一个-scp-操作方法/"},{"title":"周末我在老丈人家打了天小工","url":"/2020/08/16/周末我在老丈人家打了天小工/"},{"title":"在 wsl 2 中开启 ssh 连接","url":"/2023/04/23/在-wsl-2-中开启-ssh-连接/"},{"title":"在老丈人家的小工记三","url":"/2020/09/13/在老丈人家的小工记三/"},{"title":"在老丈人家的小工记五","url":"/2020/10/18/在老丈人家的小工记五/"},{"title":"小工周记一","url":"/2023/03/05/小工周记一/"},{"title":"在老丈人家的小工记四","url":"/2020/09/26/在老丈人家的小工记四/"},{"title":"分享一次比较诡异的 Windows 下 U盘无法退出的经历","url":"/2023/01/29/分享一次比较诡异的-Windows-下-U盘无法退出的经历/"},{"title":"寄生虫观后感","url":"/2020/03/01/寄生虫观后感/"},{"title":"屯菜惊魂记","url":"/2022/04/24/屯菜惊魂记/"},{"title":"我是如何走上跑步这条不归路的","url":"/2020/07/26/我是如何走上跑步这条不归路的/"},{"title":"深度学习入门初认识","url":"/2023/04/30/深度学习入门初认识/"},{"title":"springboot 请求响应处理流程","url":"/2023/08/27/springboot-请求响应处理流程/"},{"title":"是何原因竟让两人深夜奔袭十公里","url":"/2022/06/05/是何原因竟让两人深夜奔袭十公里/"},{"title":"看完了扫黑风暴,聊聊感想","url":"/2021/10/24/看完了扫黑风暴-聊聊感想/"},{"title":"给小电驴上牌","url":"/2022/03/20/给小电驴上牌/"},{"title":"聊一下 RocketMQ 的 NameServer 源码","url":"/2020/07/05/聊一下-RocketMQ-的-NameServer-源码/"},{"title":"搬运两个 StackOverflow 上的 Mysql 编码相关的问题解答","url":"/2022/01/16/搬运两个-StackOverflow-上的-Mysql-编码相关的问题解答/"},{"title":"聊一下 RocketMQ 的 DefaultMQPushConsumer 源码","url":"/2020/06/26/聊一下-RocketMQ-的-Consumer/"},{"title":"聊一下 RocketMQ 的消息存储三","url":"/2021/10/03/聊一下-RocketMQ-的消息存储三/"},{"title":"聊一下 RocketMQ 的消息存储之 MMAP","url":"/2021/09/04/聊一下-RocketMQ-的消息存储/"},{"title":"聊一下 RocketMQ 的消息存储二","url":"/2021/09/12/聊一下-RocketMQ-的消息存储二/"},{"title":"聊一下 RocketMQ 的顺序消息","url":"/2021/08/29/聊一下-RocketMQ-的顺序消息/"},{"title":"聊一下 SpringBoot 中使用的 cglib 作为动态代理中的一个注意点","url":"/2021/09/19/聊一下-SpringBoot-中使用的-cglib-作为动态代理中的一个注意点/"},{"title":"聊一下 SpringBoot 中动态切换数据源的方法","url":"/2021/09/26/聊一下-SpringBoot-中动态切换数据源的方法/"},{"title":"聊一下 SpringBoot 设置非 web 应用的方法","url":"/2022/07/31/聊一下-SpringBoot-设置非-web-应用的方法/"},{"title":"聊在东京奥运会闭幕式这天-二","url":"/2021/08/19/聊在东京奥运会闭幕式这天-二/"},{"title":"聊在东京奥运会闭幕式这天","url":"/2021/08/08/聊在东京奥运会闭幕式这天/"},{"title":"聊一下 RocketMQ 的消息存储四","url":"/2021/10/17/聊一下-RocketMQ-的消息存储四/"},{"title":"聊聊 Dubbo 的 SPI 续之自适应拓展","url":"/2020/06/06/聊聊-Dubbo-的-SPI-续之自适应拓展/"},{"title":"聊一下关于怎么陪伴学习","url":"/2022/11/06/聊一下关于怎么陪伴学习/"},{"title":"聊聊 Dubbo 的 SPI","url":"/2020/05/31/聊聊-Dubbo-的-SPI/"},{"title":"聊聊 Java 中绕不开的 Synchronized 关键字-二","url":"/2021/06/27/聊聊-Java-中绕不开的-Synchronized-关键字-二/"},{"title":"聊聊 Dubbo 的容错机制","url":"/2020/11/22/聊聊-Dubbo-的容错机制/"},{"title":"聊聊 Java 中绕不开的 Synchronized 关键字","url":"/2021/06/20/聊聊-Java-中绕不开的-Synchronized-关键字/"},{"title":"聊聊 Java 的类加载机制一","url":"/2020/11/08/聊聊-Java-的类加载机制/"},{"title":"聊聊 Java 的类加载机制二","url":"/2021/06/13/聊聊-Java-的类加载机制二/"},{"title":"聊聊 Java 自带的那些*逆天*工具","url":"/2020/08/02/聊聊-Java-自带的那些逆天工具/"},{"title":"聊聊 Linux 下的 top 命令","url":"/2021/03/28/聊聊-Linux-下的-top-命令/"},{"title":"聊聊 Sharding-Jdbc 分库分表下的分页方案","url":"/2022/01/09/聊聊-Sharding-Jdbc-分库分表下的分页方案/"},{"title":"聊聊 RocketMQ 的 Broker 源码","url":"/2020/07/19/聊聊-RocketMQ-的-Broker-源码/"},{"title":"聊聊 Sharding-Jdbc 的简单使用","url":"/2021/12/12/聊聊-Sharding-Jdbc-的简单使用/"},{"title":"聊聊 dubbo 的线程池","url":"/2021/04/04/聊聊-dubbo-的线程池/"},{"title":"聊聊 Sharding-Jdbc 的简单原理初篇","url":"/2021/12/26/聊聊-Sharding-Jdbc-的简单原理初篇/"},{"title":"聊聊 mysql 的 MVCC 续篇","url":"/2020/05/02/聊聊-mysql-的-MVCC-续篇/"},{"title":"聊聊 mysql 的 MVCC 续续篇之锁分析","url":"/2020/05/10/聊聊-mysql-的-MVCC-续续篇之加锁分析/"},{"title":"聊聊 mysql 的 MVCC","url":"/2020/04/26/聊聊-mysql-的-MVCC/"},{"title":"聊聊 mysql 索引的一些细节","url":"/2020/12/27/聊聊-mysql-索引的一些细节/"},{"title":"聊聊 redis 缓存的应用问题","url":"/2021/01/31/聊聊-redis-缓存的应用问题/"},{"title":"聊聊Java中的单例模式","url":"/2019/12/21/聊聊Java中的单例模式/"},{"title":"聊聊传说中的 ThreadLocal","url":"/2021/05/30/聊聊传说中的-ThreadLocal/"},{"title":"聊聊厦门旅游的好与不好","url":"/2021/04/11/聊聊厦门旅游的好与不好/"},{"title":"聊聊如何识别和意识到日常生活中的各类危险","url":"/2021/06/06/聊聊如何识别和意识到日常生活中的各类危险/"},{"title":"聊聊我刚学会的应用诊断方法","url":"/2020/05/22/聊聊我刚学会的应用诊断方法/"},{"title":"聊聊我理解的分布式事务","url":"/2020/05/17/聊聊我理解的分布式事务/"},{"title":"聊聊我的远程工作体验","url":"/2022/06/26/聊聊我的远程工作体验/"},{"title":"聊聊最近平淡的生活之又聊通勤","url":"/2021/11/07/聊聊最近平淡的生活/"},{"title":"聊聊最近平淡的生活之看《神探狄仁杰》","url":"/2021/12/19/聊聊最近平淡的生活之看《神探狄仁杰》/"},{"title":"聊聊最近平淡的生活之看看老剧","url":"/2021/11/21/聊聊最近平淡的生活之看看老剧/"},{"title":"聊聊给亲戚朋友的老电脑重装系统那些事儿","url":"/2021/05/09/聊聊给亲戚朋友的老电脑重装系统那些事儿/"},{"title":"聊聊这次换车牌及其他","url":"/2022/02/20/聊聊这次换车牌及其他/"},{"title":"聊聊那些加塞狗","url":"/2021/01/17/聊聊那些加塞狗/"},{"title":"聊聊部分公交车的设计bug","url":"/2021/12/05/聊聊部分公交车的设计bug/"},{"title":"聊聊一次 brew update 引发的血案","url":"/2020/06/13/聊聊一次-brew-update-引发的血案/"},{"title":"聊聊 SpringBoot 自动装配","url":"/2021/07/11/聊聊SpringBoot-自动装配/"},{"title":"聊聊最近平淡的生活之《花束般的恋爱》观后感","url":"/2021/12/31/聊聊最近平淡的生活之《花束般的恋爱》观后感/"},{"title":"解决 网络文件夹目前是以其他用户名和密码进行映射的 问题","url":"/2023/04/09/解决-网络文件夹目前是以其他用户名和密码进行映射的/"},{"title":"记录一次折腾自组 nas 的失败经历-续篇","url":"/2023/05/14/记录一次折腾自组-nas-的失败经历-续篇/"},{"title":"记录下 Java Stream 的一些高效操作","url":"/2022/05/15/记录下-Java-Lambda-的一些高效操作/"},{"title":"记一个容器中 dubbo 注册的小知识点","url":"/2022/10/09/记一个容器中-dubbo-注册的小知识点/"},{"title":"记录下 phpunit 的入门使用方法","url":"/2022/10/16/记录下-phpunit-的入门使用方法/"},{"title":"记录一次折腾自组 nas 的失败经历-续续续篇","url":"/2023/06/18/记录一次折腾自组-nas-的失败经历-续续续篇/"},{"title":"记录下 zookeeper 集群迁移和易错点","url":"/2022/05/29/记录下-zookeeper-集群迁移/"},{"title":"记录下 phpunit 的入门使用方法之setUp和tearDown","url":"/2022/10/23/记录下-phpunit-的入门使用方法之setUp和tearDown/"},{"title":"这周末我又在老丈人家打了天小工","url":"/2020/08/30/这周末我又在老丈人家打了天小工/"},{"title":"dubbo 客户端配置的一个重要知识点","url":"/2022/06/11/dubbo-客户端配置的一个重要知识点/"},{"title":"重看了下《蛮荒记》说说感受","url":"/2021/10/10/重看了下《蛮荒记》说说感受/"},{"title":"闲聊下乘公交的用户体验","url":"/2021/02/28/闲聊下乘公交的用户体验/"},{"title":"闲话篇-也算碰到了为老不尊和坏人变老了的典型案例","url":"/2022/05/22/闲话篇-也算碰到了为老不尊和坏人变老了的典型案例/"},{"title":"闲话篇-路遇神逻辑骑车带娃爹","url":"/2022/05/08/闲话篇-路遇神逻辑骑车带娃爹/"},{"title":"聊聊 Java 的 equals 和 hashCode 方法","url":"/2021/01/03/聊聊-Java-的-equals-和-hashCode-方法/"},{"title":"难得的大扫除","url":"/2022/04/10/难得的大扫除/"},{"title":"记录下把小米路由器 4A 千兆版刷成 openwrt 的过程","url":"/2023/05/21/记录下把小米路由器-4A-千兆版刷成-openwrt-的过程/"},{"title":"记录下 redis 的一些使用方法","url":"/2022/10/30/记录下-redis-的一些使用方法/"},{"title":"记录一次折腾自组 nas 的失败经历-续续篇","url":"/2023/05/28/记录一次折腾自组-nas-的失败经历-续续篇/"},{"title":"记录一次折腾自组 nas 的失败经历","url":"/2023/05/07/记录一次折腾自组-nas-的失败经历/"}]
\ No newline at end of file
diff --git a/page/28/index.html b/page/28/index.html
index 0fb710a878..e5e8f9d43f 100644
--- a/page/28/index.html
+++ b/page/28/index.html
@@ -1,4 +1,4 @@
-Nicksxs's Blog - What hurts more, the pain of hard work or the pain of regret?

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

事情源于周末来回家发生的两件事情,先是回去的时候从高铁下车要坐公交,现在算是有个比较好的临时候车点了,但是可能由于疫情好转,晚上都不用检查健康码就可以进候车点,但是上公交的时候还是需要看健康码,一般情况下从高铁下来的,各个地方的人都有,而且也不太清楚这边上公交车需要查验健康码,我的一个看法是候车的时候就应该放个横幅告示,或者再配合喇叭循环播放,请提前准备好健康码,上车前需要查验,因为像这周的情况,我乘坐的那辆车是间隔时间比较长,而且终点是工业开发区,可能是比较多外来务工人员的目的地,正好这部分人可能对于操作手机检验健康码这个事情不太熟悉,所以结果就是头上几个不知道怎么搞出来健康码,然后让几乎有满满一整车的人在后面堵着,司机又非常厌烦那些没有提前出示健康码的,有位乘客搞得久了点,还被误以为没刷卡买票,差点吵起来,其实公共交通或者高铁站负责的在公交指引路线上多写一句上车前需要查验健康码,可能就能改善比较多,还有就是那个积水的路,这个吐槽起来就一大坨了,整个绍兴像 dayuejin 一样到处都是破路。
第二个就是来杭州的时候,经过人行横道,远处车道的公交车停下来等我们了,为了少添麻烦总想快点穿过去,但是这时靠近我们的车道(晚上光线较暗,可见度不佳)有一辆从远处来的奥迪 A4 还是 A5 这种的车反而想加速冲过去,如果少看一下可能我已经残了,交规考的靠近人行道要减速好像基本都是个摆设了,杭州也只有公交车因为一些考核指标原因会主动礼让,人其实需要有同理心,虽然可能有些人是开车多于骑车走路的,但是总也不可能永远不穿人行道吧,甚至这些人可能还会在人行道红灯的时候走过去。这个事情不是吐槽公共交通的,只是也有些许关系,想起来还有一件事也是刚才来杭州的时候看到的,等公交的时候看到有辆路虎要加塞,而目标车道刚好是辆大货车,大货车看到按了喇叭,路虎犹豫了下还是挤进去了,可能是对路虎的扛撞性能非常自信吧,反正我是挺后怕的,这种级别的车,被撞了的话估计还是鸡蛋撞石头,吨位惯性在那,这里再延伸下,挺多开豪车的人好像都觉得这路上路权更大一些,谁谁都得让着他,可能实际吃亏的不多,所以越加巩固了这种思维,当真的碰到不管的可能就会明白了,路权这个事情在天朝也基本没啥人重视,也没想说个结论,就到这吧

题目介绍

You are given an array prices where prices[i] is the price of a given stock on the ith day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。

你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。

返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0

简单分析

其实这个跟二叉树的最长路径和有点类似,需要找到整体的最大收益,但是在迭代过程中需要一个当前的值

int maxSofar = 0;
+Nicksxs's Blog - What hurts more, the pain of hard work or the pain of regret?

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

事情源于周末来回家发生的两件事情,先是回去的时候从高铁下车要坐公交,现在算是有个比较好的临时候车点了,但是可能由于疫情好转,晚上都不用检查健康码就可以进候车点,但是上公交的时候还是需要看健康码,一般情况下从高铁下来的,各个地方的人都有,而且也不太清楚这边上公交车需要查验健康码,我的一个看法是候车的时候就应该放个横幅告示,或者再配合喇叭循环播放,请提前准备好健康码,上车前需要查验,因为像这周的情况,我乘坐的那辆车是间隔时间比较长,而且终点是工业开发区,可能是比较多外来务工人员的目的地,正好这部分人可能对于操作手机检验健康码这个事情不太熟悉,所以结果就是头上几个不知道怎么搞出来健康码,然后让几乎有满满一整车的人在后面堵着,司机又非常厌烦那些没有提前出示健康码的,有位乘客搞得久了点,还被误以为没刷卡买票,差点吵起来,其实公共交通或者高铁站负责的在公交指引路线上多写一句上车前需要查验健康码,可能就能改善比较多,还有就是那个积水的路,这个吐槽起来就一大坨了,整个绍兴像 dayuejin 一样到处都是破路。
第二个就是来杭州的时候,经过人行横道,远处车道的公交车停下来等我们了,为了少添麻烦总想快点穿过去,但是这时靠近我们的车道(晚上光线较暗,可见度不佳)有一辆从远处来的奥迪 A4 还是 A5 这种的车反而想加速冲过去,如果少看一下可能我已经残了,交规考的靠近人行道要减速好像基本都是个摆设了,杭州也只有公交车因为一些考核指标原因会主动礼让,人其实需要有同理心,虽然可能有些人是开车多于骑车走路的,但是总也不可能永远不穿人行道吧,甚至这些人可能还会在人行道红灯的时候走过去。这个事情不是吐槽公共交通的,只是也有些许关系,想起来还有一件事也是刚才来杭州的时候看到的,等公交的时候看到有辆路虎要加塞,而目标车道刚好是辆大货车,大货车看到按了喇叭,路虎犹豫了下还是挤进去了,可能是对路虎的扛撞性能非常自信吧,反正我是挺后怕的,这种级别的车,被撞了的话估计还是鸡蛋撞石头,吨位惯性在那,这里再延伸下,挺多开豪车的人好像都觉得这路上路权更大一些,谁谁都得让着他,可能实际吃亏的不多,所以越加巩固了这种思维,当真的碰到不管的可能就会明白了,路权这个事情在天朝也基本没啥人重视,也没想说个结论,就到这吧

题目介绍

You are given an array prices where prices[i] is the price of a given stock on the ith day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。

你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。

返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0

简单分析

其实这个跟二叉树的最长路径和有点类似,需要找到整体的最大收益,但是在迭代过程中需要一个当前的值

int maxSofar = 0;
 public int maxProfit(int[] prices) {
     if (prices.length <= 1) {
         return 0;
diff --git a/page/29/index.html b/page/29/index.html
index 5c2fcd7066..20e28dbb54 100644
--- a/page/29/index.html
+++ b/page/29/index.html
@@ -191,7 +191,7 @@
         if (s != null)
             // 将其唤醒
             LockSupport.unpark(s.thread);
-    }

最近群里大佬发起了一个读书打卡活动,需要每天读一会书,在群里打卡分享感悟,争取一个月能读完一本书,说实话一天十分钟的读书时间倒是问题不大,不过每天都要打卡,而且一个月要读完一本书,其实难度还是有点大的,不过也想试试看。
之前某某老大给自己立了个 flag,说要读一百本书,这对我来说挺难实现的,一则我也不喜欢书只读一小半,二则感觉对于喜欢看的内容范围还是比较有限制,可能也算是比较矫情,不爱追热门的各类东西,因为往往会有一些跟大众不一致的观点看法,显得格格不入。所以还是这个打卡活动可能会比较适合我,书是人类进步的阶梯。
到现在是打卡了三天了,读的主要是白岩松的《幸福了吗》,对于白岩松,我们这一代人是比较熟悉,并且整体印象比较不错的一个央视主持人,从《焦点访谈》开始,到疫情期间的各类一线节目,可能对我来说是个三观比较正,敢于说一些真话的主持人,这中间其实是有个空档期,没怎么看电视,也不太关注了,只是在疫情期间的节目,还是一如既往地给人一种可靠的感觉,正好有一次偶然微信读书推荐了白岩松的这本书,就看了一部分,正好这次继续往下看,因为相对来讲不会很晦涩,并且从这位知名央视主持人的角度分享他的过往和想法看法,还是比较有意思的。
从对汶川地震,08 年奥运等往事的回忆和一些细节的呈现,也让我了解比较多当时所不知道的,特别是汶川地震,那时的我还在读高中,真的是看着电视,作为“猛男”都忍不住泪目了,共和国之殇,多难兴邦,但是这对于当事人来说,都是一场醒不过来的噩梦。
然后是对于足球的热爱,其实光这个就能掰扯很多,因为我不爱足球,只爱篮球,其中原因有的没的也挺多可以说的,但是看了他的书,才能比较深入的了解一个足球迷,对足球,对中国足球,对世界杯,对阿根廷的感情。
接下去还是想能继续坚持下去,加油!

前面写过一系列的 redis 源码分析的,但是实际上很多的问题还是需要结合实际的使用,然后其实就避不开缓存使用的三个著名问题,穿透,击穿和雪崩,这三个概念也是有着千丝万缕的关系,

缓存穿透

缓存穿透是指当数据库中本身就不存在这个数据的时候,使用一般的缓存策略时访问不到缓存后就访问数据库,但是因为数据库也没数据,所以如果不做任何策略优化的话,这类数据就每次都会访问一次数据库,对数据库压力也会比较大。

缓存击穿

缓存击穿跟穿透比较类似的,都是访问缓存不在,然后去访问数据库,与穿透不一样的是击穿是在数据库中存在数据,但是可能由于第一次访问,或者缓存过期了,需要访问到数据库,这对于访问量小的情况其实算是个正常情况,但是随着请求量变高就会引发一些性能隐患。

缓存雪崩

缓存雪崩就是击穿的大规模集群效应,当大量的缓存过期失效的时候,这些请求都是直接访问到数据库了,会对数据库造成很大的压力。

对于以上三种场景也有一些比较常见的解决方案,但也不能说是万无一失的,需要随着业务去寻找合适的方案

解决缓存穿透

对于数据库中就没这个数据的时候,一种是可以对这个 key 设置下空值,即以一个特定的表示是数据库不存在的,这种情况需要合理地调整过期时间,当这个 key 在数据库中有数据了的话,也需要有策略去更新这个值,并且如果这类 key 非常多,这个方法就会不太合适,就可以使用第二种方法,就是布隆过滤器,bloom filter,前置一个布隆过滤器,当这个 key 在数据库不存在的话,先用布隆过滤器挡一道,如果不在的话就直接返回了,当然布隆过滤器不是绝对的准确的

解决缓存击穿

当一个 key 的缓存过期了,如果大量请求过来访问这个 key,请求都会落在数据库里,这个时候就可以使用一些类似于互斥锁的方式去让一个线程去访问数据库,更新缓存,但是这里其实也有个问题,就是如果是热点 key 其实这种方式也比较危险,万一更新失败,或者更新操作的时候耗时比较久,就会有一大堆请求卡在那,这种情况可能需要有一些异步提前刷新缓存,可以结合具体场景选择方式

解决缓存雪崩

雪崩的情况是指大批量的 key 都一起过期了,击穿的放大版,大批量的请求都打到数据库上了,一方面有可能直接缓存不可用了,就需要用集群化高可用的缓存服务,然后对于实际使用中也可以使用本地缓存结合 redis 缓存,去提高可用性,再配合一些限流措施,然后就是缓存使用过程总的过期时间最好能加一些随机值,防止在同一时间过期而导致雪崩,结合互斥锁防止大量请求打到数据库。

题目介绍

A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.

The path sum of a path is the sum of the node’s values in the path.

Given the root of a binary tree, return the maximum path sum of any path.

路径 被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。该路径 至少包含一个 节点,且不一定经过根节点。

路径和 是路径中各节点值的总和。

给你一个二叉树的根节点 root ,返回其 最大路径和

简要分析

其实这个题目会被误解成比较简单,左子树最大的,或者右子树最大的,或者两边加一下,仔细想想都不对,其实有可能是产生于左子树中,或者右子树中,这两个都是指跟左子树根还有右子树根没关系的,这么说感觉不太容易理解,画个图

可以看到图里,其实最长路径和是左边这个子树组成的,跟根节点还有右子树完全没关系,然后再想一种情况,如果是整棵树就是图中的左子树,那么这个最长路径和就是左子树加右子树加根节点了,所以不是我一开始想得那么简单,在代码实现中也需要一些技巧

代码

int ansNew = Integer.MIN_VALUE;
+    }

最近群里大佬发起了一个读书打卡活动,需要每天读一会书,在群里打卡分享感悟,争取一个月能读完一本书,说实话一天十分钟的读书时间倒是问题不大,不过每天都要打卡,而且一个月要读完一本书,其实难度还是有点大的,不过也想试试看。
之前某某老大给自己立了个 flag,说要读一百本书,这对我来说挺难实现的,一则我也不喜欢书只读一小半,二则感觉对于喜欢看的内容范围还是比较有限制,可能也算是比较矫情,不爱追热门的各类东西,因为往往会有一些跟大众不一致的观点看法,显得格格不入。所以还是这个打卡活动可能会比较适合我,书是人类进步的阶梯。
到现在是打卡了三天了,读的主要是白岩松的《幸福了吗》,对于白岩松,我们这一代人是比较熟悉,并且整体印象比较不错的一个央视主持人,从《焦点访谈》开始,到疫情期间的各类一线节目,可能对我来说是个三观比较正,敢于说一些真话的主持人,这中间其实是有个空档期,没怎么看电视,也不太关注了,只是在疫情期间的节目,还是一如既往地给人一种可靠的感觉,正好有一次偶然微信读书推荐了白岩松的这本书,就看了一部分,正好这次继续往下看,因为相对来讲不会很晦涩,并且从这位知名央视主持人的角度分享他的过往和想法看法,还是比较有意思的。
从对汶川地震,08 年奥运等往事的回忆和一些细节的呈现,也让我了解比较多当时所不知道的,特别是汶川地震,那时的我还在读高中,真的是看着电视,作为“猛男”都忍不住泪目了,共和国之殇,多难兴邦,但是这对于当事人来说,都是一场醒不过来的噩梦。
然后是对于足球的热爱,其实光这个就能掰扯很多,因为我不爱足球,只爱篮球,其中原因有的没的也挺多可以说的,但是看了他的书,才能比较深入的了解一个足球迷,对足球,对中国足球,对世界杯,对阿根廷的感情。
接下去还是想能继续坚持下去,加油!

前面写过一系列的 redis 源码分析的,但是实际上很多的问题还是需要结合实际的使用,然后其实就避不开缓存使用的三个著名问题,穿透,击穿和雪崩,这三个概念也是有着千丝万缕的关系,

缓存穿透

缓存穿透是指当数据库中本身就不存在这个数据的时候,使用一般的缓存策略时访问不到缓存后就访问数据库,但是因为数据库也没数据,所以如果不做任何策略优化的话,这类数据就每次都会访问一次数据库,对数据库压力也会比较大。

缓存击穿

缓存击穿跟穿透比较类似的,都是访问缓存不在,然后去访问数据库,与穿透不一样的是击穿是在数据库中存在数据,但是可能由于第一次访问,或者缓存过期了,需要访问到数据库,这对于访问量小的情况其实算是个正常情况,但是随着请求量变高就会引发一些性能隐患。

缓存雪崩

缓存雪崩就是击穿的大规模集群效应,当大量的缓存过期失效的时候,这些请求都是直接访问到数据库了,会对数据库造成很大的压力。

对于以上三种场景也有一些比较常见的解决方案,但也不能说是万无一失的,需要随着业务去寻找合适的方案

解决缓存穿透

对于数据库中就没这个数据的时候,一种是可以对这个 key 设置下空值,即以一个特定的表示是数据库不存在的,这种情况需要合理地调整过期时间,当这个 key 在数据库中有数据了的话,也需要有策略去更新这个值,并且如果这类 key 非常多,这个方法就会不太合适,就可以使用第二种方法,就是布隆过滤器,bloom filter,前置一个布隆过滤器,当这个 key 在数据库不存在的话,先用布隆过滤器挡一道,如果不在的话就直接返回了,当然布隆过滤器不是绝对的准确的

解决缓存击穿

当一个 key 的缓存过期了,如果大量请求过来访问这个 key,请求都会落在数据库里,这个时候就可以使用一些类似于互斥锁的方式去让一个线程去访问数据库,更新缓存,但是这里其实也有个问题,就是如果是热点 key 其实这种方式也比较危险,万一更新失败,或者更新操作的时候耗时比较久,就会有一大堆请求卡在那,这种情况可能需要有一些异步提前刷新缓存,可以结合具体场景选择方式

解决缓存雪崩

雪崩的情况是指大批量的 key 都一起过期了,击穿的放大版,大批量的请求都打到数据库上了,一方面有可能直接缓存不可用了,就需要用集群化高可用的缓存服务,然后对于实际使用中也可以使用本地缓存结合 redis 缓存,去提高可用性,再配合一些限流措施,然后就是缓存使用过程总的过期时间最好能加一些随机值,防止在同一时间过期而导致雪崩,结合互斥锁防止大量请求打到数据库。

题目介绍

A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.

The path sum of a path is the sum of the node’s values in the path.

Given the root of a binary tree, return the maximum path sum of any path.

路径 被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。该路径 至少包含一个 节点,且不一定经过根节点。

路径和 是路径中各节点值的总和。

给你一个二叉树的根节点 root ,返回其 最大路径和

简要分析

其实这个题目会被误解成比较简单,左子树最大的,或者右子树最大的,或者两边加一下,仔细想想都不对,其实有可能是产生于左子树中,或者右子树中,这两个都是指跟左子树根还有右子树根没关系的,这么说感觉不太容易理解,画个图

可以看到图里,其实最长路径和是左边这个子树组成的,跟根节点还有右子树完全没关系,然后再想一种情况,如果是整棵树就是图中的左子树,那么这个最长路径和就是左子树加右子树加根节点了,所以不是我一开始想得那么简单,在代码实现中也需要一些技巧

代码

int ansNew = Integer.MIN_VALUE;
 public int maxPathSum(TreeNode root) {
         maxSumNew(root);
         return ansNew;
diff --git a/page/31/index.html b/page/31/index.html
index 475b4451b3..ada38a79d7 100644
--- a/page/31/index.html
+++ b/page/31/index.html
@@ -1,4 +1,4 @@
-Nicksxs's Blog - What hurts more, the pain of hard work or the pain of regret?

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

题目介绍

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
设计一个栈,支持压栈,出站,获取栈顶元素,通过常数级复杂度获取栈中的最小元素

  • push(x) – Push element x onto stack.
  • pop() – Removes the element on top of the stack.
  • top() – Get the top element.
  • getMin() – Retrieve the minimum element in the stack.

示例

Example 1:

Input
+Nicksxs's Blog - What hurts more, the pain of hard work or the pain of regret?

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

题目介绍

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
设计一个栈,支持压栈,出站,获取栈顶元素,通过常数级复杂度获取栈中的最小元素

  • push(x) – Push element x onto stack.
  • pop() – Removes the element on top of the stack.
  • top() – Get the top element.
  • getMin() – Retrieve the minimum element in the stack.

示例

Example 1:

Input
 ["MinStack","push","push","push","getMin","pop","top","getMin"]
 [[],[-2],[0],[-3],[],[],[],[]]
 
diff --git a/page/32/index.html b/page/32/index.html
index 8834e1b91a..433d530c0f 100644
--- a/page/32/index.html
+++ b/page/32/index.html
@@ -83,7 +83,7 @@
     }
     // 前面返回后,左右取大者
     return Math.max(left + 1, right + 1);
-}

分析

其实对于树这类题,一般是以递归形式比较方便,只是要注意退出条件

终于回忆起来了,年纪大了写这种东西真的要立马写,不然很容易想不起来,那天应该是 9 月 12 日,也就是上周六,因为我爸也去了,而且娘亲(丈母娘,LD 这么叫,我也就随了她这么叫,当然是背后,当面就叫妈)也在那,早上一到那二爹就给我爸指挥了活,要挖一条院子的出水道,自己想出来的词,因为觉得下水道是竖的,在那稍稍帮了一会会忙,然后我还是比较惯例的跟着 LD 还有娘亲去住的家里,主要是老丈人可能也不太想让我干太累的活,因为上次已经差不多把三楼都整理干净了,然后就是二楼了,二楼说实话我也帮不上什么忙,主要是衣服被子什么的,正好是有张以前小孩子睡过的那种摇篮床,看上去虽然有一些破损,整体还是不错的,所以打算拿过去,我就负责把它拆掉了,比较简单的是只要拧螺丝就行了,但是其实是用了好多好多工具才搞定的,一开始只要螺丝刀就行了,但是因为年代久了,后面的螺帽也有点锈住或者本身就会串着会一起动,所以拿来了个扳手,大部分的其实都被这两个工具给搞定了,但是后期大概还剩下四分之一的时候,有一颗完全锈住,并且螺纹跟之前那些都不一样,但是这个已经是最大的螺丝刀了,也没办法换个大的了,所以又去找来个一字的,因为十字的不是也可以用一字的拧嘛,结果可能是我买的工具箱里的一字螺丝刀太新了,口子那很锋利,直接把螺丝花纹给划掉了,大的小的都划掉,然后真的变成凹进去一个圆柱体了,然后就想能不能隔一层布去拧,然而因为的确是已经变成圆柱体了,布也不太给力,不放弃的我又去找来了个老虎钳,妄图把划掉的螺丝用老虎钳钳住,另一端用扳手拧开螺帽,但是这个螺丝跟螺帽真的是生锈的太严重了,外加上钳不太牢,完全是两边一起转,实在是没办法了,在征得同意之后,直接掰断了,火死了,一颗螺丝折腾得比我拆一张床还久,那天因为早上去的也比较晚了,然后就快吃午饭了,正好想着带一点东西过去,就把一些脸盆,泡脚桶啥的拿过去了,先是去吃了饭,还是在那家快餐店,菜的口味还是依然不错,就是人比较多,我爸旁边都是素菜,都没怎么吃远一点的荤菜,下次要早点去,把荤菜放我爸旁边😄(PS:他们家饭还是依然尴尬,需要等),吃完就开到在修的房子那把东西拿了出来,我爸已经动作很快的打了一小半的地沟了,说实话那玩意真的是很重,我之前把它从三楼拿下来,就觉得这个太重了,这次还要用起来,感觉我的手会分分钟废掉,不过一开始我还是跟着LD去了住的家里,惯例睡了午觉,那天睡得比较踏实,竟然睡了一个小时,醒了想了下,其实LD她们收拾也用不上我(没啥力气活),我还是去帮我爸他们,跟LD说了下就去了在修的老房子那,两位老爹在一起钻地,看着就很累,我连忙上去想换一会他们,因为刚好是钻到混凝土地线,特别难,力道不够就会滑开,用蛮力就是钻进去拔不出来,原理是因为本身浇的时候就是很紧实的,需要边钻边动,那家伙实在是太重了,真的是汗如雨下,基本是三个人轮流来,我是个添乱的,经常卡住,然后把地线,其实就是一条混凝土横梁,里面还有14跟18的钢筋,需要割断,这个割断也是很有技巧,钢筋本身在里面是受到挤压的,直接用切割的,到快断掉的时候就会崩一下,非常危险,还是老丈人比较有经验,要留一点点,然后直接用榔头敲断就好了,本来以为这个是最难的了,结果下面是一块非常大的青基石,而且也是石头跟石头挤一块,边上一点点打钻有点杯水车薪,后来是用那种螺旋的钻,钻四个洞,相对位置大概是个长方形,这样子把中间这个长方形钻出来就比较容易地能拿出来了,后面的也容易搞出来了,后面的其实难度不是特别大了,主要是地沟打好之后得看看高低是不是符合要求的,不能本来是往外排水的反而外面高,这个怎么看就又很有技巧了,一般在地上的只要侧着看一下就好了,考究点就用下水平尺,但是在地下的,不用水平尺,其实可以借助于地沟里正要放进去的水管,放点水进去,看水往哪流就行了,铺好水管后,就剩填埋的活了,不是太麻烦了,那天真的是累到了,打那个混凝土的时候我真的是把我整个人压上去了,不过也挺爽的,有点把平时无处发泄的蛮力发泄出去了。

又 roll 到了一个以前做过的题,不过现在用 Java 也来写一下,是 easy 级别的,所以就简单说下

简要介绍

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.
就是给了两个链表,用来表示两个非负的整数,在链表中倒序放着,每个节点包含一位的数字,把他们加起来以后也按照原来的链表结构输出

样例

example 1

Input: l1 = [2,4,3], l2 = [5,6,4]
+}

分析

其实对于树这类题,一般是以递归形式比较方便,只是要注意退出条件

终于回忆起来了,年纪大了写这种东西真的要立马写,不然很容易想不起来,那天应该是 9 月 12 日,也就是上周六,因为我爸也去了,而且娘亲(丈母娘,LD 这么叫,我也就随了她这么叫,当然是背后,当面就叫妈)也在那,早上一到那二爹就给我爸指挥了活,要挖一条院子的出水道,自己想出来的词,因为觉得下水道是竖的,在那稍稍帮了一会会忙,然后我还是比较惯例的跟着 LD 还有娘亲去住的家里,主要是老丈人可能也不太想让我干太累的活,因为上次已经差不多把三楼都整理干净了,然后就是二楼了,二楼说实话我也帮不上什么忙,主要是衣服被子什么的,正好是有张以前小孩子睡过的那种摇篮床,看上去虽然有一些破损,整体还是不错的,所以打算拿过去,我就负责把它拆掉了,比较简单的是只要拧螺丝就行了,但是其实是用了好多好多工具才搞定的,一开始只要螺丝刀就行了,但是因为年代久了,后面的螺帽也有点锈住或者本身就会串着会一起动,所以拿来了个扳手,大部分的其实都被这两个工具给搞定了,但是后期大概还剩下四分之一的时候,有一颗完全锈住,并且螺纹跟之前那些都不一样,但是这个已经是最大的螺丝刀了,也没办法换个大的了,所以又去找来个一字的,因为十字的不是也可以用一字的拧嘛,结果可能是我买的工具箱里的一字螺丝刀太新了,口子那很锋利,直接把螺丝花纹给划掉了,大的小的都划掉,然后真的变成凹进去一个圆柱体了,然后就想能不能隔一层布去拧,然而因为的确是已经变成圆柱体了,布也不太给力,不放弃的我又去找来了个老虎钳,妄图把划掉的螺丝用老虎钳钳住,另一端用扳手拧开螺帽,但是这个螺丝跟螺帽真的是生锈的太严重了,外加上钳不太牢,完全是两边一起转,实在是没办法了,在征得同意之后,直接掰断了,火死了,一颗螺丝折腾得比我拆一张床还久,那天因为早上去的也比较晚了,然后就快吃午饭了,正好想着带一点东西过去,就把一些脸盆,泡脚桶啥的拿过去了,先是去吃了饭,还是在那家快餐店,菜的口味还是依然不错,就是人比较多,我爸旁边都是素菜,都没怎么吃远一点的荤菜,下次要早点去,把荤菜放我爸旁边😄(PS:他们家饭还是依然尴尬,需要等),吃完就开到在修的房子那把东西拿了出来,我爸已经动作很快的打了一小半的地沟了,说实话那玩意真的是很重,我之前把它从三楼拿下来,就觉得这个太重了,这次还要用起来,感觉我的手会分分钟废掉,不过一开始我还是跟着LD去了住的家里,惯例睡了午觉,那天睡得比较踏实,竟然睡了一个小时,醒了想了下,其实LD她们收拾也用不上我(没啥力气活),我还是去帮我爸他们,跟LD说了下就去了在修的老房子那,两位老爹在一起钻地,看着就很累,我连忙上去想换一会他们,因为刚好是钻到混凝土地线,特别难,力道不够就会滑开,用蛮力就是钻进去拔不出来,原理是因为本身浇的时候就是很紧实的,需要边钻边动,那家伙实在是太重了,真的是汗如雨下,基本是三个人轮流来,我是个添乱的,经常卡住,然后把地线,其实就是一条混凝土横梁,里面还有14跟18的钢筋,需要割断,这个割断也是很有技巧,钢筋本身在里面是受到挤压的,直接用切割的,到快断掉的时候就会崩一下,非常危险,还是老丈人比较有经验,要留一点点,然后直接用榔头敲断就好了,本来以为这个是最难的了,结果下面是一块非常大的青基石,而且也是石头跟石头挤一块,边上一点点打钻有点杯水车薪,后来是用那种螺旋的钻,钻四个洞,相对位置大概是个长方形,这样子把中间这个长方形钻出来就比较容易地能拿出来了,后面的也容易搞出来了,后面的其实难度不是特别大了,主要是地沟打好之后得看看高低是不是符合要求的,不能本来是往外排水的反而外面高,这个怎么看就又很有技巧了,一般在地上的只要侧着看一下就好了,考究点就用下水平尺,但是在地下的,不用水平尺,其实可以借助于地沟里正要放进去的水管,放点水进去,看水往哪流就行了,铺好水管后,就剩填埋的活了,不是太麻烦了,那天真的是累到了,打那个混凝土的时候我真的是把我整个人压上去了,不过也挺爽的,有点把平时无处发泄的蛮力发泄出去了。

又 roll 到了一个以前做过的题,不过现在用 Java 也来写一下,是 easy 级别的,所以就简单说下

简要介绍

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.
就是给了两个链表,用来表示两个非负的整数,在链表中倒序放着,每个节点包含一位的数字,把他们加起来以后也按照原来的链表结构输出

样例

example 1

Input: l1 = [2,4,3], l2 = [5,6,4]
 Output: [7,0,8]
 Explanation: 342 + 465 = 807.

example 2

Input: l1 = [0], l2 = [0]
 Output: [0]

example 3

Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
@@ -115,7 +115,7 @@ Output: [8,9,9,9,0,0,0,1]

这里唯二需要注意的就是两个点,一个是循环条件需要包含进位值还存在的情况,还有一个是最后一个节点,如果是空的了,就不要在 new 一个出来了,写的比较挫

Java 真的是任何一个中间件,比较常用的那种,都有很多内容值得深挖,比如这个缓存,慢慢有过一些感悟,比如如何提升性能,缓存无疑是一大重要手段,最底层开始 CPU 就有缓存,而且又小又贵,再往上一点内存一般作为硬盘存储在运行时的存储,一般在代码里也会用内存作为一些本地缓存,譬如数据库,像 mysql 这种也是有innodb_buffer_pool来提升查询效率,本质上理解就是用更快的存储作为相对慢存储的缓存,减少查询直接访问较慢的存储,并且这个都是相对的,比起 cpu 的缓存,那内存也是渣,但是与普通机械硬盘相比,那也是两个次元的水平。

闲扯这么多来说说 mybatis 的缓存,mybatis 一般作为一个轻量级的 orm 使用,相对应的就是比较重量级的 hibernate,不过不在这次讨论范围,上一次是主要讲了 mybatis 在解析 sql 过程中,对于两种占位符的不同替换实现策略,这次主要聊下 mybatis 的缓存,前面其实得了解下前置的东西,比如 sqlsession,先当做我们知道 sqlsession 是个什么玩意,可能或多或少的知道 mybatis 是有两级缓存,

一级缓存

第一级的缓存是在 BaseExecutor 中的 PerpetualCache,它是个最基本的缓存实现类,使用了 HashMap 实现缓存功能,代码其实没几十行

public class PerpetualCache implements Cache {
+    }

这里唯二需要注意的就是两个点,一个是循环条件需要包含进位值还存在的情况,还有一个是最后一个节点,如果是空的了,就不要在 new 一个出来了,写的比较挫

Java 真的是任何一个中间件,比较常用的那种,都有很多内容值得深挖,比如这个缓存,慢慢有过一些感悟,比如如何提升性能,缓存无疑是一大重要手段,最底层开始 CPU 就有缓存,而且又小又贵,再往上一点内存一般作为硬盘存储在运行时的存储,一般在代码里也会用内存作为一些本地缓存,譬如数据库,像 mysql 这种也是有innodb_buffer_pool来提升查询效率,本质上理解就是用更快的存储作为相对慢存储的缓存,减少查询直接访问较慢的存储,并且这个都是相对的,比起 cpu 的缓存,那内存也是渣,但是与普通机械硬盘相比,那也是两个次元的水平。

闲扯这么多来说说 mybatis 的缓存,mybatis 一般作为一个轻量级的 orm 使用,相对应的就是比较重量级的 hibernate,不过不在这次讨论范围,上一次是主要讲了 mybatis 在解析 sql 过程中,对于两种占位符的不同替换实现策略,这次主要聊下 mybatis 的缓存,前面其实得了解下前置的东西,比如 sqlsession,先当做我们知道 sqlsession 是个什么玩意,可能或多或少的知道 mybatis 是有两级缓存,

一级缓存

第一级的缓存是在 BaseExecutor 中的 PerpetualCache,它是个最基本的缓存实现类,使用了 HashMap 实现缓存功能,代码其实没几十行

public class PerpetualCache implements Cache {
 
   private final String id;
 
diff --git a/page/33/index.html b/page/33/index.html
index 6e78035f52..df855d532f 100644
--- a/page/33/index.html
+++ b/page/33/index.html
@@ -1,4 +1,4 @@
-Nicksxs's Blog - What hurts more, the pain of hard work or the pain of regret?

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

小工记四

第四周去的时候让我们去了现在在住的房子里,去三楼整理东西了,蛮多的东西需要收拾整理,有些需要丢一下,以前往往是把不太要用的东西就放三楼了,但是后面就不会再去收拾整理,LD 跟丈母娘负责收拾,我不太知道哪些还要的,哪些不要了,而且本来也不擅长这种收拾🤦‍♂️,然后就变成她们收拾出来废纸箱,我负责拆掉,压平,这时候终于觉得体重还算是有点作用,总体来说这个事情我其实也不擅长,不擅长的主要是捆起来,可能我总是小题大做,因为纸箱大小不一,如果不做一下分类,然后把大的折小一些的话,直接绑起来,容易拎起来就散掉了,而且一些鞋盒子这种小件的纸盒会比较薄,冰箱这种大件的比较厚,厚的比较不容易变形,需要大力踩踏,而且扎的时候需要用体重压住捆实了之后那样子才是真的捆实的,不然待会又是松松垮垮容易滑出来散架,因为压住了捆好后,下来了之后箱子就会弹开了把绳子崩紧实,感觉又是掌握到生活小技巧了😃,我这里其实比较单调无聊,然后 LD 那可以说非常厉害了,一共理出来 11 把旧电扇,还有好多没用过全新的不锈钢脸盆大大小小的,感觉比店里在卖的还多,还有是有比较多小时候的东西,特别多小时候的衣服,其实这种对我来说最难了,可能需要读一下断舍离,蛮多东西都舍不得扔,但是其实是没啥用了,然后还占地方,这天应该算是比较轻松的一天了,上午主要是把收拾出来要的和不要的搬下楼,然后下午要去把纸板给卖掉。中午还是去小快餐店吃的,在住的家里理东西还有个好处就是中午吃完饭可以小憩一下,因为我个人是非常依赖午休的,不然下午完全没精神,而且心态也会比较烦躁,一方面是客观的的确比较疲惫,另一方面应该主观心理作用也有点影响,就像上班的时候也是觉得不午睡就会很难受,心理作用也有一点,不过总之能睡还是睡一会,真的没办法就心态好点,吃完午饭之后我们就推着小平板车去收废品的地方卖掉了上午我收拾捆起来的纸板,好像卖了一百多,都是直接过地磅了,不用一捆一捆地称,不过有个小插曲,那里另外一个大爷在倒他的三轮车的时候撞了我一下,还好车速慢,屁股上肉垫后,接下来就比较麻烦了,是LD 她们两姐妹从小到大的书,也要去卖掉,小平板车就载不下了,而且着实也不太好推,轮子不太平,导致推着很累,书有好多箱,本来是想去亲戚家借电动三轮车,因为不会开摩托的那种,摩托的那种 LD 邻居家就有,可是到了那发现那个也是很大,而且刹车是用脚踩的那种,俺爹不太放心,就说第二天周日他有空会帮忙去载了卖掉的,然后比较搞笑的来了,丈母娘看错了时间,以为已经快五点了,就让我们顺便在车里带点东西去在修的房子,放到那边三楼去,到了那还跟老丈人说已经这么迟了要赶紧去菜场买菜了,结果我们回来以后才发现看错了一个小时🤦‍♂️。
前面可以没提,前三周去的我们一般就周六去一天,然后周日因为要早点回杭州,而且可能想让我们周日能休息下,但是这周就因为周日的时候我爸要去帮忙载书,然后 LD 姐姐也会过来收拾东西,我们周日就又去整理收拾了,周日由于俺爹去的很早,我过去的时候书已经木有了,主要是去收拾东西了,把一些有用没用的继续整理,基本上三楼的就处理完毕了,舒了一大口气,毕竟让丈母娘一个人收拾实在是太累了,但是要扔掉的衣服比较棘手,附近知道的青蛙回收桶被推倒了,其他地方也不知道哪里有,我们就先载了一些东西去在修的房子那,然后去找青蛙桶,结果一个小区可以进,但是已经满了,另一个不让进,后来只能让 LD 姐姐带去她们小区扔了,塞了满满一车。因为要赶回杭州的车就没有等我爸一起回来,他还在那帮忙搞卫生间的墙缝。
虽然这两天不太热,活也不算很吃力,不过我这个体重和易出汗的体质,还是让短袖不知道湿透了多少次,灌了好多水和冰红茶(下午能提提神),回来周一早上称体重也比较喜人,差一点就达到阶段目标,可以想想去哪里吃之前想好的烤肉跟火锅了(估计吃完立马回到解放前)。

又做了个题,看记录是以前用 C++写过的,现在捋一捋思路,用 Java 再写了一下,思路还是比较清晰的,但是边界细节处理得比较差

简要介绍

Given a string s, find the length of the longest substring without repeating characters.

样例

Example 1:

Input: s = "abcabcbb"
+Nicksxs's Blog - What hurts more, the pain of hard work or the pain of regret?

Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

小工记四

第四周去的时候让我们去了现在在住的房子里,去三楼整理东西了,蛮多的东西需要收拾整理,有些需要丢一下,以前往往是把不太要用的东西就放三楼了,但是后面就不会再去收拾整理,LD 跟丈母娘负责收拾,我不太知道哪些还要的,哪些不要了,而且本来也不擅长这种收拾🤦‍♂️,然后就变成她们收拾出来废纸箱,我负责拆掉,压平,这时候终于觉得体重还算是有点作用,总体来说这个事情我其实也不擅长,不擅长的主要是捆起来,可能我总是小题大做,因为纸箱大小不一,如果不做一下分类,然后把大的折小一些的话,直接绑起来,容易拎起来就散掉了,而且一些鞋盒子这种小件的纸盒会比较薄,冰箱这种大件的比较厚,厚的比较不容易变形,需要大力踩踏,而且扎的时候需要用体重压住捆实了之后那样子才是真的捆实的,不然待会又是松松垮垮容易滑出来散架,因为压住了捆好后,下来了之后箱子就会弹开了把绳子崩紧实,感觉又是掌握到生活小技巧了😃,我这里其实比较单调无聊,然后 LD 那可以说非常厉害了,一共理出来 11 把旧电扇,还有好多没用过全新的不锈钢脸盆大大小小的,感觉比店里在卖的还多,还有是有比较多小时候的东西,特别多小时候的衣服,其实这种对我来说最难了,可能需要读一下断舍离,蛮多东西都舍不得扔,但是其实是没啥用了,然后还占地方,这天应该算是比较轻松的一天了,上午主要是把收拾出来要的和不要的搬下楼,然后下午要去把纸板给卖掉。中午还是去小快餐店吃的,在住的家里理东西还有个好处就是中午吃完饭可以小憩一下,因为我个人是非常依赖午休的,不然下午完全没精神,而且心态也会比较烦躁,一方面是客观的的确比较疲惫,另一方面应该主观心理作用也有点影响,就像上班的时候也是觉得不午睡就会很难受,心理作用也有一点,不过总之能睡还是睡一会,真的没办法就心态好点,吃完午饭之后我们就推着小平板车去收废品的地方卖掉了上午我收拾捆起来的纸板,好像卖了一百多,都是直接过地磅了,不用一捆一捆地称,不过有个小插曲,那里另外一个大爷在倒他的三轮车的时候撞了我一下,还好车速慢,屁股上肉垫后,接下来就比较麻烦了,是LD 她们两姐妹从小到大的书,也要去卖掉,小平板车就载不下了,而且着实也不太好推,轮子不太平,导致推着很累,书有好多箱,本来是想去亲戚家借电动三轮车,因为不会开摩托的那种,摩托的那种 LD 邻居家就有,可是到了那发现那个也是很大,而且刹车是用脚踩的那种,俺爹不太放心,就说第二天周日他有空会帮忙去载了卖掉的,然后比较搞笑的来了,丈母娘看错了时间,以为已经快五点了,就让我们顺便在车里带点东西去在修的房子,放到那边三楼去,到了那还跟老丈人说已经这么迟了要赶紧去菜场买菜了,结果我们回来以后才发现看错了一个小时🤦‍♂️。
前面可以没提,前三周去的我们一般就周六去一天,然后周日因为要早点回杭州,而且可能想让我们周日能休息下,但是这周就因为周日的时候我爸要去帮忙载书,然后 LD 姐姐也会过来收拾东西,我们周日就又去整理收拾了,周日由于俺爹去的很早,我过去的时候书已经木有了,主要是去收拾东西了,把一些有用没用的继续整理,基本上三楼的就处理完毕了,舒了一大口气,毕竟让丈母娘一个人收拾实在是太累了,但是要扔掉的衣服比较棘手,附近知道的青蛙回收桶被推倒了,其他地方也不知道哪里有,我们就先载了一些东西去在修的房子那,然后去找青蛙桶,结果一个小区可以进,但是已经满了,另一个不让进,后来只能让 LD 姐姐带去她们小区扔了,塞了满满一车。因为要赶回杭州的车就没有等我爸一起回来,他还在那帮忙搞卫生间的墙缝。
虽然这两天不太热,活也不算很吃力,不过我这个体重和易出汗的体质,还是让短袖不知道湿透了多少次,灌了好多水和冰红茶(下午能提提神),回来周一早上称体重也比较喜人,差一点就达到阶段目标,可以想想去哪里吃之前想好的烤肉跟火锅了(估计吃完立马回到解放前)。

又做了个题,看记录是以前用 C++写过的,现在捋一捋思路,用 Java 再写了一下,思路还是比较清晰的,但是边界细节处理得比较差

简要介绍

Given a string s, find the length of the longest substring without repeating characters.

样例

Example 1:

Input: s = "abcabcbb"
 Output: 3
 Explanation: The answer is "abc", with the length of 3.

Example 2:

Input: s = "bbbbb"
 Output: 1
@@ -38,7 +38,7 @@ Output: 0

注释应该写的比较清楚了。

小工记三

前面这两周周末也都去老丈人家帮忙了,上上周周六先是去了那个在装修的旧房子那,把三楼收拾了下,因为要搬进来住,来不及等二楼装修好,就要把三楼里的东西都整理干净,这个活感觉是比较 easy,原来是就准备把三楼当放东西仓储的地方了,我们乡下大部分三层楼都是这么用的,这次也是没办法,之前搬进来的木头什么的都搬出去,主要是这上面灰尘太多,后面清理鼻孔的时候都是黑色的了,把东西都搬出去以后主要是地还是很脏,就扫了地拖了地,因为是水泥地,灰尘又太多了,拖起来都是会灰尘扬起来,整个脱完了的确干净很多,然而这会就出了个大乌龙,我们清理的是三楼的西边一间,结果老丈人上来说要住东边那间的🤦‍♂️,不过其实西边的也得清理,因为还是要放被子什么的,不算是白费功夫,接着清理东边那间,之前这个房子做过群租房,里面有个高低铺的床,当时觉得可以用在放被子什么的就没扔,只是拆掉了放旁边,我们就把它擦干净了又装好,发现螺丝🔩少了几个,亘古不变的真理,拆了以后装要不就多几个要不就少几个,不是很牢靠,不过用来放放被子省得放地上总还是可以的,对了前面还做了个事情就是铺地毯,其实也不是地毯,就是类似于墙布雨篷布那种,别人不用了送给我们的,三楼水泥地也不会铺瓷砖地板了就放一下,干净好看点,不过大小不合适要裁一下,那把剪刀是真的太难用了,我手都要抽筋了,它就是刀口只有一小个点是能剪下来的,其他都是钝的,后来还是用刀片直接裁,铺好以后,真的感觉也不太一样了,焕然一新的感觉
差不多中午了就去吃饭了,之前两次是去了一家小饭店,还是还比较干净,但是店里菜不好吃,还死贵,这次去了一家小快餐店,口味好,便宜,味道是真的不错,带鱼跟黄鱼都好吃,一点都不腥,我对这类比较腥的鱼真的是很挑剔的,基本上除了家里做的很少吃外面的,那天抱着试试的态度吃了下,真的还不错,后来丈母娘说好像这家老板是给别人结婚喜事酒席当厨师的,怪不得做的好吃,其实本来是有一点小抗拒,怕不干净什么的,后来发现菜很好吃,而且可能是老丈人跟干活的师傅去吃的比较多,老板很客气,我们吃完饭,还给我们买了葡萄吃,不过这家店有一个槽点,就是饭比较不好吃,有时候会夹生,不过后面聊起来其实是这种小菜馆饭点的通病,烧的太早太多容易多出来浪费,烧的迟了不够吃,而且大的电饭锅比较不容易烧好。
下午前面还是在处理三楼的,窗户上各种钉子,实在是太多了,我后面在走廊上排了一排🤦‍♂️,有些是直接断了,有些是就撬了出来,感觉我在杭州租房也没有这样子各种钉钉子,挂下衣服什么的也不用这么多吧,比较不能理解,搞得到处都是钉子。那天我爸也去帮忙了,主要是在卫生间里做白缝,其实也是个技术活,印象中好像我小时候自己家里也做过这个事情,但是比较模糊了,后面我们三楼搞完了就去帮我爸了,前面是我老婆二爹在那先刷上白缝,这里叫白缝,有些考究的也叫美缝,就是瓷砖铺完之后的缝,如果不去弄的话,里面水泥的颜色就露出来了,而且容易渗水,所以就要用白水泥加胶水搅拌之后糊在缝上,但是也不是直接糊,先要把缝抠一抠,因为铺瓷砖的还不会仔细到每个缝里的水泥都是一样满,而且也需要一些空间糊上去,不然就太表面的一层很容易被水直接冲掉了,然后这次其实也不是用的白水泥,而是直接现成买来就已经配好的用来填缝的,兑水搅拌均匀就好了,后面就主要是我跟我爸在搞,那个时候真的觉得我实在是太胖了,蹲下去真的没一会就受不了了,膝盖什么的太难受了,后面我跪着刷,然后膝盖又疼,也是比较不容易,不过我爸动作很快,我中间跪累了休息一会,我爸就能搞一大片,后面其实我也没做多少(谦虚一下),总体来讲这次不是很累,就是蹲着跪着腿有点受不了,是应该好好减肥了。

这个问题也是面试中常被问到的,就抽空来了解下这个,跳过一大段前面初始化的逻辑,
对于一条select * from t1 where id = #{id}这样的 sql,在初始化扫描 mapper 的xml文件的时候会根据是否是 dynamic 来判断生成 DynamicSqlSource 还是 RawSqlSource,这里它是一条 RawSqlSource,
在这里做了替换,将#{}替换成了?

前面说的是否 dynamic 就是在这里进行判断

// org.apache.ibatis.scripting.xmltags.XMLScriptBuilder#parseScriptNode
+}

注释应该写的比较清楚了。

小工记三

前面这两周周末也都去老丈人家帮忙了,上上周周六先是去了那个在装修的旧房子那,把三楼收拾了下,因为要搬进来住,来不及等二楼装修好,就要把三楼里的东西都整理干净,这个活感觉是比较 easy,原来是就准备把三楼当放东西仓储的地方了,我们乡下大部分三层楼都是这么用的,这次也是没办法,之前搬进来的木头什么的都搬出去,主要是这上面灰尘太多,后面清理鼻孔的时候都是黑色的了,把东西都搬出去以后主要是地还是很脏,就扫了地拖了地,因为是水泥地,灰尘又太多了,拖起来都是会灰尘扬起来,整个脱完了的确干净很多,然而这会就出了个大乌龙,我们清理的是三楼的西边一间,结果老丈人上来说要住东边那间的🤦‍♂️,不过其实西边的也得清理,因为还是要放被子什么的,不算是白费功夫,接着清理东边那间,之前这个房子做过群租房,里面有个高低铺的床,当时觉得可以用在放被子什么的就没扔,只是拆掉了放旁边,我们就把它擦干净了又装好,发现螺丝🔩少了几个,亘古不变的真理,拆了以后装要不就多几个要不就少几个,不是很牢靠,不过用来放放被子省得放地上总还是可以的,对了前面还做了个事情就是铺地毯,其实也不是地毯,就是类似于墙布雨篷布那种,别人不用了送给我们的,三楼水泥地也不会铺瓷砖地板了就放一下,干净好看点,不过大小不合适要裁一下,那把剪刀是真的太难用了,我手都要抽筋了,它就是刀口只有一小个点是能剪下来的,其他都是钝的,后来还是用刀片直接裁,铺好以后,真的感觉也不太一样了,焕然一新的感觉
差不多中午了就去吃饭了,之前两次是去了一家小饭店,还是还比较干净,但是店里菜不好吃,还死贵,这次去了一家小快餐店,口味好,便宜,味道是真的不错,带鱼跟黄鱼都好吃,一点都不腥,我对这类比较腥的鱼真的是很挑剔的,基本上除了家里做的很少吃外面的,那天抱着试试的态度吃了下,真的还不错,后来丈母娘说好像这家老板是给别人结婚喜事酒席当厨师的,怪不得做的好吃,其实本来是有一点小抗拒,怕不干净什么的,后来发现菜很好吃,而且可能是老丈人跟干活的师傅去吃的比较多,老板很客气,我们吃完饭,还给我们买了葡萄吃,不过这家店有一个槽点,就是饭比较不好吃,有时候会夹生,不过后面聊起来其实是这种小菜馆饭点的通病,烧的太早太多容易多出来浪费,烧的迟了不够吃,而且大的电饭锅比较不容易烧好。
下午前面还是在处理三楼的,窗户上各种钉子,实在是太多了,我后面在走廊上排了一排🤦‍♂️,有些是直接断了,有些是就撬了出来,感觉我在杭州租房也没有这样子各种钉钉子,挂下衣服什么的也不用这么多吧,比较不能理解,搞得到处都是钉子。那天我爸也去帮忙了,主要是在卫生间里做白缝,其实也是个技术活,印象中好像我小时候自己家里也做过这个事情,但是比较模糊了,后面我们三楼搞完了就去帮我爸了,前面是我老婆二爹在那先刷上白缝,这里叫白缝,有些考究的也叫美缝,就是瓷砖铺完之后的缝,如果不去弄的话,里面水泥的颜色就露出来了,而且容易渗水,所以就要用白水泥加胶水搅拌之后糊在缝上,但是也不是直接糊,先要把缝抠一抠,因为铺瓷砖的还不会仔细到每个缝里的水泥都是一样满,而且也需要一些空间糊上去,不然就太表面的一层很容易被水直接冲掉了,然后这次其实也不是用的白水泥,而是直接现成买来就已经配好的用来填缝的,兑水搅拌均匀就好了,后面就主要是我跟我爸在搞,那个时候真的觉得我实在是太胖了,蹲下去真的没一会就受不了了,膝盖什么的太难受了,后面我跪着刷,然后膝盖又疼,也是比较不容易,不过我爸动作很快,我中间跪累了休息一会,我爸就能搞一大片,后面其实我也没做多少(谦虚一下),总体来讲这次不是很累,就是蹲着跪着腿有点受不了,是应该好好减肥了。

这个问题也是面试中常被问到的,就抽空来了解下这个,跳过一大段前面初始化的逻辑,
对于一条select * from t1 where id = #{id}这样的 sql,在初始化扫描 mapper 的xml文件的时候会根据是否是 dynamic 来判断生成 DynamicSqlSource 还是 RawSqlSource,这里它是一条 RawSqlSource,
在这里做了替换,将#{}替换成了?

前面说的是否 dynamic 就是在这里进行判断

// org.apache.ibatis.scripting.xmltags.XMLScriptBuilder#parseScriptNode
 public SqlSource parseScriptNode() {
     MixedSqlNode rootSqlNode = parseDynamicTags(context);
     SqlSource sqlSource;
diff --git a/page/36/index.html b/page/36/index.html
index fd23cfee7e..e206d776c7 100644
--- a/page/36/index.html
+++ b/page/36/index.html
@@ -9,7 +9,7 @@
   git checkout master
 
   cd $last_dir
-}

对应自己的版本改改版本号就可以了,非常好用。

Adaptive

这个应该是 Dubbo SPI 里最玄妙的东西了,一开始没懂,自适应扩展点加载,
dubbo://123.123.123.123:1234/com.nicksxs.demo.service.HelloWorldService?anyhost=true&application=demo&default.loadbalance=random&default.service.filter=LoggerFilter&dubbo=2.5.3&interface=com.nicksxs.demo.service.HelloWorldService&logger=slf4j&methods=method1,method2,method3,method4&pid=4292&retries=0&side=provider&threadpool=fixed&threads=200&timeout=2000&timestamp=1590647155886
那我从比较能理解的角度或者说思路去讲讲我的理解,因为直接将原理如果脱离了使用,对于我这样的理解能力比较差的可能会比较吃力,从使用场景开始讲可能会比较舒服了,这里可以看到参数里有蛮多的,举个例子,比如这个 threadpool = fixed,说明线程池使用的是 fixed 对应的实现,也就是下图的这个

这样子似乎没啥问题了,反正就是用dubbo 的 spi 加载嘛,好像没啥问题,其实问题还是存在的,或者说不太优雅,比如要先判断我这个 fixed 对应的实现类是哪个,这里可能就有个 if-else 判断了,但是 dubbo 的开发人员似乎不太想这么做这个事情,

譬如我们在引用一个服务时,在ReferenceConfig 中的

private static final Protocol refprotocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();

就获取了自适应拓展,

public T getAdaptiveExtension() {
+}

对应自己的版本改改版本号就可以了,非常好用。

Adaptive

这个应该是 Dubbo SPI 里最玄妙的东西了,一开始没懂,自适应扩展点加载,
dubbo://123.123.123.123:1234/com.nicksxs.demo.service.HelloWorldService?anyhost=true&application=demo&default.loadbalance=random&default.service.filter=LoggerFilter&dubbo=2.5.3&interface=com.nicksxs.demo.service.HelloWorldService&logger=slf4j&methods=method1,method2,method3,method4&pid=4292&retries=0&side=provider&threadpool=fixed&threads=200&timeout=2000&timestamp=1590647155886
那我从比较能理解的角度或者说思路去讲讲我的理解,因为直接将原理如果脱离了使用,对于我这样的理解能力比较差的可能会比较吃力,从使用场景开始讲可能会比较舒服了,这里可以看到参数里有蛮多的,举个例子,比如这个 threadpool = fixed,说明线程池使用的是 fixed 对应的实现,也就是下图的这个

这样子似乎没啥问题了,反正就是用dubbo 的 spi 加载嘛,好像没啥问题,其实问题还是存在的,或者说不太优雅,比如要先判断我这个 fixed 对应的实现类是哪个,这里可能就有个 if-else 判断了,但是 dubbo 的开发人员似乎不太想这么做这个事情,

譬如我们在引用一个服务时,在ReferenceConfig 中的

private static final Protocol refprotocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();

就获取了自适应拓展,

public T getAdaptiveExtension() {
         Object instance = cachedAdaptiveInstance.get();
         if (instance == null) {
             if (createAdaptiveInstanceError == null) {
@@ -123,7 +123,7 @@
         return extension.refer(arg0, arg1);
     }
 }
-

SPI全称是Service Provider Interface,咋眼看跟api是不是有点相似,api是application interface,这两个其实在某些方面有类似的地方,也有蛮大的区别,比如我们基于 dubbo 的微服务,一般我们可以提供服务,然后非泛化调用的话,我们可以把 api 包提供给应用调用方,他们根据接口签名传对应参数并配置好对应的服务发现如 zk 等就可以调用我们的服务了,然后 spi 会有点类似但是是反过来的关系,相当于是一种规范,比如我约定完成这个功能需要两个有两个接口,一个是连接的,一个是断开的,其实就可以用 jdbc 的驱动举例,比较老套了,然后各个厂家去做具体的实现吧,到时候根据我接口的全限定名的文件来加载实际的实现类,然后运行的时候调用对应实现类的方法就完了

3sKdpg

看上面的图,java.sql.Driver就是 spi,对应在classpath 的 META-INF/services 目录下的这个文件,里边的内容就是具体的实现类

1590735097909

简单介绍了 Java的 SPI,再来说说 dubbo 的,dubbo 中为啥要用 SPI 呢,主要是为了框架的可扩展性和性能方面的考虑,比如协议层 dubbo 默认使用 dubbo 协议,同时也支持很多其他协议,也支持用户自己实现协议,那么跟 Java 的 SPI 会有什么区别呢,我们也来看个文件

bqxWMp

是不是看着很想,又有点不一样,在 Java 的 SPI 配置文件里每一行只有一个实现类的全限定名,在 Dubbo的 SPI配置文件中是 key=value 的形式,我们只需要对应的 key 就能加载对应的实现,

/**
+

SPI全称是Service Provider Interface,咋眼看跟api是不是有点相似,api是application interface,这两个其实在某些方面有类似的地方,也有蛮大的区别,比如我们基于 dubbo 的微服务,一般我们可以提供服务,然后非泛化调用的话,我们可以把 api 包提供给应用调用方,他们根据接口签名传对应参数并配置好对应的服务发现如 zk 等就可以调用我们的服务了,然后 spi 会有点类似但是是反过来的关系,相当于是一种规范,比如我约定完成这个功能需要两个有两个接口,一个是连接的,一个是断开的,其实就可以用 jdbc 的驱动举例,比较老套了,然后各个厂家去做具体的实现吧,到时候根据我接口的全限定名的文件来加载实际的实现类,然后运行的时候调用对应实现类的方法就完了

3sKdpg

看上面的图,java.sql.Driver就是 spi,对应在classpath 的 META-INF/services 目录下的这个文件,里边的内容就是具体的实现类

1590735097909

简单介绍了 Java的 SPI,再来说说 dubbo 的,dubbo 中为啥要用 SPI 呢,主要是为了框架的可扩展性和性能方面的考虑,比如协议层 dubbo 默认使用 dubbo 协议,同时也支持很多其他协议,也支持用户自己实现协议,那么跟 Java 的 SPI 会有什么区别呢,我们也来看个文件

bqxWMp

是不是看着很想,又有点不一样,在 Java 的 SPI 配置文件里每一行只有一个实现类的全限定名,在 Dubbo的 SPI配置文件中是 key=value 的形式,我们只需要对应的 key 就能加载对应的实现,

/**
      * 返回指定名字的扩展。如果指定名字的扩展不存在,则抛异常 {@link IllegalStateException}.
      *
      * @param name
diff --git a/page/39/index.html b/page/39/index.html
index 48f8b2d9e7..0a9ca25e51 100644
--- a/page/39/index.html
+++ b/page/39/index.html
@@ -104,7 +104,7 @@ OS name: "mac os x", version: "10.14.6", arch: "x86_64", family: "mac"1.8</maven.compiler.compilerVersion>
       </properties>
       </profile>
-</profiles>
但是这些都没啥用啊,真正有办法的是建个 .mavenrc,这个顾名思义就是 maven 的资源文件,类似于 .bashrc.zshrc,在里面添加 MAVEN_HOME 和 JAVA_HOME,然后执行 source .mavenrc就 OK 啦

G1: The Garbage-First Collector, 垃圾回收优先的垃圾回收器,目标是用户多核 cpu 和大内存的机器,最大的特点就是可预测的停顿时间,官方给出的介绍是提供一个用户在大的堆内存情况下一个低延迟表现的解决方案,通常是 6GB 及以上的堆大小,有低于 0.5 秒稳定的可预测的停顿时间。

这里主要介绍这个比较新的垃圾回收器,在 G1 之前的垃圾回收器都是基于如下图的内存结构分布,有新生代,老年代和永久代(jdk8 之前),然后G1 往前的那些垃圾回收器都有个分代,比如 serial,parallel 等,一般有个应用的组合,最初的 serial 和 serial old,因为新生代和老年代的收集方式不太一样,新生代主要是标记复制,所以有 eden 跟两个 survival区,老年代一般用标记整理方式,而 G1 对这个不太一样。

看一下 G1 的内存分布

可以看到这有很大的不同,G1 通过将内存分成大小相等的 region,每个region是存在于一个连续的虚拟内存范围,对于某个 region 来说其角色是类似于原来的收集器的Eden、Survivor、Old Generation,这个具体在代码层面

// We encode the value of the heap region type so the generation can be
+</profiles>
但是这些都没啥用啊,真正有办法的是建个 .mavenrc,这个顾名思义就是 maven 的资源文件,类似于 .bashrc.zshrc,在里面添加 MAVEN_HOME 和 JAVA_HOME,然后执行 source .mavenrc就 OK 啦

G1: The Garbage-First Collector, 垃圾回收优先的垃圾回收器,目标是用户多核 cpu 和大内存的机器,最大的特点就是可预测的停顿时间,官方给出的介绍是提供一个用户在大的堆内存情况下一个低延迟表现的解决方案,通常是 6GB 及以上的堆大小,有低于 0.5 秒稳定的可预测的停顿时间。

这里主要介绍这个比较新的垃圾回收器,在 G1 之前的垃圾回收器都是基于如下图的内存结构分布,有新生代,老年代和永久代(jdk8 之前),然后G1 往前的那些垃圾回收器都有个分代,比如 serial,parallel 等,一般有个应用的组合,最初的 serial 和 serial old,因为新生代和老年代的收集方式不太一样,新生代主要是标记复制,所以有 eden 跟两个 survival区,老年代一般用标记整理方式,而 G1 对这个不太一样。

看一下 G1 的内存分布

可以看到这有很大的不同,G1 通过将内存分成大小相等的 region,每个region是存在于一个连续的虚拟内存范围,对于某个 region 来说其角色是类似于原来的收集器的Eden、Survivor、Old Generation,这个具体在代码层面

// We encode the value of the heap region type so the generation can be
  // determined quickly. The tag is split into two parts:
  //
  //   major type (young, old, humongous, archive)           : top N-1 bits
diff --git a/page/41/index.html b/page/41/index.html
index 65b37e06a1..1f432b0462 100644
--- a/page/41/index.html
+++ b/page/41/index.html
@@ -106,11 +106,11 @@ typedef struct dict {
     public void doSomething(){
         //todo doSomething
     }
-}

枚举很特殊,它在类加载的时候会初始化里面的所有的实例,而且 JVM 保证了它们不会再被实例化,所以它天生就是单例的。

看完了村上春树的《1Q84》,这应该是第五本看的他的书了,继 跑步,挪威的森林,刺杀骑士团长,海边的卡夫卡之后,不是其中最长的,好像是海边的卡夫卡还是刺杀骑士团长比较长一点,都是在微信读书上看的,比较方便,最开始在上面看的是高晓松的《鱼羊野史》,不知道为啥取这个名字,但是还是满吸引我的,不过由于去年的种种,没有很多心思把它看完,而且本身的组织形式就是比较松散的,看到哪算哪,其实一些野史部分是我比较喜欢,有些谈到人物的就不太有兴趣,而且类似于大祥哥吃的东西,反正都是哇,怎么这么好吃,嗯,太爱(niu)你(bi)了,高晓松就是这个人是我最喜欢的 xxx 家,我也没去细究过他有没有说重复过,反正是不太爱,后来因为这书还一度对战争史有了浓厚的兴趣,然而事实告诉我,大部头的战争史,其实正史我是真的啃不下去,我可能只对其中 10%的内容感兴趣,不过终于也在今年把它看完了,好像高晓松的晓说也最终季了,貌似其中讲朝鲜战争的还被和谐了,看样子是说出了一些故事(truth)。

本来只是想把 《1Q84》的读后感写下,现在觉得还是把这篇当成我今年的读书总结吧,不过先从《1Q84》说起。

严格来讲,这不是很书面化的读后感,可能我想写的也只是像聊天一样的说下我读过的书,包括的技术博客其实也是类似的,以后或许会转变,但是目前水平如此吧,写多了可能会变好,也可能不会。

开始正文吧,这书有点类似于海边的卡夫卡,一开始是通过两条故事线,穿插着叙述,一条是青豆的,不算是个职业杀手的女杀手,要去解决一个经常家暴的斯文败类,穿着描述得比较性感吧,杀人方式是通过比较长的细针,从脖子后面一个精巧的位置插入,可以造成是未知原因死亡的假象,可能会推断成心梗之类的,这里有个前置的细节,就是青豆是乘坐一辆很高级的出租车,内饰什么的都非常有质感,有点不像一辆出租车,然后车里放了一首比较小众的歌,雅纳切克的《小交响曲》,但是青豆知道它,这跟后面的情节也有些许关系,这是女主人公青豆的出场;相应的男主的出场印象不是太深刻,男主叫天吾,是个不知名的作家,跟一个叫小松的编辑有比较好的关系,虽然天吾还没有拿到比较有分量的奖项,但是小松很看好他,也让他帮忙审校一个新作家奖的投稿文章,虽然天吾自身还没获得过这个奖,天吾还有个正式工作,是当数学老师,天吾在学生时代是个数学天才,但后面有对文学产生了兴趣,文学还不足以养活自己,靠着教课还是能保持温饱;

接下来是正式故事的起点了,就是小松收到了一部小说投稿,名叫《空气蛹》,是个叫深绘里的女孩子投的稿,小松对他赋予了很高的评价,这里好像记岔了,好像是天吾对这部小说很有好感,但是小松比较怀疑,然后小松看了之后也有了浓厚的兴趣,这里就是开端了,小松想让天吾来重写润色这部《空气蛹》,因为故事本身很有分量,但是描写手法叙事方式等都很拙劣,而天吾正好擅长这个,小松对天吾的评价是,描写技巧无可挑剔,就是故事主体的火花还没际遇迸发,需要一个导火索,这个就可以类比我们程序员,很多比较初中级的程序员主要擅长在原来的代码上修修改改或者给他分配个小功能,比较高级的程序员就需要能做一些项目的架构设计,核心的技术方案设计,以前我也觉得写文档这个比较无聊,但是当一个项目真的比较庞大,复杂的时候,整体和核心部分的架构设计和方案还是需要有文档沉淀的,不然别人不知道没法接受,自己过段时间也会忘记。

对于小松的这个建议,他的初衷是想搅一搅这个死气沉沉套路颇深的文坛,因为本身《空气蛹》这部小说的内容很吸引人,小松想通过天吾的润色补充让这部小说冲击新人奖,有种恶作剧的意图,天吾对此表示很多担心和顾虑,小松的这个建议其实也是一种文学作假,有两方面的担心,一方面是原作者深绘里是否同意如此操作,一方面是外界如果发现了这个事实会有什么样的后果,但是小松表示不用担心,前一步由小松牵线,让天吾跟原作者深绘里当面沟通这个代写是否被允许,结果当然是被允许了,这里有了对深绘里的初步描写,按我的理解是比较仙的感觉,然后语言沟通有些吃力,或者说有她自己的特色,当面沟通时貌似是让深绘里回去再考虑下,然后后面再由天吾去深绘里寄宿的戎野老师家沟通具体的细节。

2019年12月18日23:37:19 更新
去到戎野老师家之后,天吾知道了关于深绘里的一些事情,深绘里的父亲与戎野老师应该是老友,深绘里的父亲在当初成立了一个叫”先驱”的公社,一个独立运行的社会组织,以运营农场作为物资来源,追求更为松散的共同体,即不过分激进地公有制,进行松散的共同生活,承认私有财产,简而言之就是这样一个能稳定存活下来的独立社会组织,但是随着稳定运行,内部的激进派和稳健派开始出现分歧,不可磨合,后来两派就分裂了,深绘里的父亲,深田保留在了稳健派,但是此时其实深田保内心是矛盾的,以为一开始其实是他倡导的独立革命才组织起了这群人,然而现在他又认清了现实社会已经不太相信能通过革命来独立的可能性,后来激进派便开始越加封闭,而且进行军事训练和思想教育,而后这个先驱的激进派别便有了新的名字”黎明”,深绘里也是在此时从先驱逃离来投靠戎野老师
暂时先写到这,未完待续~

今天看了一下 redis 分布式锁 redlock 的实现,简单记录下,

加锁

原先我对 redis 锁的概念就是加锁使用 setnx,解锁使用 lua 脚本,但是 setnx 具体是啥,lua 脚本是啥不是很清楚
首先简单思考下这个问题,首先为啥不是先 get 一下 key 存不存在,然后再 set 一个 key value,因为加锁这个操作我们是要保证两点,一个是不能中途被打断,也就是说要原子性,如果是先 get 一下 key,如果不存在再 set 值的话,那就不是原子操作了;第二个是可不可以直接 set 值呢,显然不行,锁要保证唯一性,有且只能有一个线程或者其他应用单位获得该锁,正好 setnx 给了我们这种原子命令

然后是 setnx 的键和值分别是啥,键比较容易想到是要锁住的资源,比如 user_id, 这里有个我自己之前比较容易陷进去的误区,但是这个误区后
面再说,这里其实是把user_id 作为要锁住的资源,在我获得锁的时候别的线程不允许操作,以此保证业务的正确性,不会被多个线程同时修改,确定了键,再来看看值是啥,其实原先我认为值是啥都没关系,我只要锁住了,光键就够我用了,但是考虑下多个线程的问题,如果我这个线程加了锁,然后我因为 gc 停顿等原因卡死了,这个时候redis 的锁或者说就是 redis 的缓存已经过期了,这时候另一个线程获得锁成功,然后我这个线程又活过来了,然后我就仍然认为我拿着锁,我去对数据进行修改或者释放锁,是不是就出现问题了,所以是不是我们还需要一个东西来区分这个锁是哪个线程加的,所以我们可以将值设置成为一个线程独有识别的值,至少在相对长的一段时间内不会重复。

上面其实还有两个问题,一个是当 gc 超时时,我这个线程如何知道我手里的锁已经过期了,一种方法是我在加好锁之后就维护一个超时时间,这里其实还有个问题,不过跟第二个问题相关,就一起说了,就是设置超时时间,有些对于不是锁的 redis 缓存操作可以是先设置好值,然后在设置过期时间,那么这就又有上面说到的不是原子性的问题,那么就需要在同一条指令里把超时时间也设置了,幸好 redis 提供了这种支持

SET resource_name my_random_value NX PX 30000

这里借鉴一下解释下,resource_name就是 key,代表要锁住的东西,my_random_value就是识别我这个线程的,NX代表只有在不存在的时候才设置,然后PX 30000表示超时时间是 30秒自动过期

PS:记录下我原先有的一个误区,是不是要用 key 来区分加锁的线程,这样只有一个用处,就是自身线程可以识别是否是自己加的锁,但是最大的问题是别的线程不知道,其实这个用户的出发点是我在担心前面提过的一个问题,就是当 gc 停顿后,我要去判断当前的这个锁是否是我加的,还有就是当释放锁的时候,如果保证不会错误释放了其他线程加的锁,但是这样附带很多其他问题,最大的就是其他线程怎么知道能不能加这个锁。

解锁

当线程在锁过期之前就处理完了业务逻辑,那就可以提前释放这个锁,那么提前释放要怎么操作,直接del key显然是不行的,因为这样就是我前面想用线程随机值加资源名作为锁的初衷,我不能去释放别的线程加的锁,那么我要怎么办呢,先 get 一下看是不是我的?那又变成非原子的操作了,幸好redis 也考虑到了这个问题,给了lua 脚本来操作这种

if redis.call("get",KEYS[1]) == ARGV[1] then
+}

枚举很特殊,它在类加载的时候会初始化里面的所有的实例,而且 JVM 保证了它们不会再被实例化,所以它天生就是单例的。

看完了村上春树的《1Q84》,这应该是第五本看的他的书了,继 跑步,挪威的森林,刺杀骑士团长,海边的卡夫卡之后,不是其中最长的,好像是海边的卡夫卡还是刺杀骑士团长比较长一点,都是在微信读书上看的,比较方便,最开始在上面看的是高晓松的《鱼羊野史》,不知道为啥取这个名字,但是还是满吸引我的,不过由于去年的种种,没有很多心思把它看完,而且本身的组织形式就是比较松散的,看到哪算哪,其实一些野史部分是我比较喜欢,有些谈到人物的就不太有兴趣,而且类似于大祥哥吃的东西,反正都是哇,怎么这么好吃,嗯,太爱(niu)你(bi)了,高晓松就是这个人是我最喜欢的 xxx 家,我也没去细究过他有没有说重复过,反正是不太爱,后来因为这书还一度对战争史有了浓厚的兴趣,然而事实告诉我,大部头的战争史,其实正史我是真的啃不下去,我可能只对其中 10%的内容感兴趣,不过终于也在今年把它看完了,好像高晓松的晓说也最终季了,貌似其中讲朝鲜战争的还被和谐了,看样子是说出了一些故事(truth)。

本来只是想把 《1Q84》的读后感写下,现在觉得还是把这篇当成我今年的读书总结吧,不过先从《1Q84》说起。

严格来讲,这不是很书面化的读后感,可能我想写的也只是像聊天一样的说下我读过的书,包括的技术博客其实也是类似的,以后或许会转变,但是目前水平如此吧,写多了可能会变好,也可能不会。

开始正文吧,这书有点类似于海边的卡夫卡,一开始是通过两条故事线,穿插着叙述,一条是青豆的,不算是个职业杀手的女杀手,要去解决一个经常家暴的斯文败类,穿着描述得比较性感吧,杀人方式是通过比较长的细针,从脖子后面一个精巧的位置插入,可以造成是未知原因死亡的假象,可能会推断成心梗之类的,这里有个前置的细节,就是青豆是乘坐一辆很高级的出租车,内饰什么的都非常有质感,有点不像一辆出租车,然后车里放了一首比较小众的歌,雅纳切克的《小交响曲》,但是青豆知道它,这跟后面的情节也有些许关系,这是女主人公青豆的出场;相应的男主的出场印象不是太深刻,男主叫天吾,是个不知名的作家,跟一个叫小松的编辑有比较好的关系,虽然天吾还没有拿到比较有分量的奖项,但是小松很看好他,也让他帮忙审校一个新作家奖的投稿文章,虽然天吾自身还没获得过这个奖,天吾还有个正式工作,是当数学老师,天吾在学生时代是个数学天才,但后面有对文学产生了兴趣,文学还不足以养活自己,靠着教课还是能保持温饱;

接下来是正式故事的起点了,就是小松收到了一部小说投稿,名叫《空气蛹》,是个叫深绘里的女孩子投的稿,小松对他赋予了很高的评价,这里好像记岔了,好像是天吾对这部小说很有好感,但是小松比较怀疑,然后小松看了之后也有了浓厚的兴趣,这里就是开端了,小松想让天吾来重写润色这部《空气蛹》,因为故事本身很有分量,但是描写手法叙事方式等都很拙劣,而天吾正好擅长这个,小松对天吾的评价是,描写技巧无可挑剔,就是故事主体的火花还没际遇迸发,需要一个导火索,这个就可以类比我们程序员,很多比较初中级的程序员主要擅长在原来的代码上修修改改或者给他分配个小功能,比较高级的程序员就需要能做一些项目的架构设计,核心的技术方案设计,以前我也觉得写文档这个比较无聊,但是当一个项目真的比较庞大,复杂的时候,整体和核心部分的架构设计和方案还是需要有文档沉淀的,不然别人不知道没法接受,自己过段时间也会忘记。

对于小松的这个建议,他的初衷是想搅一搅这个死气沉沉套路颇深的文坛,因为本身《空气蛹》这部小说的内容很吸引人,小松想通过天吾的润色补充让这部小说冲击新人奖,有种恶作剧的意图,天吾对此表示很多担心和顾虑,小松的这个建议其实也是一种文学作假,有两方面的担心,一方面是原作者深绘里是否同意如此操作,一方面是外界如果发现了这个事实会有什么样的后果,但是小松表示不用担心,前一步由小松牵线,让天吾跟原作者深绘里当面沟通这个代写是否被允许,结果当然是被允许了,这里有了对深绘里的初步描写,按我的理解是比较仙的感觉,然后语言沟通有些吃力,或者说有她自己的特色,当面沟通时貌似是让深绘里回去再考虑下,然后后面再由天吾去深绘里寄宿的戎野老师家沟通具体的细节。

2019年12月18日23:37:19 更新
去到戎野老师家之后,天吾知道了关于深绘里的一些事情,深绘里的父亲与戎野老师应该是老友,深绘里的父亲在当初成立了一个叫”先驱”的公社,一个独立运行的社会组织,以运营农场作为物资来源,追求更为松散的共同体,即不过分激进地公有制,进行松散的共同生活,承认私有财产,简而言之就是这样一个能稳定存活下来的独立社会组织,但是随着稳定运行,内部的激进派和稳健派开始出现分歧,不可磨合,后来两派就分裂了,深绘里的父亲,深田保留在了稳健派,但是此时其实深田保内心是矛盾的,以为一开始其实是他倡导的独立革命才组织起了这群人,然而现在他又认清了现实社会已经不太相信能通过革命来独立的可能性,后来激进派便开始越加封闭,而且进行军事训练和思想教育,而后这个先驱的激进派别便有了新的名字”黎明”,深绘里也是在此时从先驱逃离来投靠戎野老师
暂时先写到这,未完待续~

今天看了一下 redis 分布式锁 redlock 的实现,简单记录下,

加锁

原先我对 redis 锁的概念就是加锁使用 setnx,解锁使用 lua 脚本,但是 setnx 具体是啥,lua 脚本是啥不是很清楚
首先简单思考下这个问题,首先为啥不是先 get 一下 key 存不存在,然后再 set 一个 key value,因为加锁这个操作我们是要保证两点,一个是不能中途被打断,也就是说要原子性,如果是先 get 一下 key,如果不存在再 set 值的话,那就不是原子操作了;第二个是可不可以直接 set 值呢,显然不行,锁要保证唯一性,有且只能有一个线程或者其他应用单位获得该锁,正好 setnx 给了我们这种原子命令

然后是 setnx 的键和值分别是啥,键比较容易想到是要锁住的资源,比如 user_id, 这里有个我自己之前比较容易陷进去的误区,但是这个误区后
面再说,这里其实是把user_id 作为要锁住的资源,在我获得锁的时候别的线程不允许操作,以此保证业务的正确性,不会被多个线程同时修改,确定了键,再来看看值是啥,其实原先我认为值是啥都没关系,我只要锁住了,光键就够我用了,但是考虑下多个线程的问题,如果我这个线程加了锁,然后我因为 gc 停顿等原因卡死了,这个时候redis 的锁或者说就是 redis 的缓存已经过期了,这时候另一个线程获得锁成功,然后我这个线程又活过来了,然后我就仍然认为我拿着锁,我去对数据进行修改或者释放锁,是不是就出现问题了,所以是不是我们还需要一个东西来区分这个锁是哪个线程加的,所以我们可以将值设置成为一个线程独有识别的值,至少在相对长的一段时间内不会重复。

上面其实还有两个问题,一个是当 gc 超时时,我这个线程如何知道我手里的锁已经过期了,一种方法是我在加好锁之后就维护一个超时时间,这里其实还有个问题,不过跟第二个问题相关,就一起说了,就是设置超时时间,有些对于不是锁的 redis 缓存操作可以是先设置好值,然后在设置过期时间,那么这就又有上面说到的不是原子性的问题,那么就需要在同一条指令里把超时时间也设置了,幸好 redis 提供了这种支持

SET resource_name my_random_value NX PX 30000

这里借鉴一下解释下,resource_name就是 key,代表要锁住的东西,my_random_value就是识别我这个线程的,NX代表只有在不存在的时候才设置,然后PX 30000表示超时时间是 30秒自动过期

PS:记录下我原先有的一个误区,是不是要用 key 来区分加锁的线程,这样只有一个用处,就是自身线程可以识别是否是自己加的锁,但是最大的问题是别的线程不知道,其实这个用户的出发点是我在担心前面提过的一个问题,就是当 gc 停顿后,我要去判断当前的这个锁是否是我加的,还有就是当释放锁的时候,如果保证不会错误释放了其他线程加的锁,但是这样附带很多其他问题,最大的就是其他线程怎么知道能不能加这个锁。

解锁

当线程在锁过期之前就处理完了业务逻辑,那就可以提前释放这个锁,那么提前释放要怎么操作,直接del key显然是不行的,因为这样就是我前面想用线程随机值加资源名作为锁的初衷,我不能去释放别的线程加的锁,那么我要怎么办呢,先 get 一下看是不是我的?那又变成非原子的操作了,幸好redis 也考虑到了这个问题,给了lua 脚本来操作这种

if redis.call("get",KEYS[1]) == ARGV[1] then
     return redis.call("del",KEYS[1])
 else
     return 0
-end

这里的KEYS[1]就是前面加锁的resource_name,ARGV[1]就是线程的随机值my_random_value

多节点

前面说的其实是单节点 redis 作为分布式锁的情况,那么当我们的 redis 有多节点的情况呢,如果多节点下处于加锁或者解锁或者锁有效情况下
redis 的某个节点宕掉了怎么办,这里就有一些需要思考的地方,是否单独搞一个单节点的 redis作为分布式锁专用的,但是如果这个单节点的挂了呢,还有就是成本问题,所以我们需要一个多节点的分布式锁方案
这里就引出了开头说到的redlock,这个可是 redis的作者写的, 他的加锁过程是分以下几步去做这个事情

  • 获取当前时间(毫秒数)。
  • 按顺序依次向N个Redis节点执行获取锁的操作。这个获取操作跟前面基于单Redis节点的获取锁的过程相同,包含随机字符串my_random_value,也包含过期时间(比如PX 30000,即锁的有效时间)。为了保证在某个Redis节点不可用的时候算法能够继续运行,这个获取锁的操作还有一个超时时间(time out),它要远小于锁的有效时间(几十毫秒量级)。客户端在向某个Redis节点获取锁失败以后,应该立即尝试下一个Redis节点。这里的失败,应该包含任何类型的失败,比如该Redis节点不可用,或者该Redis节点上的锁已经被其它客户端持有(注:Redlock原文中这里只提到了Redis节点不可用的情况,但也应该包含其它的失败情况)。
  • 计算整个获取锁的过程总共消耗了多长时间,计算方法是用当前时间减去第1步记录的时间。如果客户端从大多数Redis节点(>= N/2+1)成功获取到了锁,并且获取锁总共消耗的时间没有超过锁的有效时间(lock validity time),那么这时客户端才认为最终获取锁成功;否则,认为最终获取锁失败。
  • 如果最终获取锁成功了,那么这个锁的有效时间应该重新计算,它等于最初的锁的有效时间减去第3步计算出来的获取锁消耗的时间。
  • 如果最终获取锁失败了(可能由于获取到锁的Redis节点个数少于N/2+1,或者整个获取锁的过程消耗的时间超过了锁的最初有效时间),那么客户端应该立即向所有Redis节点发起释放锁的操作(即前面介绍的Redis Lua脚本)。
    释放锁的过程比较简单:客户端向所有Redis节点发起释放锁的操作,不管这些节点当时在获取锁的时候成功与否。这里为什么要向所有的节点发送释放锁的操作呢,这里是因为有部分的节点的失败原因可能是加锁时阻塞,加锁成功的结果没有及时返回,所以为了防止这种情况还是需要向所有发起这个释放锁的操作。
    初步记录就先到这。

对 Java 的 gc 实现比较感兴趣,原先一般都是看周志明的书,但其实并没有讲具体的 gc 源码,而是把整个思路和流程讲解了一下
特别是 G1 的具体实现
一般对 G1 的理解其实就是把原先整块的新生代老年代分成了以 region 为单位的小块内存,简而言之,就是原先对新生代老年代的收集会涉及到整个代的堆内存空间,而G1 把它变成了更细致的小块内存
这带来了一个很明显的好处和一个很明显的坏处,好处是内存收集可以更灵活,耗时会变短,但整个收集的处理复杂度就变高了
目前看了一点点关于 G1 收集的预期时间相关的代码

HeapWord* G1CollectedHeap::do_collection_pause(size_t word_size,
+end

这里的KEYS[1]就是前面加锁的resource_name,ARGV[1]就是线程的随机值my_random_value

多节点

前面说的其实是单节点 redis 作为分布式锁的情况,那么当我们的 redis 有多节点的情况呢,如果多节点下处于加锁或者解锁或者锁有效情况下
redis 的某个节点宕掉了怎么办,这里就有一些需要思考的地方,是否单独搞一个单节点的 redis作为分布式锁专用的,但是如果这个单节点的挂了呢,还有就是成本问题,所以我们需要一个多节点的分布式锁方案
这里就引出了开头说到的redlock,这个可是 redis的作者写的, 他的加锁过程是分以下几步去做这个事情

  • 获取当前时间(毫秒数)。
  • 按顺序依次向N个Redis节点执行获取锁的操作。这个获取操作跟前面基于单Redis节点的获取锁的过程相同,包含随机字符串my_random_value,也包含过期时间(比如PX 30000,即锁的有效时间)。为了保证在某个Redis节点不可用的时候算法能够继续运行,这个获取锁的操作还有一个超时时间(time out),它要远小于锁的有效时间(几十毫秒量级)。客户端在向某个Redis节点获取锁失败以后,应该立即尝试下一个Redis节点。这里的失败,应该包含任何类型的失败,比如该Redis节点不可用,或者该Redis节点上的锁已经被其它客户端持有(注:Redlock原文中这里只提到了Redis节点不可用的情况,但也应该包含其它的失败情况)。
  • 计算整个获取锁的过程总共消耗了多长时间,计算方法是用当前时间减去第1步记录的时间。如果客户端从大多数Redis节点(>= N/2+1)成功获取到了锁,并且获取锁总共消耗的时间没有超过锁的有效时间(lock validity time),那么这时客户端才认为最终获取锁成功;否则,认为最终获取锁失败。
  • 如果最终获取锁成功了,那么这个锁的有效时间应该重新计算,它等于最初的锁的有效时间减去第3步计算出来的获取锁消耗的时间。
  • 如果最终获取锁失败了(可能由于获取到锁的Redis节点个数少于N/2+1,或者整个获取锁的过程消耗的时间超过了锁的最初有效时间),那么客户端应该立即向所有Redis节点发起释放锁的操作(即前面介绍的Redis Lua脚本)。
    释放锁的过程比较简单:客户端向所有Redis节点发起释放锁的操作,不管这些节点当时在获取锁的时候成功与否。这里为什么要向所有的节点发送释放锁的操作呢,这里是因为有部分的节点的失败原因可能是加锁时阻塞,加锁成功的结果没有及时返回,所以为了防止这种情况还是需要向所有发起这个释放锁的操作。
    初步记录就先到这。

对 Java 的 gc 实现比较感兴趣,原先一般都是看周志明的书,但其实并没有讲具体的 gc 源码,而是把整个思路和流程讲解了一下
特别是 G1 的具体实现
一般对 G1 的理解其实就是把原先整块的新生代老年代分成了以 region 为单位的小块内存,简而言之,就是原先对新生代老年代的收集会涉及到整个代的堆内存空间,而G1 把它变成了更细致的小块内存
这带来了一个很明显的好处和一个很明显的坏处,好处是内存收集可以更灵活,耗时会变短,但整个收集的处理复杂度就变高了
目前看了一点点关于 G1 收集的预期时间相关的代码

HeapWord* G1CollectedHeap::do_collection_pause(size_t word_size,
                                                uint gc_count_before,
                                                bool* succeeded,
                                                GCCause::Cause gc_cause) {
diff --git a/search.xml b/search.xml
index f814d39467..c74cf65425 100644
--- a/search.xml
+++ b/search.xml
@@ -12,8 +12,8 @@
 

2019年12月18日23:37:19 更新
去到戎野老师家之后,天吾知道了关于深绘里的一些事情,深绘里的父亲与戎野老师应该是老友,深绘里的父亲在当初成立了一个叫”先驱”的公社,一个独立运行的社会组织,以运营农场作为物资来源,追求更为松散的共同体,即不过分激进地公有制,进行松散的共同生活,承认私有财产,简而言之就是这样一个能稳定存活下来的独立社会组织,但是随着稳定运行,内部的激进派和稳健派开始出现分歧,不可磨合,后来两派就分裂了,深绘里的父亲,深田保留在了稳健派,但是此时其实深田保内心是矛盾的,以为一开始其实是他倡导的独立革命才组织起了这群人,然而现在他又认清了现实社会已经不太相信能通过革命来独立的可能性,后来激进派便开始越加封闭,而且进行军事训练和思想教育,而后这个先驱的激进派别便有了新的名字”黎明”,深绘里也是在此时从先驱逃离来投靠戎野老师
暂时先写到这,未完待续~

]]> - 生活 读后感 + 生活 村上春树 @@ -21,26 +21,32 @@ - 2021 年中总结 - /2021/07/18/2021-%E5%B9%B4%E4%B8%AD%E6%80%BB%E7%BB%93/ - 又到半年总结时,第一次写总结类型的文章感觉挺好写的,但是后面总觉得这过去的一段时间所做的事情,能力上的成长低于预期,但是是需要总结下,找找问题,顺便展望下未来。

-

这一年做的最让自己满意的应该就是看了一些书,由折腾群洋总发起的读书打卡活动,到目前为止已经读完了这几本书,《cUrl 必知必会》,《古董局中局 1》,《古董局中局 2》,《算法图解》,《每天 5 分钟玩转 Kubernetes》《幸福了吗?》《高可用可伸缩微服务架构:基于 Dubbo、Spring Cloud和 Service Mesh》《Rust 权威指南》后面可以写个专题说说看的这些书,虽然每天打卡如果时间安排不好,并且看的书像 rust 这样比较难的话还是会有点小焦虑,不过也是个调整过程,一方面可以在白天就抽空看一会,然后也不必要每次都看很大一章,注重吸收。

-

技术上的成长的话,有一些比较小的长进吧,对于一些之前忽视的 synchronized,ThreadLocal 和 AQS 等知识点做了下查漏补缺了,然后多了解了一些 Java 垃圾回收的内容,但是在实操上还是比较欠缺,成型的技术方案,架构上所谓的优化也比较少,一些想法也还有考虑不周全的地方,还需要多花时间和心思去学习加强,特别是在目前已经有的基础上如何做系统深层次的优化,既不要是鸡毛蒜皮的,也不能出现一些不可接受的问题和故障,这是个很重要的课题,需要好好学习,后面考虑定一些周期性目标,两个月左右能有一些成果和总结。

-

另外一部分是自己的服务,因为 ucloud 的机器太贵就没续费了,所以都迁移到腾讯云的小机器上了,顺便折腾了一点点 traefik,但是还很不熟练,不太习惯这一套,一方面是 docker 还不习惯,这也加重了对这套环境的不适应,还是习惯裸机部署,另一方面就是 k8s 了,家里的机器还没虚拟化,没有很好的条件可以做实验,这也是读书打卡的一个没做好的点,整体的学习效果受限于深度和实操,后面是看都是用 traefik,也找到了一篇文章可以 traefik 转发到裸机应用,因为主仓库用的是裸机的 gogs。

-

还有就是运动减肥上,唉,这又是很大的一个痛点,基本没效果,只是还算稳定,昨天看到一个视频说还需要力量训练来增肌,以此可以提升基础代谢,打算往这个方向尝试下,因为今天没有疫情限制了,在 6 月底完成了 200 公里的跑步小目标,只是有些膝盖跟大腿根外侧不适,抽空得去看下医生,后面打算每天也能做点卷腹跟俯卧撑。

-

下半年还希望能继续多看看书,比很多网上各种乱七八糟的文章会好很多,结合豆瓣评分,找一些评价高一些的文章,但也不是说分稍低点的就不行,有些也看人是不是适合,一般 6 分以上评价比较多的就可以试试。

+ 2019年终总结 + /2020/02/01/2019%E5%B9%B4%E7%BB%88%E6%80%BB%E7%BB%93/ + 今天是农历初八了,年前一个月的时候就准备做下今年的年终总结,可是写了一点觉得太情绪化了,希望后面写个平淡点的,正好最近技术方面还没有看到一个完整成文的内容,就来写一下这一年的总结,尽量少写一点太情绪化的东西。

+

跳槽

年初换了个公司,也算换了个环境,跟前公司不太一样,做的事情方向也不同,可能是侧重点不同,一开始有些不适应,主要是压力上,会觉得压力比较大,但是总体来说与人相处的部分还是不错的,做的技术方向还是Java,这里也感谢前东家让我有机会转了Java,个人感觉杭州整个市场还是Java比较有优势,不过在开始的时候总觉得对Java有点不适应,应该值得深究的东西还是很多的,而且对于面试来说,也是有很多可以问的,后面慢慢发现除开某里等一线超一线互联网公司之外,大部分的面试还是有大概的套路跟大纲的,不过更细致的则因人而异了,面试有时候也还看缘分,面试官关注的点跟应试者比较契合的话就很容易通过面试,不然的话总会有能刁难或者理性化地说比较难回答的问题。这个后面可以单独说一下,先按下不表。
刚进公司没多久就负责比较重要的项目,工期也比较紧张,整体来说那段时间的压力的确是比较大的,不过总算最后结果不坏,这里应该说对一些原来在前东家都是掌握的不太好的部分,比如maven,其实maven对于java程序员来说还是很重要的,但是我碰到过的面试基本没问过这个,我自己也在后面的面试中没问过相关的,不知道咋问,比如dependence分析、冲突解决,比如对bean的理解,这个算是我一直以来的疑问点,因为以前刚开始学Java学spring,上来就是bean,但是bean到底是啥,IOC是啥,可能网上的文章跟大多数书籍跟我的理解思路不太match,导致一直不能很好的理解这玩意,到后面才理解,要理解这个bean,需要有两个基本概念,一个是面向对象,一个是对象容器跟依赖反转,还是只说到这,后面可以有专题说一下,总之自认为技术上有了不小的长进了,方向上应该是偏实用的。这个重要的项目完成后慢慢能喘口气了,后面也有一些比较紧急且工作量大的,不过在我TL的帮助下还是能尽量协调好资源。

+

面试

后面因为项目比较多,缺少开发,所以也参与帮忙做一些面试,这里总体感觉是面的候选人还是比较多样的,有些工作了蛮多年但是一些基础问题回答的不好,有些还是在校学生,但是面试技巧不错,针对常见的面试题都有不错的准备,不过还是觉得光靠这些面试题不能完全说明问题,真正工作了需要的是解决问题的人,而不是会背题的,退一步来说能好好准备面试还是比较重要的,也是双向选择中的基本尊重,印象比较深刻的是参加了去杭州某高校的校招面试,感觉参加校招的同学还是很多的,大部分是20年将毕业的研究生,挺多都是基础很扎实,对比起我刚要毕业时还是很汗颜,挺多来面试的同学都非常不错,那天强度也很大,从下午到那开始一直面到六七点,在这祝福那些来面试的同学,也都不容易的,能找到心仪的工作。

+

技术方向

这一年前大半部分还是比较焦虑不能恢复那种主动找时间学习的状态,可能换了公司是主要的原因,初期有个适应的过程也比较正常,总体来说可能是到九十月份开始慢慢有所改善,对这些方面有学习了下,

+
    +
  • spring方向,spring真的是个庞然大物,但是还是要先抓住根本,慢慢发散去了解其他的细节,抓住bean的生命周期,当然也不是死记硬背,让我一个个背下来我也不行,但是知道它究竟是干嘛的,有啥用,并且在工作中能用起来是最重要的
  • +
  • mysql数据库,这部分主要是关注了mvcc,知道了个大概,源码实现细节还没具体研究,有时间可以来个专题(一大堆待写的内容)
  • +
  • java的一些源码,比如aqs这种,结合文章看了下源码,一开始总感觉静不下心来看,然后有一次被LD刺激了下就看完了,包括conditionObject等
  • +
  • redis的源码,这里包括了Redis分布式锁和redis的数据结构源码,已经写成文章,不过比较着急成文,所以质量不是特别好,希望后面再来补补
  • +
  • jvm源码,这部分正好是想了解下g1收集器,大概把周志明的书看完了,但是还没完整的理解掌握,还有就是g1收集器的部分,一是概念部分大概理解了,后面是就是想从源码层面去学习理解,这也是新一年的主要计划
  • +
  • mq的部分是了解了zero copy,sendfile等,跟消息队列主题关系不大🤦‍♂️
    这么看还是学了点东西的,希望新一年再接再厉。
  • +
+

生活

住的地方没变化,主要是周边设施比较方便,暂时没找到更好的就没打算换,主要的问题是没电梯,一开始没觉得有啥,真正住起来还是觉得比较累的,希望后面租的可以有电梯,或者楼层低一点,还有就是要通下水道,第一次让师傅上门,花了两百大洋,后来自学成才了,让师傅通了一次才撑了一个月就不行了,后面自己通的差不多可以撑半年,还是比较有成就感的😀,然后就是跑步了,年初的时候去了紫金港跑步,后面因为工作的原因没去了,但是公司的跑步机倒是让我重拾起这个唯一的运动健身项目,后面因为肠胃问题,体重也需要控制,所以就周末回来也在家这边坚持跑步,下半年的话基本保持每周一次以上,比较那些跑马拉松的大牛还是差距很大,不过也是突破自我了,有一次跑了12公里,最远的距离,而且后面感觉跑十公里也不是特别吃不消了,这一年达成了300公里的目标,体重也稍有下降,比较满意的结果。

+

期待

希望工作方面技术方面能有所长进,生活上能多点时间陪家人,继续跑步减肥,家人健健康康的,嗯

]]>
生活 - 年中总结 - 2021 + 年终总结 + 2019 生活 - 2021 - 技术 - 读书 - 年中总结 + 年终总结 + 2019
@@ -69,32 +75,45 @@ - 2019年终总结 - /2020/02/01/2019%E5%B9%B4%E7%BB%88%E6%80%BB%E7%BB%93/ - 今天是农历初八了,年前一个月的时候就准备做下今年的年终总结,可是写了一点觉得太情绪化了,希望后面写个平淡点的,正好最近技术方面还没有看到一个完整成文的内容,就来写一下这一年的总结,尽量少写一点太情绪化的东西。

-

跳槽

年初换了个公司,也算换了个环境,跟前公司不太一样,做的事情方向也不同,可能是侧重点不同,一开始有些不适应,主要是压力上,会觉得压力比较大,但是总体来说与人相处的部分还是不错的,做的技术方向还是Java,这里也感谢前东家让我有机会转了Java,个人感觉杭州整个市场还是Java比较有优势,不过在开始的时候总觉得对Java有点不适应,应该值得深究的东西还是很多的,而且对于面试来说,也是有很多可以问的,后面慢慢发现除开某里等一线超一线互联网公司之外,大部分的面试还是有大概的套路跟大纲的,不过更细致的则因人而异了,面试有时候也还看缘分,面试官关注的点跟应试者比较契合的话就很容易通过面试,不然的话总会有能刁难或者理性化地说比较难回答的问题。这个后面可以单独说一下,先按下不表。
刚进公司没多久就负责比较重要的项目,工期也比较紧张,整体来说那段时间的压力的确是比较大的,不过总算最后结果不坏,这里应该说对一些原来在前东家都是掌握的不太好的部分,比如maven,其实maven对于java程序员来说还是很重要的,但是我碰到过的面试基本没问过这个,我自己也在后面的面试中没问过相关的,不知道咋问,比如dependence分析、冲突解决,比如对bean的理解,这个算是我一直以来的疑问点,因为以前刚开始学Java学spring,上来就是bean,但是bean到底是啥,IOC是啥,可能网上的文章跟大多数书籍跟我的理解思路不太match,导致一直不能很好的理解这玩意,到后面才理解,要理解这个bean,需要有两个基本概念,一个是面向对象,一个是对象容器跟依赖反转,还是只说到这,后面可以有专题说一下,总之自认为技术上有了不小的长进了,方向上应该是偏实用的。这个重要的项目完成后慢慢能喘口气了,后面也有一些比较紧急且工作量大的,不过在我TL的帮助下还是能尽量协调好资源。

-

面试

后面因为项目比较多,缺少开发,所以也参与帮忙做一些面试,这里总体感觉是面的候选人还是比较多样的,有些工作了蛮多年但是一些基础问题回答的不好,有些还是在校学生,但是面试技巧不错,针对常见的面试题都有不错的准备,不过还是觉得光靠这些面试题不能完全说明问题,真正工作了需要的是解决问题的人,而不是会背题的,退一步来说能好好准备面试还是比较重要的,也是双向选择中的基本尊重,印象比较深刻的是参加了去杭州某高校的校招面试,感觉参加校招的同学还是很多的,大部分是20年将毕业的研究生,挺多都是基础很扎实,对比起我刚要毕业时还是很汗颜,挺多来面试的同学都非常不错,那天强度也很大,从下午到那开始一直面到六七点,在这祝福那些来面试的同学,也都不容易的,能找到心仪的工作。

-

技术方向

这一年前大半部分还是比较焦虑不能恢复那种主动找时间学习的状态,可能换了公司是主要的原因,初期有个适应的过程也比较正常,总体来说可能是到九十月份开始慢慢有所改善,对这些方面有学习了下,

-
    -
  • spring方向,spring真的是个庞然大物,但是还是要先抓住根本,慢慢发散去了解其他的细节,抓住bean的生命周期,当然也不是死记硬背,让我一个个背下来我也不行,但是知道它究竟是干嘛的,有啥用,并且在工作中能用起来是最重要的
  • -
  • mysql数据库,这部分主要是关注了mvcc,知道了个大概,源码实现细节还没具体研究,有时间可以来个专题(一大堆待写的内容)
  • -
  • java的一些源码,比如aqs这种,结合文章看了下源码,一开始总感觉静不下心来看,然后有一次被LD刺激了下就看完了,包括conditionObject等
  • -
  • redis的源码,这里包括了Redis分布式锁和redis的数据结构源码,已经写成文章,不过比较着急成文,所以质量不是特别好,希望后面再来补补
  • -
  • jvm源码,这部分正好是想了解下g1收集器,大概把周志明的书看完了,但是还没完整的理解掌握,还有就是g1收集器的部分,一是概念部分大概理解了,后面是就是想从源码层面去学习理解,这也是新一年的主要计划
  • -
  • mq的部分是了解了zero copy,sendfile等,跟消息队列主题关系不大🤦‍♂️
    这么看还是学了点东西的,希望新一年再接再厉。
  • -
-

生活

住的地方没变化,主要是周边设施比较方便,暂时没找到更好的就没打算换,主要的问题是没电梯,一开始没觉得有啥,真正住起来还是觉得比较累的,希望后面租的可以有电梯,或者楼层低一点,还有就是要通下水道,第一次让师傅上门,花了两百大洋,后来自学成才了,让师傅通了一次才撑了一个月就不行了,后面自己通的差不多可以撑半年,还是比较有成就感的😀,然后就是跑步了,年初的时候去了紫金港跑步,后面因为工作的原因没去了,但是公司的跑步机倒是让我重拾起这个唯一的运动健身项目,后面因为肠胃问题,体重也需要控制,所以就周末回来也在家这边坚持跑步,下半年的话基本保持每周一次以上,比较那些跑马拉松的大牛还是差距很大,不过也是突破自我了,有一次跑了12公里,最远的距离,而且后面感觉跑十公里也不是特别吃不消了,这一年达成了300公里的目标,体重也稍有下降,比较满意的结果。

-

期待

希望工作方面技术方面能有所长进,生活上能多点时间陪家人,继续跑步减肥,家人健健康康的,嗯

+ 2020年中总结 + /2020/07/11/2020%E5%B9%B4%E4%B8%AD%E6%80%BB%E7%BB%93/ + 很快2020 年就过了一半了,而且是今年这么特殊的一年,很多事情都发生的出乎意料,疫情这个绕不过去的话题,之前写了点比较愤青的文字,感觉不太适合发出来就烂在草稿箱里吧,这个目前一大影响估计是今年都没办法完全摘下口罩了,前面几个月来回杭州都开车,因为彭埠大桥不通行了,实在是非常不方便,每条路都灰常堵,心累,吐槽下杭州的交通规划和交警同志,工作实在做的不咋地。

+

另外一件是就是蜗壳,从前不知道黝黑蜗壳是啥意思,只是经常会在他的视频里看到,大学的时候在缘网下了一个集锦,炒鸡帅气,各种空接扣篮,越来越能明白那句“你永远不知道意外和明天不知道哪个会先来,且行且珍惜”的含义,只是听了很多道理,依然活不好这一生,知易行难,王阳明真的是这方面的大师,有空可以看看这方面的书,一直想写写我跟篮球跟蜗壳的这十几年,争取能早日写好吧,不过得找个静得下来的时候写。

+

正事方面上半年还是挺让人失望的,没有达成一些目标,应该还是能力不足吧,技术方面分析一下还是停留在看的表面层,有些实操的,或者结合业务场景的能力不太行,算是在坚持写写 blog,主要是被这个每周一篇的目标推着走,有时会比较焦虑,内容产出也还比较差,希望能在后面有些改善,可能会降低频率,只是觉得降低了也不一定能有比较好的提升,无法战胜自己的惰性,所以暂时还是坚持下这个目标吧,还有就是 coding 能力,有时候也应该刷刷题,提升思维敏捷度,大脑用太少可能生锈了,况且本来就不是很有优势,虽然失望也只能继续努力吧,日拱一卒,来日方长,加油吧~😔

+

还有就是跑步减肥了,截止今天,上半年跑了 136 公里了,因为疫情影响,农历年后是从 4 月 17 号开始跑的,去年跑到了 300 公里,奖励自己了一个手表(真的挺后悔的,还不如 200 块买个手表),今年希望可以能在这个基础上再进一步,一直跟领导说,跑步算是我坚持下来的唯一一个好习惯了,618 买了个跑步机,周末回家了可以不受天气影响的多跑跑,不过如果天气好可能还是会出去跑跑,跑步机跑道多少还是有点拘束,只是感觉可能是我还是吃得太多了🤦‍♂️,效果不是很明显,还在 80 这个坎徘徊,等于浪费了大半年,可能是年初的项目太费心力,压力比较大,吃得更多,是不是可以算工伤😄,这方面也需要好好调整,可以放得开一点,虽然不太可能一下子到位,但是总要去努力下,随着年龄成长总要承担更多,也要看得开一点,没法事事如愿,尽力就好了,减肥这个事情还在结合一些俯卧撑啥的,希望也能坚持下去,加油吧,不知道原话怎么说的,意思是人类最大的勇敢就是看透了人世间的苦难,仍然热爱生活。我当然没可能让内心变得这么强大,试着去努力吧,奥力给!

]]>
生活 - 年终总结 - 2019 + 年中总结 + 2020 生活 - 年终总结 - 2019 + 2020 + 年中总结 + +
+ + 2021 年中总结 + /2021/07/18/2021-%E5%B9%B4%E4%B8%AD%E6%80%BB%E7%BB%93/ + 又到半年总结时,第一次写总结类型的文章感觉挺好写的,但是后面总觉得这过去的一段时间所做的事情,能力上的成长低于预期,但是是需要总结下,找找问题,顺便展望下未来。

+

这一年做的最让自己满意的应该就是看了一些书,由折腾群洋总发起的读书打卡活动,到目前为止已经读完了这几本书,《cUrl 必知必会》,《古董局中局 1》,《古董局中局 2》,《算法图解》,《每天 5 分钟玩转 Kubernetes》《幸福了吗?》《高可用可伸缩微服务架构:基于 Dubbo、Spring Cloud和 Service Mesh》《Rust 权威指南》后面可以写个专题说说看的这些书,虽然每天打卡如果时间安排不好,并且看的书像 rust 这样比较难的话还是会有点小焦虑,不过也是个调整过程,一方面可以在白天就抽空看一会,然后也不必要每次都看很大一章,注重吸收。

+

技术上的成长的话,有一些比较小的长进吧,对于一些之前忽视的 synchronized,ThreadLocal 和 AQS 等知识点做了下查漏补缺了,然后多了解了一些 Java 垃圾回收的内容,但是在实操上还是比较欠缺,成型的技术方案,架构上所谓的优化也比较少,一些想法也还有考虑不周全的地方,还需要多花时间和心思去学习加强,特别是在目前已经有的基础上如何做系统深层次的优化,既不要是鸡毛蒜皮的,也不能出现一些不可接受的问题和故障,这是个很重要的课题,需要好好学习,后面考虑定一些周期性目标,两个月左右能有一些成果和总结。

+

另外一部分是自己的服务,因为 ucloud 的机器太贵就没续费了,所以都迁移到腾讯云的小机器上了,顺便折腾了一点点 traefik,但是还很不熟练,不太习惯这一套,一方面是 docker 还不习惯,这也加重了对这套环境的不适应,还是习惯裸机部署,另一方面就是 k8s 了,家里的机器还没虚拟化,没有很好的条件可以做实验,这也是读书打卡的一个没做好的点,整体的学习效果受限于深度和实操,后面是看都是用 traefik,也找到了一篇文章可以 traefik 转发到裸机应用,因为主仓库用的是裸机的 gogs。

+

还有就是运动减肥上,唉,这又是很大的一个痛点,基本没效果,只是还算稳定,昨天看到一个视频说还需要力量训练来增肌,以此可以提升基础代谢,打算往这个方向尝试下,因为今天没有疫情限制了,在 6 月底完成了 200 公里的跑步小目标,只是有些膝盖跟大腿根外侧不适,抽空得去看下医生,后面打算每天也能做点卷腹跟俯卧撑。

+

下半年还希望能继续多看看书,比很多网上各种乱七八糟的文章会好很多,结合豆瓣评分,找一些评价高一些的文章,但也不是说分稍低点的就不行,有些也看人是不是适合,一般 6 分以上评价比较多的就可以试试。

+]]>
+ + 生活 + 年中总结 + 2021 + + + 生活 + 2021 + 年中总结 + 技术 + 读书
@@ -115,485 +134,237 @@ - AQS篇二 之 Condition 浅析笔记 - /2021/02/21/AQS-%E4%B9%8B-Condition-%E6%B5%85%E6%9E%90%E7%AC%94%E8%AE%B0/ - Condition也是 AQS 中很重要的一块内容,可以先看段示例代码,这段代码应该来自于Doug Lea大大,可以在 javadoc 中的 condition 部分找到,其实大大原来写过基于 synchronized 实现的,后面我也贴下代码

-
import java.util.concurrent.locks.Condition;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReentrantLock;
-
-class BoundedBuffer {
-    final Lock lock = new ReentrantLock();
-    // condition 依赖于 lock 来产生
-    final Condition notFull = lock.newCondition();
-    final Condition notEmpty = lock.newCondition();
+    2022 年终总结
+    /2023/01/15/2022-%E5%B9%B4%E7%BB%88%E6%80%BB%E7%BB%93/
+    一年又一年,时间匆匆,这一年过得不太容易,很多事情都是来得猝不及防,很多规划也照例是没有完成,今年更多了一些,又是比较丧的一篇总结
工作上的变化让我多理解了一些社会跟职场的现实吧,可能的确是我不够优秀,也可能是其他,说回我自身,在工作中今年应该是收获比较一般的一年,不能说没有,对原先不熟悉的业务的掌握程度有了比较大的提升,只是问题依旧存在,也挺难推动完全改变,只能尽自己所能,而这一点也主要是在团队中的定位因为前面说的一些原因,在前期不明确,限制比较大,虽然现在并没有完全解决,但也有了一些明显的改善,如果明年继续为这家公司服务,希望能有所突破,在人心沟通上的技巧总是比较反感,可也是不得不使用或者说被迫学习使用的,LD说我的对错观太强了,拗不过来,希望能有所改变。
长远的规划上没有什么明确的想法,很容易否定原来的各种想法,见识过各种现实的残酷,明白以前的一些想法不够全面或者比较幼稚,想有更上一层楼的机会,只是不希望是通过自己不认可的方式。比较能接受的是通过提升自己的技术和执行力,能够有更进一步的可能。
技术上是挺失败的去年跟前年还是能看一些书,学一些东西,今年少了很多,可能对原来比较熟悉的都有些遗忘,最近有在改善博客的内容,能更多的是系列化的,由浅入深,只是还很不完善,没什么规划,体系上也还不完整,不过还是以mybatis作为一个开头,后续新开始的内容或者原先写过的相关的都能做个整理,不再是想到啥就写点啥。最近的一个重点是在k8s上,学习方式跟一些特别优秀的人比起来还是会慢一些,不过也是自己的方法,能够更深入的理解整个体系,并讲解出来,可能会尝试采用视频的方式,对一些比较好的内容做尝试,看看会不会有比较好的数据和反馈,在22年还苟着周更的独立技术博客也算是比较稀有了的,其他站的发布也要勤一些,形成所谓的“矩阵”。
跑步减肥这个么还是比较惨,22年只跑了368公里,比21年少了85公里,有一些客观但很多是主观的原因,还是需要跑起来,只是减肥也很迫切,体重比较大跑步还是有些压力的,买了动感单车,就是时间稍长屁股痛这个目前比较难解决,骑还是每天在骑就是强度跟时间不太够,要保证每天30分钟的量可能会比较好。
加油吧,愿23年家人和自己都健康,顺遂。大家也一样。

+]]>
+ + 生活 + 年终总结 + + + 生活 + 年终总结 + 2022 + 2023 + + + + AQS篇一 + /2021/02/14/AQS%E7%AF%87%E4%B8%80/ + 很多东西都是时看时新,而且时间长了也会忘,所以再来复习下,也会有一些新的角度看法这次来聊下AQS的内容,主要是这几个点,

+

第一个线程

第一个线程抢到锁了,此时state跟阻塞队列是怎么样的,其实这里是之前没理解对的地方

+
/**
+         * Fair version of tryAcquire.  Don't grant access unless
+         * recursive call or no waiters or is first.
+         */
+        protected final boolean tryAcquire(int acquires) {
+            final Thread current = Thread.currentThread();
+            int c = getState();
+            // 这里如果state还是0说明锁还空着
+            if (c == 0) {
+                // 因为是公平锁版本的,先去看下是否阻塞队列里有排着队的
+                if (!hasQueuedPredecessors() &&
+                    compareAndSetState(0, acquires)) {
+                    // 没有排队的,并且state使用cas设置成功的就标记当前占有锁的线程是我
+                    setExclusiveOwnerThread(current);
+                    // 然后其实就返回了,包括阻塞队列的head和tail节点和waitStatus都没有设置
+                    return true;
+                }
+            }
+            else if (current == getExclusiveOwnerThread()) {
+                int nextc = c + acquires;
+                if (nextc < 0)
+                    throw new Error("Maximum lock count exceeded");
+                setState(nextc);
+                return true;
+            }
+            // 这里就是第二个线程会返回false
+            return false;
+        }
+    }
- // 对象池子,put 跟 take 的就是这里的 - final Object[] items = new Object[100]; - int putptr, takeptr, count; +

第二个线程

当第二个线程进来的时候应该是怎么样,结合代码来看

+
/**
+     * Acquires in exclusive mode, ignoring interrupts.  Implemented
+     * by invoking at least once {@link #tryAcquire},
+     * returning on success.  Otherwise the thread is queued, possibly
+     * repeatedly blocking and unblocking, invoking {@link
+     * #tryAcquire} until success.  This method can be used
+     * to implement method {@link Lock#lock}.
+     *
+     * @param arg the acquire argument.  This value is conveyed to
+     *        {@link #tryAcquire} but is otherwise uninterpreted and
+     *        can represent anything you like.
+     */
+    public final void acquire(int arg) {
+        // 前面第一种情况是tryAcquire直接成功了,这个if判断第一个条件就是false,就不往下执行了
+        // 如果是第二个线程,第一个条件获取锁不成功,条件判断!tryAcquire(arg) == true,就会走
+        // acquireQueued(addWaiter(Node.EXCLUSIVE), arg)
+        if (!tryAcquire(arg) &&
+            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
+            selfInterrupt();
+    }
- // 生产 - public void put(Object x) throws InterruptedException { - // 这里也说明了,需要先拥有锁 - lock.lock(); - try { - while (count == items.length) - notFull.await(); // 队列已满,等待,直到 not full 才能继续生产 - items[putptr] = x; - if (++putptr == items.length) putptr = 0; - ++count; - notEmpty.signal(); // 生产成功,队列已经 not empty 了,发个通知出去 - } finally { - lock.unlock(); +

然后来看下addWaiter的逻辑

+
/**
+     * Creates and enqueues node for current thread and given mode.
+     *
+     * @param mode Node.EXCLUSIVE for exclusive, Node.SHARED for shared
+     * @return the new node
+     */
+    private Node addWaiter(Node mode) {
+        // 这里是包装成一个node
+        Node node = new Node(Thread.currentThread(), mode);
+        // Try the fast path of enq; backup to full enq on failure
+        // 最快的方式就是把当前线程的节点放在阻塞队列的最后
+        Node pred = tail;
+        // 只有当tail,也就是pred不为空的时候可以直接接上
+        if (pred != null) {
+            node.prev = pred;
+            // 如果这里cas成功了,就直接接上返回了
+            if (compareAndSetTail(pred, node)) {
+                pred.next = node;
+                return node;
+            }
         }
-    }
+        // 不然就会继续走到这里
+        enq(node);
+        return node;
+    }
- // 消费 - public Object take() throws InterruptedException { - lock.lock(); - try { - while (count == 0) - notEmpty.await(); // 队列为空,等待,直到队列 not empty,才能继续消费 - Object x = items[takeptr]; - if (++takeptr == items.length) takeptr = 0; - --count; - notFull.signal(); // 被我消费掉一个,队列 not full 了,发个通知出去 - return x; - } finally { - lock.unlock(); +

然后就是enq的逻辑了

+
/**
+     * Inserts node into queue, initializing if necessary. See picture above.
+     * @param node the node to insert
+     * @return node's predecessor
+     */
+    private Node enq(final Node node) {
+        for (;;) {
+            // 如果状态没变化的话,tail这时还是null的
+            Node t = tail;
+            if (t == null) { // Must initialize
+                // 这里就会初始化头结点,就是个空节点
+                if (compareAndSetHead(new Node()))
+                    // tail也赋值成head
+                    tail = head;
+            } else {
+                // 这里就设置tail了
+                node.prev = t;
+                if (compareAndSetTail(t, node)) {
+                    t.next = node;
+                    return t;
+                }
+            }
         }
-    }
-}
+ }
-

介绍下 Condition 的结构

-
public class ConditionObject implements Condition, java.io.Serializable {
-        private static final long serialVersionUID = 1173984872572414699L;
-        /** First node of condition queue. */
-        private transient Node firstWaiter;
-        /** Last node of condition queue. */
-        private transient Node lastWaiter;
-

主要的就这么点,而且也复用了 AQS 阻塞队列或者大大叫 lock queue中同样的 Node 节点,只不过它没有使用其中的双向队列,也就是prev 和 next,而是在 Node 中的 nextWaiter,所以只是个单向的队列,没使用 next 其实还有个用处,后面会提到,看下结构的示意图

然后主要是看两个方法,awaitsignal,
先来看下 await

-
/**
- * Implements interruptible condition wait.
- * <ol>
- * <li> If current thread is interrupted, throw InterruptedException.
- * <li> Save lock state returned by {@link #getState}.
- * <li> Invoke {@link #release} with saved state as argument,
- *      throwing IllegalMonitorStateException if it fails.
- * <li> Block until signalled or interrupted.
- * <li> Reacquire by invoking specialized version of
- *      {@link #acquire} with saved state as argument.
- * <li> If interrupted while blocked in step 4, throw InterruptedException.
- * </ol>
- */
-public final void await() throws InterruptedException {
-    if (Thread.interrupted())
-        throw new InterruptedException();
-
-    // 将当前节点包装成一个  condition waiter node 节点
-    Node node = addConditionWaiter();
-
-    // 完全释放占有的锁,这里需要是占有锁的线程
-    int savedState = fullyRelease(node);
-    int interruptMode = 0;
-
-    // 判断下是否在阻塞队列中,因为有可能被其他节点从等待队列移动到阻塞队列
-    while (!isOnSyncQueue(node)) {
-        // park等待,等待被唤醒
-        LockSupport.park(this);
-        if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
-            break;
-    }
-
-    // 被唤醒后进入阻塞队列,等待获取锁,这里继续用了fullyRelease返回的 state
-    if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
-        interruptMode = REINTERRUPT;
-    if (node.nextWaiter != null) // clean up if cancelled
-        unlinkCancelledWaiters();
-    if (interruptMode != 0)
-        reportInterruptAfterWait(interruptMode);
-}
-

添加条件队列节点

+

所以从这里可以看出来,其实head头结点不是个真实的带有线程的节点,并且不是在第一个线程进来的时候设置的

+

解锁

通过代码来看下

/**
- * Adds a new waiter to wait queue.
- * @return its new wait node
- */
-private Node addConditionWaiter() {
-    Node t = lastWaiter;
-    // If lastWaiter is cancelled, clean out.
-    // 如果节点已经不是 CONDITION 状态了,表示已经取消了
-    if (t != null && t.waitStatus != Node.CONDITION) {
-        // 把等待队列中取消的节点清理出去
-        unlinkCancelledWaiters();
-        t = lastWaiter;
+     * Attempts to release this lock.
+     *
+     * <p>If the current thread is the holder of this lock then the hold
+     * count is decremented.  If the hold count is now zero then the lock
+     * is released.  If the current thread is not the holder of this
+     * lock then {@link IllegalMonitorStateException} is thrown.
+     *
+     * @throws IllegalMonitorStateException if the current thread does not
+     *         hold this lock
+     */
+    public void unlock() {
+        // 释放锁
+        sync.release(1);
     }
-    // 把当前线程包装成waitStatus=CONDITION 的节点
-    Node node = new Node(Thread.currentThread(), Node.CONDITION);
-    // 没有 lastWaiter 节点,直接是 firstWaiter
-    if (t == null)
-        firstWaiter = node;
-    else
-    // 不然就接在 lastWaiter 后面
-        t.nextWaiter = node;
-    // 当前节点就会变成新的 lastWaiter
-    lastWaiter = node;
-    return node;
-}
-

清理取消的节点

-
/**
- * Unlinks cancelled waiter nodes from condition queue.
- * Called only while holding lock. This is called when
- * cancellation occurred during condition wait, and upon
- * insertion of a new waiter when lastWaiter is seen to have
- * been cancelled. This method is needed to avoid garbage
- * retention in the absence of signals. So even though it may
- * require a full traversal, it comes into play only when
- * timeouts or cancellations occur in the absence of
- * signals. It traverses all nodes rather than stopping at a
- * particular target to unlink all pointers to garbage nodes
- * without requiring many re-traversals during cancellation
- * storms.
- */
-private void unlinkCancelledWaiters() {
-    Node t = firstWaiter;
-    Node trail = null;
-    // 循环遍历单向链表的节点,如果状态不是 CONDITION 就清出去
-    while (t != null) {
-        Node next = t.nextWaiter;
-        // 循环链表操作,清掉取消的节点
-        if (t.waitStatus != Node.CONDITION) {
-            t.nextWaiter = null;
-            if (trail == null)
-                firstWaiter = next;
-            else
-                trail.nextWaiter = next;
-            if (next == null)
-                lastWaiter = trail;
+/**
+     * Releases in exclusive mode.  Implemented by unblocking one or
+     * more threads if {@link #tryRelease} returns true.
+     * This method can be used to implement method {@link Lock#unlock}.
+     *
+     * @param arg the release argument.  This value is conveyed to
+     *        {@link #tryRelease} but is otherwise uninterpreted and
+     *        can represent anything you like.
+     * @return the value returned from {@link #tryRelease}
+     */
+    public final boolean release(int arg) {
+        // 尝试去释放
+        if (tryRelease(arg)) {
+            Node h = head;
+            if (h != null && h.waitStatus != 0)
+                unparkSuccessor(h);
+            return true;
         }
-        else
-            trail = t;
-        t = next;
+        return false;
     }
-}
+protected final boolean tryRelease(int releases) { + int c = getState() - releases; + if (Thread.currentThread() != getExclusiveOwnerThread()) + throw new IllegalMonitorStateException(); + boolean free = false; + // 判断是否完全释放锁,因为可重入 + if (c == 0) { + free = true; + setExclusiveOwnerThread(null); + } + setState(c); + return free; + } +// 这段代码和上面的一致,只是为了顺序性,又拷下来看下 -

完全释放锁

-
/**
- * Invokes release with current state value; returns saved state.
- * Cancels node and throws exception on failure.
- * @param node the condition node for this wait
- * @return previous sync state
- */
-final int fullyRelease(Node node) {
-    boolean failed = true;
-    try {
-        // 获取下当前的 state 值,因为是可重入的,所以这个值要保存下来
-        int savedState = getState();
-        // 这里还包含比较多操作,不过跟前面分析 AQS 的释放比较类似,不深入了
-        if (release(savedState)) {
-            failed = false;
-            // 返回这个值
-            return savedState;
-        } else {
-            throw new IllegalMonitorStateException();
+public final boolean release(int arg) {
+        // 尝试去释放,如果是完全释放,返回的就是true,否则是false
+        if (tryRelease(arg)) {
+            Node h = head;
+            // 这里判断头结点是否为空以及waitStatus的状态,前面说了head节点其实是
+            // 在第二个线程进来的时候初始化的,如果是空的话说明没后续节点,并且waitStatus
+            // 也表示了后续的等待状态
+            if (h != null && h.waitStatus != 0)
+                unparkSuccessor(h);
+            return true;
         }
-    } finally {
-        if (failed)
-            node.waitStatus = Node.CANCELLED;
-    }
-}
-

判断是否在阻塞队列中

-
/**
- * Returns true if a node, always one that was initially placed on
- * a condition queue, is now waiting to reacquire on sync queue.
- * @param node the node
- * @return true if is reacquiring
- */
-final boolean isOnSyncQueue(Node node) {
-    // 如果waitStatus 是 CONDITION 或者没有 prev 前置节点肯定就不在
-    if (node.waitStatus == Node.CONDITION || node.prev == null)
         return false;
-    // 这里就是我前面提到的 next 的作用
-    if (node.next != null) // If has successor, it must be on queue
-        return true;
-    // 从 tail 开始找,是否在阻塞队列中
-    /*
-     * node.prev can be non-null, but not yet on queue because
-     * the CAS to place it on queue can fail. So we have to
-     * traverse from tail to make sure it actually made it.  It
-     * will always be near the tail in calls to this method, and
-     * unless the CAS failed (which is unlikely), it will be
-     * there, so we hardly ever traverse much.
-     */
-    return findNodeFromTail(node);
-}
-/**
- * Returns true if node is on sync queue by searching backwards from tail.
- * Called only when needed by isOnSyncQueue.
- * @return true if present
- */
-private boolean findNodeFromTail(Node node) {
-    Node t = tail;
-    // 从 tail 开始,从后往前找
-    for (;;) {
-        if (t == node)
-            return true;
-        if (t == null)
-            return false;
-        t = t.prev;
     }
-}
-

await 的逻辑差不多就是这样子,主要的就是把自己包成一个 Node 节点,waitStatus 的状态是 CONDITION,挂在等待队列的最后,然后完全释放锁,park 等待

-

signal

/**
- * Moves the longest-waiting thread, if one exists, from the
- * wait queue for this condition to the wait queue for the
- * owning lock.
- *
- * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
- *         returns {@code false}
- */
-public final void signal() {
-    if (!isHeldExclusively())
-        throw new IllegalMonitorStateException();
-    // firstWaiter 肯定是最早开始等待的
-    Node first = firstWaiter;
-    // 如果不为空就唤醒
-    if (first != null)
-        doSignal(first);
-}
+
 /**
- * Removes and transfers nodes until hit non-cancelled one or
- * null. Split out from signal in part to encourage compilers
- * to inline the case of no waiters.
- * @param first (non-null) the first node on condition queue
- */
-private void doSignal(Node first) {
-    do {
-        // 因为要去唤醒 first 节点了,firstWaiter 需要再从后面找一个
-        // 并且判断是否为空,如果是空的话就直接可以把 lastWaiter 设置成空了
-        if ( (firstWaiter = first.nextWaiter) == null)
-            lastWaiter = null;
-        //  first 不需要继续保存后面的 waiter 了,因为 firstWaiter 已经是 first 的后置节点了
-        first.nextWaiter = null;
-    // 如果 first 节点转移不成功,并且 firstWaiter 节点不为空,则继续进入循环
-    } while (!transferForSignal(first) &&
-             (first = firstWaiter) != null);
-}
-/**
- * Transfers a node from a condition queue onto sync queue.
- * Returns true if successful.
- * @param node the node
- * @return true if successfully transferred (else the node was
- * cancelled before signal)
- */
-final boolean transferForSignal(Node node) {
-    /*
-     * If cannot change waitStatus, the node has been cancelled.
-     */
-    // 如果状态已经不是 CONDITION 就不会设置成功,返回 false
-    if (!compareAndSetWaitStatus(node, Node.CONDITION, 0))
-        return false;
-    /*
-     * Splice onto queue and try to set waitStatus of predecessor to
-     * indicate that thread is (probably) waiting. If cancelled or
-     * attempt to set waitStatus fails, wake up to resync (in which
-     * case the waitStatus can be transiently and harmlessly wrong).
+     * Wakes up node's successor, if one exists.
+     *
+     * @param node the node
      */
-    // 调用跟aqs 第一篇中一样的 enq 方法进入阻塞队列,返回入队后的前一节点
-    Node p = enq(node);
-    int ws = p.waitStatus;
-    // 将前置节点状态设置成SIGNAL,表示后面有节点在等了
-    if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL))
-        LockSupport.unpark(node.thread);
-    // 返回 true,上一个方法的循环就退出了
-    return true;
-}
-

这里其实就是把 condition 等待队列的第一个未取消的节点入队到阻塞队列去争锁

-

附录

synchronized 版的 BoundedBuffer

-
/*
-  File: BoundedBuffer.java
-
-  Originally written by Doug Lea and released into the public domain.
-  This may be used for any purposes whatsoever without acknowledgment.
-  Thanks for the assistance and support of Sun Microsystems Labs,
-  and everyone contributing, testing, and using this code.
-
-  History:
-  Date       Who                What
-  11Jun1998  dl               Create public version
-  17Jul1998  dl               Simplified by eliminating wait counts
-  25aug1998  dl               added peek
-   5May1999  dl               replace % with conditional (slightly faster)
-*/
-
-package EDU.oswego.cs.dl.util.concurrent;
-
-/**
- * Efficient array-based bounded buffer class.
- * Adapted from CPJ, chapter 8, which describes design.
- * <p>[<a href="http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html"> Introduction to this package. </a>] <p>
- **/
-
-public class BoundedBuffer implements BoundedChannel {
-
-  protected final Object[]  array_;      // the elements
-
-  protected int takePtr_ = 0;            // circular indices
-  protected int putPtr_ = 0;       
-
-  protected int usedSlots_ = 0;          // length
-  protected int emptySlots_;             // capacity - length
-
-  /**
-   * Helper monitor to handle puts. 
-   **/
-  protected final Object putMonitor_ = new Object();
-
-  /**
-   * Create a BoundedBuffer with the given capacity.
-   * @exception IllegalArgumentException if capacity less or equal to zero
-   **/
-  public BoundedBuffer(int capacity) throws IllegalArgumentException {
-    if (capacity <= 0) throw new IllegalArgumentException();
-    array_ = new Object[capacity];
-    emptySlots_ = capacity;
-  }
-
-  /**
-   * Create a buffer with the current default capacity
-   **/
-
-  public BoundedBuffer() { 
-    this(DefaultChannelCapacity.get()); 
-  }
-
-  /** 
-   * Return the number of elements in the buffer.
-   * This is only a snapshot value, that may change
-   * immediately after returning.
-   **/
-  public synchronized int size() { return usedSlots_; }
-
-  public int capacity() { return array_.length; }
-
-  protected void incEmptySlots() {
-    synchronized(putMonitor_) {
-      ++emptySlots_;
-      putMonitor_.notify();
-    }
-  }
-
-  protected synchronized void incUsedSlots() {
-    ++usedSlots_;
-    notify();
-  }
-
-  protected final void insert(Object x) { // mechanics of put
-    --emptySlots_;
-    array_[putPtr_] = x;
-    if (++putPtr_ >= array_.length) putPtr_ = 0;
-  }
-
-  protected final Object extract() { // mechanics of take
-    --usedSlots_;
-    Object old = array_[takePtr_];
-    array_[takePtr_] = null;
-    if (++takePtr_ >= array_.length) takePtr_ = 0;
-    return old;
-  }
-
-  public Object peek() {
-    synchronized(this) {
-      if (usedSlots_ > 0)
-        return array_[takePtr_];
-      else
-        return null;
-    }
-  }
-
-
-  public void put(Object x) throws InterruptedException {
-    if (x == null) throw new IllegalArgumentException();
-    if (Thread.interrupted()) throw new InterruptedException();
-
-    synchronized(putMonitor_) {
-      while (emptySlots_ <= 0) {
-	try { putMonitor_.wait(); }
-        catch (InterruptedException ex) {
-          putMonitor_.notify();
-          throw ex;
-        }
-      }
-      insert(x);
-    }
-    incUsedSlots();
-  }
-
-  public boolean offer(Object x, long msecs) throws InterruptedException {
-    if (x == null) throw new IllegalArgumentException();
-    if (Thread.interrupted()) throw new InterruptedException();
+// 唤醒后继节点
+    private void unparkSuccessor(Node node) {
+        /*
+         * If status is negative (i.e., possibly needing signal) try
+         * to clear in anticipation of signalling.  It is OK if this
+         * fails or if status is changed by waiting thread.
+         */
+        int ws = node.waitStatus;
+        if (ws < 0)
+            compareAndSetWaitStatus(node, ws, 0);
 
-    synchronized(putMonitor_) {
-      long start = (msecs <= 0)? 0 : System.currentTimeMillis();
-      long waitTime = msecs;
-      while (emptySlots_ <= 0) {
-        if (waitTime <= 0) return false;
-	try { putMonitor_.wait(waitTime); }
-        catch (InterruptedException ex) {
-          putMonitor_.notify();
-          throw ex;
+        /*
+         * Thread to unpark is held in successor, which is normally
+         * just the next node.  But if cancelled or apparently null,
+         * traverse backwards from tail to find the actual
+         * non-cancelled successor.
+         */
+        Node s = node.next;
+        // 如果后继节点是空或者当前节点取消等待了
+        if (s == null || s.waitStatus > 0) {
+            s = null;
+            // 从后往前找,找到非取消的节点,注意这里不是找到就退出,而是一直找到头
+            // 所以不必担心中间有取消的
+            for (Node t = tail; t != null && t != node; t = t.prev)
+                if (t.waitStatus <= 0)
+                    s = t;
         }
-        waitTime = msecs - (System.currentTimeMillis() - start);
-      }
-      insert(x);
-    }
-    incUsedSlots();
-    return true;
-  }
-
-
+        if (s != null)
+            // 将其唤醒
+            LockSupport.unpark(s.thread);
+    }
- public Object take() throws InterruptedException { - if (Thread.interrupted()) throw new InterruptedException(); - Object old = null; - synchronized(this) { - while (usedSlots_ <= 0) { - try { wait(); } - catch (InterruptedException ex) { - notify(); - throw ex; - } - } - old = extract(); - } - incEmptySlots(); - return old; - } - public Object poll(long msecs) throws InterruptedException { - if (Thread.interrupted()) throw new InterruptedException(); - Object old = null; - synchronized(this) { - long start = (msecs <= 0)? 0 : System.currentTimeMillis(); - long waitTime = msecs; - - while (usedSlots_ <= 0) { - if (waitTime <= 0) return null; - try { wait(waitTime); } - catch (InterruptedException ex) { - notify(); - throw ex; - } - waitTime = msecs - (System.currentTimeMillis() - start); - } - old = extract(); - } - incEmptySlots(); - return old; - } -} -
]]> Java @@ -604,30 +375,6 @@ 并发 j.u.c aqs - condition - await - signal - lock - unlock - - - - 2020年中总结 - /2020/07/11/2020%E5%B9%B4%E4%B8%AD%E6%80%BB%E7%BB%93/ - 很快2020 年就过了一半了,而且是今年这么特殊的一年,很多事情都发生的出乎意料,疫情这个绕不过去的话题,之前写了点比较愤青的文字,感觉不太适合发出来就烂在草稿箱里吧,这个目前一大影响估计是今年都没办法完全摘下口罩了,前面几个月来回杭州都开车,因为彭埠大桥不通行了,实在是非常不方便,每条路都灰常堵,心累,吐槽下杭州的交通规划和交警同志,工作实在做的不咋地。

-

另外一件是就是蜗壳,从前不知道黝黑蜗壳是啥意思,只是经常会在他的视频里看到,大学的时候在缘网下了一个集锦,炒鸡帅气,各种空接扣篮,越来越能明白那句“你永远不知道意外和明天不知道哪个会先来,且行且珍惜”的含义,只是听了很多道理,依然活不好这一生,知易行难,王阳明真的是这方面的大师,有空可以看看这方面的书,一直想写写我跟篮球跟蜗壳的这十几年,争取能早日写好吧,不过得找个静得下来的时候写。

-

正事方面上半年还是挺让人失望的,没有达成一些目标,应该还是能力不足吧,技术方面分析一下还是停留在看的表面层,有些实操的,或者结合业务场景的能力不太行,算是在坚持写写 blog,主要是被这个每周一篇的目标推着走,有时会比较焦虑,内容产出也还比较差,希望能在后面有些改善,可能会降低频率,只是觉得降低了也不一定能有比较好的提升,无法战胜自己的惰性,所以暂时还是坚持下这个目标吧,还有就是 coding 能力,有时候也应该刷刷题,提升思维敏捷度,大脑用太少可能生锈了,况且本来就不是很有优势,虽然失望也只能继续努力吧,日拱一卒,来日方长,加油吧~😔

-

还有就是跑步减肥了,截止今天,上半年跑了 136 公里了,因为疫情影响,农历年后是从 4 月 17 号开始跑的,去年跑到了 300 公里,奖励自己了一个手表(真的挺后悔的,还不如 200 块买个手表),今年希望可以能在这个基础上再进一步,一直跟领导说,跑步算是我坚持下来的唯一一个好习惯了,618 买了个跑步机,周末回家了可以不受天气影响的多跑跑,不过如果天气好可能还是会出去跑跑,跑步机跑道多少还是有点拘束,只是感觉可能是我还是吃得太多了🤦‍♂️,效果不是很明显,还在 80 这个坎徘徊,等于浪费了大半年,可能是年初的项目太费心力,压力比较大,吃得更多,是不是可以算工伤😄,这方面也需要好好调整,可以放得开一点,虽然不太可能一下子到位,但是总要去努力下,随着年龄成长总要承担更多,也要看得开一点,没法事事如愿,尽力就好了,减肥这个事情还在结合一些俯卧撑啥的,希望也能坚持下去,加油吧,不知道原话怎么说的,意思是人类最大的勇敢就是看透了人世间的苦难,仍然热爱生活。我当然没可能让内心变得这么强大,试着去努力吧,奥力给!

-]]>
- - 生活 - 年中总结 - 2020 - - - 生活 - 2020 - 年中总结
@@ -799,234 +546,6 @@ public: c++ - - AQS篇一 - /2021/02/14/AQS%E7%AF%87%E4%B8%80/ - 很多东西都是时看时新,而且时间长了也会忘,所以再来复习下,也会有一些新的角度看法这次来聊下AQS的内容,主要是这几个点,

-

第一个线程

第一个线程抢到锁了,此时state跟阻塞队列是怎么样的,其实这里是之前没理解对的地方

-
/**
-         * Fair version of tryAcquire.  Don't grant access unless
-         * recursive call or no waiters or is first.
-         */
-        protected final boolean tryAcquire(int acquires) {
-            final Thread current = Thread.currentThread();
-            int c = getState();
-            // 这里如果state还是0说明锁还空着
-            if (c == 0) {
-                // 因为是公平锁版本的,先去看下是否阻塞队列里有排着队的
-                if (!hasQueuedPredecessors() &&
-                    compareAndSetState(0, acquires)) {
-                    // 没有排队的,并且state使用cas设置成功的就标记当前占有锁的线程是我
-                    setExclusiveOwnerThread(current);
-                    // 然后其实就返回了,包括阻塞队列的head和tail节点和waitStatus都没有设置
-                    return true;
-                }
-            }
-            else if (current == getExclusiveOwnerThread()) {
-                int nextc = c + acquires;
-                if (nextc < 0)
-                    throw new Error("Maximum lock count exceeded");
-                setState(nextc);
-                return true;
-            }
-            // 这里就是第二个线程会返回false
-            return false;
-        }
-    }
- -

第二个线程

当第二个线程进来的时候应该是怎么样,结合代码来看

-
/**
-     * Acquires in exclusive mode, ignoring interrupts.  Implemented
-     * by invoking at least once {@link #tryAcquire},
-     * returning on success.  Otherwise the thread is queued, possibly
-     * repeatedly blocking and unblocking, invoking {@link
-     * #tryAcquire} until success.  This method can be used
-     * to implement method {@link Lock#lock}.
-     *
-     * @param arg the acquire argument.  This value is conveyed to
-     *        {@link #tryAcquire} but is otherwise uninterpreted and
-     *        can represent anything you like.
-     */
-    public final void acquire(int arg) {
-        // 前面第一种情况是tryAcquire直接成功了,这个if判断第一个条件就是false,就不往下执行了
-        // 如果是第二个线程,第一个条件获取锁不成功,条件判断!tryAcquire(arg) == true,就会走
-        // acquireQueued(addWaiter(Node.EXCLUSIVE), arg)
-        if (!tryAcquire(arg) &&
-            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
-            selfInterrupt();
-    }
- -

然后来看下addWaiter的逻辑

-
/**
-     * Creates and enqueues node for current thread and given mode.
-     *
-     * @param mode Node.EXCLUSIVE for exclusive, Node.SHARED for shared
-     * @return the new node
-     */
-    private Node addWaiter(Node mode) {
-        // 这里是包装成一个node
-        Node node = new Node(Thread.currentThread(), mode);
-        // Try the fast path of enq; backup to full enq on failure
-        // 最快的方式就是把当前线程的节点放在阻塞队列的最后
-        Node pred = tail;
-        // 只有当tail,也就是pred不为空的时候可以直接接上
-        if (pred != null) {
-            node.prev = pred;
-            // 如果这里cas成功了,就直接接上返回了
-            if (compareAndSetTail(pred, node)) {
-                pred.next = node;
-                return node;
-            }
-        }
-        // 不然就会继续走到这里
-        enq(node);
-        return node;
-    }
- -

然后就是enq的逻辑了

-
/**
-     * Inserts node into queue, initializing if necessary. See picture above.
-     * @param node the node to insert
-     * @return node's predecessor
-     */
-    private Node enq(final Node node) {
-        for (;;) {
-            // 如果状态没变化的话,tail这时还是null的
-            Node t = tail;
-            if (t == null) { // Must initialize
-                // 这里就会初始化头结点,就是个空节点
-                if (compareAndSetHead(new Node()))
-                    // tail也赋值成head
-                    tail = head;
-            } else {
-                // 这里就设置tail了
-                node.prev = t;
-                if (compareAndSetTail(t, node)) {
-                    t.next = node;
-                    return t;
-                }
-            }
-        }
-    }
- -

所以从这里可以看出来,其实head头结点不是个真实的带有线程的节点,并且不是在第一个线程进来的时候设置的

-

解锁

通过代码来看下

-
/**
-     * Attempts to release this lock.
-     *
-     * <p>If the current thread is the holder of this lock then the hold
-     * count is decremented.  If the hold count is now zero then the lock
-     * is released.  If the current thread is not the holder of this
-     * lock then {@link IllegalMonitorStateException} is thrown.
-     *
-     * @throws IllegalMonitorStateException if the current thread does not
-     *         hold this lock
-     */
-    public void unlock() {
-        // 释放锁
-        sync.release(1);
-    }
-/**
-     * Releases in exclusive mode.  Implemented by unblocking one or
-     * more threads if {@link #tryRelease} returns true.
-     * This method can be used to implement method {@link Lock#unlock}.
-     *
-     * @param arg the release argument.  This value is conveyed to
-     *        {@link #tryRelease} but is otherwise uninterpreted and
-     *        can represent anything you like.
-     * @return the value returned from {@link #tryRelease}
-     */
-    public final boolean release(int arg) {
-        // 尝试去释放
-        if (tryRelease(arg)) {
-            Node h = head;
-            if (h != null && h.waitStatus != 0)
-                unparkSuccessor(h);
-            return true;
-        }
-        return false;
-    }
-protected final boolean tryRelease(int releases) {
-            int c = getState() - releases;
-            if (Thread.currentThread() != getExclusiveOwnerThread())
-                throw new IllegalMonitorStateException();
-            boolean free = false;
-    		// 判断是否完全释放锁,因为可重入
-            if (c == 0) {
-                free = true;
-                setExclusiveOwnerThread(null);
-            }
-            setState(c);
-            return free;
-        }
-// 这段代码和上面的一致,只是为了顺序性,又拷下来看下
-
-public final boolean release(int arg) {
-        // 尝试去释放,如果是完全释放,返回的就是true,否则是false
-        if (tryRelease(arg)) {
-            Node h = head;
-            // 这里判断头结点是否为空以及waitStatus的状态,前面说了head节点其实是
-            // 在第二个线程进来的时候初始化的,如果是空的话说明没后续节点,并且waitStatus
-            // 也表示了后续的等待状态
-            if (h != null && h.waitStatus != 0)
-                unparkSuccessor(h);
-            return true;
-        }
-        return false;
-    }
-
-/**
-     * Wakes up node's successor, if one exists.
-     *
-     * @param node the node
-     */
-// 唤醒后继节点
-    private void unparkSuccessor(Node node) {
-        /*
-         * If status is negative (i.e., possibly needing signal) try
-         * to clear in anticipation of signalling.  It is OK if this
-         * fails or if status is changed by waiting thread.
-         */
-        int ws = node.waitStatus;
-        if (ws < 0)
-            compareAndSetWaitStatus(node, ws, 0);
-
-        /*
-         * Thread to unpark is held in successor, which is normally
-         * just the next node.  But if cancelled or apparently null,
-         * traverse backwards from tail to find the actual
-         * non-cancelled successor.
-         */
-        Node s = node.next;
-        // 如果后继节点是空或者当前节点取消等待了
-        if (s == null || s.waitStatus > 0) {
-            s = null;
-            // 从后往前找,找到非取消的节点,注意这里不是找到就退出,而是一直找到头
-            // 所以不必担心中间有取消的
-            for (Node t = tail; t != null && t != node; t = t.prev)
-                if (t.waitStatus <= 0)
-                    s = t;
-        }
-        if (s != null)
-            // 将其唤醒
-            LockSupport.unpark(s.thread);
-    }
- - - - -]]>
- - Java - 并发 - - - java - 并发 - j.u.c - aqs - -
Apollo 如何获取当前环境 /2022/09/04/Apollo-%E5%A6%82%E4%BD%95%E8%8E%B7%E5%8F%96%E5%BD%93%E5%89%8D%E7%8E%AF%E5%A2%83/ @@ -1501,18 +1020,71 @@ public: - Comparator使用小记 - /2020/04/05/Comparator%E4%BD%BF%E7%94%A8%E5%B0%8F%E8%AE%B0/ - 在Java8的stream之前,将对象进行排序的时候,可能需要对象实现Comparable接口,或者自己实现一个Comparator,

-

比如这样子

-

我的对象是Entity

-
public class Entity {
-
-    private Long id;
+    Clone Graph Part I
+    /2014/12/30/Clone-Graph-Part-I/
+    problem
Clone a graph. Input is a Node pointer. Return the Node pointer of the cloned graph.
 
-    private Long sortValue;
+A graph is defined below:
+struct Node {
+vector neighbors;
+}
- public Long getId() { + +

code

typedef unordered_map<Node *, Node *> Map;
+ 
+Node *clone(Node *graph) {
+    if (!graph) return NULL;
+ 
+    Map map;
+    queue<Node *> q;
+    q.push(graph);
+ 
+    Node *graphCopy = new Node();
+    map[graph] = graphCopy;
+ 
+    while (!q.empty()) {
+        Node *node = q.front();
+        q.pop();
+        int n = node->neighbors.size();
+        for (int i = 0; i < n; i++) {
+            Node *neighbor = node->neighbors[i];
+            // no copy exists
+            if (map.find(neighbor) == map.end()) {
+                Node *p = new Node();
+                map[node]->neighbors.push_back(p);
+                map[neighbor] = p;
+                q.push(neighbor);
+            } else {     // a copy already exists
+                map[node]->neighbors.push_back(map[neighbor]);
+            }
+        }
+    }
+ 
+    return graphCopy;
+}
+

anlysis

using the Breadth-first traversal
and use a map to save the neighbors not to be duplicated.

+]]>
+ + leetcode + + + leetcode + C++ + + + + Comparator使用小记 + /2020/04/05/Comparator%E4%BD%BF%E7%94%A8%E5%B0%8F%E8%AE%B0/ + 在Java8的stream之前,将对象进行排序的时候,可能需要对象实现Comparable接口,或者自己实现一个Comparator,

+

比如这样子

+

我的对象是Entity

+
public class Entity {
+
+    private Long id;
+
+    private Long sortValue;
+
+    public Long getId() {
         return id;
     }
 
@@ -1601,97 +1173,6 @@ public:
         nullsfirst
       
   
-  
-    Clone Graph Part I
-    /2014/12/30/Clone-Graph-Part-I/
-    problem
Clone a graph. Input is a Node pointer. Return the Node pointer of the cloned graph.
-
-A graph is defined below:
-struct Node {
-vector neighbors;
-}
- - -

code

typedef unordered_map<Node *, Node *> Map;
- 
-Node *clone(Node *graph) {
-    if (!graph) return NULL;
- 
-    Map map;
-    queue<Node *> q;
-    q.push(graph);
- 
-    Node *graphCopy = new Node();
-    map[graph] = graphCopy;
- 
-    while (!q.empty()) {
-        Node *node = q.front();
-        q.pop();
-        int n = node->neighbors.size();
-        for (int i = 0; i < n; i++) {
-            Node *neighbor = node->neighbors[i];
-            // no copy exists
-            if (map.find(neighbor) == map.end()) {
-                Node *p = new Node();
-                map[node]->neighbors.push_back(p);
-                map[neighbor] = p;
-                q.push(neighbor);
-            } else {     // a copy already exists
-                map[node]->neighbors.push_back(map[neighbor]);
-            }
-        }
-    }
- 
-    return graphCopy;
-}
-

anlysis

using the Breadth-first traversal
and use a map to save the neighbors not to be duplicated.

-]]>
- - leetcode - - - C++ - leetcode - -
- - 2022 年终总结 - /2023/01/15/2022-%E5%B9%B4%E7%BB%88%E6%80%BB%E7%BB%93/ - 一年又一年,时间匆匆,这一年过得不太容易,很多事情都是来得猝不及防,很多规划也照例是没有完成,今年更多了一些,又是比较丧的一篇总结
工作上的变化让我多理解了一些社会跟职场的现实吧,可能的确是我不够优秀,也可能是其他,说回我自身,在工作中今年应该是收获比较一般的一年,不能说没有,对原先不熟悉的业务的掌握程度有了比较大的提升,只是问题依旧存在,也挺难推动完全改变,只能尽自己所能,而这一点也主要是在团队中的定位因为前面说的一些原因,在前期不明确,限制比较大,虽然现在并没有完全解决,但也有了一些明显的改善,如果明年继续为这家公司服务,希望能有所突破,在人心沟通上的技巧总是比较反感,可也是不得不使用或者说被迫学习使用的,LD说我的对错观太强了,拗不过来,希望能有所改变。
长远的规划上没有什么明确的想法,很容易否定原来的各种想法,见识过各种现实的残酷,明白以前的一些想法不够全面或者比较幼稚,想有更上一层楼的机会,只是不希望是通过自己不认可的方式。比较能接受的是通过提升自己的技术和执行力,能够有更进一步的可能。
技术上是挺失败的去年跟前年还是能看一些书,学一些东西,今年少了很多,可能对原来比较熟悉的都有些遗忘,最近有在改善博客的内容,能更多的是系列化的,由浅入深,只是还很不完善,没什么规划,体系上也还不完整,不过还是以mybatis作为一个开头,后续新开始的内容或者原先写过的相关的都能做个整理,不再是想到啥就写点啥。最近的一个重点是在k8s上,学习方式跟一些特别优秀的人比起来还是会慢一些,不过也是自己的方法,能够更深入的理解整个体系,并讲解出来,可能会尝试采用视频的方式,对一些比较好的内容做尝试,看看会不会有比较好的数据和反馈,在22年还苟着周更的独立技术博客也算是比较稀有了的,其他站的发布也要勤一些,形成所谓的“矩阵”。
跑步减肥这个么还是比较惨,22年只跑了368公里,比21年少了85公里,有一些客观但很多是主观的原因,还是需要跑起来,只是减肥也很迫切,体重比较大跑步还是有些压力的,买了动感单车,就是时间稍长屁股痛这个目前比较难解决,骑还是每天在骑就是强度跟时间不太够,要保证每天30分钟的量可能会比较好。
加油吧,愿23年家人和自己都健康,顺遂。大家也一样。

-]]>
- - 生活 - 年终总结 - - - 生活 - 年终总结 - 2022 - 2023 - -
- - Dubbo 使用的几个记忆点 - /2022/04/02/Dubbo-%E4%BD%BF%E7%94%A8%E7%9A%84%E5%87%A0%E4%B8%AA%E8%AE%B0%E5%BF%86%E7%82%B9/ - 因为后台使用的 dubbo 作为 rpc 框架,并且会有一些日常使用情景有一些小的技巧,在这里做下记录作笔记用

-

dubbo 只拉取不注册

<dubbo:registry address="zookeeper://127.0.0.1:2181" register="false" />
-

就是只要 register="false" 就可以了,这样比如我们在开发环境想运行服务,但又不想让开发环境正常的请求调用到本地来,当然这不是唯一的方式,通过 dubbo 2.7 以上的 tag 路由也可以实现或者自行改造拉取和注册服务的逻辑,因为注册到注册中心的其实是一串带参数的 url,还是比较方便改造的。相反的就是只注册,不拉取

-

dubbo 只注册不拉取

<dubbo:registry address="zookeeper://127.0.0.1:2181" subscribe="false" />
-

这个使用场景就是如果我这个服务只作为 provider,没有任何调用其他的服务,其实就可以这么设置

-

权重配置

<dubbo:provider loadbalance="random" weight="50"/>
-

首先这是在使用了随机的负载均衡策略的时候可以进行配置,并且是对于多个 provider 的情况下,这样其实也可以部分解决上面的只拉取不注册的问题,我把自己的权重调成 0 或者很低

-]]>
- - Java - Dubbo - - - Java - Dubbo - RPC - 负载均衡 - -
Disruptor 系列一 /2022/02/13/Disruptor-%E7%B3%BB%E5%88%97%E4%B8%80/ @@ -1782,79 +1263,284 @@ Node *clone(Node *graph) { - Filter, Interceptor, Aop, 啥, 啥, 啥? 这些都是啥? - /2020/08/22/Filter-Intercepter-Aop-%E5%95%A5-%E5%95%A5-%E5%95%A5-%E8%BF%99%E4%BA%9B%E9%83%BD%E6%98%AF%E5%95%A5/ - 本来是想取个像现在那些公众号转了又转的文章标题,”面试官再问你xxxxx,就把这篇文章甩给他看”这种标题,但是觉得实在太 low 了,还是用一部我比较喜欢的电影里的一句台词,《人在囧途》里王宝强对着那张老板给他的欠条,看不懂字时候说的那句,这些都是些啥(第四声)
当我刚开始面 Java 的时候,其实我真的没注意这方面的东西,实话说就是不知道这些是啥,开发中用过 Interceptor和 Aop,了解 aop 的实现原理,但是不知道 Java web 中的 Filter 是怎么回事,知道 dubbo 的 filter,就这样,所以被问到了的确是回答不出来,可能就觉得这个渣渣,这么简单的都不会,所以还是花点时间来看看这个是个啥,为了避免我口吐芬芳,还是耐下性子来简单说下这几个东西
首先是 servlet,怎么去解释这个呢,因为之前是 PHPer,所以比较喜欢用它来举例子,在普通的 PHP 的 web 应用中一般有几部分组成,接受 HTTP 请求的是前置的 nginx 或者 apache,但是这俩玩意都是只能处理静态的请求,远古时代 PHP 和 HTML 混编是通过 apache 的 php module,跟后来 nginx 使用 php-fpm 其实道理类似,就是把请求中需要 PHP 处理的转发给 PHP,在 Java 中呢,是有个比较牛叉的叫 Tomcat 的,它可以把请求转成 servlet,而 servlet 其实就是一种实现了特定接口的 Java 代码,

-

-package javax.servlet;
+    Disruptor 系列二
+    /2022/02/27/Disruptor-%E7%B3%BB%E5%88%97%E4%BA%8C/
+    这里开始慢慢深入的讲一下 disruptor,首先是 lock free , 相比于前面介绍的两个阻塞队列,
disruptor 本身是不直接使用锁的,因为本身的设计是单个线程去生产,通过 cas 来维护头指针,
不直接维护尾指针,这样就减少了锁的使用,提升了性能;第二个是这次介绍的重点,
减少 false sharing 的情况,也就是常说的 伪共享 问题,那么什么叫 伪共享 呢,
这里要扯到一些 cpu 缓存的知识,

譬如我在用的这个笔记本

这里就可能看到 L2 Cache 就是针对每个核的

这里可以看到现代 CPU 的结构里,分为三级缓存,越靠近 cpu 的速度越快,存储容量越小,
而 L1 跟 L2 是 CPU 核专属的每个核都有自己的 L1 和 L2 的,其中 L1 还分为数据和指令,
像我上面的图中显示的 L1 Cache 只有 64KB 大小,其中数据 32KB,指令 32KB,
而 L2 则有 256KB,L3 有 4MB,其中的 Line Size 是我们这里比较重要的一个值,
CPU 其实会就近地从 Cache 中读取数据,碰到 Cache Miss 就再往下一级 Cache 读取,
每次读取是按照缓存行 Cache Line 读取,并且也遵循了“就近原则”,
也就是相近的数据有可能也会马上被读取,所以以行的形式读取,然而这也造成了 false sharing
因为类似于 ArrayBlockingQueue,需要有 takeIndex , putIndex , count , 因为在同一个类中,
很有可能存在于同一个 Cache Line 中,但是这几个值会被不同的线程修改,
导致从 Cache 取出来以后立马就会被失效,所谓的就近原则也就没用了,
因为需要反复地标记 dirty 脏位,然后把 Cache 刷掉,就造成了false sharing这种情况
而在 disruptor 中则使用了填充的方式,让我的头指针能够不产生false sharing

+
class LhsPadding
+{
+    protected long p1, p2, p3, p4, p5, p6, p7;
+}
 
-import java.io.IOException;
+class Value extends LhsPadding
+{
+    protected volatile long value;
+}
+
+class RhsPadding extends Value
+{
+    protected long p9, p10, p11, p12, p13, p14, p15;
+}
 
 /**
- * Defines methods that all servlets must implement.
- *
- * <p>
- * A servlet is a small Java program that runs within a Web server. Servlets
- * receive and respond to requests from Web clients, usually across HTTP, the
- * HyperText Transfer Protocol.
- *
- * <p>
- * To implement this interface, you can write a generic servlet that extends
- * <code>javax.servlet.GenericServlet</code> or an HTTP servlet that extends
- * <code>javax.servlet.http.HttpServlet</code>.
- *
- * <p>
- * This interface defines methods to initialize a servlet, to service requests,
- * and to remove a servlet from the server. These are known as life-cycle
- * methods and are called in the following sequence:
- * <ol>
- * <li>The servlet is constructed, then initialized with the <code>init</code>
- * method.
- * <li>Any calls from clients to the <code>service</code> method are handled.
- * <li>The servlet is taken out of service, then destroyed with the
- * <code>destroy</code> method, then garbage collected and finalized.
- * </ol>
- *
- * <p>
- * In addition to the life-cycle methods, this interface provides the
- * <code>getServletConfig</code> method, which the servlet can use to get any
- * startup information, and the <code>getServletInfo</code> method, which allows
- * the servlet to return basic information about itself, such as author,
- * version, and copyright.
+ * <p>Concurrent sequence class used for tracking the progress of
+ * the ring buffer and event processors.  Support a number
+ * of concurrent operations including CAS and order writes.
  *
- * @see GenericServlet
- * @see javax.servlet.http.HttpServlet
+ * <p>Also attempts to be more efficient with regards to false
+ * sharing by adding padding around the volatile field.
  */
-public interface Servlet {
+public class Sequence extends RhsPadding
+{
+

通过代码可以看到,sequence 中其实真正有意义的是 value 字段,因为需要在多线程环境下可见也
使用了volatile 关键字,而 LhsPaddingRhsPadding 分别在value 前后填充了各
7 个 long 型的变量,long 型的变量在 Java 中是占用 8 bytes,这样就相当于不管怎么样,
value 都会单独使用一个缓存行,使得其不会产生 false sharing 的问题。

+]]>
+ + Java + + + Java + Disruptor + + + + Disruptor 系列三 + /2022/09/25/Disruptor-%E7%B3%BB%E5%88%97%E4%B8%89/ + 原来一直有点被误导,
gatingSequences用来标识每个 processer 的操作位点,但是怎么记录更新有点搞不清楚
其实问题在于 gatingSequences 是个 Sequence 数组,首先要看下怎么加进去的,
可以看到是在 com.lmax.disruptor.RingBuffer#addGatingSequences 这个方法里添加
首先是 com.lmax.disruptor.dsl.Disruptor#handleEventsWith(com.lmax.disruptor.EventHandler<? super T>...)
然后执行 com.lmax.disruptor.dsl.Disruptor#createEventProcessors(com.lmax.disruptor.Sequence[], com.lmax.disruptor.EventHandler<? super T>[])

+
EventHandlerGroup<T> createEventProcessors(
+        final Sequence[] barrierSequences,
+        final EventHandler<? super T>[] eventHandlers)
+    {
+        checkNotStarted();
 
-    /**
-     * Called by the servlet container to indicate to a servlet that the servlet
-     * is being placed into service.
-     *
-     * <p>
-     * The servlet container calls the <code>init</code> method exactly once
-     * after instantiating the servlet. The <code>init</code> method must
-     * complete successfully before the servlet can receive any requests.
-     *
-     * <p>
-     * The servlet container cannot place the servlet into service if the
-     * <code>init</code> method
-     * <ol>
-     * <li>Throws a <code>ServletException</code>
-     * <li>Does not return within a time period defined by the Web server
-     * </ol>
-     *
-     *
-     * @param config
-     *            a <code>ServletConfig</code> object containing the servlet's
-     *            configuration and initialization parameters
-     *
-     * @exception ServletException
-     *                if an exception has occurred that interferes with the
-     *                servlet's normal operation
-     *
-     * @see UnavailableException
-     * @see #getServletConfig
+        final Sequence[] processorSequences = new Sequence[eventHandlers.length];
+        final SequenceBarrier barrier = ringBuffer.newBarrier(barrierSequences);
+
+        for (int i = 0, eventHandlersLength = eventHandlers.length; i < eventHandlersLength; i++)
+        {
+            final EventHandler<? super T> eventHandler = eventHandlers[i];
+
+            // 这里将 handler 包装成一个 BatchEventProcessor
+            final BatchEventProcessor<T> batchEventProcessor =
+                new BatchEventProcessor<>(ringBuffer, barrier, eventHandler);
+
+            if (exceptionHandler != null)
+            {
+                batchEventProcessor.setExceptionHandler(exceptionHandler);
+            }
+
+            consumerRepository.add(batchEventProcessor, eventHandler, barrier);
+            processorSequences[i] = batchEventProcessor.getSequence();
+        }
+
+        updateGatingSequencesForNextInChain(barrierSequences, processorSequences);
+
+        return new EventHandlerGroup<>(this, consumerRepository, processorSequences);
+    }
+ +

BatchEventProcessor 在类内有个定义 sequence

+
private final Sequence sequence = new Sequence(Sequencer.INITIAL_CURSOR_VALUE);
+

然后在上面循环中的这一句取出来

+
processorSequences[i] = batchEventProcessor.getSequence();
+

调用com.lmax.disruptor.dsl.Disruptor#updateGatingSequencesForNextInChain 方法

+
private void updateGatingSequencesForNextInChain(final Sequence[] barrierSequences, final Sequence[] processorSequences)
+    {
+        if (processorSequences.length > 0)
+        {
+            // 然后在这里添加
+            ringBuffer.addGatingSequences(processorSequences);
+            for (final Sequence barrierSequence : barrierSequences)
+            {
+                ringBuffer.removeGatingSequence(barrierSequence);
+            }
+            consumerRepository.unMarkEventProcessorsAsEndOfChain(barrierSequences);
+        }
+    }
+ +

而如何更新则是在处理器 com.lmax.disruptor.BatchEventProcessor#run

+
public void run()
+    {
+        if (running.compareAndSet(IDLE, RUNNING))
+        {
+            sequenceBarrier.clearAlert();
+
+            notifyStart();
+            try
+            {
+                if (running.get() == RUNNING)
+                {
+                    processEvents();
+                }
+            }
+            finally
+            {
+                notifyShutdown();
+                running.set(IDLE);
+            }
+        }
+        else
+        {
+            // This is a little bit of guess work.  The running state could of changed to HALTED by
+            // this point.  However, Java does not have compareAndExchange which is the only way
+            // to get it exactly correct.
+            if (running.get() == RUNNING)
+            {
+                throw new IllegalStateException("Thread is already running");
+            }
+            else
+            {
+                earlyExit();
+            }
+        }
+    }
+

然后是

+
private void processEvents()
+    {
+        T event = null;
+        long nextSequence = sequence.get() + 1L;
+
+        while (true)
+        {
+            try
+            {
+                final long availableSequence = sequenceBarrier.waitFor(nextSequence);
+                if (batchStartAware != null)
+                {
+                    batchStartAware.onBatchStart(availableSequence - nextSequence + 1);
+                }
+
+                while (nextSequence <= availableSequence)
+                {
+                    event = dataProvider.get(nextSequence);
+                    eventHandler.onEvent(event, nextSequence, nextSequence == availableSequence);
+                    nextSequence++;
+                }
+                // 如果正常处理完,那就是会更新为 availableSequence,因为都处理好了
+                sequence.set(availableSequence);
+            }
+            catch (final TimeoutException e)
+            {
+                notifyTimeout(sequence.get());
+            }
+            catch (final AlertException ex)
+            {
+                if (running.get() != RUNNING)
+                {
+                    break;
+                }
+            }
+            catch (final Throwable ex)
+            {
+                handleEventException(ex, nextSequence, event);
+                // 如果是异常就只是 nextSequence
+                sequence.set(nextSequence);
+                nextSequence++;
+            }
+        }
+    }
+]]>
+ + Java + + + Java + Disruptor + +
+ + Dubbo 使用的几个记忆点 + /2022/04/02/Dubbo-%E4%BD%BF%E7%94%A8%E7%9A%84%E5%87%A0%E4%B8%AA%E8%AE%B0%E5%BF%86%E7%82%B9/ + 因为后台使用的 dubbo 作为 rpc 框架,并且会有一些日常使用情景有一些小的技巧,在这里做下记录作笔记用

+

dubbo 只拉取不注册

<dubbo:registry address="zookeeper://127.0.0.1:2181" register="false" />
+

就是只要 register="false" 就可以了,这样比如我们在开发环境想运行服务,但又不想让开发环境正常的请求调用到本地来,当然这不是唯一的方式,通过 dubbo 2.7 以上的 tag 路由也可以实现或者自行改造拉取和注册服务的逻辑,因为注册到注册中心的其实是一串带参数的 url,还是比较方便改造的。相反的就是只注册,不拉取

+

dubbo 只注册不拉取

<dubbo:registry address="zookeeper://127.0.0.1:2181" subscribe="false" />
+

这个使用场景就是如果我这个服务只作为 provider,没有任何调用其他的服务,其实就可以这么设置

+

权重配置

<dubbo:provider loadbalance="random" weight="50"/>
+

首先这是在使用了随机的负载均衡策略的时候可以进行配置,并且是对于多个 provider 的情况下,这样其实也可以部分解决上面的只拉取不注册的问题,我把自己的权重调成 0 或者很低

+]]>
+ + Java + Dubbo + + + Java + Dubbo + RPC + 负载均衡 + +
+ + Filter, Interceptor, Aop, 啥, 啥, 啥? 这些都是啥? + /2020/08/22/Filter-Intercepter-Aop-%E5%95%A5-%E5%95%A5-%E5%95%A5-%E8%BF%99%E4%BA%9B%E9%83%BD%E6%98%AF%E5%95%A5/ + 本来是想取个像现在那些公众号转了又转的文章标题,”面试官再问你xxxxx,就把这篇文章甩给他看”这种标题,但是觉得实在太 low 了,还是用一部我比较喜欢的电影里的一句台词,《人在囧途》里王宝强对着那张老板给他的欠条,看不懂字时候说的那句,这些都是些啥(第四声)
当我刚开始面 Java 的时候,其实我真的没注意这方面的东西,实话说就是不知道这些是啥,开发中用过 Interceptor和 Aop,了解 aop 的实现原理,但是不知道 Java web 中的 Filter 是怎么回事,知道 dubbo 的 filter,就这样,所以被问到了的确是回答不出来,可能就觉得这个渣渣,这么简单的都不会,所以还是花点时间来看看这个是个啥,为了避免我口吐芬芳,还是耐下性子来简单说下这几个东西
首先是 servlet,怎么去解释这个呢,因为之前是 PHPer,所以比较喜欢用它来举例子,在普通的 PHP 的 web 应用中一般有几部分组成,接受 HTTP 请求的是前置的 nginx 或者 apache,但是这俩玩意都是只能处理静态的请求,远古时代 PHP 和 HTML 混编是通过 apache 的 php module,跟后来 nginx 使用 php-fpm 其实道理类似,就是把请求中需要 PHP 处理的转发给 PHP,在 Java 中呢,是有个比较牛叉的叫 Tomcat 的,它可以把请求转成 servlet,而 servlet 其实就是一种实现了特定接口的 Java 代码,

+

+package javax.servlet;
+
+import java.io.IOException;
+
+/**
+ * Defines methods that all servlets must implement.
+ *
+ * <p>
+ * A servlet is a small Java program that runs within a Web server. Servlets
+ * receive and respond to requests from Web clients, usually across HTTP, the
+ * HyperText Transfer Protocol.
+ *
+ * <p>
+ * To implement this interface, you can write a generic servlet that extends
+ * <code>javax.servlet.GenericServlet</code> or an HTTP servlet that extends
+ * <code>javax.servlet.http.HttpServlet</code>.
+ *
+ * <p>
+ * This interface defines methods to initialize a servlet, to service requests,
+ * and to remove a servlet from the server. These are known as life-cycle
+ * methods and are called in the following sequence:
+ * <ol>
+ * <li>The servlet is constructed, then initialized with the <code>init</code>
+ * method.
+ * <li>Any calls from clients to the <code>service</code> method are handled.
+ * <li>The servlet is taken out of service, then destroyed with the
+ * <code>destroy</code> method, then garbage collected and finalized.
+ * </ol>
+ *
+ * <p>
+ * In addition to the life-cycle methods, this interface provides the
+ * <code>getServletConfig</code> method, which the servlet can use to get any
+ * startup information, and the <code>getServletInfo</code> method, which allows
+ * the servlet to return basic information about itself, such as author,
+ * version, and copyright.
+ *
+ * @see GenericServlet
+ * @see javax.servlet.http.HttpServlet
+ */
+public interface Servlet {
+
+    /**
+     * Called by the servlet container to indicate to a servlet that the servlet
+     * is being placed into service.
+     *
+     * <p>
+     * The servlet container calls the <code>init</code> method exactly once
+     * after instantiating the servlet. The <code>init</code> method must
+     * complete successfully before the servlet can receive any requests.
+     *
+     * <p>
+     * The servlet container cannot place the servlet into service if the
+     * <code>init</code> method
+     * <ol>
+     * <li>Throws a <code>ServletException</code>
+     * <li>Does not return within a time period defined by the Web server
+     * </ol>
+     *
+     *
+     * @param config
+     *            a <code>ServletConfig</code> object containing the servlet's
+     *            configuration and initialization parameters
+     *
+     * @exception ServletException
+     *                if an exception has occurred that interferes with the
+     *                servlet's normal operation
+     *
+     * @see UnavailableException
+     * @see #getServletConfig
      */
     public void init(ServletConfig config) throws ServletException;
 
@@ -2319,419 +2005,777 @@ Node *clone(Node *graph) {
       
         Java
         JVM
-        GC
         C++
+        GC
       
       
         Java
-        JVM
         C++
+        JVM
         G1
         GC
         Garbage-First Collector
       
   
   
-    JVM源码分析之G1垃圾收集器分析一
-    /2019/12/07/JVM-G1-Part-1/
-    对 Java 的 gc 实现比较感兴趣,原先一般都是看周志明的书,但其实并没有讲具体的 gc 源码,而是把整个思路和流程讲解了一下
特别是 G1 的具体实现
一般对 G1 的理解其实就是把原先整块的新生代老年代分成了以 region 为单位的小块内存,简而言之,就是原先对新生代老年代的收集会涉及到整个代的堆内存空间,而G1 把它变成了更细致的小块内存
这带来了一个很明显的好处和一个很明显的坏处,好处是内存收集可以更灵活,耗时会变短,但整个收集的处理复杂度就变高了
目前看了一点点关于 G1 收集的预期时间相关的代码

-
HeapWord* G1CollectedHeap::do_collection_pause(size_t word_size,
-                                               uint gc_count_before,
-                                               bool* succeeded,
-                                               GCCause::Cause gc_cause) {
-  assert_heap_not_locked_and_not_at_safepoint();
-  VM_G1CollectForAllocation op(word_size,
-                               gc_count_before,
-                               gc_cause,
-                               false, /* should_initiate_conc_mark */
-                               g1_policy()->max_pause_time_ms());
-  VMThread::execute(&op);
-
-  HeapWord* result = op.result();
-  bool ret_succeeded = op.prologue_succeeded() && op.pause_succeeded();
-  assert(result == NULL || ret_succeeded,
-         "the result should be NULL if the VM did not succeed");
-  *succeeded = ret_succeeded;
-
-  assert_heap_not_locked();
-  return result;
-}
-

这里就是收集时需要停顿的,其中VMThread::execute(&op);是具体执行的,真正执行的是VM_G1CollectForAllocation::doit方法

-
void VM_G1CollectForAllocation::doit() {
-  G1CollectedHeap* g1h = G1CollectedHeap::heap();
-  assert(!_should_initiate_conc_mark || g1h->should_do_concurrent_full_gc(_gc_cause),
-      "only a GC locker, a System.gc(), stats update, whitebox, or a hum allocation induced GC should start a cycle");
-
-  if (_word_size > 0) {
-    // An allocation has been requested. So, try to do that first.
-    _result = g1h->attempt_allocation_at_safepoint(_word_size,
-                                                   false /* expect_null_cur_alloc_region */);
-    if (_result != NULL) {
-      // If we can successfully allocate before we actually do the
-      // pause then we will consider this pause successful.
-      _pause_succeeded = true;
-      return;
-    }
-  }
+    Headscale初体验以及踩坑记
+    /2023/01/22/Headscale%E5%88%9D%E4%BD%93%E9%AA%8C%E4%BB%A5%E5%8F%8A%E8%B8%A9%E5%9D%91%E8%AE%B0/
+    最近或者说很久以前就想着能够把几个散装服务器以及家里的网络连起来,譬如一些remote desktop的访问,之前搞了下frp,因为家里电脑没怎么注意安全性就被搞了一下,所以还是想用相对更安全的方式,比如限定ip和端口进行访问,但是感觉ip也不固定就比较难搞,后来看到了 TailscaleHeadscale 的方式,就想着试试看,没想到一开始就踩了几个比较莫名其妙的坑。
可以按官方文档去搭建,也可以在网上找一些其他人搭建的教程。我碰到的主要是关于配置文件的问题

+

第一个问题

Error initializing error="failed to read or create private key: failed to save private key to disk: open /etc/headscale/private.key: read-only file system"
+

其实一开始看到这个我都有点懵了,咋回事呢,read-only file system一般有可能是文件系统出问题了,不可写入,需要重启或者修改挂载方式,被这个错误的错误日志给误导了,后面才知道是配置文件,在另一个教程中也有个类似的回复,一开始没注意,其实就是同一个问题。
默认的配置文件是这样的

+
---
+# headscale will look for a configuration file named `config.yaml` (or `config.json`) in the following order:
+#
+# - `/etc/headscale`
+# - `~/.headscale`
+# - current working directory
 
-  GCCauseSetter x(g1h, _gc_cause);
-  if (_should_initiate_conc_mark) {
-    // It's safer to read old_marking_cycles_completed() here, given
-    // that noone else will be updating it concurrently. Since we'll
-    // only need it if we're initiating a marking cycle, no point in
-    // setting it earlier.
-    _old_marking_cycles_completed_before = g1h->old_marking_cycles_completed();
+# The url clients will connect to.
+# Typically this will be a domain like:
+#
+# https://myheadscale.example.com:443
+#
+server_url: http://127.0.0.1:8080
 
-    // At this point we are supposed to start a concurrent cycle. We
-    // will do so if one is not already in progress.
-    bool res = g1h->g1_policy()->force_initial_mark_if_outside_cycle(_gc_cause);
+# Address to listen to / bind to on the server
+#
+# For production:
+# listen_addr: 0.0.0.0:8080
+listen_addr: 127.0.0.1:8080
 
-    // The above routine returns true if we were able to force the
-    // next GC pause to be an initial mark; it returns false if a
-    // marking cycle is already in progress.
-    //
-    // If a marking cycle is already in progress just return and skip the
-    // pause below - if the reason for requesting this initial mark pause
-    // was due to a System.gc() then the requesting thread should block in
-    // doit_epilogue() until the marking cycle is complete.
-    //
-    // If this initial mark pause was requested as part of a humongous
-    // allocation then we know that the marking cycle must just have
-    // been started by another thread (possibly also allocating a humongous
-    // object) as there was no active marking cycle when the requesting
-    // thread checked before calling collect() in
-    // attempt_allocation_humongous(). Retrying the GC, in this case,
-    // will cause the requesting thread to spin inside collect() until the
-    // just started marking cycle is complete - which may be a while. So
-    // we do NOT retry the GC.
-    if (!res) {
-      assert(_word_size == 0, "Concurrent Full GC/Humongous Object IM shouldn't be allocating");
-      if (_gc_cause != GCCause::_g1_humongous_allocation) {
-        _should_retry_gc = true;
-      }
-      return;
-    }
-  }
+# Address to listen to /metrics, you may want
+# to keep this endpoint private to your internal
+# network
+#
+metrics_listen_addr: 127.0.0.1:9090
 
-  // Try a partial collection of some kind.
-  _pause_succeeded = g1h->do_collection_pause_at_safepoint(_target_pause_time_ms);
+# Address to listen for gRPC.
+# gRPC is used for controlling a headscale server
+# remotely with the CLI
+# Note: Remote access _only_ works if you have
+# valid certificates.
+#
+# For production:
+# grpc_listen_addr: 0.0.0.0:50443
+grpc_listen_addr: 127.0.0.1:50443
 
-  if (_pause_succeeded) {
-    if (_word_size > 0) {
-      // An allocation had been requested. Do it, eventually trying a stronger
-      // kind of GC.
-      _result = g1h->satisfy_failed_allocation(_word_size, &_pause_succeeded);
-    } else {
-      bool should_upgrade_to_full = !g1h->should_do_concurrent_full_gc(_gc_cause) &&
-                                    !g1h->has_regions_left_for_allocation();
-      if (should_upgrade_to_full) {
-        // There has been a request to perform a GC to free some space. We have no
-        // information on how much memory has been asked for. In case there are
-        // absolutely no regions left to allocate into, do a maximally compacting full GC.
-        log_info(gc, ergo)("Attempting maximally compacting collection");
-        _pause_succeeded = g1h->do_full_collection(false, /* explicit gc */
-                                                   true   /* clear_all_soft_refs */);
-      }
-    }
-    guarantee(_pause_succeeded, "Elevated collections during the safepoint must always succeed.");
-  } else {
-    assert(_result == NULL, "invariant");
-    // The only reason for the pause to not be successful is that, the GC locker is
-    // active (or has become active since the prologue was executed). In this case
-    // we should retry the pause after waiting for the GC locker to become inactive.
-    _should_retry_gc = true;
-  }
-}
-

这里可以看到核心的是G1CollectedHeap::do_collection_pause_at_safepoint这个方法,它带上了目标暂停时间的值

-
G1CollectedHeap::do_collection_pause_at_safepoint(double target_pause_time_ms) {
-  assert_at_safepoint_on_vm_thread();
-  guarantee(!is_gc_active(), "collection is not reentrant");
+# Allow the gRPC admin interface to run in INSECURE
+# mode. This is not recommended as the traffic will
+# be unencrypted. Only enable if you know what you
+# are doing.
+grpc_allow_insecure: false
 
-  if (GCLocker::check_active_before_gc()) {
-    return false;
-  }
+# Private key used to encrypt the traffic between headscale
+# and Tailscale clients.
+# The private key file will be autogenerated if it's missing.
+#
+# For production:
+# /var/lib/headscale/private.key
+private_key_path: ./private.key
 
-  _gc_timer_stw->register_gc_start();
+# The Noise section includes specific configuration for the
+# TS2021 Noise protocol
+noise:
+  # The Noise private key is used to encrypt the
+  # traffic between headscale and Tailscale clients when
+  # using the new Noise-based protocol. It must be different
+  # from the legacy private key.
+  #
+  # For production:
+  # private_key_path: /var/lib/headscale/noise_private.key
+  private_key_path: ./noise_private.key
 
-  GCIdMark gc_id_mark;
-  _gc_tracer_stw->report_gc_start(gc_cause(), _gc_timer_stw->gc_start());
+# List of IP prefixes to allocate tailaddresses from.
+# Each prefix consists of either an IPv4 or IPv6 address,
+# and the associated prefix length, delimited by a slash.
+# While this looks like it can take arbitrary values, it
+# needs to be within IP ranges supported by the Tailscale
+# client.
+# IPv6: https://github.com/tailscale/tailscale/blob/22ebb25e833264f58d7c3f534a8b166894a89536/net/tsaddr/tsaddr.go#LL81C52-L81C71
+# IPv4: https://github.com/tailscale/tailscale/blob/22ebb25e833264f58d7c3f534a8b166894a89536/net/tsaddr/tsaddr.go#L33
+ip_prefixes:
+  - fd7a:115c:a1e0::/48
+  - 100.64.0.0/10
 
-  SvcGCMarker sgcm(SvcGCMarker::MINOR);
-  ResourceMark rm;
+# DERP is a relay system that Tailscale uses when a direct
+# connection cannot be established.
+# https://tailscale.com/blog/how-tailscale-works/#encrypted-tcp-relays-derp
+#
+# headscale needs a list of DERP servers that can be presented
+# to the clients.
+derp:
+  server:
+    # If enabled, runs the embedded DERP server and merges it into the rest of the DERP config
+    # The Headscale server_url defined above MUST be using https, DERP requires TLS to be in place
+    enabled: false
 
-  g1_policy()->note_gc_start();
+    # Region ID to use for the embedded DERP server.
+    # The local DERP prevails if the region ID collides with other region ID coming from
+    # the regular DERP config.
+    region_id: 999
 
-  wait_for_root_region_scanning();
+    # Region code and name are displayed in the Tailscale UI to identify a DERP region
+    region_code: "headscale"
+    region_name: "Headscale Embedded DERP"
 
-  print_heap_before_gc();
-  print_heap_regions();
-  trace_heap_before_gc(_gc_tracer_stw);
+    # Listens over UDP at the configured address for STUN connections - to help with NAT traversal.
+    # When the embedded DERP server is enabled stun_listen_addr MUST be defined.
+    #
+    # For more details on how this works, check this great article: https://tailscale.com/blog/how-tailscale-works/
+    stun_listen_addr: "0.0.0.0:3478"
 
-  _verifier->verify_region_sets_optional();
-  _verifier->verify_dirty_young_regions();
+  # List of externally available DERP maps encoded in JSON
+  urls:
+    - https://controlplane.tailscale.com/derpmap/default
 
-  // We should not be doing initial mark unless the conc mark thread is running
-  if (!_cm_thread->should_terminate()) {
-    // This call will decide whether this pause is an initial-mark
-    // pause. If it is, in_initial_mark_gc() will return true
-    // for the duration of this pause.
-    g1_policy()->decide_on_conc_mark_initiation();
-  }
+  # Locally available DERP map files encoded in YAML
+  #
+  # This option is mostly interesting for people hosting
+  # their own DERP servers:
+  # https://tailscale.com/kb/1118/custom-derp-servers/
+  #
+  # paths:
+  #   - /etc/headscale/derp-example.yaml
+  paths: []
 
-  // We do not allow initial-mark to be piggy-backed on a mixed GC.
-  assert(!collector_state()->in_initial_mark_gc() ||
-          collector_state()->in_young_only_phase(), "sanity");
+  # If enabled, a worker will be set up to periodically
+  # refresh the given sources and update the derpmap
+  # will be set up.
+  auto_update_enabled: true
 
-  // We also do not allow mixed GCs during marking.
-  assert(!collector_state()->mark_or_rebuild_in_progress() || collector_state()->in_young_only_phase(), "sanity");
+  # How often should we check for DERP updates?
+  update_frequency: 24h
 
-  // Record whether this pause is an initial mark. When the current
-  // thread has completed its logging output and it's safe to signal
-  // the CM thread, the flag's value in the policy has been reset.
-  bool should_start_conc_mark = collector_state()->in_initial_mark_gc();
+# Disables the automatic check for headscale updates on startup
+disable_check_updates: false
 
-  // Inner scope for scope based logging, timers, and stats collection
-  {
-    EvacuationInfo evacuation_info;
+# Time before an inactive ephemeral node is deleted?
+ephemeral_node_inactivity_timeout: 30m
 
-    if (collector_state()->in_initial_mark_gc()) {
-      // We are about to start a marking cycle, so we increment the
-      // full collection counter.
-      increment_old_marking_cycles_started();
-      _cm->gc_tracer_cm()->set_gc_cause(gc_cause());
-    }
+# Period to check for node updates within the tailnet. A value too low will severely affect
+# CPU consumption of Headscale. A value too high (over 60s) will cause problems
+# for the nodes, as they won't get updates or keep alive messages frequently enough.
+# In case of doubts, do not touch the default 10s.
+node_update_check_interval: 10s
 
-    _gc_tracer_stw->report_yc_type(collector_state()->yc_type());
+# SQLite config
+db_type: sqlite3
 
-    GCTraceCPUTime tcpu;
+# For production:
+# db_path: /var/lib/headscale/db.sqlite
+db_path: ./db.sqlite
 
-    G1HeapVerifier::G1VerifyType verify_type;
-    FormatBuffer<> gc_string("Pause Young ");
-    if (collector_state()->in_initial_mark_gc()) {
-      gc_string.append("(Concurrent Start)");
-      verify_type = G1HeapVerifier::G1VerifyConcurrentStart;
-    } else if (collector_state()->in_young_only_phase()) {
-      if (collector_state()->in_young_gc_before_mixed()) {
-        gc_string.append("(Prepare Mixed)");
-      } else {
-        gc_string.append("(Normal)");
-      }
-      verify_type = G1HeapVerifier::G1VerifyYoungNormal;
-    } else {
-      gc_string.append("(Mixed)");
-      verify_type = G1HeapVerifier::G1VerifyMixed;
-    }
-    GCTraceTime(Info, gc) tm(gc_string, NULL, gc_cause(), true);
-
-    uint active_workers = AdaptiveSizePolicy::calc_active_workers(workers()->total_workers(),
-                                                                  workers()->active_workers(),
-                                                                  Threads::number_of_non_daemon_threads());
-    active_workers = workers()->update_active_workers(active_workers);
-    log_info(gc,task)("Using %u workers of %u for evacuation", active_workers, workers()->total_workers());
-
-    TraceCollectorStats tcs(g1mm()->incremental_collection_counters());
-    TraceMemoryManagerStats tms(&_memory_manager, gc_cause(),
-                                collector_state()->yc_type() == Mixed /* allMemoryPoolsAffected */);
-
-    G1HeapTransition heap_transition(this);
-    size_t heap_used_bytes_before_gc = used();
-
-    // Don't dynamically change the number of GC threads this early.  A value of
-    // 0 is used to indicate serial work.  When parallel work is done,
-    // it will be set.
-
-    { // Call to jvmpi::post_class_unload_events must occur outside of active GC
-      IsGCActiveMark x;
-
-      gc_prologue(false);
+# # Postgres config
+# If using a Unix socket to connect to Postgres, set the socket path in the 'host' field and leave 'port' blank.
+# db_type: postgres
+# db_host: localhost
+# db_port: 5432
+# db_name: headscale
+# db_user: foo
+# db_pass: bar
 
-      if (VerifyRememberedSets) {
-        log_info(gc, verify)("[Verifying RemSets before GC]");
-        VerifyRegionRemSetClosure v_cl;
-        heap_region_iterate(&v_cl);
-      }
+# If other 'sslmode' is required instead of 'require(true)' and 'disabled(false)', set the 'sslmode' you need
+# in the 'db_ssl' field. Refers to https://www.postgresql.org/docs/current/libpq-ssl.html Table 34.1.
+# db_ssl: false
 
-      _verifier->verify_before_gc(verify_type);
+### TLS configuration
+#
+## Let's encrypt / ACME
+#
+# headscale supports automatically requesting and setting up
+# TLS for a domain with Let's Encrypt.
+#
+# URL to ACME directory
+acme_url: https://acme-v02.api.letsencrypt.org/directory
 
-      _verifier->check_bitmaps("GC Start");
+# Email to register with ACME provider
+acme_email: ""
 
-#if COMPILER2_OR_JVMCI
-      DerivedPointerTable::clear();
-#endif
+# Domain name to request a TLS certificate for:
+tls_letsencrypt_hostname: ""
 
-      // Please see comment in g1CollectedHeap.hpp and
-      // G1CollectedHeap::ref_processing_init() to see how
-      // reference processing currently works in G1.
+# Path to store certificates and metadata needed by
+# letsencrypt
+# For production:
+# tls_letsencrypt_cache_dir: /var/lib/headscale/cache
+tls_letsencrypt_cache_dir: ./cache
 
-      // Enable discovery in the STW reference processor
-      _ref_processor_stw->enable_discovery();
+# Type of ACME challenge to use, currently supported types:
+# HTTP-01 or TLS-ALPN-01
+# See [docs/tls.md](docs/tls.md) for more information
+tls_letsencrypt_challenge_type: HTTP-01
+# When HTTP-01 challenge is chosen, letsencrypt must set up a
+# verification endpoint, and it will be listening on:
+# :http = port 80
+tls_letsencrypt_listen: ":http"
 
-      {
-        // We want to temporarily turn off discovery by the
-        // CM ref processor, if necessary, and turn it back on
-        // on again later if we do. Using a scoped
-        // NoRefDiscovery object will do this.
-        NoRefDiscovery no_cm_discovery(_ref_processor_cm);
+## Use already defined certificates:
+tls_cert_path: ""
+tls_key_path: ""
 
-        // Forget the current alloc region (we might even choose it to be part
-        // of the collection set!).
-        _allocator->release_mutator_alloc_region();
+log:
+  # Output formatting for logs: text or json
+  format: text
+  level: info
 
-        // This timing is only used by the ergonomics to handle our pause target.
-        // It is unclear why this should not include the full pause. We will
-        // investigate this in CR 7178365.
-        //
-        // Preserving the old comment here if that helps the investigation:
-        //
-        // The elapsed time induced by the start time below deliberately elides
-        // the possible verification above.
-        double sample_start_time_sec = os::elapsedTime();
+# Path to a file containg ACL policies.
+# ACLs can be defined as YAML or HUJSON.
+# https://tailscale.com/kb/1018/acls/
+acl_policy_path: ""
 
-        g1_policy()->record_collection_pause_start(sample_start_time_sec);
+## DNS
+#
+# headscale supports Tailscale's DNS configuration and MagicDNS.
+# Please have a look to their KB to better understand the concepts:
+#
+# - https://tailscale.com/kb/1054/dns/
+# - https://tailscale.com/kb/1081/magicdns/
+# - https://tailscale.com/blog/2021-09-private-dns-with-magicdns/
+#
+dns_config:
+  # Whether to prefer using Headscale provided DNS or use local.
+  override_local_dns: true
 
-        if (collector_state()->in_initial_mark_gc()) {
-          concurrent_mark()->pre_initial_mark();
-        }
+  # List of DNS servers to expose to clients.
+  nameservers:
+    - 1.1.1.1
 
-        g1_policy()->finalize_collection_set(target_pause_time_ms, &_survivor);
+  # NextDNS (see https://tailscale.com/kb/1218/nextdns/).
+  # "abc123" is example NextDNS ID, replace with yours.
+  #
+  # With metadata sharing:
+  # nameservers:
+  #   - https://dns.nextdns.io/abc123
+  #
+  # Without metadata sharing:
+  # nameservers:
+  #   - 2a07:a8c0::ab:c123
+  #   - 2a07:a8c1::ab:c123
 
-        evacuation_info.set_collectionset_regions(collection_set()->region_length());
+  # Split DNS (see https://tailscale.com/kb/1054/dns/),
+  # list of search domains and the DNS to query for each one.
+  #
+  # restricted_nameservers:
+  #   foo.bar.com:
+  #     - 1.1.1.1
+  #   darp.headscale.net:
+  #     - 1.1.1.1
+  #     - 8.8.8.8
 
-        // Make sure the remembered sets are up to date. This needs to be
-        // done before register_humongous_regions_with_cset(), because the
-        // remembered sets are used there to choose eager reclaim candidates.
-        // If the remembered sets are not up to date we might miss some
-        // entries that need to be handled.
-        g1_rem_set()->cleanupHRRS();
+  # Search domains to inject.
+  domains: []
 
-        register_humongous_regions_with_cset();
+  # Extra DNS records
+  # so far only A-records are supported (on the tailscale side)
+  # See https://github.com/juanfont/headscale/blob/main/docs/dns-records.md#Limitations
+  # extra_records:
+  #   - name: "grafana.myvpn.example.com"
+  #     type: "A"
+  #     value: "100.64.0.3"
+  #
+  #   # you can also put it in one line
+  #   - { name: "prometheus.myvpn.example.com", type: "A", value: "100.64.0.3" }
 
-        assert(_verifier->check_cset_fast_test(), "Inconsistency in the InCSetState table.");
+  # Whether to use [MagicDNS](https://tailscale.com/kb/1081/magicdns/).
+  # Only works if there is at least a nameserver defined.
+  magic_dns: true
 
-        // We call this after finalize_cset() to
-        // ensure that the CSet has been finalized.
-        _cm->verify_no_cset_oops();
+  # Defines the base domain to create the hostnames for MagicDNS.
+  # `base_domain` must be a FQDNs, without the trailing dot.
+  # The FQDN of the hosts will be
+  # `hostname.user.base_domain` (e.g., _myhost.myuser.example.com_).
+  base_domain: example.com
 
-        if (_hr_printer.is_active()) {
-          G1PrintCollectionSetClosure cl(&_hr_printer);
-          _collection_set.iterate(&cl);
-        }
+# Unix socket used for the CLI to connect without authentication
+# Note: for production you will want to set this to something like:
+# unix_socket: /var/run/headscale.sock
+unix_socket: ./headscale.sock
+unix_socket_permission: "0770"
+#
+# headscale supports experimental OpenID connect support,
+# it is still being tested and might have some bugs, please
+# help us test it.
+# OpenID Connect
+# oidc:
+#   only_start_if_oidc_is_available: true
+#   issuer: "https://your-oidc.issuer.com/path"
+#   client_id: "your-oidc-client-id"
+#   client_secret: "your-oidc-client-secret"
+#   # Alternatively, set `client_secret_path` to read the secret from the file.
+#   # It resolves environment variables, making integration to systemd's
+#   # `LoadCredential` straightforward:
+#   client_secret_path: "${CREDENTIALS_DIRECTORY}/oidc_client_secret"
+#   # client_secret and client_secret_path are mutually exclusive.
+#
+#   Customize the scopes used in the OIDC flow, defaults to "openid", "profile" and "email" and add custom query
+#   parameters to the Authorize Endpoint request. Scopes default to "openid", "profile" and "email".
+#
+#   scope: ["openid", "profile", "email", "custom"]
+#   extra_params:
+#     domain_hint: example.com
+#
+#   List allowed principal domains and/or users. If an authenticated user's domain is not in this list, the
+#   authentication request will be rejected.
+#
+#   allowed_domains:
+#     - example.com
+# Groups from keycloak have a leading '/'
+#   allowed_groups:
+#     - /headscale
+#   allowed_users:
+#     - alice@example.com
+#
+#   If `strip_email_domain` is set to `true`, the domain part of the username email address will be removed.
+#   This will transform `first-name.last-name@example.com` to the user `first-name.last-name`
+#   If `strip_email_domain` is set to `false` the domain part will NOT be removed resulting to the following
+#   user: `first-name.last-name.example.com`
+#
+#   strip_email_domain: true
 
-        // Initialize the GC alloc regions.
-        _allocator->init_gc_alloc_regions(evacuation_info);
+# Logtail configuration
+# Logtail is Tailscales logging and auditing infrastructure, it allows the control panel
+# to instruct tailscale nodes to log their activity to a remote server.
+logtail:
+  # Enable logtail for this headscales clients.
+  # As there is currently no support for overriding the log server in headscale, this is
+  # disabled by default. Enabling this will make your clients send logs to Tailscale Inc.
+  enabled: false
 
-        G1ParScanThreadStateSet per_thread_states(this, workers()->active_workers(), collection_set()->young_region_length());
-        pre_evacuate_collection_set();
+# Enabling this option makes devices prefer a random port for WireGuard traffic over the
+# default static port 41641. This option is intended as a workaround for some buggy
+# firewall devices. See https://tailscale.com/kb/1181/firewalls/ for more information.
+randomize_client_port: false
- // Actually do the work... - evacuate_collection_set(&per_thread_states); +

问题就是出在几个文件路径的配置,默认都是当前目录,也就是headscale的可执行文件所在目录,需要按它配置说明中的生产配置进行修改

+
# For production:
+# /var/lib/headscale/private.key
+private_key_path: /var/lib/headscale/private.key
+

直接改成绝对路径就好了,还有两个文件路径
另一个也是个秘钥的路径问题

+
noise:
+  # The Noise private key is used to encrypt the
+  # traffic between headscale and Tailscale clients when
+  # using the new Noise-based protocol. It must be different
+  # from the legacy private key.
+  #
+  # For production:
+  # private_key_path: /var/lib/headscale/noise_private.key
+  private_key_path: /var/lib/headscale/noise_private.key
+

第二个问题

这个问题也是一种误导,
错误信息是

+
Error initializing error="unable to open database file: out of memory (14)"
+

这就是个文件,内存也完全没有被占满的迹象,原来也是文件路径的问题

+
# For production:
+# db_path: /var/lib/headscale/db.sqlite
+db_path: /var/lib/headscale/db.sqlite
+

都改成绝对路径就可以了,然后这里还有个就是要对/var/lib/headscale//etc/headscale/等路径赋予headscale用户权限,有时候对这类问题的排查真的蛮头疼,日志报错都不是真实的错误信息,开源项目对这些错误的提示真的也需要优化,后续的譬如mac也加入节点等后面再开篇讲

+]]>
+ + headscale + + + headscale + + + + JVM源码分析之G1垃圾收集器分析一 + /2019/12/07/JVM-G1-Part-1/ + 对 Java 的 gc 实现比较感兴趣,原先一般都是看周志明的书,但其实并没有讲具体的 gc 源码,而是把整个思路和流程讲解了一下
特别是 G1 的具体实现
一般对 G1 的理解其实就是把原先整块的新生代老年代分成了以 region 为单位的小块内存,简而言之,就是原先对新生代老年代的收集会涉及到整个代的堆内存空间,而G1 把它变成了更细致的小块内存
这带来了一个很明显的好处和一个很明显的坏处,好处是内存收集可以更灵活,耗时会变短,但整个收集的处理复杂度就变高了
目前看了一点点关于 G1 收集的预期时间相关的代码

+
HeapWord* G1CollectedHeap::do_collection_pause(size_t word_size,
+                                               uint gc_count_before,
+                                               bool* succeeded,
+                                               GCCause::Cause gc_cause) {
+  assert_heap_not_locked_and_not_at_safepoint();
+  VM_G1CollectForAllocation op(word_size,
+                               gc_count_before,
+                               gc_cause,
+                               false, /* should_initiate_conc_mark */
+                               g1_policy()->max_pause_time_ms());
+  VMThread::execute(&op);
 
-        post_evacuate_collection_set(evacuation_info, &per_thread_states);
+  HeapWord* result = op.result();
+  bool ret_succeeded = op.prologue_succeeded() && op.pause_succeeded();
+  assert(result == NULL || ret_succeeded,
+         "the result should be NULL if the VM did not succeed");
+  *succeeded = ret_succeeded;
 
-        const size_t* surviving_young_words = per_thread_states.surviving_young_words();
-        free_collection_set(&_collection_set, evacuation_info, surviving_young_words);
+  assert_heap_not_locked();
+  return result;
+}
+

这里就是收集时需要停顿的,其中VMThread::execute(&op);是具体执行的,真正执行的是VM_G1CollectForAllocation::doit方法

+
void VM_G1CollectForAllocation::doit() {
+  G1CollectedHeap* g1h = G1CollectedHeap::heap();
+  assert(!_should_initiate_conc_mark || g1h->should_do_concurrent_full_gc(_gc_cause),
+      "only a GC locker, a System.gc(), stats update, whitebox, or a hum allocation induced GC should start a cycle");
 
-        eagerly_reclaim_humongous_regions();
+  if (_word_size > 0) {
+    // An allocation has been requested. So, try to do that first.
+    _result = g1h->attempt_allocation_at_safepoint(_word_size,
+                                                   false /* expect_null_cur_alloc_region */);
+    if (_result != NULL) {
+      // If we can successfully allocate before we actually do the
+      // pause then we will consider this pause successful.
+      _pause_succeeded = true;
+      return;
+    }
+  }
 
-        record_obj_copy_mem_stats();
-        _survivor_evac_stats.adjust_desired_plab_sz();
-        _old_evac_stats.adjust_desired_plab_sz();
+  GCCauseSetter x(g1h, _gc_cause);
+  if (_should_initiate_conc_mark) {
+    // It's safer to read old_marking_cycles_completed() here, given
+    // that noone else will be updating it concurrently. Since we'll
+    // only need it if we're initiating a marking cycle, no point in
+    // setting it earlier.
+    _old_marking_cycles_completed_before = g1h->old_marking_cycles_completed();
 
-        double start = os::elapsedTime();
-        start_new_collection_set();
-        g1_policy()->phase_times()->record_start_new_cset_time_ms((os::elapsedTime() - start) * 1000.0);
+    // At this point we are supposed to start a concurrent cycle. We
+    // will do so if one is not already in progress.
+    bool res = g1h->g1_policy()->force_initial_mark_if_outside_cycle(_gc_cause);
 
-        if (evacuation_failed()) {
-          set_used(recalculate_used());
-          if (_archive_allocator != NULL) {
-            _archive_allocator->clear_used();
-          }
-          for (uint i = 0; i < ParallelGCThreads; i++) {
-            if (_evacuation_failed_info_array[i].has_failed()) {
-              _gc_tracer_stw->report_evacuation_failed(_evacuation_failed_info_array[i]);
-            }
-          }
-        } else {
-          // The "used" of the the collection set have already been subtracted
-          // when they were freed.  Add in the bytes evacuated.
-          increase_used(g1_policy()->bytes_copied_during_gc());
-        }
+    // The above routine returns true if we were able to force the
+    // next GC pause to be an initial mark; it returns false if a
+    // marking cycle is already in progress.
+    //
+    // If a marking cycle is already in progress just return and skip the
+    // pause below - if the reason for requesting this initial mark pause
+    // was due to a System.gc() then the requesting thread should block in
+    // doit_epilogue() until the marking cycle is complete.
+    //
+    // If this initial mark pause was requested as part of a humongous
+    // allocation then we know that the marking cycle must just have
+    // been started by another thread (possibly also allocating a humongous
+    // object) as there was no active marking cycle when the requesting
+    // thread checked before calling collect() in
+    // attempt_allocation_humongous(). Retrying the GC, in this case,
+    // will cause the requesting thread to spin inside collect() until the
+    // just started marking cycle is complete - which may be a while. So
+    // we do NOT retry the GC.
+    if (!res) {
+      assert(_word_size == 0, "Concurrent Full GC/Humongous Object IM shouldn't be allocating");
+      if (_gc_cause != GCCause::_g1_humongous_allocation) {
+        _should_retry_gc = true;
+      }
+      return;
+    }
+  }
 
-        if (collector_state()->in_initial_mark_gc()) {
-          // We have to do this before we notify the CM threads that
-          // they can start working to make sure that all the
-          // appropriate initialization is done on the CM object.
-          concurrent_mark()->post_initial_mark();
-          // Note that we don't actually trigger the CM thread at
-          // this point. We do that later when we're sure that
-          // the current thread has completed its logging output.
-        }
+  // Try a partial collection of some kind.
+  _pause_succeeded = g1h->do_collection_pause_at_safepoint(_target_pause_time_ms);
 
-        allocate_dummy_regions();
+  if (_pause_succeeded) {
+    if (_word_size > 0) {
+      // An allocation had been requested. Do it, eventually trying a stronger
+      // kind of GC.
+      _result = g1h->satisfy_failed_allocation(_word_size, &_pause_succeeded);
+    } else {
+      bool should_upgrade_to_full = !g1h->should_do_concurrent_full_gc(_gc_cause) &&
+                                    !g1h->has_regions_left_for_allocation();
+      if (should_upgrade_to_full) {
+        // There has been a request to perform a GC to free some space. We have no
+        // information on how much memory has been asked for. In case there are
+        // absolutely no regions left to allocate into, do a maximally compacting full GC.
+        log_info(gc, ergo)("Attempting maximally compacting collection");
+        _pause_succeeded = g1h->do_full_collection(false, /* explicit gc */
+                                                   true   /* clear_all_soft_refs */);
+      }
+    }
+    guarantee(_pause_succeeded, "Elevated collections during the safepoint must always succeed.");
+  } else {
+    assert(_result == NULL, "invariant");
+    // The only reason for the pause to not be successful is that, the GC locker is
+    // active (or has become active since the prologue was executed). In this case
+    // we should retry the pause after waiting for the GC locker to become inactive.
+    _should_retry_gc = true;
+  }
+}
+

这里可以看到核心的是G1CollectedHeap::do_collection_pause_at_safepoint这个方法,它带上了目标暂停时间的值

+
G1CollectedHeap::do_collection_pause_at_safepoint(double target_pause_time_ms) {
+  assert_at_safepoint_on_vm_thread();
+  guarantee(!is_gc_active(), "collection is not reentrant");
 
-        _allocator->init_mutator_alloc_region();
+  if (GCLocker::check_active_before_gc()) {
+    return false;
+  }
 
-        {
-          size_t expand_bytes = _heap_sizing_policy->expansion_amount();
-          if (expand_bytes > 0) {
-            size_t bytes_before = capacity();
-            // No need for an ergo logging here,
-            // expansion_amount() does this when it returns a value > 0.
-            double expand_ms;
-            if (!expand(expand_bytes, _workers, &expand_ms)) {
-              // We failed to expand the heap. Cannot do anything about it.
-            }
-            g1_policy()->phase_times()->record_expand_heap_time(expand_ms);
-          }
-        }
+  _gc_timer_stw->register_gc_start();
 
-        // We redo the verification but now wrt to the new CSet which
-        // has just got initialized after the previous CSet was freed.
-        _cm->verify_no_cset_oops();
+  GCIdMark gc_id_mark;
+  _gc_tracer_stw->report_gc_start(gc_cause(), _gc_timer_stw->gc_start());
 
-        // This timing is only used by the ergonomics to handle our pause target.
-        // It is unclear why this should not include the full pause. We will
-        // investigate this in CR 7178365.
-        double sample_end_time_sec = os::elapsedTime();
-        double pause_time_ms = (sample_end_time_sec - sample_start_time_sec) * MILLIUNITS;
-        size_t total_cards_scanned = g1_policy()->phase_times()->sum_thread_work_items(G1GCPhaseTimes::ScanRS, G1GCPhaseTimes::ScanRSScannedCards);
-        g1_policy()->record_collection_pause_end(pause_time_ms, total_cards_scanned, heap_used_bytes_before_gc);
+  SvcGCMarker sgcm(SvcGCMarker::MINOR);
+  ResourceMark rm;
 
-        evacuation_info.set_collectionset_used_before(collection_set()->bytes_used_before());
-        evacuation_info.set_bytes_copied(g1_policy()->bytes_copied_during_gc());
+  g1_policy()->note_gc_start();
 
-        if (VerifyRememberedSets) {
-          log_info(gc, verify)("[Verifying RemSets after GC]");
-          VerifyRegionRemSetClosure v_cl;
-          heap_region_iterate(&v_cl);
-        }
+  wait_for_root_region_scanning();
 
-        _verifier->verify_after_gc(verify_type);
-        _verifier->check_bitmaps("GC End");
+  print_heap_before_gc();
+  print_heap_regions();
+  trace_heap_before_gc(_gc_tracer_stw);
 
-        assert(!_ref_processor_stw->discovery_enabled(), "Postcondition");
-        _ref_processor_stw->verify_no_references_recorded();
+  _verifier->verify_region_sets_optional();
+  _verifier->verify_dirty_young_regions();
 
-        // CM reference discovery will be re-enabled if necessary.
-      }
+  // We should not be doing initial mark unless the conc mark thread is running
+  if (!_cm_thread->should_terminate()) {
+    // This call will decide whether this pause is an initial-mark
+    // pause. If it is, in_initial_mark_gc() will return true
+    // for the duration of this pause.
+    g1_policy()->decide_on_conc_mark_initiation();
+  }
 
-#ifdef TRACESPINNING
-      ParallelTaskTerminator::print_termination_counts();
-#endif
+  // We do not allow initial-mark to be piggy-backed on a mixed GC.
+  assert(!collector_state()->in_initial_mark_gc() ||
+          collector_state()->in_young_only_phase(), "sanity");
 
-      gc_epilogue(false);
-    }
+  // We also do not allow mixed GCs during marking.
+  assert(!collector_state()->mark_or_rebuild_in_progress() || collector_state()->in_young_only_phase(), "sanity");
 
-    // Print the remainder of the GC log output.
-    if (evacuation_failed()) {
-      log_info(gc)("To-space exhausted");
-    }
+  // Record whether this pause is an initial mark. When the current
+  // thread has completed its logging output and it's safe to signal
+  // the CM thread, the flag's value in the policy has been reset.
+  bool should_start_conc_mark = collector_state()->in_initial_mark_gc();
 
-    g1_policy()->print_phases();
-    heap_transition.print();
+  // Inner scope for scope based logging, timers, and stats collection
+  {
+    EvacuationInfo evacuation_info;
 
-    // It is not yet to safe to tell the concurrent mark to
-    // start as we have some optional output below. We don't want the
+    if (collector_state()->in_initial_mark_gc()) {
+      // We are about to start a marking cycle, so we increment the
+      // full collection counter.
+      increment_old_marking_cycles_started();
+      _cm->gc_tracer_cm()->set_gc_cause(gc_cause());
+    }
+
+    _gc_tracer_stw->report_yc_type(collector_state()->yc_type());
+
+    GCTraceCPUTime tcpu;
+
+    G1HeapVerifier::G1VerifyType verify_type;
+    FormatBuffer<> gc_string("Pause Young ");
+    if (collector_state()->in_initial_mark_gc()) {
+      gc_string.append("(Concurrent Start)");
+      verify_type = G1HeapVerifier::G1VerifyConcurrentStart;
+    } else if (collector_state()->in_young_only_phase()) {
+      if (collector_state()->in_young_gc_before_mixed()) {
+        gc_string.append("(Prepare Mixed)");
+      } else {
+        gc_string.append("(Normal)");
+      }
+      verify_type = G1HeapVerifier::G1VerifyYoungNormal;
+    } else {
+      gc_string.append("(Mixed)");
+      verify_type = G1HeapVerifier::G1VerifyMixed;
+    }
+    GCTraceTime(Info, gc) tm(gc_string, NULL, gc_cause(), true);
+
+    uint active_workers = AdaptiveSizePolicy::calc_active_workers(workers()->total_workers(),
+                                                                  workers()->active_workers(),
+                                                                  Threads::number_of_non_daemon_threads());
+    active_workers = workers()->update_active_workers(active_workers);
+    log_info(gc,task)("Using %u workers of %u for evacuation", active_workers, workers()->total_workers());
+
+    TraceCollectorStats tcs(g1mm()->incremental_collection_counters());
+    TraceMemoryManagerStats tms(&_memory_manager, gc_cause(),
+                                collector_state()->yc_type() == Mixed /* allMemoryPoolsAffected */);
+
+    G1HeapTransition heap_transition(this);
+    size_t heap_used_bytes_before_gc = used();
+
+    // Don't dynamically change the number of GC threads this early.  A value of
+    // 0 is used to indicate serial work.  When parallel work is done,
+    // it will be set.
+
+    { // Call to jvmpi::post_class_unload_events must occur outside of active GC
+      IsGCActiveMark x;
+
+      gc_prologue(false);
+
+      if (VerifyRememberedSets) {
+        log_info(gc, verify)("[Verifying RemSets before GC]");
+        VerifyRegionRemSetClosure v_cl;
+        heap_region_iterate(&v_cl);
+      }
+
+      _verifier->verify_before_gc(verify_type);
+
+      _verifier->check_bitmaps("GC Start");
+
+#if COMPILER2_OR_JVMCI
+      DerivedPointerTable::clear();
+#endif
+
+      // Please see comment in g1CollectedHeap.hpp and
+      // G1CollectedHeap::ref_processing_init() to see how
+      // reference processing currently works in G1.
+
+      // Enable discovery in the STW reference processor
+      _ref_processor_stw->enable_discovery();
+
+      {
+        // We want to temporarily turn off discovery by the
+        // CM ref processor, if necessary, and turn it back on
+        // on again later if we do. Using a scoped
+        // NoRefDiscovery object will do this.
+        NoRefDiscovery no_cm_discovery(_ref_processor_cm);
+
+        // Forget the current alloc region (we might even choose it to be part
+        // of the collection set!).
+        _allocator->release_mutator_alloc_region();
+
+        // This timing is only used by the ergonomics to handle our pause target.
+        // It is unclear why this should not include the full pause. We will
+        // investigate this in CR 7178365.
+        //
+        // Preserving the old comment here if that helps the investigation:
+        //
+        // The elapsed time induced by the start time below deliberately elides
+        // the possible verification above.
+        double sample_start_time_sec = os::elapsedTime();
+
+        g1_policy()->record_collection_pause_start(sample_start_time_sec);
+
+        if (collector_state()->in_initial_mark_gc()) {
+          concurrent_mark()->pre_initial_mark();
+        }
+
+        g1_policy()->finalize_collection_set(target_pause_time_ms, &_survivor);
+
+        evacuation_info.set_collectionset_regions(collection_set()->region_length());
+
+        // Make sure the remembered sets are up to date. This needs to be
+        // done before register_humongous_regions_with_cset(), because the
+        // remembered sets are used there to choose eager reclaim candidates.
+        // If the remembered sets are not up to date we might miss some
+        // entries that need to be handled.
+        g1_rem_set()->cleanupHRRS();
+
+        register_humongous_regions_with_cset();
+
+        assert(_verifier->check_cset_fast_test(), "Inconsistency in the InCSetState table.");
+
+        // We call this after finalize_cset() to
+        // ensure that the CSet has been finalized.
+        _cm->verify_no_cset_oops();
+
+        if (_hr_printer.is_active()) {
+          G1PrintCollectionSetClosure cl(&_hr_printer);
+          _collection_set.iterate(&cl);
+        }
+
+        // Initialize the GC alloc regions.
+        _allocator->init_gc_alloc_regions(evacuation_info);
+
+        G1ParScanThreadStateSet per_thread_states(this, workers()->active_workers(), collection_set()->young_region_length());
+        pre_evacuate_collection_set();
+
+        // Actually do the work...
+        evacuate_collection_set(&per_thread_states);
+
+        post_evacuate_collection_set(evacuation_info, &per_thread_states);
+
+        const size_t* surviving_young_words = per_thread_states.surviving_young_words();
+        free_collection_set(&_collection_set, evacuation_info, surviving_young_words);
+
+        eagerly_reclaim_humongous_regions();
+
+        record_obj_copy_mem_stats();
+        _survivor_evac_stats.adjust_desired_plab_sz();
+        _old_evac_stats.adjust_desired_plab_sz();
+
+        double start = os::elapsedTime();
+        start_new_collection_set();
+        g1_policy()->phase_times()->record_start_new_cset_time_ms((os::elapsedTime() - start) * 1000.0);
+
+        if (evacuation_failed()) {
+          set_used(recalculate_used());
+          if (_archive_allocator != NULL) {
+            _archive_allocator->clear_used();
+          }
+          for (uint i = 0; i < ParallelGCThreads; i++) {
+            if (_evacuation_failed_info_array[i].has_failed()) {
+              _gc_tracer_stw->report_evacuation_failed(_evacuation_failed_info_array[i]);
+            }
+          }
+        } else {
+          // The "used" of the the collection set have already been subtracted
+          // when they were freed.  Add in the bytes evacuated.
+          increase_used(g1_policy()->bytes_copied_during_gc());
+        }
+
+        if (collector_state()->in_initial_mark_gc()) {
+          // We have to do this before we notify the CM threads that
+          // they can start working to make sure that all the
+          // appropriate initialization is done on the CM object.
+          concurrent_mark()->post_initial_mark();
+          // Note that we don't actually trigger the CM thread at
+          // this point. We do that later when we're sure that
+          // the current thread has completed its logging output.
+        }
+
+        allocate_dummy_regions();
+
+        _allocator->init_mutator_alloc_region();
+
+        {
+          size_t expand_bytes = _heap_sizing_policy->expansion_amount();
+          if (expand_bytes > 0) {
+            size_t bytes_before = capacity();
+            // No need for an ergo logging here,
+            // expansion_amount() does this when it returns a value > 0.
+            double expand_ms;
+            if (!expand(expand_bytes, _workers, &expand_ms)) {
+              // We failed to expand the heap. Cannot do anything about it.
+            }
+            g1_policy()->phase_times()->record_expand_heap_time(expand_ms);
+          }
+        }
+
+        // We redo the verification but now wrt to the new CSet which
+        // has just got initialized after the previous CSet was freed.
+        _cm->verify_no_cset_oops();
+
+        // This timing is only used by the ergonomics to handle our pause target.
+        // It is unclear why this should not include the full pause. We will
+        // investigate this in CR 7178365.
+        double sample_end_time_sec = os::elapsedTime();
+        double pause_time_ms = (sample_end_time_sec - sample_start_time_sec) * MILLIUNITS;
+        size_t total_cards_scanned = g1_policy()->phase_times()->sum_thread_work_items(G1GCPhaseTimes::ScanRS, G1GCPhaseTimes::ScanRSScannedCards);
+        g1_policy()->record_collection_pause_end(pause_time_ms, total_cards_scanned, heap_used_bytes_before_gc);
+
+        evacuation_info.set_collectionset_used_before(collection_set()->bytes_used_before());
+        evacuation_info.set_bytes_copied(g1_policy()->bytes_copied_during_gc());
+
+        if (VerifyRememberedSets) {
+          log_info(gc, verify)("[Verifying RemSets after GC]");
+          VerifyRegionRemSetClosure v_cl;
+          heap_region_iterate(&v_cl);
+        }
+
+        _verifier->verify_after_gc(verify_type);
+        _verifier->check_bitmaps("GC End");
+
+        assert(!_ref_processor_stw->discovery_enabled(), "Postcondition");
+        _ref_processor_stw->verify_no_references_recorded();
+
+        // CM reference discovery will be re-enabled if necessary.
+      }
+
+#ifdef TRACESPINNING
+      ParallelTaskTerminator::print_termination_counts();
+#endif
+
+      gc_epilogue(false);
+    }
+
+    // Print the remainder of the GC log output.
+    if (evacuation_failed()) {
+      log_info(gc)("To-space exhausted");
+    }
+
+    g1_policy()->print_phases();
+    heap_transition.print();
+
+    // It is not yet to safe to tell the concurrent mark to
+    // start as we have some optional output below. We don't want the
     // output from the concurrent mark thread interfering with this
     // logging output either.
 
@@ -2928,30 +2972,102 @@ Node *clone(Node *graph) {
       
         Java
         JVM
-        GC
         C++
+        GC
       
       
         Java
-        JVM
         C++
+        JVM
       
   
   
-    Leetcode 028 实现 strStr() ( Implement strStr() ) 题解分析
-    /2021/10/31/Leetcode-028-%E5%AE%9E%E7%8E%B0-strStr-Implement-strStr-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/
-    题目介绍

Implement strStr().

-

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

-

Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

-

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C’s strstr() and Java’s indexOf().

-

示例

Example 1:

-
Input: haystack = "hello", needle = "ll"
-Output: 2
-

Example 2:

-
Input: haystack = "aaaaa", needle = "bba"
-Output: -1
-

Example 3:

-
Input: haystack = "", needle = ""
+    Leetcode 021 合并两个有序链表 ( Merge Two Sorted Lists ) 题解分析
+    /2021/10/07/Leetcode-021-%E5%90%88%E5%B9%B6%E4%B8%A4%E4%B8%AA%E6%9C%89%E5%BA%8F%E9%93%BE%E8%A1%A8-Merge-Two-Sorted-Lists-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/
+    题目介绍

Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.

+

将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

+

示例 1

+
+

输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]

+
+

示例 2

+

输入: l1 = [], l2 = []
输出: []

+
+

示例 3

+

输入: l1 = [], l2 = [0]
输出: [0]

+
+

简要分析

这题是 Easy 的,看着也挺简单,两个链表进行合并,就是比较下大小,可能将就点的话最好就在两个链表中原地合并

+

题解代码

public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
+        // 下面两个if判断了入参的边界,如果其一为null,直接返回另一个就可以了
+        if (l1 == null) {
+            return l2;
+        }
+        if (l2 == null) {
+            return l1;
+        }
+        // new 一个合并后的头结点
+        ListNode merged = new ListNode();
+        // 这个是当前节点
+        ListNode current = merged;
+        // 一开始给这个while加了l1和l2不全为null的条件,后面想了下不需要
+        // 因为内部前两个if就是跳出条件
+        while (true) {
+            if (l1 == null) {
+                // 这里其实跟开头类似,只不过这里需要将l2剩余部分接到merged链表后面
+                // 所以不能是直接current = l2,这样就是把后面的直接丢了
+                current.val = l2.val;
+                current.next = l2.next;
+                break;
+            }
+            if (l2 == null) {
+                current.val = l1.val;
+                current.next = l1.next;
+                break;
+            }
+            // 这里是两个链表都不为空的时候,就比较下大小
+            if (l1.val < l2.val) {
+                current.val = l1.val;
+                l1 = l1.next;
+            } else {
+                current.val = l2.val;
+                l2 = l2.next;
+            }
+            // 这里是new个新的,其实也可以放在循环头上
+            current.next = new ListNode();
+            current = current.next;
+        }
+        current = null;
+        // 返回这个头结点
+        return merged;
+    }
+ +

结果

+]]>
+ + Java + leetcode + + + java + leetcode + 题解 + + + + Leetcode 028 实现 strStr() ( Implement strStr() ) 题解分析 + /2021/10/31/Leetcode-028-%E5%AE%9E%E7%8E%B0-strStr-Implement-strStr-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/ + 题目介绍

Implement strStr().

+

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

+

Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

+

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C’s strstr() and Java’s indexOf().

+

示例

Example 1:

+
Input: haystack = "hello", needle = "ll"
+Output: 2
+

Example 2:

+
Input: haystack = "aaaaa", needle = "bba"
+Output: -1
+

Example 3:

+
Input: haystack = "", needle = ""
 Output: 0

题解

字符串比较其实是写代码里永恒的主题,底层的编译器等处理肯定需要字符串对比,像 kmp 算法也是很厉害

@@ -3007,8 +3123,8 @@ Output: 0
@@ -3046,94 +3162,9 @@ Output: 0
public SqlSource parseScriptNode() {
-  MixedSqlNode rootSqlNode = parseDynamicTags(context);
-  SqlSource sqlSource;
-  if (isDynamic) {
-    sqlSource = new DynamicSqlSource(configuration, rootSqlNode);
-  } else {
-    sqlSource = new RawSqlSource(configuration, rootSqlNode, parameterType);
+

这里主要是创建了Builder包含了Parser
然后调用parse方法

+
public Configuration parse() {
+  if (parsed) {
+    throw new BuilderException("Each XMLConfigBuilder can only be used once.");
   }
-  return sqlSource;
+  // 标记下是否已解析,但是这里是否有线程安全问题
+  parsed = true;
+  // --------> 解析配置
+  parseConfiguration(parser.evalNode("/configuration"));
+  return configuration;
 }
-

首先要解析dynamicTag,调用了org.apache.ibatis.scripting.xmltags.XMLScriptBuilder#parseDynamicTags

-
protected MixedSqlNode parseDynamicTags(XNode node) {
-    List<SqlNode> contents = new ArrayList<>();
-    NodeList children = node.getNode().getChildNodes();
-    for (int i = 0; i < children.getLength(); i++) {
-      XNode child = node.newXNode(children.item(i));
-      if (child.getNode().getNodeType() == Node.CDATA_SECTION_NODE || child.getNode().getNodeType() == Node.TEXT_NODE) {
-        String data = child.getStringBody("");
-        TextSqlNode textSqlNode = new TextSqlNode(data);
-        // ---------> 主要是这边的逻辑
-        if (textSqlNode.isDynamic()) {
-          contents.add(textSqlNode);
-          isDynamic = true;
+

实际的解析区分了各类标签

+
private void parseConfiguration(XNode root) {
+  try {
+    // issue #117 read properties first
+    // 解析properties,这个不是spring自带的,需要额外配置,并且在config文件里应该放在最前
+    propertiesElement(root.evalNode("properties"));
+    Properties settings = settingsAsProperties(root.evalNode("settings"));
+    loadCustomVfs(settings);
+    loadCustomLogImpl(settings);
+    typeAliasesElement(root.evalNode("typeAliases"));
+    pluginElement(root.evalNode("plugins"));
+    objectFactoryElement(root.evalNode("objectFactory"));
+    objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
+    reflectorFactoryElement(root.evalNode("reflectorFactory"));
+    settingsElement(settings);
+    // read it after objectFactory and objectWrapperFactory issue #631
+    environmentsElement(root.evalNode("environments"));
+    databaseIdProviderElement(root.evalNode("databaseIdProvider"));
+    typeHandlerElement(root.evalNode("typeHandlers"));
+    // ----------> 我们需要关注的是mapper的处理
+    mapperElement(root.evalNode("mappers"));
+  } catch (Exception e) {
+    throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
+  }
+}
+ +

然后就是调用到mapperElement方法了

+
private void mapperElement(XNode parent) throws Exception {
+  if (parent != null) {
+    for (XNode child : parent.getChildren()) {
+      if ("package".equals(child.getName())) {
+        String mapperPackage = child.getStringAttribute("name");
+        configuration.addMappers(mapperPackage);
+      } else {
+        String resource = child.getStringAttribute("resource");
+        String url = child.getStringAttribute("url");
+        String mapperClass = child.getStringAttribute("class");
+        if (resource != null && url == null && mapperClass == null) {
+          ErrorContext.instance().resource(resource);
+          try(InputStream inputStream = Resources.getResourceAsStream(resource)) {
+            XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
+            // --------> 我们这没有指定package,所以是走到这
+            mapperParser.parse();
+          }
+        } else if (resource == null && url != null && mapperClass == null) {
+          ErrorContext.instance().resource(url);
+          try(InputStream inputStream = Resources.getUrlAsStream(url)){
+            XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());
+            mapperParser.parse();
+          }
+        } else if (resource == null && url == null && mapperClass != null) {
+          Class<?> mapperInterface = Resources.classForName(mapperClass);
+          configuration.addMapper(mapperInterface);
         } else {
-          contents.add(new StaticTextSqlNode(data));
-        }
-      } else if (child.getNode().getNodeType() == Node.ELEMENT_NODE) { // issue #628
-        String nodeName = child.getNode().getNodeName();
-        NodeHandler handler = nodeHandlerMap.get(nodeName);
-        if (handler == null) {
-          throw new BuilderException("Unknown element <" + nodeName + "> in SQL statement.");
+          throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");
         }
-        handler.handleNode(child, contents);
-        isDynamic = true;
       }
     }
-    return new MixedSqlNode(contents);
-  }
+ } +}
-

判断是否是动态sql,调用了org.apache.ibatis.scripting.xmltags.TextSqlNode#isDynamic

-
public boolean isDynamic() {
-  DynamicCheckerTokenParser checker = new DynamicCheckerTokenParser();
-  // ----------> 主要是这里的方法
-  GenericTokenParser parser = createParser(checker);
-  parser.parse(text);
-  return checker.isDynamic();
+

核心就在这个parse()方法

+
public void parse() {
+  if (!configuration.isResourceLoaded(resource)) {
+    // -------> 然后就是走到这里,配置xml的mapper节点的内容
+    configurationElement(parser.evalNode("/mapper"));
+    configuration.addLoadedResource(resource);
+    bindMapperForNamespace();
+  }
+
+  parsePendingResultMaps();
+  parsePendingCacheRefs();
+  parsePendingStatements();
+}
+ +

具体的处理逻辑

+
private void configurationElement(XNode context) {
+  try {
+    String namespace = context.getStringAttribute("namespace");
+    if (namespace == null || namespace.isEmpty()) {
+      throw new BuilderException("Mapper's namespace cannot be empty");
+    }
+    builderAssistant.setCurrentNamespace(namespace);
+    cacheRefElement(context.evalNode("cache-ref"));
+    cacheElement(context.evalNode("cache"));
+    parameterMapElement(context.evalNodes("/mapper/parameterMap"));
+    resultMapElements(context.evalNodes("/mapper/resultMap"));
+    sqlElement(context.evalNodes("/mapper/sql"));
+    // ------->  走到这,从上下文构建statement
+    buildStatementFromContext(context.evalNodes("select|insert|update|delete"));
+  } catch (Exception e) {
+    throw new BuilderException("Error parsing Mapper XML. The XML location is '" + resource + "'. Cause: " + e, e);
+  }
+}
+ +

具体代码在这,从上下文构建statement,只不过区分了下databaseId

+
private void buildStatementFromContext(List<XNode> list) {
+  if (configuration.getDatabaseId() != null) {
+    buildStatementFromContext(list, configuration.getDatabaseId());
+  }
+  // -----> 判断databaseId
+  buildStatementFromContext(list, null);
 }
-

创建parser的时候可以看到这个parser是干了啥,其实就是找有没有${ , }

-
private GenericTokenParser createParser(TokenHandler handler) {
-  return new GenericTokenParser("${", "}", handler);
-}
+

判断下databaseId

+
private void buildStatementFromContext(List<XNode> list, String requiredDatabaseId) {
+  for (XNode context : list) {
+    final XMLStatementBuilder statementParser = new XMLStatementBuilder(configuration, builderAssistant, context, requiredDatabaseId);
+    try {
+      // -------> 解析statement节点
+      statementParser.parseStatementNode();
+    } catch (IncompleteElementException e) {
+      configuration.addIncompleteStatement(statementParser);
+    }
+  }
+}
-

如果是的话,就在上面把 isDynamic 设置为true 如果是true 的话就创建 DynamicSqlSource

-
sqlSource = new DynamicSqlSource(configuration, rootSqlNode);
+

接下来就是真正处理的xml语句内容的,各个节点的信息内容

+
public void parseStatementNode() {
+  String id = context.getStringAttribute("id");
+  String databaseId = context.getStringAttribute("databaseId");
 
-

如果不是的话就创建RawSqlSource

-
sqlSource = new RawSqlSource(configuration, rootSqlNode, parameterType);
-```java
+  if (!databaseIdMatchesCurrent(id, databaseId, this.requiredDatabaseId)) {
+    return;
+  }
 
-但是这不是一个真实可用的 `sqlSource` ,
-实际创建的时候会走到这
-```java
-public RawSqlSource(Configuration configuration, SqlNode rootSqlNode, Class<?> parameterType) {
-    this(configuration, getSql(configuration, rootSqlNode), parameterType);
+  String nodeName = context.getNode().getNodeName();
+  SqlCommandType sqlCommandType = SqlCommandType.valueOf(nodeName.toUpperCase(Locale.ENGLISH));
+  boolean isSelect = sqlCommandType == SqlCommandType.SELECT;
+  boolean flushCache = context.getBooleanAttribute("flushCache", !isSelect);
+  boolean useCache = context.getBooleanAttribute("useCache", isSelect);
+  boolean resultOrdered = context.getBooleanAttribute("resultOrdered", false);
+
+  // Include Fragments before parsing
+  XMLIncludeTransformer includeParser = new XMLIncludeTransformer(configuration, builderAssistant);
+  includeParser.applyIncludes(context.getNode());
+
+  String parameterType = context.getStringAttribute("parameterType");
+  Class<?> parameterTypeClass = resolveClass(parameterType);
+
+  String lang = context.getStringAttribute("lang");
+  LanguageDriver langDriver = getLanguageDriver(lang);
+
+  // Parse selectKey after includes and remove them.
+  processSelectKeyNodes(id, parameterTypeClass, langDriver);
+
+  // Parse the SQL (pre: <selectKey> and <include> were parsed and removed)
+  KeyGenerator keyGenerator;
+  String keyStatementId = id + SelectKeyGenerator.SELECT_KEY_SUFFIX;
+  keyStatementId = builderAssistant.applyCurrentNamespace(keyStatementId, true);
+  if (configuration.hasKeyGenerator(keyStatementId)) {
+    keyGenerator = configuration.getKeyGenerator(keyStatementId);
+  } else {
+    keyGenerator = context.getBooleanAttribute("useGeneratedKeys",
+        configuration.isUseGeneratedKeys() && SqlCommandType.INSERT.equals(sqlCommandType))
+        ? Jdbc3KeyGenerator.INSTANCE : NoKeyGenerator.INSTANCE;
   }
 
-  public RawSqlSource(Configuration configuration, String sql, Class<?> parameterType) {
-    SqlSourceBuilder sqlSourceParser = new SqlSourceBuilder(configuration);
-    Class<?> clazz = parameterType == null ? Object.class : parameterType;
-    sqlSource = sqlSourceParser.parse(sql, clazz, new HashMap<>());
-  }
+ // 语句的主要参数解析 + SqlSource sqlSource = langDriver.createSqlSource(configuration, context, parameterTypeClass); + StatementType statementType = StatementType.valueOf(context.getStringAttribute("statementType", StatementType.PREPARED.toString())); + Integer fetchSize = context.getIntAttribute("fetchSize"); + Integer timeout = context.getIntAttribute("timeout"); + String parameterMap = context.getStringAttribute("parameterMap"); + String resultType = context.getStringAttribute("resultType"); + Class<?> resultTypeClass = resolveClass(resultType); + String resultMap = context.getStringAttribute("resultMap"); + String resultSetType = context.getStringAttribute("resultSetType"); + ResultSetType resultSetTypeEnum = resolveResultSetType(resultSetType); + if (resultSetTypeEnum == null) { + resultSetTypeEnum = configuration.getDefaultResultSetType(); + } + String keyProperty = context.getStringAttribute("keyProperty"); + String keyColumn = context.getStringAttribute("keyColumn"); + String resultSets = context.getStringAttribute("resultSets"); + + // --------> 添加映射的statement + builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType, + fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass, + resultSetTypeEnum, flushCache, useCache, resultOrdered, + keyGenerator, keyProperty, keyColumn, databaseId, langDriver, resultSets); +}
+ + +

添加的逻辑具体可以看下

+
public MappedStatement addMappedStatement(
+    String id,
+    SqlSource sqlSource,
+    StatementType statementType,
+    SqlCommandType sqlCommandType,
+    Integer fetchSize,
+    Integer timeout,
+    String parameterMap,
+    Class<?> parameterType,
+    String resultMap,
+    Class<?> resultType,
+    ResultSetType resultSetType,
+    boolean flushCache,
+    boolean useCache,
+    boolean resultOrdered,
+    KeyGenerator keyGenerator,
+    String keyProperty,
+    String keyColumn,
+    String databaseId,
+    LanguageDriver lang,
+    String resultSets) {
 
-

具体的sqlSource是通过org.apache.ibatis.builder.SqlSourceBuilder#parse 创建的
具体的代码逻辑是

-
public SqlSource parse(String originalSql, Class<?> parameterType, Map<String, Object> additionalParameters) {
-  ParameterMappingTokenHandler handler = new ParameterMappingTokenHandler(configuration, parameterType, additionalParameters);
-  GenericTokenParser parser = new GenericTokenParser("#{", "}", handler);
-  String sql;
-  if (configuration.isShrinkWhitespacesInSql()) {
-    sql = parser.parse(removeExtraWhitespaces(originalSql));
-  } else {
-    sql = parser.parse(originalSql);
+  if (unresolvedCacheRef) {
+    throw new IncompleteElementException("Cache-ref not yet resolved");
   }
-  return new StaticSqlSource(configuration, sql, handler.getParameterMappings());
-}
- -

这里创建的其实是StaticSqlSource ,多带一句前面的parser是将原来这样select * from student where id = #{id}sql 解析成了select * from student where id = ? 然后创建了StaticSqlSource

-
public StaticSqlSource(Configuration configuration, String sql, List<ParameterMapping> parameterMappings) {
-  this.sql = sql;
-  this.parameterMappings = parameterMappings;
-  this.configuration = configuration;
-}
- -

为什么前面要讲这么多好像没什么关系的代码呢,其实在最开始我们执行sql的代码中

-
@Override
-  public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
-    BoundSql boundSql = ms.getBoundSql(parameterObject);
-    CacheKey key = createCacheKey(ms, parameterObject, rowBounds, boundSql);
-    return query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
-  }
-

这里获取了BoundSql,而BoundSql是怎么来的呢,首先调用了org.apache.ibatis.mapping.MappedStatement#getBoundSql

-
public BoundSql getBoundSql(Object parameterObject) {
-    BoundSql boundSql = sqlSource.getBoundSql(parameterObject);
-    List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
-    if (parameterMappings == null || parameterMappings.isEmpty()) {
-      boundSql = new BoundSql(configuration, boundSql.getSql(), parameterMap.getParameterMappings(), parameterObject);
-    }
+  id = applyCurrentNamespace(id, false);
+  boolean isSelect = sqlCommandType == SqlCommandType.SELECT;
 
-    // check for nested result maps in parameter mappings (issue #30)
-    for (ParameterMapping pm : boundSql.getParameterMappings()) {
-      String rmId = pm.getResultMapId();
-      if (rmId != null) {
-        ResultMap rm = configuration.getResultMap(rmId);
-        if (rm != null) {
-          hasNestedResultMaps |= rm.hasNestedResultMaps();
-        }
-      }
-    }
+  MappedStatement.Builder statementBuilder = new MappedStatement.Builder(configuration, id, sqlSource, sqlCommandType)
+      .resource(resource)
+      .fetchSize(fetchSize)
+      .timeout(timeout)
+      .statementType(statementType)
+      .keyGenerator(keyGenerator)
+      .keyProperty(keyProperty)
+      .keyColumn(keyColumn)
+      .databaseId(databaseId)
+      .lang(lang)
+      .resultOrdered(resultOrdered)
+      .resultSets(resultSets)
+      .resultMaps(getStatementResultMaps(resultMap, resultType, id))
+      .resultSetType(resultSetType)
+      .flushCacheRequired(valueOrDefault(flushCache, !isSelect))
+      .useCache(valueOrDefault(useCache, isSelect))
+      .cache(currentCache);
 
-    return boundSql;
-  }
+ ParameterMap statementParameterMap = getStatementParameterMap(parameterMap, parameterType, id); + if (statementParameterMap != null) { + statementBuilder.parameterMap(statementParameterMap); + } -

而我们从上面的解析中可以看到这里的sqlSource是一层RawSqlSource , 它的getBoundSql又是调用内部的sqlSource的方法

-
@Override
-public BoundSql getBoundSql(Object parameterObject) {
-  return sqlSource.getBoundSql(parameterObject);
-}
+ MappedStatement statement = statementBuilder.build(); + // ------> 正好是这里在configuration中添加了映射好的statement + configuration.addMappedStatement(statement); + return statement; +}
-

内部的sqlSource 就是StaticSqlSource

-
@Override
-public BoundSql getBoundSql(Object parameterObject) {
-  return new BoundSql(configuration, sql, parameterMappings, parameterObject);
-}
+

而里面就是往map里添加

+
public void addMappedStatement(MappedStatement ms) {
+  mappedStatements.put(ms.getId(), ms);
+}
-

这个BoundSql的内容也比较简单

-
public BoundSql(Configuration configuration, String sql, List<ParameterMapping> parameterMappings, Object parameterObject) {
-  this.sql = sql;
-  this.parameterMappings = parameterMappings;
-  this.parameterObject = parameterObject;
-  this.additionalParameters = new HashMap<>();
-  this.metaParameters = configuration.newMetaObject(additionalParameters);
-}
+

获取mapper

StudentDO studentDO = session.selectOne("com.nicksxs.mybatisdemo.StudentMapper.selectStudent", 1);
-

而上次在这边org.apache.ibatis.executor.SimpleExecutor#doQuery 的时候落了个东西,就是StatementHandler的逻辑

-
@Override
-public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
-  Statement stmt = null;
-  try {
-    Configuration configuration = ms.getConfiguration();
-    StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
-    stmt = prepareStatement(handler, ms.getStatementLog());
-    return handler.query(stmt, resultHandler);
-  } finally {
-    closeStatement(stmt);
+

就是调用了 org.apache.ibatis.session.defaults.DefaultSqlSession#selectOne(java.lang.String, java.lang.Object)

+
public <T> T selectOne(String statement, Object parameter) {
+  // Popular vote was to return null on 0 results and throw exception on too many.
+  List<T> list = this.selectList(statement, parameter);
+  if (list.size() == 1) {
+    return list.get(0);
+  } else if (list.size() > 1) {
+    throw new TooManyResultsException("Expected one result (or null) to be returned by selectOne(), but found: " + list.size());
+  } else {
+    return null;
   }
-}
+}
-

它是通过statementType来区分应该使用哪个statementHandler,我们这使用的就是PreparedStatementHandler

-
public RoutingStatementHandler(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
+

调用实际的实现方法

+
public <E> List<E> selectList(String statement, Object parameter) {
+  return this.selectList(statement, parameter, RowBounds.DEFAULT);
+}
- switch (ms.getStatementType()) { - case STATEMENT: - delegate = new SimpleStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql); - break; - case PREPARED: - delegate = new PreparedStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql); - break; - case CALLABLE: - delegate = new CallableStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql); - break; - default: - throw new ExecutorException("Unknown statement type: " + ms.getStatementType()); - } +

这里还有一层

+
public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
+  return selectList(statement, parameter, rowBounds, Executor.NO_RESULT_HANDLER);
+}
-}
-

所以上次有个细节可以补充,这边的doQuery里面的handler.query 应该是调用了PreparedStatementHandler 的query方法

-
@Override
-public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
-  Statement stmt = null;
+

根本的就是从configuration里获取了mappedStatement

+
private <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) {
   try {
-    Configuration configuration = ms.getConfiguration();
-    StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
-    stmt = prepareStatement(handler, ms.getStatementLog());
-    return handler.query(stmt, resultHandler);
+    // 这里进行了获取
+    MappedStatement ms = configuration.getMappedStatement(statement);
+    return executor.query(ms, wrapCollection(parameter), rowBounds, handler);
+  } catch (Exception e) {
+    throw ExceptionFactory.wrapException("Error querying database.  Cause: " + e, e);
   } finally {
-    closeStatement(stmt);
+    ErrorContext.instance().reset();
   }
-}
- - -

因为上面prepareStatement中getConnection拿到connection是com.mysql.cj.jdbc.ConnectionImpl#ConnectionImpl(com.mysql.cj.conf.HostInfo)

-
@Override
-public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
-  PreparedStatement ps = (PreparedStatement) statement;
-  ps.execute();
-  return resultSetHandler.handleResultSets(ps);
-}
+}
+]]> + + Java + Mybatis + + + Java + Mysql + Mybatis + + + + mybatis系列-connection连接池解析 + /2023/02/19/mybatis%E7%B3%BB%E5%88%97-connection%E8%BF%9E%E6%8E%A5%E6%B1%A0%E8%A7%A3%E6%9E%90/ + 连接池主要是两个逻辑,首先是获取连接的逻辑,结合代码来讲一讲

+
private PooledConnection popConnection(String username, String password) throws SQLException {
+    boolean countedWait = false;
+    PooledConnection conn = null;
+    long t = System.currentTimeMillis();
+    int localBadConnectionCount = 0;
 
-

那又为什么是这个呢,可以在网上找,我们在mybatis-config.xml里配置的

-
<transactionManager type="JDBC"/>
+ // 循环获取连接 + while (conn == null) { + // 加锁 + lock.lock(); + try { + // 如果闲置的连接列表不为空 + if (!state.idleConnections.isEmpty()) { + // Pool has available connection + // 连接池有可用的连接 + conn = state.idleConnections.remove(0); + if (log.isDebugEnabled()) { + log.debug("Checked out connection " + conn.getRealHashCode() + " from pool."); + } + } else { + // Pool does not have available connection + // 进入这个分支表示没有空闲连接,但是活跃连接数还没达到最大活跃连接数上限,那么这时候就可以创建一个新连接 + if (state.activeConnections.size() < poolMaximumActiveConnections) { + // Can create new connection + // 这里创建连接我们之前讲过, + conn = new PooledConnection(dataSource.getConnection(), this); + if (log.isDebugEnabled()) { + log.debug("Created connection " + conn.getRealHashCode() + "."); + } + } else { + // Cannot create new connection + // 进到这个分支了就表示没法创建新连接了,那么怎么办呢,这里引入了一个 poolMaximumCheckoutTime,这代表了我去控制连接一次被使用的最长时间,如果超过这个时间了,我就要去关闭失效它 + PooledConnection oldestActiveConnection = state.activeConnections.get(0); + long longestCheckoutTime = oldestActiveConnection.getCheckoutTime(); + if (longestCheckoutTime > poolMaximumCheckoutTime) { + // Can claim overdue connection + // 所有超时连接从池中被借出的次数+1 + state.claimedOverdueConnectionCount++; + // 所有超时连接从池中被借出并归还的时间总和 + 当前连接借出时间 + state.accumulatedCheckoutTimeOfOverdueConnections += longestCheckoutTime; + // 所有连接从池中被借出并归还的时间总和 + 当前连接借出时间 + state.accumulatedCheckoutTime += longestCheckoutTime; + // 从活跃连接数中移除此连接 + state.activeConnections.remove(oldestActiveConnection); + // 如果该连接不是自动提交的,则尝试回滚 + if (!oldestActiveConnection.getRealConnection().getAutoCommit()) { + try { + oldestActiveConnection.getRealConnection().rollback(); + } catch (SQLException e) { + /* + Just log a message for debug and continue to execute the following + statement like nothing happened. + Wrap the bad connection with a new PooledConnection, this will help + to not interrupt current executing thread and give current thread a + chance to join the next competition for another valid/good database + connection. At the end of this loop, bad {@link @conn} will be set as null. + */ + log.debug("Bad connection. Could not roll back"); + } + } + // 用此连接的真实连接再创建一个连接,并设置时间 + conn = new PooledConnection(oldestActiveConnection.getRealConnection(), this); + conn.setCreatedTimestamp(oldestActiveConnection.getCreatedTimestamp()); + conn.setLastUsedTimestamp(oldestActiveConnection.getLastUsedTimestamp()); + oldestActiveConnection.invalidate(); + if (log.isDebugEnabled()) { + log.debug("Claimed overdue connection " + conn.getRealHashCode() + "."); + } + } else { + // Must wait + // 这样还是获取不到连接就只能等待了 + try { + // 标记状态,然后把等待计数+1 + if (!countedWait) { + state.hadToWaitCount++; + countedWait = true; + } + if (log.isDebugEnabled()) { + log.debug("Waiting as long as " + poolTimeToWait + " milliseconds for connection."); + } + long wt = System.currentTimeMillis(); + // 等待 poolTimeToWait 时间 + condition.await(poolTimeToWait, TimeUnit.MILLISECONDS); + // 记录等待时间 + state.accumulatedWaitTime += System.currentTimeMillis() - wt; + } catch (InterruptedException e) { + // set interrupt flag + Thread.currentThread().interrupt(); + break; + } + } + } + } + // 如果连接不为空 + if (conn != null) { + // ping to server and check the connection is valid or not + // 判断是否有效 + if (conn.isValid()) { + if (!conn.getRealConnection().getAutoCommit()) { + // 回滚未提交的 + conn.getRealConnection().rollback(); + } + conn.setConnectionTypeCode(assembleConnectionTypeCode(dataSource.getUrl(), username, password)); + // 设置时间 + conn.setCheckoutTimestamp(System.currentTimeMillis()); + conn.setLastUsedTimestamp(System.currentTimeMillis()); + // 添加进活跃连接 + state.activeConnections.add(conn); + state.requestCount++; + state.accumulatedRequestTime += System.currentTimeMillis() - t; + } else { + if (log.isDebugEnabled()) { + log.debug("A bad connection (" + conn.getRealHashCode() + ") was returned from the pool, getting another connection."); + } + // 连接无效,坏连接+1 + state.badConnectionCount++; + localBadConnectionCount++; + conn = null; + // 如果坏连接已经超过了容忍上限,就抛异常 + if (localBadConnectionCount > (poolMaximumIdleConnections + poolMaximumLocalBadConnectionTolerance)) { + if (log.isDebugEnabled()) { + log.debug("PooledDataSource: Could not get a good connection to the database."); + } + throw new SQLException("PooledDataSource: Could not get a good connection to the database."); + } + } + } + } finally { + // 释放锁 + lock.unlock(); + } -

因此在parseConfiguration中配置environment时

-
private void parseConfiguration(XNode root) {
-    try {
-      // issue #117 read properties first
-      propertiesElement(root.evalNode("properties"));
-      Properties settings = settingsAsProperties(root.evalNode("settings"));
-      loadCustomVfs(settings);
-      loadCustomLogImpl(settings);
-      typeAliasesElement(root.evalNode("typeAliases"));
-      pluginElement(root.evalNode("plugins"));
-      objectFactoryElement(root.evalNode("objectFactory"));
-      objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
-      reflectorFactoryElement(root.evalNode("reflectorFactory"));
-      settingsElement(settings);
-      // read it after objectFactory and objectWrapperFactory issue #631
-      // ----------> 就是这里
-      environmentsElement(root.evalNode("environments"));
-      databaseIdProviderElement(root.evalNode("databaseIdProvider"));
-      typeHandlerElement(root.evalNode("typeHandlers"));
-      mapperElement(root.evalNode("mappers"));
-    } catch (Exception e) {
-      throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
     }
-  }
-

调用的这个方法通过获取xml中的transactionManager 配置的类型,也就是JDBC

-
private void environmentsElement(XNode context) throws Exception {
-  if (context != null) {
-    if (environment == null) {
-      environment = context.getStringAttribute("default");
-    }
-    for (XNode child : context.getChildren()) {
-      String id = child.getStringAttribute("id");
-      if (isSpecifiedEnvironment(id)) {
-        // -------> 找到这里
-        TransactionFactory txFactory = transactionManagerElement(child.evalNode("transactionManager"));
-        DataSourceFactory dsFactory = dataSourceElement(child.evalNode("dataSource"));
-        DataSource dataSource = dsFactory.getDataSource();
-        Environment.Builder environmentBuilder = new Environment.Builder(id)
-            .transactionFactory(txFactory)
-            .dataSource(dataSource);
-        configuration.setEnvironment(environmentBuilder.build());
-        break;
+    if (conn == null) {
+      // 连接仍为空
+      if (log.isDebugEnabled()) {
+        log.debug("PooledDataSource: Unknown severe error condition.  The connection pool returned a null connection.");
       }
+      // 抛出异常
+      throw new SQLException("PooledDataSource: Unknown severe error condition.  The connection pool returned a null connection.");
     }
-  }
-}
+ // fanhui + return conn; + }
-

是通过以下方法获取的,

-
// 方法全限定名 org.apache.ibatis.builder.xml.XMLConfigBuilder#transactionManagerElement
-private TransactionFactory transactionManagerElement(XNode context) throws Exception {
-    if (context != null) {
-      String type = context.getStringAttribute("type");
-      Properties props = context.getChildrenAsProperties();
-      TransactionFactory factory = (TransactionFactory) resolveClass(type).getDeclaredConstructor().newInstance();
-      factory.setProperties(props);
-      return factory;
+

然后是还回连接

+
protected void pushConnection(PooledConnection conn) throws SQLException {
+    // 加锁
+    lock.lock();
+    try {
+      // 从活跃连接中移除当前连接
+      state.activeConnections.remove(conn);
+      if (conn.isValid()) {
+        // 当前的空闲连接数小于连接池中允许的最大空闲连接数
+        if (state.idleConnections.size() < poolMaximumIdleConnections && conn.getConnectionTypeCode() == expectedConnectionTypeCode) {
+          // 记录借出时间
+          state.accumulatedCheckoutTime += conn.getCheckoutTime();
+          if (!conn.getRealConnection().getAutoCommit()) {
+            // 同样是做回滚
+            conn.getRealConnection().rollback();
+          }
+          // 新建一个连接
+          PooledConnection newConn = new PooledConnection(conn.getRealConnection(), this);
+          // 加入到空闲连接列表中
+          state.idleConnections.add(newConn);
+          newConn.setCreatedTimestamp(conn.getCreatedTimestamp());
+          newConn.setLastUsedTimestamp(conn.getLastUsedTimestamp());
+          // 原连接失效
+          conn.invalidate();
+          if (log.isDebugEnabled()) {
+            log.debug("Returned connection " + newConn.getRealHashCode() + " to pool.");
+          }
+          // 提醒前面等待的
+          condition.signal();
+        } else {
+          // 上面是相同的,就是这里是空闲连接数已经超过上限
+          state.accumulatedCheckoutTime += conn.getCheckoutTime();
+          if (!conn.getRealConnection().getAutoCommit()) {
+            conn.getRealConnection().rollback();
+          }
+          conn.getRealConnection().close();
+          if (log.isDebugEnabled()) {
+            log.debug("Closed connection " + conn.getRealHashCode() + ".");
+          }
+          conn.invalidate();
+        }
+      } else {
+        if (log.isDebugEnabled()) {
+          log.debug("A bad connection (" + conn.getRealHashCode() + ") attempted to return to the pool, discarding connection.");
+        }
+        state.badConnectionCount++;
+      }
+    } finally {
+      lock.unlock();
     }
-    throw new BuilderException("Environment declaration requires a TransactionFactory.");
+  }
+]]> + + Java + Mybatis + + + Java + Mysql + Mybatis + + + + mybatis系列-foreach 解析 + /2023/06/11/mybatis%E7%B3%BB%E5%88%97-foreach-%E8%A7%A3%E6%9E%90/ + 在 org.apache.ibatis.builder.xml.XMLConfigBuilder#parseConfiguration 中进行配置解析,其中这一行就是解析 mappers

+
mapperElement(root.evalNode("mappers"));
+

具体的代码会执行到这

+
private void mapperElement(XNode parent) throws Exception {
+  if (parent != null) {
+    for (XNode child : parent.getChildren()) {
+      if ("package".equals(child.getName())) {
+        // 这里解析的不是 package
+        String mapperPackage = child.getStringAttribute("name");
+        configuration.addMappers(mapperPackage);
+      } else {
+        // 根据 resource 和 url 还有 mapperClass 判断
+        String resource = child.getStringAttribute("resource");
+        String url = child.getStringAttribute("url");
+        String mapperClass = child.getStringAttribute("class");
+        // resource 不为空其他为空的情况,就开始将 resource 读成输入流
+        if (resource != null && url == null && mapperClass == null) {
+          ErrorContext.instance().resource(resource);
+          try(InputStream inputStream = Resources.getResourceAsStream(resource)) {
+            // 初始化 XMLMapperBuilder 来解析 mapper
+            XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
+            mapperParser.parse();
+          }
+

然后再是 parse 过程

+
public void parse() {
+  if (!configuration.isResourceLoaded(resource)) {
+    // 解析 mapper 节点,也就是下图中的mapper
+    configurationElement(parser.evalNode("/mapper"));
+    configuration.addLoadedResource(resource);
+    bindMapperForNamespace();
   }
 
-// 方法全限定名 org.apache.ibatis.builder.BaseBuilder#resolveClass
-protected <T> Class<? extends T> resolveClass(String alias) {
-    if (alias == null) {
-      return null;
+  parsePendingResultMaps();
+  parsePendingCacheRefs();
+  parsePendingStatements();
+}
+

image

+

继续往下走

+
private void configurationElement(XNode context) {
+    try {
+      String namespace = context.getStringAttribute("namespace");
+      if (namespace == null || namespace.isEmpty()) {
+        throw new BuilderException("Mapper's namespace cannot be empty");
+      }
+      builderAssistant.setCurrentNamespace(namespace);
+      // 处理cache 和 cache 应用
+      cacheRefElement(context.evalNode("cache-ref"));
+      cacheElement(context.evalNode("cache"));
+      parameterMapElement(context.evalNodes("/mapper/parameterMap"));
+      resultMapElements(context.evalNodes("/mapper/resultMap"));
+      sqlElement(context.evalNodes("/mapper/sql"));
+      // 因为我们是个 sql 查询,所以具体逻辑是在这里面
+      buildStatementFromContext(context.evalNodes("select|insert|update|delete"));
+    } catch (Exception e) {
+      throw new BuilderException("Error parsing Mapper XML. The XML location is '" + resource + "'. Cause: " + e, e);
     }
+  }
+

然后是

+
private void buildStatementFromContext(List<XNode> list) {
+  if (configuration.getDatabaseId() != null) {
+    buildStatementFromContext(list, configuration.getDatabaseId());
+  }
+  // 然后没有 databaseId 就走到这
+  buildStatementFromContext(list, null);
+}
+

继续

+
private void buildStatementFromContext(List<XNode> list, String requiredDatabaseId) {
+  for (XNode context : list) {
+    // 创建语句解析器
+    final XMLStatementBuilder statementParser = new XMLStatementBuilder(configuration, builderAssistant, context, requiredDatabaseId);
     try {
-      return resolveAlias(alias);
-    } catch (Exception e) {
-      throw new BuilderException("Error resolving class. Cause: " + e, e);
+      // 解析节点
+      statementParser.parseStatementNode();
+    } catch (IncompleteElementException e) {
+      configuration.addIncompleteStatement(statementParser);
     }
   }
+}
+

这个代码比较长,做下简略,只保留相关代码

+
public void parseStatementNode() {
+    String id = context.getStringAttribute("id");
+    String databaseId = context.getStringAttribute("databaseId");
 
-// 方法全限定名 org.apache.ibatis.builder.BaseBuilder#resolveAlias
-  protected <T> Class<? extends T> resolveAlias(String alias) {
-    return typeAliasRegistry.resolveAlias(alias);
-  }
-// 方法全限定名 org.apache.ibatis.type.TypeAliasRegistry#resolveAlias
-  public <T> Class<T> resolveAlias(String string) {
-    try {
-      if (string == null) {
-        return null;
-      }
-      // issue #748
-      String key = string.toLowerCase(Locale.ENGLISH);
-      Class<T> value;
-      if (typeAliases.containsKey(key)) {
-        value = (Class<T>) typeAliases.get(key);
-      } else {
-        value = (Class<T>) Resources.classForName(string);
-      }
-      return value;
-    } catch (ClassNotFoundException e) {
-      throw new TypeException("Could not resolve type alias '" + string + "'.  Cause: " + e, e);
+    if (!databaseIdMatchesCurrent(id, databaseId, this.requiredDatabaseId)) {
+      return;
     }
-  }
-

而通过JDBC获取得是啥的,就是在Configuration的构造方法里写了的JdbcTransactionFactory

-
public Configuration() {
-  typeAliasRegistry.registerAlias("JDBC", JdbcTransactionFactory.class);
-

所以我们在这

-
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
-  Transaction tx = null;
-  try {
-    final Environment environment = configuration.getEnvironment();
-    final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
+ String nodeName = context.getNode().getNodeName(); + SqlCommandType sqlCommandType = SqlCommandType.valueOf(nodeName.toUpperCase(Locale.ENGLISH)); + boolean isSelect = sqlCommandType == SqlCommandType.SELECT; + boolean flushCache = context.getBooleanAttribute("flushCache", !isSelect); + boolean useCache = context.getBooleanAttribute("useCache", isSelect); + boolean resultOrdered = context.getBooleanAttribute("resultOrdered", false); -

获得到的TransactionFactory 就是 JdbcTransactionFactory ,而后

-
tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
-```java
 
-创建的transaction就是JdbcTransaction 
-```java
-  @Override
-  public Transaction newTransaction(DataSource ds, TransactionIsolationLevel level, boolean autoCommit) {
-    return new JdbcTransaction(ds, level, autoCommit, skipSetAutoCommitOnClose);
-  }
+ // 简略前后代码,主要看这里,创建 sqlSource -

然后我们再会上去看代码getConnection ,

-
protected Connection getConnection(Log statementLog) throws SQLException {
-  // -------> 这里的transaction就是JdbcTransaction
-  Connection connection = transaction.getConnection();
-  if (statementLog.isDebugEnabled()) {
-    return ConnectionLogger.newInstance(connection, statementLog, queryStack);
+    SqlSource sqlSource = langDriver.createSqlSource(configuration, context, parameterTypeClass);
+    
+
+

然后根据 LanguageDriver,我们这用的 XMLLanguageDriver,先是初始化

+
  @Override
+  public SqlSource createSqlSource(Configuration configuration, XNode script, Class<?> parameterType) {
+    XMLScriptBuilder builder = new XMLScriptBuilder(configuration, script, parameterType);
+    return builder.parseScriptNode();
+  }
+// 初始化有一些逻辑
+  public XMLScriptBuilder(Configuration configuration, XNode context, Class<?> parameterType) {
+    super(configuration);
+    this.context = context;
+    this.parameterType = parameterType;
+    // 特别是这,我这次特意在 mapper 中加了 foreach,就是为了说下这一块的解析
+    initNodeHandlerMap();
+  }
+// 设置各种类型的处理器
+  private void initNodeHandlerMap() {
+    nodeHandlerMap.put("trim", new TrimHandler());
+    nodeHandlerMap.put("where", new WhereHandler());
+    nodeHandlerMap.put("set", new SetHandler());
+    nodeHandlerMap.put("foreach", new ForEachHandler());
+    nodeHandlerMap.put("if", new IfHandler());
+    nodeHandlerMap.put("choose", new ChooseHandler());
+    nodeHandlerMap.put("when", new IfHandler());
+    nodeHandlerMap.put("otherwise", new OtherwiseHandler());
+    nodeHandlerMap.put("bind", new BindHandler());
+  }
+

初始化解析器以后就开始解析了

+
public SqlSource parseScriptNode() {
+  // 先是解析 parseDynamicTags
+  MixedSqlNode rootSqlNode = parseDynamicTags(context);
+  SqlSource sqlSource;
+  if (isDynamic) {
+    sqlSource = new DynamicSqlSource(configuration, rootSqlNode);
   } else {
-    return connection;
+    sqlSource = new RawSqlSource(configuration, rootSqlNode, parameterType);
   }
-}
- -

即调用了

+ return sqlSource; +}
+

但是这里可能做的事情比较多

+
protected MixedSqlNode parseDynamicTags(XNode node) {
+    List<SqlNode> contents = new ArrayList<>();
+    // 获取子节点,这里可以把我 xml 中的 SELECT 语句分成三部分,第一部分是 select 到 in,然后是 foreach 部分,最后是\n结束符
+    NodeList children = node.getNode().getChildNodes();
+    for (int i = 0; i < children.getLength(); i++) {
+      XNode child = node.newXNode(children.item(i));
+      // 第一个节点是个纯 text 节点就会走到这
+      if (child.getNode().getNodeType() == Node.CDATA_SECTION_NODE || child.getNode().getNodeType() == Node.TEXT_NODE) {
+        String data = child.getStringBody("");
+        TextSqlNode textSqlNode = new TextSqlNode(data);
+        if (textSqlNode.isDynamic()) {
+          contents.add(textSqlNode);
+          isDynamic = true;
+        } else {
+          // 在 content 中添加这个 node
+          contents.add(new StaticTextSqlNode(data));
+        }
+      } else if (child.getNode().getNodeType() == Node.ELEMENT_NODE) { // issue #628
+        // 第二个节点是个带 foreach 的,是个内部元素节点
+        String nodeName = child.getNode().getNodeName();
+        // 通过 nodeName 获取处理器
+        NodeHandler handler = nodeHandlerMap.get(nodeName);
+        if (handler == null) {
+          throw new BuilderException("Unknown element <" + nodeName + "> in SQL statement.");
+        }
+        // 调用处理器来处理
+        handler.handleNode(child, contents);
+        isDynamic = true;
+      }
+    }
+    // 然后返回这个混合 sql 节点
+    return new MixedSqlNode(contents);
+  }
+

再看下 handleNode 的逻辑

+
    @Override
+    public void handleNode(XNode nodeToHandle, List<SqlNode> targetContents) {
+      // 又会套娃执行这里的 parseDynamicTags
+      MixedSqlNode mixedSqlNode = parseDynamicTags(nodeToHandle);
+      String collection = nodeToHandle.getStringAttribute("collection");
+      Boolean nullable = nodeToHandle.getBooleanAttribute("nullable");
+      String item = nodeToHandle.getStringAttribute("item");
+      String index = nodeToHandle.getStringAttribute("index");
+      String open = nodeToHandle.getStringAttribute("open");
+      String close = nodeToHandle.getStringAttribute("close");
+      String separator = nodeToHandle.getStringAttribute("separator");
+      ForEachSqlNode forEachSqlNode = new ForEachSqlNode(configuration, mixedSqlNode, collection, nullable, index, item, open, close, separator);
+      targetContents.add(forEachSqlNode);
+    }
+// 这里走的逻辑不一样了
+protected MixedSqlNode parseDynamicTags(XNode node) {
+    List<SqlNode> contents = new ArrayList<>();
+    // 这里是 foreach 内部的,所以是个 text_node
+    NodeList children = node.getNode().getChildNodes();
+    for (int i = 0; i < children.getLength(); i++) {
+      XNode child = node.newXNode(children.item(i));
+      // 第一个节点是个纯 text 节点就会走到这
+      if (child.getNode().getNodeType() == Node.CDATA_SECTION_NODE || child.getNode().getNodeType() == Node.TEXT_NODE) {
+        String data = child.getStringBody("");
+        TextSqlNode textSqlNode = new TextSqlNode(data);
+        // 判断是否动态是根据代码里是否有 ${}
+        if (textSqlNode.isDynamic()) {
+          contents.add(textSqlNode);
+          isDynamic = true;
+        } else {
+          // 所以还是会走到这
+          // 在 content 中添加这个 node
+          contents.add(new StaticTextSqlNode(data));
+        }
+// 最后继续包装成 MixedSqlNode
+// 再回到这里
+    @Override
+    public void handleNode(XNode nodeToHandle, List<SqlNode> targetContents) {
+      MixedSqlNode mixedSqlNode = parseDynamicTags(nodeToHandle);
+      // 处理 foreach 内部的各个变量
+      String collection = nodeToHandle.getStringAttribute("collection");
+      Boolean nullable = nodeToHandle.getBooleanAttribute("nullable");
+      String item = nodeToHandle.getStringAttribute("item");
+      String index = nodeToHandle.getStringAttribute("index");
+      String open = nodeToHandle.getStringAttribute("open");
+      String close = nodeToHandle.getStringAttribute("close");
+      String separator = nodeToHandle.getStringAttribute("separator");
+      ForEachSqlNode forEachSqlNode = new ForEachSqlNode(configuration, mixedSqlNode, collection, nullable, index, item, open, close, separator);
+      targetContents.add(forEachSqlNode);
+    }
+

再回过来

+
public SqlSource parseScriptNode() {
+  MixedSqlNode rootSqlNode = parseDynamicTags(context);
+  SqlSource sqlSource;
+  // 因为在 foreach 节点处理时直接是把 isDynamic 置成了 true
+  if (isDynamic) {
+    // 所以是个 DynamicSqlSource
+    sqlSource = new DynamicSqlSource(configuration, rootSqlNode);
+  } else {
+    sqlSource = new RawSqlSource(configuration, rootSqlNode, parameterType);
+  }
+  return sqlSource;
+}
+

这里就做完了预处理工作,真正在执行的执行的时候还需要进一步解析

+

因为前面讲过很多了,所以直接跳到这里

  @Override
-  public Connection getConnection() throws SQLException {
-    if (connection == null) {
-      openConnection();
+  public <T> T selectOne(String statement, Object parameter) {
+    // Popular vote was to return null on 0 results and throw exception on too many.
+    // 都知道是在这进去
+    List<T> list = this.selectList(statement, parameter);
+    if (list.size() == 1) {
+      return list.get(0);
+    } else if (list.size() > 1) {
+      throw new TooManyResultsException("Expected one result (or null) to be returned by selectOne(), but found: " + list.size());
+    } else {
+      return null;
     }
-    return connection;
   }
 
-  protected void openConnection() throws SQLException {
-    if (log.isDebugEnabled()) {
-      log.debug("Opening JDBC Connection");
-    }
-    connection = dataSource.getConnection();
-    if (level != null) {
-      connection.setTransactionIsolation(level.getLevel());
+  @Override
+  public <E> List<E> selectList(String statement, Object parameter) {
+    return this.selectList(statement, parameter, RowBounds.DEFAULT);
+  }
+  @Override
+  public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
+    return selectList(statement, parameter, rowBounds, Executor.NO_RESULT_HANDLER);
+  }
+  private <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) {
+    try {
+      // 前面也讲过这个,
+      MappedStatement ms = configuration.getMappedStatement(statement);
+      return executor.query(ms, wrapCollection(parameter), rowBounds, handler);
+    } catch (Exception e) {
+      throw ExceptionFactory.wrapException("Error querying database.  Cause: " + e, e);
+    } finally {
+      ErrorContext.instance().reset();
     }
-    setDesiredAutoCommit(autoCommit);
   }
+  // 包括这里,是调用的org.apache.ibatis.executor.CachingExecutor#query(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.session.ResultHandler)
   @Override
-  public Connection getConnection() throws SQLException {
-    return popConnection(dataSource.getUsername(), dataSource.getPassword()).getProxyConnection();
+  public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
+    BoundSql boundSql = ms.getBoundSql(parameterObject);
+    CacheKey key = createCacheKey(ms, parameterObject, rowBounds, boundSql);
+    return query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
   }
-
-private PooledConnection popConnection(String username, String password) throws SQLException {
-    boolean countedWait = false;
-    PooledConnection conn = null;
-    long t = System.currentTimeMillis();
-    int localBadConnectionCount = 0;
-
-    while (conn == null) {
-      lock.lock();
-      try {
-        if (!state.idleConnections.isEmpty()) {
-          // Pool has available connection
-          conn = state.idleConnections.remove(0);
-          if (log.isDebugEnabled()) {
-            log.debug("Checked out connection " + conn.getRealHashCode() + " from pool.");
-          }
-        } else {
-          // Pool does not have available connection
-          if (state.activeConnections.size() < poolMaximumActiveConnections) {
-            // Can create new connection
-            // ------------> 走到这里会创建PooledConnection,但是里面会先调用dataSource.getConnection()
-            conn = new PooledConnection(dataSource.getConnection(), this);
-            if (log.isDebugEnabled()) {
-              log.debug("Created connection " + conn.getRealHashCode() + ".");
-            }
-          } else {
-            // Cannot create new connection
-            PooledConnection oldestActiveConnection = state.activeConnections.get(0);
-            long longestCheckoutTime = oldestActiveConnection.getCheckoutTime();
-            if (longestCheckoutTime > poolMaximumCheckoutTime) {
-              // Can claim overdue connection
-              state.claimedOverdueConnectionCount++;
-              state.accumulatedCheckoutTimeOfOverdueConnections += longestCheckoutTime;
-              state.accumulatedCheckoutTime += longestCheckoutTime;
-              state.activeConnections.remove(oldestActiveConnection);
-              if (!oldestActiveConnection.getRealConnection().getAutoCommit()) {
-                try {
-                  oldestActiveConnection.getRealConnection().rollback();
-                } catch (SQLException e) {
-                  /*
-                     Just log a message for debug and continue to execute the following
-                     statement like nothing happened.
-                     Wrap the bad connection with a new PooledConnection, this will help
-                     to not interrupt current executing thread and give current thread a
-                     chance to join the next competition for another valid/good database
-                     connection. At the end of this loop, bad {@link @conn} will be set as null.
-                   */
-                  log.debug("Bad connection. Could not roll back");
-                }
-              }
-              conn = new PooledConnection(oldestActiveConnection.getRealConnection(), this);
-              conn.setCreatedTimestamp(oldestActiveConnection.getCreatedTimestamp());
-              conn.setLastUsedTimestamp(oldestActiveConnection.getLastUsedTimestamp());
-              oldestActiveConnection.invalidate();
-              if (log.isDebugEnabled()) {
-                log.debug("Claimed overdue connection " + conn.getRealHashCode() + ".");
-              }
-            } else {
-              // Must wait
-              try {
-                if (!countedWait) {
-                  state.hadToWaitCount++;
-                  countedWait = true;
-                }
-                if (log.isDebugEnabled()) {
-                  log.debug("Waiting as long as " + poolTimeToWait + " milliseconds for connection.");
-                }
-                long wt = System.currentTimeMillis();
-                condition.await(poolTimeToWait, TimeUnit.MILLISECONDS);
-                state.accumulatedWaitTime += System.currentTimeMillis() - wt;
-              } catch (InterruptedException e) {
-                // set interrupt flag
-                Thread.currentThread().interrupt();
-                break;
-              }
-            }
-          }
-        }
-        if (conn != null) {
-          // ping to server and check the connection is valid or not
-          if (conn.isValid()) {
-            if (!conn.getRealConnection().getAutoCommit()) {
-              conn.getRealConnection().rollback();
-            }
-            conn.setConnectionTypeCode(assembleConnectionTypeCode(dataSource.getUrl(), username, password));
-            conn.setCheckoutTimestamp(System.currentTimeMillis());
-            conn.setLastUsedTimestamp(System.currentTimeMillis());
-            state.activeConnections.add(conn);
-            state.requestCount++;
-            state.accumulatedRequestTime += System.currentTimeMillis() - t;
-          } else {
-            if (log.isDebugEnabled()) {
-              log.debug("A bad connection (" + conn.getRealHashCode() + ") was returned from the pool, getting another connection.");
-            }
-            state.badConnectionCount++;
-            localBadConnectionCount++;
-            conn = null;
-            if (localBadConnectionCount > (poolMaximumIdleConnections + poolMaximumLocalBadConnectionTolerance)) {
-              if (log.isDebugEnabled()) {
-                log.debug("PooledDataSource: Could not get a good connection to the database.");
-              }
-              throw new SQLException("PooledDataSource: Could not get a good connection to the database.");
-            }
-          }
-        }
-      } finally {
-        lock.unlock();
-      }
-
+// 然后是获取 BoundSql
+  public BoundSql getBoundSql(Object parameterObject) {
+    BoundSql boundSql = sqlSource.getBoundSql(parameterObject);
+    List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
+    if (parameterMappings == null || parameterMappings.isEmpty()) {
+      boundSql = new BoundSql(configuration, boundSql.getSql(), parameterMap.getParameterMappings(), parameterObject);
     }
 
-    if (conn == null) {
-      if (log.isDebugEnabled()) {
-        log.debug("PooledDataSource: Unknown severe error condition.  The connection pool returned a null connection.");
+    // check for nested result maps in parameter mappings (issue #30)
+    for (ParameterMapping pm : boundSql.getParameterMappings()) {
+      String rmId = pm.getResultMapId();
+      if (rmId != null) {
+        ResultMap rm = configuration.getResultMap(rmId);
+        if (rm != null) {
+          hasNestedResultMaps |= rm.hasNestedResultMaps();
+        }
       }
-      throw new SQLException("PooledDataSource: Unknown severe error condition.  The connection pool returned a null connection.");
     }
 
-    return conn;
-  }
- -

其实就是调用的

-
// org.apache.ibatis.datasource.unpooled.UnpooledDataSource#getConnection()
+    return boundSql;
+  }
+// 因为前面讲了是生成的 DynamicSqlSource,所以也是调用这个的 getBoundSql
   @Override
-  public Connection getConnection() throws SQLException {
-    return doGetConnection(username, password);
+  public BoundSql getBoundSql(Object parameterObject) {
+    DynamicContext context = new DynamicContext(configuration, parameterObject);
+    // 重点关注着
+    rootSqlNode.apply(context);
+    SqlSourceBuilder sqlSourceParser = new SqlSourceBuilder(configuration);
+    Class<?> parameterType = parameterObject == null ? Object.class : parameterObject.getClass();
+    SqlSource sqlSource = sqlSourceParser.parse(context.getSql(), parameterType, context.getBindings());
+    BoundSql boundSql = sqlSource.getBoundSql(parameterObject);
+    context.getBindings().forEach(boundSql::setAdditionalParameter);
+    return boundSql;
   }
-```java
-
-然后就是
-```java
-private Connection doGetConnection(String username, String password) throws SQLException {
-    Properties props = new Properties();
-    if (driverProperties != null) {
-      props.putAll(driverProperties);
+// 继续是这个 DynamicSqlNode 的 apply
+  public boolean apply(DynamicContext context) {
+    contents.forEach(node -> node.apply(context));
+    return true;
+  }
+// 看下面的图
+

image

+

我们重点看 foreach 的逻辑

+
@Override
+  public boolean apply(DynamicContext context) {
+    Map<String, Object> bindings = context.getBindings();
+    final Iterable<?> iterable = evaluator.evaluateIterable(collectionExpression, bindings,
+      Optional.ofNullable(nullable).orElseGet(configuration::isNullableOnForEach));
+    if (iterable == null || !iterable.iterator().hasNext()) {
+      return true;
     }
-    if (username != null) {
-      props.setProperty("user", username);
+    boolean first = true;
+    // 开始符号
+    applyOpen(context);
+    int i = 0;
+    for (Object o : iterable) {
+      DynamicContext oldContext = context;
+      if (first || separator == null) {
+        context = new PrefixedContext(context, "");
+      } else {
+        context = new PrefixedContext(context, separator);
+      }
+      int uniqueNumber = context.getUniqueNumber();
+      // Issue #709
+      if (o instanceof Map.Entry) {
+        @SuppressWarnings("unchecked")
+        Map.Entry<Object, Object> mapEntry = (Map.Entry<Object, Object>) o;
+        applyIndex(context, mapEntry.getKey(), uniqueNumber);
+        applyItem(context, mapEntry.getValue(), uniqueNumber);
+      } else {
+        applyIndex(context, i, uniqueNumber);
+        applyItem(context, o, uniqueNumber);
+      }
+      // 转换变量名,变成这种形式 select * from student where id in
+      //   (  
+      //  #{__frch_id_0}
+      //   )
+      contents.apply(new FilteredDynamicContext(configuration, context, index, item, uniqueNumber));
+      if (first) {
+        first = !((PrefixedContext) context).isPrefixApplied();
+      }
+      context = oldContext;
+      i++;
     }
-    if (password != null) {
-      props.setProperty("password", password);
+    applyClose(context);
+    context.getBindings().remove(item);
+    context.getBindings().remove(index);
+    return true;
+  }
+// 回到外层就会调用 parse 方法, 把#{} 这段替换成 ?
+public SqlSource parse(String originalSql, Class<?> parameterType, Map<String, Object> additionalParameters) {
+    ParameterMappingTokenHandler handler = new ParameterMappingTokenHandler(configuration, parameterType, additionalParameters);
+    GenericTokenParser parser = new GenericTokenParser("#{", "}", handler);
+    String sql;
+    if (configuration.isShrinkWhitespacesInSql()) {
+      sql = parser.parse(removeExtraWhitespaces(originalSql));
+    } else {
+      sql = parser.parse(originalSql);
     }
-    return doGetConnection(props);
-  }
- -

继续这个逻辑

-
  private Connection doGetConnection(Properties properties) throws SQLException {
-    initializeDriver();
-    Connection connection = DriverManager.getConnection(url, properties);
-    configureConnection(connection);
-    return connection;
+    return new StaticSqlSource(configuration, sql, handler.getParameterMappings());
+  }
+

image

+

可以看到这里,然后再进行替换

+

image

+

真实的从 ? 替换成具体的变量值,是在这里
org.apache.ibatis.executor.SimpleExecutor#doQuery
调用了

+
private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
+    Statement stmt;
+    Connection connection = getConnection(statementLog);
+    stmt = handler.prepare(connection, transaction.getTimeout());
+    handler.parameterize(stmt);
+    return stmt;
+  }
+  @Override
+  public void parameterize(Statement statement) throws SQLException {
+    parameterHandler.setParameters((PreparedStatement) statement);
   }
-    @CallerSensitive
-    public static Connection getConnection(String url,
-        java.util.Properties info) throws SQLException {
-
-        return (getConnection(url, info, Reflection.getCallerClass()));
-    }
-private static Connection getConnection(
-        String url, java.util.Properties info, Class<?> caller) throws SQLException {
-        /*
-         * When callerCl is null, we should check the application's
-         * (which is invoking this class indirectly)
-         * classloader, so that the JDBC driver class outside rt.jar
-         * can be loaded from here.
-         */
-        ClassLoader callerCL = caller != null ? caller.getClassLoader() : null;
-        synchronized(DriverManager.class) {
-            // synchronize loading of the correct classloader.
-            if (callerCL == null) {
-                callerCL = Thread.currentThread().getContextClassLoader();
-            }
-        }
-
-        if(url == null) {
-            throw new SQLException("The url cannot be null", "08001");
+    @Override
+  public void setParameters(PreparedStatement ps) {
+    ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId());
+    List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
+    if (parameterMappings != null) {
+      for (int i = 0; i < parameterMappings.size(); i++) {
+        ParameterMapping parameterMapping = parameterMappings.get(i);
+        if (parameterMapping.getMode() != ParameterMode.OUT) {
+          Object value;
+          String propertyName = parameterMapping.getProperty();
+          if (boundSql.hasAdditionalParameter(propertyName)) { // issue #448 ask first for additional params
+            value = boundSql.getAdditionalParameter(propertyName);
+          } else if (parameterObject == null) {
+            value = null;
+          } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
+            value = parameterObject;
+          } else {
+            MetaObject metaObject = configuration.newMetaObject(parameterObject);
+            value = metaObject.getValue(propertyName);
+          }
+          TypeHandler typeHandler = parameterMapping.getTypeHandler();
+          JdbcType jdbcType = parameterMapping.getJdbcType();
+          if (value == null && jdbcType == null) {
+            jdbcType = configuration.getJdbcTypeForNull();
+          }
+          try {
+            // --------------------------> 
+            // 替换变量
+            typeHandler.setParameter(ps, i + 1, value, jdbcType);
+          } catch (TypeException | SQLException e) {
+            throw new TypeException("Could not set parameters for mapping: " + parameterMapping + ". Cause: " + e, e);
+          }
         }
+      }
+    }
+  }
+]]>
+ + Java + Mybatis + + + Java + Mysql + Mybatis + +
+ + mybatis系列-sql 类的简要分析 + /2023/03/19/mybatis%E7%B3%BB%E5%88%97-sql-%E7%B1%BB%E7%9A%84%E7%AE%80%E8%A6%81%E5%88%86%E6%9E%90/ + 上次就比较简单的讲了使用,这块也比较简单,因为封装得不是很复杂,首先我们从 select 作为入口来看看,这个具体的实现,

+
String selectSql = new SQL() {{
+            SELECT("id", "name");
+            FROM("student");
+            WHERE("id = #{id}");
+        }}.toString();
+

SELECT 方法的实现,

+
public T SELECT(String... columns) {
+  sql().statementType = SQLStatement.StatementType.SELECT;
+  sql().select.addAll(Arrays.asList(columns));
+  return getSelf();
+}
+

statementType是个枚举

+
public enum StatementType {
+  DELETE, INSERT, SELECT, UPDATE
+}
+

那这个就是个 select 语句,然后会把参数转成 list 添加到 select 变量里,
然后是 from 语句,这个大概也能猜到就是设置下表名,

+
public T FROM(String table) {
+  sql().tables.add(table);
+  return getSelf();
+}
+

往 tables 里添加了 table,这个 tables 是什么呢
这里也可以看下所有的变量,

+
StatementType statementType;
+List<String> sets = new ArrayList<>();
+List<String> select = new ArrayList<>();
+List<String> tables = new ArrayList<>();
+List<String> join = new ArrayList<>();
+List<String> innerJoin = new ArrayList<>();
+List<String> outerJoin = new ArrayList<>();
+List<String> leftOuterJoin = new ArrayList<>();
+List<String> rightOuterJoin = new ArrayList<>();
+List<String> where = new ArrayList<>();
+List<String> having = new ArrayList<>();
+List<String> groupBy = new ArrayList<>();
+List<String> orderBy = new ArrayList<>();
+List<String> lastList = new ArrayList<>();
+List<String> columns = new ArrayList<>();
+List<List<String>> valuesList = new ArrayList<>();
+

可以看到是一堆 List 先暂存这些sql 片段,然后再拼装成 sql 语句,
因为它重写了 toString 方法

+
@Override
+public String toString() {
+  StringBuilder sb = new StringBuilder();
+  sql().sql(sb);
+  return sb.toString();
+}
+

调用的 sql 方法是

+
public String sql(Appendable a) {
+      SafeAppendable builder = new SafeAppendable(a);
+      if (statementType == null) {
+        return null;
+      }
 
-        println("DriverManager.getConnection(\"" + url + "\")");
-
-        // Walk through the loaded registeredDrivers attempting to make a connection.
-        // Remember the first exception that gets raised so we can reraise it.
-        SQLException reason = null;
-
-        for(DriverInfo aDriver : registeredDrivers) {
-            // If the caller does not have permission to load the driver then
-            // skip it.
-            if(isDriverAllowed(aDriver.driver, callerCL)) {
-                try {
-                    // ----------> driver[className=com.mysql.cj.jdbc.Driver@64030b91]
-                    println("    trying " + aDriver.driver.getClass().getName());
-                    Connection con = aDriver.driver.connect(url, info);
-                    if (con != null) {
-                        // Success!
-                        println("getConnection returning " + aDriver.driver.getClass().getName());
-                        return (con);
-                    }
-                } catch (SQLException ex) {
-                    if (reason == null) {
-                        reason = ex;
-                    }
-                }
-
-            } else {
-                println("    skipping: " + aDriver.getClass().getName());
-            }
-
-        }
+      String answer;
 
-        // if we got here nobody could connect.
-        if (reason != null)    {
-            println("getConnection failed: " + reason);
-            throw reason;
-        }
+      switch (statementType) {
+        case DELETE:
+          answer = deleteSQL(builder);
+          break;
 
-        println("getConnection: no suitable driver found for "+ url);
-        throw new SQLException("No suitable driver found for "+ url, "08001");
-    }
+ case INSERT: + answer = insertSQL(builder); + break; + case SELECT: + answer = selectSQL(builder); + break; -

上面的driver就是driver[className=com.mysql.cj.jdbc.Driver@64030b91]

-
// com.mysql.cj.jdbc.NonRegisteringDriver#connect
-public Connection connect(String url, Properties info) throws SQLException {
-        try {
-            try {
-                if (!ConnectionUrl.acceptsUrl(url)) {
-                    return null;
-                } else {
-                    ConnectionUrl conStr = ConnectionUrl.getConnectionUrlInstance(url, info);
-                    switch (conStr.getType()) {
-                        case SINGLE_CONNECTION:
-                            return ConnectionImpl.getInstance(conStr.getMainHost());
-                        case FAILOVER_CONNECTION:
-                        case FAILOVER_DNS_SRV_CONNECTION:
-                            return FailoverConnectionProxy.createProxyInstance(conStr);
-                        case LOADBALANCE_CONNECTION:
-                        case LOADBALANCE_DNS_SRV_CONNECTION:
-                            return LoadBalancedConnectionProxy.createProxyInstance(conStr);
-                        case REPLICATION_CONNECTION:
-                        case REPLICATION_DNS_SRV_CONNECTION:
-                            return ReplicationConnectionProxy.createProxyInstance(conStr);
-                        default:
-                            return null;
-                    }
-                }
-            } catch (UnsupportedConnectionStringException var5) {
-                return null;
-            } catch (CJException var6) {
-                throw (UnableToConnectException)ExceptionFactory.createException(UnableToConnectException.class, Messages.getString("NonRegisteringDriver.17", new Object[]{var6.toString()}), var6);
-            }
-        } catch (CJException var7) {
-            throw SQLExceptionsMapping.translateException(var7);
-        }
-    }
+ case UPDATE: + answer = updateSQL(builder); + break; -

这是个 SINGLE_CONNECTION ,所以调用的就是 return ConnectionImpl.getInstance(conStr.getMainHost());
然后在这里设置了代理类

-
public PooledConnection(Connection connection, PooledDataSource dataSource) {
-    this.hashCode = connection.hashCode();
-    this.realConnection = connection;
-    this.dataSource = dataSource;
-    this.createdTimestamp = System.currentTimeMillis();
-    this.lastUsedTimestamp = System.currentTimeMillis();
-    this.valid = true;
-    this.proxyConnection = (Connection) Proxy.newProxyInstance(Connection.class.getClassLoader(), IFACES, this);
-  }
+ default: + answer = null; + } -

结合这个

-
@Override
-public Connection getConnection() throws SQLException {
-  return popConnection(dataSource.getUsername(), dataSource.getPassword()).getProxyConnection();
-}
+ return answer; + }
+

根据上面的 statementType判断是个什么 sql,我们这个是 selectSQL 就走的 SELECT 这个分支

+
private String selectSQL(SafeAppendable builder) {
+  if (distinct) {
+    sqlClause(builder, "SELECT DISTINCT", select, "", "", ", ");
+  } else {
+    sqlClause(builder, "SELECT", select, "", "", ", ");
+  }
 
-

所以最终的connection就是com.mysql.cj.jdbc.ConnectionImpl@358ab600

+ sqlClause(builder, "FROM", tables, "", "", ", "); + joins(builder); + sqlClause(builder, "WHERE", where, "(", ")", " AND "); + sqlClause(builder, "GROUP BY", groupBy, "", "", ", "); + sqlClause(builder, "HAVING", having, "(", ")", " AND "); + sqlClause(builder, "ORDER BY", orderBy, "", "", ", "); + limitingRowsStrategy.appendClause(builder, offset, limit); + return builder.toString(); +}
+

上面的可以看出来就是按我们常规的 sql 理解顺序来处理
就是select ... from ... where ... 这样子
再看下 sqlClause 的代码

+
private void sqlClause(SafeAppendable builder, String keyword, List<String> parts, String open, String close,
+                           String conjunction) {
+      if (!parts.isEmpty()) {
+        if (!builder.isEmpty()) {
+          builder.append("\n");
+        }
+        builder.append(keyword);
+        builder.append(" ");
+        builder.append(open);
+        String last = "________";
+        for (int i = 0, n = parts.size(); i < n; i++) {
+          String part = parts.get(i);
+          if (i > 0 && !part.equals(AND) && !part.equals(OR) && !last.equals(AND) && !last.equals(OR)) {
+            builder.append(conjunction);
+          }
+          builder.append(part);
+          last = part;
+        }
+        builder.append(close);
+      }
+    }
+

这里的拼接方式还需要判断 AND 和 OR 的判断逻辑,其他就没什么特别的了,只是where 语句中的 lastList 不知道是干嘛的,好像只有添加跟赋值的操作,有知道的大神也可以评论指导下

]]> Java @@ -9110,251 +8765,128 @@ public: - pcre-intro-and-a-simple-package - /2015/01/16/pcre-intro-and-a-simple-package/ - Pcre
-

Perl Compatible Regular Expressions (PCRE) is a regular
expression C library inspired by the regular expression
capabilities in the Perl programming language, written
by Philip Hazel, starting in summer 1997.

-
-

因为最近工作内容的一部分需要做字符串的识别处理,所以就顺便用上了之前在PHP中用过的正则,在C/C++中本身不包含正则库,这里使用的pcre,对MFC开发,在这里提供了静态链接库,在引入lib跟.h文件后即可使用。

- - -

Regular Expression Syntax

然后是一些正则语法,官方的语法文档比较科学严谨,特别是对类似于贪婪匹配等细节的说明,当然一般的使用可以在网上找到很多匹配语法,例如这个

-

PCRE函数介绍

-

pcre_compile
原型:

-
-
#include <pcre.h>
-pcre *pcre_compile(const char *pattern, int options, const char **errptr, int *erroffset, const unsigned char *tableptr);
-

功能:将一个正则表达式编译成一个内部表示,在匹配多个字符串时,可以加速匹配。其同pcre_compile2功能一样只是缺少一个参数errorcodeptr。
参数:
pattern 正则表达式
options 为0,或者其他参数选项
errptr 出错消息
erroffset 出错位置
tableptr 指向一个字符数组的指针,可以设置为空NULL

-
-

pcre_exec
原型:

-
-
#include <pcre.h>
-int pcre_exec(const pcre *code, const pcre_extra *extra, const char *subject, int length, int startoffset, int options, int *ovector, int ovecsize)
-

功能:使用编译好的模式进行匹配,采用与Perl相似的算法,返回匹配串的偏移位置。
参数:
code 编译好的模式
extra 指向一个pcre_extra结构体,可以为NULL
subject 需要匹配的字符串
length 匹配的字符串长度(Byte)
startoffset 匹配的开始位置
options 选项位
ovector 指向一个结果的整型数组
ovecsize 数组大小。

-

这里是两个最常用的函数的简单说明,pcre的静态库提供了一系列的函数以供使用,可以参考这个博客说明,另外对于以上函数的具体参数详细说明可以参考官网此处

-

一个丑陋的封装

void COcxDemoDlg::pcre_exec_all(const pcre * re, PCRE_SPTR src, vector<pair<int, int>> &vc)
-{
-	int rc;
-	int ovector[30];
-	int i = 0;
-	pair<int, int> pr;
-	rc = pcre_exec(re, NULL, src, strlen(src), i, 0, ovector, 30);
-	for (; rc > 0;)
-	{
-		i = ovector[1];
-		pr.first = ovector[2];
-		pr.second = ovector[3];
-		vc.push_back(pr);
-		rc = pcre_exec(re, NULL, src, strlen(src), i, 0, ovector, 30);
-	}
-}
-

vector中是全文匹配后的索引对,只是简单地用下。

-]]>
- - C++ - - - c++ - mfc - -
- - openresty - /2019/06/18/openresty/ - 目前公司要对一些新的产品功能做灰度测试,因为在后端业务代码层面添加判断比较麻烦,所以想在nginx上做点手脚,就想到了openresty
前后也踩了不少坑,这边先写一点

-

首先是日志
error_log logs/error.log debug;
需要nginx开启日志的debug才能看到日志

-

使用 lua_code_cache off即可, 另外注意只有使用 content_by_lua_file 才会生效

-
http {
-  lua_code_cache off;
-}
+    mybatis系列-typeAliases系统
+    /2023/01/01/mybatis%E7%B3%BB%E5%88%97-typeAliases%E7%B3%BB%E7%BB%9F/
+    其实前面已经聊到过这个概念,在mybatis的配置中,以及一些初始化逻辑都是用了typeAliases,

+
<typeAliases>
+  <typeAlias alias="Author" type="domain.blog.Author"/>
+  <typeAlias alias="Blog" type="domain.blog.Blog"/>
+  <typeAlias alias="Comment" type="domain.blog.Comment"/>
+  <typeAlias alias="Post" type="domain.blog.Post"/>
+  <typeAlias alias="Section" type="domain.blog.Section"/>
+  <typeAlias alias="Tag" type="domain.blog.Tag"/>
+</typeAliases>
+

可以在这里注册类型别名,然后在mybatis中配置使用时,可以简化这些类型的使用,其底层逻辑主要是一个map,

+
public class TypeAliasRegistry {
 
-location ~* /(\d+-.*)/api/orgunits/load_all(.*) {
-   default_type 'application/json;charset=utf-8';
-   content_by_lua_file /data/projects/xxx/current/lua/controller/load_data.lua;
-}
+ private final Map<String, Class<?>> typeAliases = new HashMap<>();
+

以string作为key,class对象作为value,比如我们在一开始使用的配置文件

+
<dataSource type="POOLED">
+    <property name="driver" value="${driver}"/>
+    <property name="url" value="${url}"/>
+    <property name="username" value="${username}"/>
+    <property name="password" value="${password}"/>
+</dataSource>
+

这里使用的dataSource是POOLED,那它肯定是个别名或者需要对应处理
而这个别名就是在Configuration的构造方法里初始化

+
public Configuration() {
+    typeAliasRegistry.registerAlias("JDBC", JdbcTransactionFactory.class);
+    typeAliasRegistry.registerAlias("MANAGED", ManagedTransactionFactory.class);
 
-

使用lua给nginx请求response头添加内容可以用这个

-
ngx.header['response'] = 'header'
+ typeAliasRegistry.registerAlias("JNDI", JndiDataSourceFactory.class); + typeAliasRegistry.registerAlias("POOLED", PooledDataSourceFactory.class); + typeAliasRegistry.registerAlias("UNPOOLED", UnpooledDataSourceFactory.class); + typeAliasRegistry.registerAlias("PERPETUAL", PerpetualCache.class); + typeAliasRegistry.registerAlias("FIFO", FifoCache.class); + typeAliasRegistry.registerAlias("LRU", LruCache.class); + typeAliasRegistry.registerAlias("SOFT", SoftCache.class); + typeAliasRegistry.registerAlias("WEAK", WeakCache.class); -

使用总结

-

后续:

-
    -
  1. 一开始在本地环境的时候使用content_by_lua_file只关注了头,后来发到测试环境发现请求内容都没代理转发到后端服务上
    网上查了下发现content_by_lua_file是将请求的所有内容包括response都用这里面的lua脚本生成了,content这个词就表示是请求内容
    后来改成了access_by_lua_file就正常了,只是要去获取请求内容和修改响应头,并不是要完整的接管请求

    -
  2. -
  3. 后来又碰到了一个坑是nginx有个client_body_buffer_size的配置参数,nginx在32位和64位系统里有8K和16K两个默认值,当请求内容大于这两个值的时候,会把请求内容放到临时文件里,这个时候openresty里的ngx.req.get_post_args()就会报“failed to get post args: requesty body in temp file not supported”这个错误,将client_body_buffer_size这个参数配置调大一点就好了

    -
  4. -
  5. 还有就是lua的异常捕获,网上看一般是用pcall和xpcall来进行保护调用,因为问题主要出在cjson的decode,这里有两个解决方案,一个就是将cjson.decode使用pcall封装,

    -
    local decode = require("cjson").decode
    +    typeAliasRegistry.registerAlias("DB_VENDOR", VendorDatabaseIdProvider.class);
     
    -function json_decode( str )
    -    local ok, t = pcall(decode, str)
    -    if not ok then
    -      return nil
    -    end
    +    typeAliasRegistry.registerAlias("XML", XMLLanguageDriver.class);
    +    typeAliasRegistry.registerAlias("RAW", RawLanguageDriver.class);
     
    -    return t
    -end
    -

    这个是使用了pcall,称为保护调用,会在内部错误后返回两个参数,第一个是false,第二个是错误信息
    还有一种是使用cjson.safe包

    -
    local json = require("cjson.safe")
    -local str = [[ {"key:"value"} ]]
    +    typeAliasRegistry.registerAlias("SLF4J", Slf4jImpl.class);
    +    typeAliasRegistry.registerAlias("COMMONS_LOGGING", JakartaCommonsLoggingImpl.class);
    +    typeAliasRegistry.registerAlias("LOG4J", Log4jImpl.class);
    +    typeAliasRegistry.registerAlias("LOG4J2", Log4j2Impl.class);
    +    typeAliasRegistry.registerAlias("JDK_LOGGING", Jdk14LoggingImpl.class);
    +    typeAliasRegistry.registerAlias("STDOUT_LOGGING", StdOutImpl.class);
    +    typeAliasRegistry.registerAlias("NO_LOGGING", NoLoggingImpl.class);
     
    -local t = json.decode(str)
    -if t then
    -    ngx.say(" --> ", type(t))
    -end
    -

    cjson.safe包会在解析失败的时候返回nil

    -
  6. -
  7. 还有一个是redis链接时如果host使用的是域名的话会提示“failed to connect: no resolver defined to resolve “redis.xxxxxx.com””,这里需要使用nginx的resolver指令,
    resolver 8.8.8.8 valid=3600s;

    -
  8. -
  9. 还有一点补充下
    就是业务在使用redis的时候使用了db的特性,所以在lua访问redis的时候也需要执行db,这里lua的redis库也支持了这个特性,可以使用instance:select(config:get(‘db’))来切换db

    -
  10. -
  11. 性能优化tips
    建议是尽量少使用阶段钩子,例如content_by_lua_file,*_by_lua

    -
  12. -
  13. 发现一个不错的openresty站点
    地址

    -
  14. -
-]]> - - nginx - - - nginx - openresty - - - - mybatis系列-foreach 解析 - /2023/06/11/mybatis%E7%B3%BB%E5%88%97-foreach-%E8%A7%A3%E6%9E%90/ - 在 org.apache.ibatis.builder.xml.XMLConfigBuilder#parseConfiguration 中进行配置解析,其中这一行就是解析 mappers

-
mapperElement(root.evalNode("mappers"));
-

具体的代码会执行到这

-
private void mapperElement(XNode parent) throws Exception {
-  if (parent != null) {
-    for (XNode child : parent.getChildren()) {
-      if ("package".equals(child.getName())) {
-        // 这里解析的不是 package
-        String mapperPackage = child.getStringAttribute("name");
-        configuration.addMappers(mapperPackage);
-      } else {
-        // 根据 resource 和 url 还有 mapperClass 判断
-        String resource = child.getStringAttribute("resource");
-        String url = child.getStringAttribute("url");
-        String mapperClass = child.getStringAttribute("class");
-        // resource 不为空其他为空的情况,就开始将 resource 读成输入流
-        if (resource != null && url == null && mapperClass == null) {
-          ErrorContext.instance().resource(resource);
-          try(InputStream inputStream = Resources.getResourceAsStream(resource)) {
-            // 初始化 XMLMapperBuilder 来解析 mapper
-            XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
-            mapperParser.parse();
-          }
-

然后再是 parse 过程

-
public void parse() {
-  if (!configuration.isResourceLoaded(resource)) {
-    // 解析 mapper 节点,也就是下图中的mapper
-    configurationElement(parser.evalNode("/mapper"));
-    configuration.addLoadedResource(resource);
-    bindMapperForNamespace();
-  }
+    typeAliasRegistry.registerAlias("CGLIB", CglibProxyFactory.class);
+    typeAliasRegistry.registerAlias("JAVASSIST", JavassistProxyFactory.class);
 
-  parsePendingResultMaps();
-  parsePendingCacheRefs();
-  parsePendingStatements();
-}
-

image

-

继续往下走

-
private void configurationElement(XNode context) {
-    try {
-      String namespace = context.getStringAttribute("namespace");
-      if (namespace == null || namespace.isEmpty()) {
-        throw new BuilderException("Mapper's namespace cannot be empty");
-      }
-      builderAssistant.setCurrentNamespace(namespace);
-      // 处理cache 和 cache 应用
-      cacheRefElement(context.evalNode("cache-ref"));
-      cacheElement(context.evalNode("cache"));
-      parameterMapElement(context.evalNodes("/mapper/parameterMap"));
-      resultMapElements(context.evalNodes("/mapper/resultMap"));
-      sqlElement(context.evalNodes("/mapper/sql"));
-      // 因为我们是个 sql 查询,所以具体逻辑是在这里面
-      buildStatementFromContext(context.evalNodes("select|insert|update|delete"));
-    } catch (Exception e) {
-      throw new BuilderException("Error parsing Mapper XML. The XML location is '" + resource + "'. Cause: " + e, e);
-    }
-  }
-

然后是

-
private void buildStatementFromContext(List<XNode> list) {
-  if (configuration.getDatabaseId() != null) {
-    buildStatementFromContext(list, configuration.getDatabaseId());
+    languageRegistry.setDefaultDriverClass(XMLLanguageDriver.class);
+    languageRegistry.register(RawLanguageDriver.class);
+  }
+

正是通过typeAliasRegistry.registerAlias("POOLED", PooledDataSourceFactory.class);这一行,注册了
POOLED对应的别名类型是PooledDataSourceFactory.class
具体的注册方法是在

+
public void registerAlias(String alias, Class<?> value) {
+  if (alias == null) {
+    throw new TypeException("The parameter alias cannot be null");
   }
-  // 然后没有 databaseId 就走到这
-  buildStatementFromContext(list, null);
-}
-

继续

-
private void buildStatementFromContext(List<XNode> list, String requiredDatabaseId) {
-  for (XNode context : list) {
-    // 创建语句解析器
-    final XMLStatementBuilder statementParser = new XMLStatementBuilder(configuration, builderAssistant, context, requiredDatabaseId);
-    try {
-      // 解析节点
-      statementParser.parseStatementNode();
-    } catch (IncompleteElementException e) {
-      configuration.addIncompleteStatement(statementParser);
-    }
+  // issue #748
+  // 转换成小写,
+  String key = alias.toLowerCase(Locale.ENGLISH);
+  // 判断是否已经注册过了
+  if (typeAliases.containsKey(key) && typeAliases.get(key) != null && !typeAliases.get(key).equals(value)) {
+    throw new TypeException("The alias '" + alias + "' is already mapped to the value '" + typeAliases.get(key).getName() + "'.");
   }
-}
-

这个代码比较长,做下简略,只保留相关代码

-
public void parseStatementNode() {
-    String id = context.getStringAttribute("id");
-    String databaseId = context.getStringAttribute("databaseId");
-
-    if (!databaseIdMatchesCurrent(id, databaseId, this.requiredDatabaseId)) {
-      return;
+  // 放进map里
+  typeAliases.put(key, value);
+}
+

而获取的逻辑在这

+
public <T> Class<T> resolveAlias(String string) {
+    try {
+      if (string == null) {
+        return null;
+      }
+      // issue #748
+      // 同样的转成小写
+      String key = string.toLowerCase(Locale.ENGLISH);
+      Class<T> value;
+      if (typeAliases.containsKey(key)) {
+        value = (Class<T>) typeAliases.get(key);
+      } else {
+        // 这里还有从路径下处理的逻辑
+        value = (Class<T>) Resources.classForName(string);
+      }
+      return value;
+    } catch (ClassNotFoundException e) {
+      throw new TypeException("Could not resolve type alias '" + string + "'.  Cause: " + e, e);
     }
+  }
+

逻辑比较简单,但是在mybatis中也是不可或缺的一块概念

+]]>
+ + Java + Mybatis + + + Java + Mysql + Mybatis + +
+ + mybatis系列-第一条sql的更多细节 + /2022/12/18/mybatis%E7%B3%BB%E5%88%97-%E7%AC%AC%E4%B8%80%E6%9D%A1sql%E7%9A%84%E6%9B%B4%E5%A4%9A%E7%BB%86%E8%8A%82/ + 执行细节
首先设置了默认的languageDriver
org/mybatis/mybatis/3.5.11/mybatis-3.5.11-sources.jar!/org/apache/ibatis/session/Configuration.java:215
configuration的构造方法里

+
languageRegistry.setDefaultDriverClass(XMLLanguageDriver.class);
- String nodeName = context.getNode().getNodeName(); - SqlCommandType sqlCommandType = SqlCommandType.valueOf(nodeName.toUpperCase(Locale.ENGLISH)); - boolean isSelect = sqlCommandType == SqlCommandType.SELECT; - boolean flushCache = context.getBooleanAttribute("flushCache", !isSelect); - boolean useCache = context.getBooleanAttribute("useCache", isSelect); - boolean resultOrdered = context.getBooleanAttribute("resultOrdered", false); - +

而在
org.apache.ibatis.builder.xml.XMLStatementBuilder#parseStatementNode
中,创建了sqlSource,这里就会根据前面的 LanguageDriver 的实现选择对应的 sqlSource

+
SqlSource sqlSource = langDriver.createSqlSource(configuration, context, parameterTypeClass);
- // 简略前后代码,主要看这里,创建 sqlSource +

createSqlSource 就会调用

+
@Override
+public SqlSource createSqlSource(Configuration configuration, XNode script, Class<?> parameterType) {
+  XMLScriptBuilder builder = new XMLScriptBuilder(configuration, script, parameterType);
+  return builder.parseScriptNode();
+}
- SqlSource sqlSource = langDriver.createSqlSource(configuration, context, parameterTypeClass); - -
-

然后根据 LanguageDriver,我们这用的 XMLLanguageDriver,先是初始化

-
  @Override
-  public SqlSource createSqlSource(Configuration configuration, XNode script, Class<?> parameterType) {
-    XMLScriptBuilder builder = new XMLScriptBuilder(configuration, script, parameterType);
-    return builder.parseScriptNode();
-  }
-// 初始化有一些逻辑
-  public XMLScriptBuilder(Configuration configuration, XNode context, Class<?> parameterType) {
-    super(configuration);
-    this.context = context;
-    this.parameterType = parameterType;
-    // 特别是这,我这次特意在 mapper 中加了 foreach,就是为了说下这一块的解析
-    initNodeHandlerMap();
-  }
-// 设置各种类型的处理器
-  private void initNodeHandlerMap() {
-    nodeHandlerMap.put("trim", new TrimHandler());
-    nodeHandlerMap.put("where", new WhereHandler());
-    nodeHandlerMap.put("set", new SetHandler());
-    nodeHandlerMap.put("foreach", new ForEachHandler());
-    nodeHandlerMap.put("if", new IfHandler());
-    nodeHandlerMap.put("choose", new ChooseHandler());
-    nodeHandlerMap.put("when", new IfHandler());
-    nodeHandlerMap.put("otherwise", new OtherwiseHandler());
-    nodeHandlerMap.put("bind", new BindHandler());
-  }
-

初始化解析器以后就开始解析了

+

再往下的逻辑在 parseScriptNode 中,org.apache.ibatis.scripting.xmltags.XMLScriptBuilder#parseScriptNode

public SqlSource parseScriptNode() {
-  // 先是解析 parseDynamicTags
   MixedSqlNode rootSqlNode = parseDynamicTags(context);
   SqlSource sqlSource;
   if (isDynamic) {
@@ -9363,149 +8895,101 @@ location ~*= new RawSqlSource(configuration, rootSqlNode, parameterType);
   }
   return sqlSource;
-}
-

但是这里可能做的事情比较多

+}
+ +

首先要解析dynamicTag,调用了org.apache.ibatis.scripting.xmltags.XMLScriptBuilder#parseDynamicTags

protected MixedSqlNode parseDynamicTags(XNode node) {
     List<SqlNode> contents = new ArrayList<>();
-    // 获取子节点,这里可以把我 xml 中的 SELECT 语句分成三部分,第一部分是 select 到 in,然后是 foreach 部分,最后是\n结束符
     NodeList children = node.getNode().getChildNodes();
     for (int i = 0; i < children.getLength(); i++) {
       XNode child = node.newXNode(children.item(i));
-      // 第一个节点是个纯 text 节点就会走到这
       if (child.getNode().getNodeType() == Node.CDATA_SECTION_NODE || child.getNode().getNodeType() == Node.TEXT_NODE) {
         String data = child.getStringBody("");
         TextSqlNode textSqlNode = new TextSqlNode(data);
+        // ---------> 主要是这边的逻辑
         if (textSqlNode.isDynamic()) {
           contents.add(textSqlNode);
           isDynamic = true;
         } else {
-          // 在 content 中添加这个 node
           contents.add(new StaticTextSqlNode(data));
         }
       } else if (child.getNode().getNodeType() == Node.ELEMENT_NODE) { // issue #628
-        // 第二个节点是个带 foreach 的,是个内部元素节点
         String nodeName = child.getNode().getNodeName();
-        // 通过 nodeName 获取处理器
         NodeHandler handler = nodeHandlerMap.get(nodeName);
         if (handler == null) {
           throw new BuilderException("Unknown element <" + nodeName + "> in SQL statement.");
         }
-        // 调用处理器来处理
         handler.handleNode(child, contents);
         isDynamic = true;
       }
     }
-    // 然后返回这个混合 sql 节点
     return new MixedSqlNode(contents);
-  }
-

再看下 handleNode 的逻辑

-
    @Override
-    public void handleNode(XNode nodeToHandle, List<SqlNode> targetContents) {
-      // 又会套娃执行这里的 parseDynamicTags
-      MixedSqlNode mixedSqlNode = parseDynamicTags(nodeToHandle);
-      String collection = nodeToHandle.getStringAttribute("collection");
-      Boolean nullable = nodeToHandle.getBooleanAttribute("nullable");
-      String item = nodeToHandle.getStringAttribute("item");
-      String index = nodeToHandle.getStringAttribute("index");
-      String open = nodeToHandle.getStringAttribute("open");
-      String close = nodeToHandle.getStringAttribute("close");
-      String separator = nodeToHandle.getStringAttribute("separator");
-      ForEachSqlNode forEachSqlNode = new ForEachSqlNode(configuration, mixedSqlNode, collection, nullable, index, item, open, close, separator);
-      targetContents.add(forEachSqlNode);
-    }
-// 这里走的逻辑不一样了
-protected MixedSqlNode parseDynamicTags(XNode node) {
-    List<SqlNode> contents = new ArrayList<>();
-    // 这里是 foreach 内部的,所以是个 text_node
-    NodeList children = node.getNode().getChildNodes();
-    for (int i = 0; i < children.getLength(); i++) {
-      XNode child = node.newXNode(children.item(i));
-      // 第一个节点是个纯 text 节点就会走到这
-      if (child.getNode().getNodeType() == Node.CDATA_SECTION_NODE || child.getNode().getNodeType() == Node.TEXT_NODE) {
-        String data = child.getStringBody("");
-        TextSqlNode textSqlNode = new TextSqlNode(data);
-        // 判断是否动态是根据代码里是否有 ${}
-        if (textSqlNode.isDynamic()) {
-          contents.add(textSqlNode);
-          isDynamic = true;
-        } else {
-          // 所以还是会走到这
-          // 在 content 中添加这个 node
-          contents.add(new StaticTextSqlNode(data));
-        }
-// 最后继续包装成 MixedSqlNode
-// 再回到这里
-    @Override
-    public void handleNode(XNode nodeToHandle, List<SqlNode> targetContents) {
-      MixedSqlNode mixedSqlNode = parseDynamicTags(nodeToHandle);
-      // 处理 foreach 内部的各个变量
-      String collection = nodeToHandle.getStringAttribute("collection");
-      Boolean nullable = nodeToHandle.getBooleanAttribute("nullable");
-      String item = nodeToHandle.getStringAttribute("item");
-      String index = nodeToHandle.getStringAttribute("index");
-      String open = nodeToHandle.getStringAttribute("open");
-      String close = nodeToHandle.getStringAttribute("close");
-      String separator = nodeToHandle.getStringAttribute("separator");
-      ForEachSqlNode forEachSqlNode = new ForEachSqlNode(configuration, mixedSqlNode, collection, nullable, index, item, open, close, separator);
-      targetContents.add(forEachSqlNode);
-    }
-

再回过来

-
public SqlSource parseScriptNode() {
-  MixedSqlNode rootSqlNode = parseDynamicTags(context);
-  SqlSource sqlSource;
-  // 因为在 foreach 节点处理时直接是把 isDynamic 置成了 true
-  if (isDynamic) {
-    // 所以是个 DynamicSqlSource
-    sqlSource = new DynamicSqlSource(configuration, rootSqlNode);
-  } else {
-    sqlSource = new RawSqlSource(configuration, rootSqlNode, parameterType);
-  }
-  return sqlSource;
-}
-

这里就做完了预处理工作,真正在执行的执行的时候还需要进一步解析

-

因为前面讲过很多了,所以直接跳到这里

-
  @Override
-  public <T> T selectOne(String statement, Object parameter) {
-    // Popular vote was to return null on 0 results and throw exception on too many.
-    // 都知道是在这进去
-    List<T> list = this.selectList(statement, parameter);
-    if (list.size() == 1) {
-      return list.get(0);
-    } else if (list.size() > 1) {
-      throw new TooManyResultsException("Expected one result (or null) to be returned by selectOne(), but found: " + list.size());
-    } else {
-      return null;
-    }
-  }
+  }
- @Override - public <E> List<E> selectList(String statement, Object parameter) { - return this.selectList(statement, parameter, RowBounds.DEFAULT); - } - @Override - public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) { - return selectList(statement, parameter, rowBounds, Executor.NO_RESULT_HANDLER); +

判断是否是动态sql,调用了org.apache.ibatis.scripting.xmltags.TextSqlNode#isDynamic

+
public boolean isDynamic() {
+  DynamicCheckerTokenParser checker = new DynamicCheckerTokenParser();
+  // ----------> 主要是这里的方法
+  GenericTokenParser parser = createParser(checker);
+  parser.parse(text);
+  return checker.isDynamic();
+}
+ +

创建parser的时候可以看到这个parser是干了啥,其实就是找有没有${ , }

+
private GenericTokenParser createParser(TokenHandler handler) {
+  return new GenericTokenParser("${", "}", handler);
+}
+ +

如果是的话,就在上面把 isDynamic 设置为true 如果是true 的话就创建 DynamicSqlSource

+
sqlSource = new DynamicSqlSource(configuration, rootSqlNode);
+ +

如果不是的话就创建RawSqlSource

+
sqlSource = new RawSqlSource(configuration, rootSqlNode, parameterType);
+```java
+
+但是这不是一个真实可用的 `sqlSource` ,
+实际创建的时候会走到这
+```java
+public RawSqlSource(Configuration configuration, SqlNode rootSqlNode, Class<?> parameterType) {
+    this(configuration, getSql(configuration, rootSqlNode), parameterType);
   }
-  private <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) {
-    try {
-      // 前面也讲过这个,
-      MappedStatement ms = configuration.getMappedStatement(statement);
-      return executor.query(ms, wrapCollection(parameter), rowBounds, handler);
-    } catch (Exception e) {
-      throw ExceptionFactory.wrapException("Error querying database.  Cause: " + e, e);
-    } finally {
-      ErrorContext.instance().reset();
-    }
+
+  public RawSqlSource(Configuration configuration, String sql, Class<?> parameterType) {
+    SqlSourceBuilder sqlSourceParser = new SqlSourceBuilder(configuration);
+    Class<?> clazz = parameterType == null ? Object.class : parameterType;
+    sqlSource = sqlSourceParser.parse(sql, clazz, new HashMap<>());
+  }
+ +

具体的sqlSource是通过org.apache.ibatis.builder.SqlSourceBuilder#parse 创建的
具体的代码逻辑是

+
public SqlSource parse(String originalSql, Class<?> parameterType, Map<String, Object> additionalParameters) {
+  ParameterMappingTokenHandler handler = new ParameterMappingTokenHandler(configuration, parameterType, additionalParameters);
+  GenericTokenParser parser = new GenericTokenParser("#{", "}", handler);
+  String sql;
+  if (configuration.isShrinkWhitespacesInSql()) {
+    sql = parser.parse(removeExtraWhitespaces(originalSql));
+  } else {
+    sql = parser.parse(originalSql);
   }
-  // 包括这里,是调用的org.apache.ibatis.executor.CachingExecutor#query(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.session.ResultHandler)
-  @Override
+  return new StaticSqlSource(configuration, sql, handler.getParameterMappings());
+}
+ +

这里创建的其实是StaticSqlSource ,多带一句前面的parser是将原来这样select * from student where id = #{id}sql 解析成了select * from student where id = ? 然后创建了StaticSqlSource

+
public StaticSqlSource(Configuration configuration, String sql, List<ParameterMapping> parameterMappings) {
+  this.sql = sql;
+  this.parameterMappings = parameterMappings;
+  this.configuration = configuration;
+}
+ +

为什么前面要讲这么多好像没什么关系的代码呢,其实在最开始我们执行sql的代码中

+
@Override
   public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
     BoundSql boundSql = ms.getBoundSql(parameterObject);
     CacheKey key = createCacheKey(ms, parameterObject, rowBounds, boundSql);
     return query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
-  }
-// 然后是获取 BoundSql
-  public BoundSql getBoundSql(Object parameterObject) {
+  }
+ +

这里获取了BoundSql,而BoundSql是怎么来的呢,首先调用了org.apache.ibatis.mapping.MappedStatement#getBoundSql

+
public BoundSql getBoundSql(Object parameterObject) {
     BoundSql boundSql = sqlSource.getBoundSql(parameterObject);
     List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
     if (parameterMappings == null || parameterMappings.isEmpty()) {
@@ -9524,481 +9008,765 @@ location ~*}
 
     return boundSql;
+  }
+ +

而我们从上面的解析中可以看到这里的sqlSource是一层RawSqlSource , 它的getBoundSql又是调用内部的sqlSource的方法

+
@Override
+public BoundSql getBoundSql(Object parameterObject) {
+  return sqlSource.getBoundSql(parameterObject);
+}
+ +

内部的sqlSource 就是StaticSqlSource

+
@Override
+public BoundSql getBoundSql(Object parameterObject) {
+  return new BoundSql(configuration, sql, parameterMappings, parameterObject);
+}
+ +

这个BoundSql的内容也比较简单

+
public BoundSql(Configuration configuration, String sql, List<ParameterMapping> parameterMappings, Object parameterObject) {
+  this.sql = sql;
+  this.parameterMappings = parameterMappings;
+  this.parameterObject = parameterObject;
+  this.additionalParameters = new HashMap<>();
+  this.metaParameters = configuration.newMetaObject(additionalParameters);
+}
+ +

而上次在这边org.apache.ibatis.executor.SimpleExecutor#doQuery 的时候落了个东西,就是StatementHandler的逻辑

+
@Override
+public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
+  Statement stmt = null;
+  try {
+    Configuration configuration = ms.getConfiguration();
+    StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
+    stmt = prepareStatement(handler, ms.getStatementLog());
+    return handler.query(stmt, resultHandler);
+  } finally {
+    closeStatement(stmt);
   }
-// 因为前面讲了是生成的 DynamicSqlSource,所以也是调用这个的 getBoundSql
-  @Override
-  public BoundSql getBoundSql(Object parameterObject) {
-    DynamicContext context = new DynamicContext(configuration, parameterObject);
-    // 重点关注着
-    rootSqlNode.apply(context);
-    SqlSourceBuilder sqlSourceParser = new SqlSourceBuilder(configuration);
-    Class<?> parameterType = parameterObject == null ? Object.class : parameterObject.getClass();
-    SqlSource sqlSource = sqlSourceParser.parse(context.getSql(), parameterType, context.getBindings());
-    BoundSql boundSql = sqlSource.getBoundSql(parameterObject);
-    context.getBindings().forEach(boundSql::setAdditionalParameter);
-    return boundSql;
+}
+ +

它是通过statementType来区分应该使用哪个statementHandler,我们这使用的就是PreparedStatementHandler

+
public RoutingStatementHandler(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
+
+  switch (ms.getStatementType()) {
+    case STATEMENT:
+      delegate = new SimpleStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
+      break;
+    case PREPARED:
+      delegate = new PreparedStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
+      break;
+    case CALLABLE:
+      delegate = new CallableStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
+      break;
+    default:
+      throw new ExecutorException("Unknown statement type: " + ms.getStatementType());
   }
-// 继续是这个 DynamicSqlNode 的 apply
-  public boolean apply(DynamicContext context) {
-    contents.forEach(node -> node.apply(context));
-    return true;
+
+}
+ +

所以上次有个细节可以补充,这边的doQuery里面的handler.query 应该是调用了PreparedStatementHandler 的query方法

+
@Override
+public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
+  Statement stmt = null;
+  try {
+    Configuration configuration = ms.getConfiguration();
+    StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
+    stmt = prepareStatement(handler, ms.getStatementLog());
+    return handler.query(stmt, resultHandler);
+  } finally {
+    closeStatement(stmt);
   }
-// 看下面的图
-

image

-

我们重点看 foreach 的逻辑

+}
+ + +

因为上面prepareStatement中getConnection拿到connection是com.mysql.cj.jdbc.ConnectionImpl#ConnectionImpl(com.mysql.cj.conf.HostInfo)

@Override
-  public boolean apply(DynamicContext context) {
-    Map<String, Object> bindings = context.getBindings();
-    final Iterable<?> iterable = evaluator.evaluateIterable(collectionExpression, bindings,
-      Optional.ofNullable(nullable).orElseGet(configuration::isNullableOnForEach));
-    if (iterable == null || !iterable.iterator().hasNext()) {
-      return true;
+public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
+  PreparedStatement ps = (PreparedStatement) statement;
+  ps.execute();
+  return resultSetHandler.handleResultSets(ps);
+}
+ +

那又为什么是这个呢,可以在网上找,我们在mybatis-config.xml里配置的

+
<transactionManager type="JDBC"/>
+ +

因此在parseConfiguration中配置environment时

+
private void parseConfiguration(XNode root) {
+    try {
+      // issue #117 read properties first
+      propertiesElement(root.evalNode("properties"));
+      Properties settings = settingsAsProperties(root.evalNode("settings"));
+      loadCustomVfs(settings);
+      loadCustomLogImpl(settings);
+      typeAliasesElement(root.evalNode("typeAliases"));
+      pluginElement(root.evalNode("plugins"));
+      objectFactoryElement(root.evalNode("objectFactory"));
+      objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
+      reflectorFactoryElement(root.evalNode("reflectorFactory"));
+      settingsElement(settings);
+      // read it after objectFactory and objectWrapperFactory issue #631
+      // ----------> 就是这里
+      environmentsElement(root.evalNode("environments"));
+      databaseIdProviderElement(root.evalNode("databaseIdProvider"));
+      typeHandlerElement(root.evalNode("typeHandlers"));
+      mapperElement(root.evalNode("mappers"));
+    } catch (Exception e) {
+      throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
     }
-    boolean first = true;
-    // 开始符号
-    applyOpen(context);
-    int i = 0;
-    for (Object o : iterable) {
-      DynamicContext oldContext = context;
-      if (first || separator == null) {
-        context = new PrefixedContext(context, "");
-      } else {
-        context = new PrefixedContext(context, separator);
+  }
+ +

调用的这个方法通过获取xml中的transactionManager 配置的类型,也就是JDBC

+
private void environmentsElement(XNode context) throws Exception {
+  if (context != null) {
+    if (environment == null) {
+      environment = context.getStringAttribute("default");
+    }
+    for (XNode child : context.getChildren()) {
+      String id = child.getStringAttribute("id");
+      if (isSpecifiedEnvironment(id)) {
+        // -------> 找到这里
+        TransactionFactory txFactory = transactionManagerElement(child.evalNode("transactionManager"));
+        DataSourceFactory dsFactory = dataSourceElement(child.evalNode("dataSource"));
+        DataSource dataSource = dsFactory.getDataSource();
+        Environment.Builder environmentBuilder = new Environment.Builder(id)
+            .transactionFactory(txFactory)
+            .dataSource(dataSource);
+        configuration.setEnvironment(environmentBuilder.build());
+        break;
       }
-      int uniqueNumber = context.getUniqueNumber();
-      // Issue #709
-      if (o instanceof Map.Entry) {
-        @SuppressWarnings("unchecked")
-        Map.Entry<Object, Object> mapEntry = (Map.Entry<Object, Object>) o;
-        applyIndex(context, mapEntry.getKey(), uniqueNumber);
-        applyItem(context, mapEntry.getValue(), uniqueNumber);
-      } else {
-        applyIndex(context, i, uniqueNumber);
-        applyItem(context, o, uniqueNumber);
+    }
+  }
+}
+ +

是通过以下方法获取的,

+
// 方法全限定名 org.apache.ibatis.builder.xml.XMLConfigBuilder#transactionManagerElement
+private TransactionFactory transactionManagerElement(XNode context) throws Exception {
+    if (context != null) {
+      String type = context.getStringAttribute("type");
+      Properties props = context.getChildrenAsProperties();
+      TransactionFactory factory = (TransactionFactory) resolveClass(type).getDeclaredConstructor().newInstance();
+      factory.setProperties(props);
+      return factory;
+    }
+    throw new BuilderException("Environment declaration requires a TransactionFactory.");
+  }
+
+// 方法全限定名 org.apache.ibatis.builder.BaseBuilder#resolveClass
+protected <T> Class<? extends T> resolveClass(String alias) {
+    if (alias == null) {
+      return null;
+    }
+    try {
+      return resolveAlias(alias);
+    } catch (Exception e) {
+      throw new BuilderException("Error resolving class. Cause: " + e, e);
+    }
+  }
+
+// 方法全限定名 org.apache.ibatis.builder.BaseBuilder#resolveAlias
+  protected <T> Class<? extends T> resolveAlias(String alias) {
+    return typeAliasRegistry.resolveAlias(alias);
+  }
+// 方法全限定名 org.apache.ibatis.type.TypeAliasRegistry#resolveAlias
+  public <T> Class<T> resolveAlias(String string) {
+    try {
+      if (string == null) {
+        return null;
       }
-      // 转换变量名,变成这种形式 select * from student where id in
-      //   (  
-      //  #{__frch_id_0}
-      //   )
-      contents.apply(new FilteredDynamicContext(configuration, context, index, item, uniqueNumber));
-      if (first) {
-        first = !((PrefixedContext) context).isPrefixApplied();
+      // issue #748
+      String key = string.toLowerCase(Locale.ENGLISH);
+      Class<T> value;
+      if (typeAliases.containsKey(key)) {
+        value = (Class<T>) typeAliases.get(key);
+      } else {
+        value = (Class<T>) Resources.classForName(string);
       }
-      context = oldContext;
-      i++;
+      return value;
+    } catch (ClassNotFoundException e) {
+      throw new TypeException("Could not resolve type alias '" + string + "'.  Cause: " + e, e);
+    }
+  }
+

而通过JDBC获取得是啥的,就是在Configuration的构造方法里写了的JdbcTransactionFactory

+
public Configuration() {
+  typeAliasRegistry.registerAlias("JDBC", JdbcTransactionFactory.class);
+ +

所以我们在这

+
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
+  Transaction tx = null;
+  try {
+    final Environment environment = configuration.getEnvironment();
+    final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
+ +

获得到的TransactionFactory 就是 JdbcTransactionFactory ,而后

+
tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
+```java
+
+创建的transaction就是JdbcTransaction 
+```java
+  @Override
+  public Transaction newTransaction(DataSource ds, TransactionIsolationLevel level, boolean autoCommit) {
+    return new JdbcTransaction(ds, level, autoCommit, skipSetAutoCommitOnClose);
+  }
+ +

然后我们再会上去看代码getConnection ,

+
protected Connection getConnection(Log statementLog) throws SQLException {
+  // -------> 这里的transaction就是JdbcTransaction
+  Connection connection = transaction.getConnection();
+  if (statementLog.isDebugEnabled()) {
+    return ConnectionLogger.newInstance(connection, statementLog, queryStack);
+  } else {
+    return connection;
+  }
+}
+ +

即调用了

+
  @Override
+  public Connection getConnection() throws SQLException {
+    if (connection == null) {
+      openConnection();
     }
-    applyClose(context);
-    context.getBindings().remove(item);
-    context.getBindings().remove(index);
-    return true;
+    return connection;
   }
-// 回到外层就会调用 parse 方法, 把#{} 这段替换成 ?
-public SqlSource parse(String originalSql, Class<?> parameterType, Map<String, Object> additionalParameters) {
-    ParameterMappingTokenHandler handler = new ParameterMappingTokenHandler(configuration, parameterType, additionalParameters);
-    GenericTokenParser parser = new GenericTokenParser("#{", "}", handler);
-    String sql;
-    if (configuration.isShrinkWhitespacesInSql()) {
-      sql = parser.parse(removeExtraWhitespaces(originalSql));
-    } else {
-      sql = parser.parse(originalSql);
+
+  protected void openConnection() throws SQLException {
+    if (log.isDebugEnabled()) {
+      log.debug("Opening JDBC Connection");
     }
-    return new StaticSqlSource(configuration, sql, handler.getParameterMappings());
-  }
-

image

-

可以看到这里,然后再进行替换

-

image

-

真实的从 ? 替换成具体的变量值,是在这里
org.apache.ibatis.executor.SimpleExecutor#doQuery
调用了

-
private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
-    Statement stmt;
-    Connection connection = getConnection(statementLog);
-    stmt = handler.prepare(connection, transaction.getTimeout());
-    handler.parameterize(stmt);
-    return stmt;
+    connection = dataSource.getConnection();
+    if (level != null) {
+      connection.setTransactionIsolation(level.getLevel());
+    }
+    setDesiredAutoCommit(autoCommit);
   }
   @Override
-  public void parameterize(Statement statement) throws SQLException {
-    parameterHandler.setParameters((PreparedStatement) statement);
+  public Connection getConnection() throws SQLException {
+    return popConnection(dataSource.getUsername(), dataSource.getPassword()).getProxyConnection();
   }
-    @Override
-  public void setParameters(PreparedStatement ps) {
-    ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId());
-    List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
-    if (parameterMappings != null) {
-      for (int i = 0; i < parameterMappings.size(); i++) {
-        ParameterMapping parameterMapping = parameterMappings.get(i);
-        if (parameterMapping.getMode() != ParameterMode.OUT) {
-          Object value;
-          String propertyName = parameterMapping.getProperty();
-          if (boundSql.hasAdditionalParameter(propertyName)) { // issue #448 ask first for additional params
-            value = boundSql.getAdditionalParameter(propertyName);
-          } else if (parameterObject == null) {
-            value = null;
-          } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
-            value = parameterObject;
-          } else {
-            MetaObject metaObject = configuration.newMetaObject(parameterObject);
-            value = metaObject.getValue(propertyName);
+
+private PooledConnection popConnection(String username, String password) throws SQLException {
+    boolean countedWait = false;
+    PooledConnection conn = null;
+    long t = System.currentTimeMillis();
+    int localBadConnectionCount = 0;
+
+    while (conn == null) {
+      lock.lock();
+      try {
+        if (!state.idleConnections.isEmpty()) {
+          // Pool has available connection
+          conn = state.idleConnections.remove(0);
+          if (log.isDebugEnabled()) {
+            log.debug("Checked out connection " + conn.getRealHashCode() + " from pool.");
           }
-          TypeHandler typeHandler = parameterMapping.getTypeHandler();
-          JdbcType jdbcType = parameterMapping.getJdbcType();
-          if (value == null && jdbcType == null) {
-            jdbcType = configuration.getJdbcTypeForNull();
+        } else {
+          // Pool does not have available connection
+          if (state.activeConnections.size() < poolMaximumActiveConnections) {
+            // Can create new connection
+            // ------------> 走到这里会创建PooledConnection,但是里面会先调用dataSource.getConnection()
+            conn = new PooledConnection(dataSource.getConnection(), this);
+            if (log.isDebugEnabled()) {
+              log.debug("Created connection " + conn.getRealHashCode() + ".");
+            }
+          } else {
+            // Cannot create new connection
+            PooledConnection oldestActiveConnection = state.activeConnections.get(0);
+            long longestCheckoutTime = oldestActiveConnection.getCheckoutTime();
+            if (longestCheckoutTime > poolMaximumCheckoutTime) {
+              // Can claim overdue connection
+              state.claimedOverdueConnectionCount++;
+              state.accumulatedCheckoutTimeOfOverdueConnections += longestCheckoutTime;
+              state.accumulatedCheckoutTime += longestCheckoutTime;
+              state.activeConnections.remove(oldestActiveConnection);
+              if (!oldestActiveConnection.getRealConnection().getAutoCommit()) {
+                try {
+                  oldestActiveConnection.getRealConnection().rollback();
+                } catch (SQLException e) {
+                  /*
+                     Just log a message for debug and continue to execute the following
+                     statement like nothing happened.
+                     Wrap the bad connection with a new PooledConnection, this will help
+                     to not interrupt current executing thread and give current thread a
+                     chance to join the next competition for another valid/good database
+                     connection. At the end of this loop, bad {@link @conn} will be set as null.
+                   */
+                  log.debug("Bad connection. Could not roll back");
+                }
+              }
+              conn = new PooledConnection(oldestActiveConnection.getRealConnection(), this);
+              conn.setCreatedTimestamp(oldestActiveConnection.getCreatedTimestamp());
+              conn.setLastUsedTimestamp(oldestActiveConnection.getLastUsedTimestamp());
+              oldestActiveConnection.invalidate();
+              if (log.isDebugEnabled()) {
+                log.debug("Claimed overdue connection " + conn.getRealHashCode() + ".");
+              }
+            } else {
+              // Must wait
+              try {
+                if (!countedWait) {
+                  state.hadToWaitCount++;
+                  countedWait = true;
+                }
+                if (log.isDebugEnabled()) {
+                  log.debug("Waiting as long as " + poolTimeToWait + " milliseconds for connection.");
+                }
+                long wt = System.currentTimeMillis();
+                condition.await(poolTimeToWait, TimeUnit.MILLISECONDS);
+                state.accumulatedWaitTime += System.currentTimeMillis() - wt;
+              } catch (InterruptedException e) {
+                // set interrupt flag
+                Thread.currentThread().interrupt();
+                break;
+              }
+            }
           }
-          try {
-            // --------------------------> 
-            // 替换变量
-            typeHandler.setParameter(ps, i + 1, value, jdbcType);
-          } catch (TypeException | SQLException e) {
-            throw new TypeException("Could not set parameters for mapping: " + parameterMapping + ". Cause: " + e, e);
+        }
+        if (conn != null) {
+          // ping to server and check the connection is valid or not
+          if (conn.isValid()) {
+            if (!conn.getRealConnection().getAutoCommit()) {
+              conn.getRealConnection().rollback();
+            }
+            conn.setConnectionTypeCode(assembleConnectionTypeCode(dataSource.getUrl(), username, password));
+            conn.setCheckoutTimestamp(System.currentTimeMillis());
+            conn.setLastUsedTimestamp(System.currentTimeMillis());
+            state.activeConnections.add(conn);
+            state.requestCount++;
+            state.accumulatedRequestTime += System.currentTimeMillis() - t;
+          } else {
+            if (log.isDebugEnabled()) {
+              log.debug("A bad connection (" + conn.getRealHashCode() + ") was returned from the pool, getting another connection.");
+            }
+            state.badConnectionCount++;
+            localBadConnectionCount++;
+            conn = null;
+            if (localBadConnectionCount > (poolMaximumIdleConnections + poolMaximumLocalBadConnectionTolerance)) {
+              if (log.isDebugEnabled()) {
+                log.debug("PooledDataSource: Could not get a good connection to the database.");
+              }
+              throw new SQLException("PooledDataSource: Could not get a good connection to the database.");
+            }
           }
         }
+      } finally {
+        lock.unlock();
       }
-    }
-  }
-]]> - - Java - Mybatis - - - Java - Mysql - Mybatis - - - - mybatis系列-第一条sql的细节 - /2022/12/11/mybatis%E7%B3%BB%E5%88%97-%E7%AC%AC%E4%B8%80%E6%9D%A1sql%E7%9A%84%E7%BB%86%E8%8A%82/ - 先补充两个点,
第一是前面我们说了
使用org.apache.ibatis.builder.xml.XMLConfigBuilder 创建了parser解析器,那么解析的结果是什么
看这个方法的返回值

-
public Configuration parse() {
-  if (parsed) {
-    throw new BuilderException("Each XMLConfigBuilder can only be used once.");
-  }
-  parsed = true;
-  parseConfiguration(parser.evalNode("/configuration"));
-  return configuration;
-}
- -

返回的是 org.apache.ibatis.session.Configuration , 而这个 Configuration 也是 mybatis 中特别重要的配置核心类,贴一下里面的成员变量,

-
public class Configuration {
 
-  protected Environment environment;
+    }
 
-  protected boolean safeRowBoundsEnabled;
-  protected boolean safeResultHandlerEnabled = true;
-  protected boolean mapUnderscoreToCamelCase;
-  protected boolean aggressiveLazyLoading;
-  protected boolean multipleResultSetsEnabled = true;
-  protected boolean useGeneratedKeys;
-  protected boolean useColumnLabel = true;
-  protected boolean cacheEnabled = true;
-  protected boolean callSettersOnNulls;
-  protected boolean useActualParamName = true;
-  protected boolean returnInstanceForEmptyRow;
-  protected boolean shrinkWhitespacesInSql;
-  protected boolean nullableOnForEach;
-  protected boolean argNameBasedConstructorAutoMapping;
+    if (conn == null) {
+      if (log.isDebugEnabled()) {
+        log.debug("PooledDataSource: Unknown severe error condition.  The connection pool returned a null connection.");
+      }
+      throw new SQLException("PooledDataSource: Unknown severe error condition.  The connection pool returned a null connection.");
+    }
 
-  protected String logPrefix;
-  protected Class<? extends Log> logImpl;
-  protected Class<? extends VFS> vfsImpl;
-  protected Class<?> defaultSqlProviderType;
-  protected LocalCacheScope localCacheScope = LocalCacheScope.SESSION;
-  protected JdbcType jdbcTypeForNull = JdbcType.OTHER;
-  protected Set<String> lazyLoadTriggerMethods = new HashSet<>(Arrays.asList("equals", "clone", "hashCode", "toString"));
-  protected Integer defaultStatementTimeout;
-  protected Integer defaultFetchSize;
-  protected ResultSetType defaultResultSetType;
-  protected ExecutorType defaultExecutorType = ExecutorType.SIMPLE;
-  protected AutoMappingBehavior autoMappingBehavior = AutoMappingBehavior.PARTIAL;
-  protected AutoMappingUnknownColumnBehavior autoMappingUnknownColumnBehavior = AutoMappingUnknownColumnBehavior.NONE;
+    return conn;
+  }
- protected Properties variables = new Properties(); - protected ReflectorFactory reflectorFactory = new DefaultReflectorFactory(); - protected ObjectFactory objectFactory = new DefaultObjectFactory(); - protected ObjectWrapperFactory objectWrapperFactory = new DefaultObjectWrapperFactory(); +

其实就是调用的

+
// org.apache.ibatis.datasource.unpooled.UnpooledDataSource#getConnection()
+  @Override
+  public Connection getConnection() throws SQLException {
+    return doGetConnection(username, password);
+  }
+```java
 
-  protected boolean lazyLoadingEnabled = false;
-  protected ProxyFactory proxyFactory = new JavassistProxyFactory(); // #224 Using internal Javassist instead of OGNL
+然后就是
+```java
+private Connection doGetConnection(String username, String password) throws SQLException {
+    Properties props = new Properties();
+    if (driverProperties != null) {
+      props.putAll(driverProperties);
+    }
+    if (username != null) {
+      props.setProperty("user", username);
+    }
+    if (password != null) {
+      props.setProperty("password", password);
+    }
+    return doGetConnection(props);
+  }
- protected String databaseId; - /** - * Configuration factory class. - * Used to create Configuration for loading deserialized unread properties. - * - * @see <a href='https://github.com/mybatis/old-google-code-issues/issues/300'>Issue 300 (google code)</a> - */ - protected Class<?> configurationFactory; +

继续这个逻辑

+
  private Connection doGetConnection(Properties properties) throws SQLException {
+    initializeDriver();
+    Connection connection = DriverManager.getConnection(url, properties);
+    configureConnection(connection);
+    return connection;
+  }
+    @CallerSensitive
+    public static Connection getConnection(String url,
+        java.util.Properties info) throws SQLException {
 
-  protected final MapperRegistry mapperRegistry = new MapperRegistry(this);
-  protected final InterceptorChain interceptorChain = new InterceptorChain();
-  protected final TypeHandlerRegistry typeHandlerRegistry = new TypeHandlerRegistry(this);
-  protected final TypeAliasRegistry typeAliasRegistry = new TypeAliasRegistry();
-  protected final LanguageDriverRegistry languageRegistry = new LanguageDriverRegistry();
+        return (getConnection(url, info, Reflection.getCallerClass()));
+    }
+private static Connection getConnection(
+        String url, java.util.Properties info, Class<?> caller) throws SQLException {
+        /*
+         * When callerCl is null, we should check the application's
+         * (which is invoking this class indirectly)
+         * classloader, so that the JDBC driver class outside rt.jar
+         * can be loaded from here.
+         */
+        ClassLoader callerCL = caller != null ? caller.getClassLoader() : null;
+        synchronized(DriverManager.class) {
+            // synchronize loading of the correct classloader.
+            if (callerCL == null) {
+                callerCL = Thread.currentThread().getContextClassLoader();
+            }
+        }
 
-  protected final Map<String, MappedStatement> mappedStatements = new StrictMap<MappedStatement>("Mapped Statements collection")
-      .conflictMessageProducer((savedValue, targetValue) ->
-          ". please check " + savedValue.getResource() + " and " + targetValue.getResource());
-  protected final Map<String, Cache> caches = new StrictMap<>("Caches collection");
-  protected final Map<String, ResultMap> resultMaps = new StrictMap<>("Result Maps collection");
-  protected final Map<String, ParameterMap> parameterMaps = new StrictMap<>("Parameter Maps collection");
-  protected final Map<String, KeyGenerator> keyGenerators = new StrictMap<>("Key Generators collection");
+        if(url == null) {
+            throw new SQLException("The url cannot be null", "08001");
+        }
 
-  protected final Set<String> loadedResources = new HashSet<>();
-  protected final Map<String, XNode> sqlFragments = new StrictMap<>("XML fragments parsed from previous mappers");
+        println("DriverManager.getConnection(\"" + url + "\")");
 
-  protected final Collection<XMLStatementBuilder> incompleteStatements = new LinkedList<>();
-  protected final Collection<CacheRefResolver> incompleteCacheRefs = new LinkedList<>();
-  protected final Collection<ResultMapResolver> incompleteResultMaps = new LinkedList<>();
-  protected final Collection<MethodResolver> incompleteMethods = new LinkedList<>();
+ // Walk through the loaded registeredDrivers attempting to make a connection. + // Remember the first exception that gets raised so we can reraise it. + SQLException reason = null; -

这么多成员变量,先不一一解释作用,但是其中的几个参数我们应该是已经知道了的,第一个就是 mappedStatements ,上一篇我们知道被解析的mapper就是放在这里,后面的 resultMapsparameterMaps 也比较常用的就是我们参数和结果的映射map,这里跟我之前有一篇解释为啥我们一些变量的使用会比较特殊,比如list,可以参考这篇keyGenerators是在我们需要定义主键生成器的时候使用。
然后第二点是我们创建的 org.apache.ibatis.session.SqlSessionFactory 是哪个,

-
public SqlSessionFactory build(Configuration config) {
-  return new DefaultSqlSessionFactory(config);
-}
+ for(DriverInfo aDriver : registeredDrivers) { + // If the caller does not have permission to load the driver then + // skip it. + if(isDriverAllowed(aDriver.driver, callerCL)) { + try { + // ----------> driver[className=com.mysql.cj.jdbc.Driver@64030b91] + println(" trying " + aDriver.driver.getClass().getName()); + Connection con = aDriver.driver.connect(url, info); + if (con != null) { + // Success! + println("getConnection returning " + aDriver.driver.getClass().getName()); + return (con); + } + } catch (SQLException ex) { + if (reason == null) { + reason = ex; + } + } -

是这个 DefaultSqlSessionFactory ,这是其中一个 SqlSessionFactory 的实现
接下来我们看看 openSession 里干了啥

-
public SqlSession openSession() {
-  return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
-}
+ } else { + println(" skipping: " + aDriver.getClass().getName()); + } -

这边有几个参数,第一个是默认的执行器类型,往上找找上面贴着的 Configuration 的成员变量里可以看到默认是
protected ExecutorType defaultExecutorType = ExecutorType.SIMPLE;

-

因为没有指明特殊的执行逻辑,所以默认我们也就用简单类型的,第二个参数是是事务级别,第三个是是否自动提交

-
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
-  Transaction tx = null;
-  try {
-    final Environment environment = configuration.getEnvironment();
-    final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
-    tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
-    // --------> 先关注这里
-    final Executor executor = configuration.newExecutor(tx, execType);
-    return new DefaultSqlSession(configuration, executor, autoCommit);
-  } catch (Exception e) {
-    closeTransaction(tx); // may have fetched a connection so lets call close()
-    throw ExceptionFactory.wrapException("Error opening session.  Cause: " + e, e);
-  } finally {
-    ErrorContext.instance().reset();
-  }
-}
+ } -

具体是调用了 Configuration 的这个方法

-
public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
-  executorType = executorType == null ? defaultExecutorType : executorType;
-  Executor executor;
-  if (ExecutorType.BATCH == executorType) {
-    executor = new BatchExecutor(this, transaction);
-  } else if (ExecutorType.REUSE == executorType) {
-    executor = new ReuseExecutor(this, transaction);
-  } else {
-    // ---------> 会走到这个分支
-    executor = new SimpleExecutor(this, transaction);
-  }
-  if (cacheEnabled) {
-    executor = new CachingExecutor(executor);
-  }
-  executor = (Executor) interceptorChain.pluginAll(executor);
-  return executor;
-}
+ // if we got here nobody could connect. + if (reason != null) { + println("getConnection failed: " + reason); + throw reason; + } -

上面传入的 executorTypeConfiguration 的默认类型,也就是 simple 类型,并且 cacheEnabledConfiguration 默认为 true,所以会包装成CachingExecutor ,然后后面就是插件了,这块我们先不展开
然后我们的openSession返回的就是创建了DefaultSqlSession

-
public DefaultSqlSession(Configuration configuration, Executor executor, boolean autoCommit) {
-    this.configuration = configuration;
-    this.executor = executor;
-    this.dirty = false;
-    this.autoCommit = autoCommit;
-  }
+ println("getConnection: no suitable driver found for "+ url); + throw new SQLException("No suitable driver found for "+ url, "08001"); + }
-

然后就是调用 selectOne, 因为前面已经把这部分代码说过了,就直接跳转过来
org.apache.ibatis.session.defaults.DefaultSqlSession#selectList(java.lang.String, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.session.ResultHandler)

-
private <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) {
-  try {
-    MappedStatement ms = configuration.getMappedStatement(statement);
-    return executor.query(ms, wrapCollection(parameter), rowBounds, handler);
-  } catch (Exception e) {
-    throw ExceptionFactory.wrapException("Error querying database.  Cause: " + e, e);
-  } finally {
-    ErrorContext.instance().reset();
-  }
-}
-

因为前面说了 executor 包装了 CachingExecutor ,所以会先调用

+

上面的driver就是driver[className=com.mysql.cj.jdbc.Driver@64030b91]

+
// com.mysql.cj.jdbc.NonRegisteringDriver#connect
+public Connection connect(String url, Properties info) throws SQLException {
+        try {
+            try {
+                if (!ConnectionUrl.acceptsUrl(url)) {
+                    return null;
+                } else {
+                    ConnectionUrl conStr = ConnectionUrl.getConnectionUrlInstance(url, info);
+                    switch (conStr.getType()) {
+                        case SINGLE_CONNECTION:
+                            return ConnectionImpl.getInstance(conStr.getMainHost());
+                        case FAILOVER_CONNECTION:
+                        case FAILOVER_DNS_SRV_CONNECTION:
+                            return FailoverConnectionProxy.createProxyInstance(conStr);
+                        case LOADBALANCE_CONNECTION:
+                        case LOADBALANCE_DNS_SRV_CONNECTION:
+                            return LoadBalancedConnectionProxy.createProxyInstance(conStr);
+                        case REPLICATION_CONNECTION:
+                        case REPLICATION_DNS_SRV_CONNECTION:
+                            return ReplicationConnectionProxy.createProxyInstance(conStr);
+                        default:
+                            return null;
+                    }
+                }
+            } catch (UnsupportedConnectionStringException var5) {
+                return null;
+            } catch (CJException var6) {
+                throw (UnableToConnectException)ExceptionFactory.createException(UnableToConnectException.class, Messages.getString("NonRegisteringDriver.17", new Object[]{var6.toString()}), var6);
+            }
+        } catch (CJException var7) {
+            throw SQLExceptionsMapping.translateException(var7);
+        }
+    }
+ +

这是个 SINGLE_CONNECTION ,所以调用的就是 return ConnectionImpl.getInstance(conStr.getMainHost());
然后在这里设置了代理类

+
public PooledConnection(Connection connection, PooledDataSource dataSource) {
+    this.hashCode = connection.hashCode();
+    this.realConnection = connection;
+    this.dataSource = dataSource;
+    this.createdTimestamp = System.currentTimeMillis();
+    this.lastUsedTimestamp = System.currentTimeMillis();
+    this.valid = true;
+    this.proxyConnection = (Connection) Proxy.newProxyInstance(Connection.class.getClassLoader(), IFACES, this);
+  }
+ +

结合这个

@Override
-public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
-  BoundSql boundSql = ms.getBoundSql(parameterObject);
-  CacheKey key = createCacheKey(ms, parameterObject, rowBounds, boundSql);
-  return query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
-}
+public Connection getConnection() throws SQLException { + return popConnection(dataSource.getUsername(), dataSource.getPassword()).getProxyConnection(); +}
+ +

所以最终的connection就是com.mysql.cj.jdbc.ConnectionImpl@358ab600

+]]>
+ + Java + Mybatis + + + Java + Mysql + Mybatis + +
+ + nginx 日志小记 + /2022/04/17/nginx-%E6%97%A5%E5%BF%97%E5%B0%8F%E8%AE%B0/ + nginx 默认的日志有特定的格式,我们也可以自定义,

+

默认的格式是预定义的 combined

+
log_format combined '$remote_addr - $remote_user [$time_local] '
+                    '"$request" $status $body_bytes_sent '
+                    '"$http_referer" "$http_user_agent"';
-

然后是调用的真实的query方法

-
@Override
-public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)
-    throws SQLException {
-  Cache cache = ms.getCache();
-  if (cache != null) {
-    flushCacheIfRequired(ms);
-    if (ms.isUseCache() && resultHandler == null) {
-      ensureNoOutParams(ms, boundSql);
-      @SuppressWarnings("unchecked")
-      List<E> list = (List<E>) tcm.getObject(cache, key);
-      if (list == null) {
-        list = delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
-        tcm.putObject(cache, key, list); // issue #578 and #116
-      }
-      return list;
-    }
-  }
-  return delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
-}
+

配置的日志可以使用这个默认的,如果满足需求的话

+
Syntax:	access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]];
+        access_log off;
+Default: access_log logs/access.log combined;
+Context: http, server, location, if in location, limit_except
-

这里是第一次查询,没有缓存就先到最后一行,继续是调用到 org.apache.ibatis.executor.BaseExecutor#queryFromDatabase

-
@Override
-  public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
-    ErrorContext.instance().resource(ms.getResource()).activity("executing a query").object(ms.getId());
-    if (closed) {
-      throw new ExecutorException("Executor was closed.");
-    }
-    if (queryStack == 0 && ms.isFlushCacheRequired()) {
-      clearLocalCache();
-    }
-    List<E> list;
-    try {
-      queryStack++;
-      list = resultHandler == null ? (List<E>) localCache.getObject(key) : null;
-      if (list != null) {
-        handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);
-      } else {
-        // ----------->会走到这里
-        list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);
-      }
-    } finally {
-      queryStack--;
-    }
-    if (queryStack == 0) {
-      for (DeferredLoad deferredLoad : deferredLoads) {
-        deferredLoad.load();
-      }
-      // issue #601
-      deferredLoads.clear();
-      if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) {
-        // issue #482
-        clearLocalCache();
-      }
-    }
-    return list;
-  }
+

而如果需要额外的一些配置的话可以自己定义 log_format ,比如我想要给日志里加上请求时间,那就可以自己定义一个 log_format 比如添加下

+
$request_time
+request processing time in seconds with a milliseconds resolution;   
+time elapsed between the first bytes were read from the client and the log write after the last bytes were sent to the client
-

然后是

-
private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
-  List<E> list;
-  localCache.putObject(key, EXECUTION_PLACEHOLDER);
-  try {
-    list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);
-  } finally {
-    localCache.removeObject(key);
-  }
-  localCache.putObject(key, list);
-  if (ms.getStatementType() == StatementType.CALLABLE) {
-    localOutputParameterCache.putObject(key, parameter);
-  }
-  return list;
-}
+
log_format combined_extend '$remote_addr - $remote_user [$time_local] '
+                    '"$request" $status $body_bytes_sent '
+                    '"$http_referer" "$http_user_agent" "$request_time"';
-

然后就是 simpleExecutor 的执行过程

-
@Override
-public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
-  Statement stmt = null;
-  try {
-    Configuration configuration = ms.getConfiguration();
-    StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
-    stmt = prepareStatement(handler, ms.getStatementLog());
-    return handler.query(stmt, resultHandler);
-  } finally {
-    closeStatement(stmt);
-  }
-}
+

然后其他的比如还有 gzip 压缩,可以设置压缩级别,flush 刷盘时间还有根据条件控制

+

这里的条件控制简单看了下还比较厉害

+

比如我想对2xx 跟 3xx 的访问不记录日志

+
map $status $loggable {
+    ~^[23]  0;
+    default 1;
+}
 
-

接下去其实就是跟jdbc交互了

-
@Override
-public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
-  PreparedStatement ps = (PreparedStatement) statement;
-  ps.execute();
-  return resultSetHandler.handleResultSets(ps);
-}
+access_log /path/to/access.log combined if=$loggable;
-

com.mysql.cj.jdbc.ClientPreparedStatement#execute

-
public boolean execute() throws SQLException {
-        try {
-            synchronized(this.checkClosed().getConnectionMutex()) {
-                JdbcConnection locallyScopedConn = this.connection;
-                if (!this.doPingInstead && !this.checkReadOnlySafeStatement()) {
-                    throw SQLError.createSQLException(Messages.getString("PreparedStatement.20") + Messages.getString("PreparedStatement.21"), "S1009", this.exceptionInterceptor);
-                } else {
-                    ResultSetInternalMethods rs = null;
-                    this.lastQueryIsOnDupKeyUpdate = false;
-                    if (this.retrieveGeneratedKeys) {
-                        this.lastQueryIsOnDupKeyUpdate = this.containsOnDuplicateKeyUpdate();
-                    }
+

$loggable 是 0 或者空时表示 if 条件为否,上面的默认就是 1,只有当请求状态 status 是 2xx 或 3xx 时才是 0,代表不用记录,有了这个特性就可以更灵活地配置日志

+

文章主要参考了 nginx 的 log 模块的文档

+]]> + + nginx + + + nginx + 日志 + + + + mybatis系列-入门篇 + /2022/11/27/mybatis%E7%B3%BB%E5%88%97-%E5%85%A5%E9%97%A8%E7%AF%87/ + mybatis是我们比较常用的orm框架,下面是官网的介绍

+
+

MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

+
+

mybatis一大特点,或者说比较为人熟知的应该就是比 hibernate 是更轻量化,为国人所爱好的orm框架,对于hibernate目前还没有深入的拆解过,后续可以也写一下,在使用体验上觉得是个比较精巧的框架,看代码也比较容易,所以就想写个系列,第一篇先是介绍下使用
根据官网的文档上我们先来尝试一下简单使用
首先我们有个简单的配置,这个文件是mybatis-config.xml

+
<?xml version="1.0" encoding="UTF-8" ?>
+<!DOCTYPE configuration
+        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
+        "https://mybatis.org/dtd/mybatis-3-config.dtd">
+<configuration>
+    <!-- 需要加入的properties-->
+    <properties resource="application-development.properties"/>
+    <!-- 指出使用哪个环境,默认是development-->
+    <environments default="development">
+        <environment id="development">
+        <!-- 指定事务管理器类型-->
+            <transactionManager type="JDBC"/>
+            <!-- 指定数据源类型-->
+            <dataSource type="POOLED">
+                <!-- 下面就是具体的参数占位了-->
+                <property name="driver" value="${driver}"/>
+                <property name="url" value="${url}"/>
+                <property name="username" value="${username}"/>
+                <property name="password" value="${password}"/>
+            </dataSource>
+        </environment>
+    </environments>
+    <mappers>
+        <!-- 指定mapper xml的位置或文件-->
+        <mapper resource="mapper/StudentMapper.xml"/>
+    </mappers>
+</configuration>
+

在代码里创建mybatis里重要入口

+
String resource = "mybatis-config.xml";
+InputStream inputStream = Resources.getResourceAsStream(resource);
+SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
+

然后我们上面的StudentMapper.xml

+
<?xml version="1.0" encoding="UTF-8" ?>
+<!DOCTYPE mapper
+        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
+        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
+<mapper namespace="com.nicksxs.mybatisdemo.StudentMapper">
+    <select id="selectStudent" resultType="com.nicksxs.mybatisdemo.StudentDO">
+        select * from student where id = #{id}
+    </select>
+</mapper>
+

那么我们就要使用这个mapper,

+
String resource = "mybatis-config.xml";
+InputStream inputStream = Resources.getResourceAsStream(resource);
+SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
+try (SqlSession session = sqlSessionFactory.openSession()) {
+    StudentDO studentDO = session.selectOne("com.nicksxs.mybatisdemo.StudentMapper.selectStudent", 1);
+    System.out.println("id is " + studentDO.getId() + " name is " +studentDO.getName());
+} catch (Exception e) {
+    e.printStackTrace();
+}
+

sqlSessionFactory是sqlSession的工厂,我们可以通过sqlSessionFactory来创建sqlSession,而SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句。可以看到mapper.xml中有定义mapper的namespace,就可以通过session.selectOne()传入namespace+id来调用这个方法
但是这样调用比较不合理的点,或者说按后面mybatis优化之后我们可以指定mapper接口

+
public interface StudentMapper {
 
-                    this.batchedGeneratedKeys = null;
-                    this.resetCancelledState();
-                    this.implicitlyCloseAllOpenResults();
-                    this.clearWarnings();
-                    if (this.doPingInstead) {
-                        this.doPingInstead();
-                        return true;
-                    } else {
-                        this.setupStreamingTimeout(locallyScopedConn);
-                        Message sendPacket = ((PreparedQuery)this.query).fillSendPacket(((PreparedQuery)this.query).getQueryBindings());
-                        String oldDb = null;
-                        if (!locallyScopedConn.getDatabase().equals(this.getCurrentDatabase())) {
-                            oldDb = locallyScopedConn.getDatabase();
-                            locallyScopedConn.setDatabase(this.getCurrentDatabase());
-                        }
+    public StudentDO selectStudent(Long id);
+}
+

就可以可以通过mapper接口获取方法,这样就不用涉及到未知的变量转换等异常

+
try (SqlSession session = sqlSessionFactory.openSession()) {
+    StudentMapper mapper = session.getMapper(StudentMapper.class);
+    StudentDO studentDO = mapper.selectStudent(1L);
+    System.out.println("id is " + studentDO.getId() + " name is " +studentDO.getName());
+} catch (Exception e) {
+    e.printStackTrace();
+}
+

这一篇咱们先介绍下简单的使用,后面可以先介绍下这些的原理。

+]]>
+ + Java + Mybatis + + + Java + Mysql + Mybatis + +
+ + openresty + /2019/06/18/openresty/ + 目前公司要对一些新的产品功能做灰度测试,因为在后端业务代码层面添加判断比较麻烦,所以想在nginx上做点手脚,就想到了openresty
前后也踩了不少坑,这边先写一点

+

首先是日志
error_log logs/error.log debug;
需要nginx开启日志的debug才能看到日志

+

使用 lua_code_cache off即可, 另外注意只有使用 content_by_lua_file 才会生效

+
http {
+  lua_code_cache off;
+}
 
-                        CachedResultSetMetaData cachedMetadata = null;
-                        boolean cacheResultSetMetadata = (Boolean)locallyScopedConn.getPropertySet().getBooleanProperty(PropertyKey.cacheResultSetMetadata).getValue();
-                        if (cacheResultSetMetadata) {
-                            cachedMetadata = locallyScopedConn.getCachedMetaData(((PreparedQuery)this.query).getOriginalSql());
-                        }
+location ~* /(\d+-.*)/api/orgunits/load_all(.*) {
+   default_type 'application/json;charset=utf-8';
+   content_by_lua_file /data/projects/xxx/current/lua/controller/load_data.lua;
+}
+ +

使用lua给nginx请求response头添加内容可以用这个

+
ngx.header['response'] = 'header'
- locallyScopedConn.setSessionMaxRows(this.getQueryInfo().getFirstStmtChar() == 'S' ? this.maxRows : -1); - rs = this.executeInternal(this.maxRows, sendPacket, this.createStreamingResultSet(), this.getQueryInfo().getFirstStmtChar() == 'S', cachedMetadata, false); - if (cachedMetadata != null) { - locallyScopedConn.initializeResultsMetadataFromCache(((PreparedQuery)this.query).getOriginalSql(), cachedMetadata, rs); - } else if (rs.hasRows() && cacheResultSetMetadata) { - locallyScopedConn.initializeResultsMetadataFromCache(((PreparedQuery)this.query).getOriginalSql(), (CachedResultSetMetaData)null, rs); - } - if (this.retrieveGeneratedKeys) { - rs.setFirstCharOfQuery(this.getQueryInfo().getFirstStmtChar()); - } +

使用总结

+

后续:

+
    +
  1. 一开始在本地环境的时候使用content_by_lua_file只关注了头,后来发到测试环境发现请求内容都没代理转发到后端服务上
    网上查了下发现content_by_lua_file是将请求的所有内容包括response都用这里面的lua脚本生成了,content这个词就表示是请求内容
    后来改成了access_by_lua_file就正常了,只是要去获取请求内容和修改响应头,并不是要完整的接管请求

    +
  2. +
  3. 后来又碰到了一个坑是nginx有个client_body_buffer_size的配置参数,nginx在32位和64位系统里有8K和16K两个默认值,当请求内容大于这两个值的时候,会把请求内容放到临时文件里,这个时候openresty里的ngx.req.get_post_args()就会报“failed to get post args: requesty body in temp file not supported”这个错误,将client_body_buffer_size这个参数配置调大一点就好了

    +
  4. +
  5. 还有就是lua的异常捕获,网上看一般是用pcall和xpcall来进行保护调用,因为问题主要出在cjson的decode,这里有两个解决方案,一个就是将cjson.decode使用pcall封装,

    +
    local decode = require("cjson").decode
     
    -                        if (oldDb != null) {
    -                            locallyScopedConn.setDatabase(oldDb);
    -                        }
    +function json_decode( str )
    +    local ok, t = pcall(decode, str)
    +    if not ok then
    +      return nil
    +    end
     
    -                        if (rs != null) {
    -                            this.lastInsertId = rs.getUpdateID();
    -                            this.results = rs;
    -                        }
    +    return t
    +end
    +

    这个是使用了pcall,称为保护调用,会在内部错误后返回两个参数,第一个是false,第二个是错误信息
    还有一种是使用cjson.safe包

    +
    local json = require("cjson.safe")
    +local str = [[ {"key:"value"} ]]
     
    -                        return rs != null && rs.hasRows();
    -                    }
    -                }
    -            }
    -        } catch (CJException var11) {
    -            throw SQLExceptionsMapping.translateException(var11, this.getExceptionInterceptor());
    -        }
    -    }
    +local t = json.decode(str) +if t then + ngx.say(" --> ", type(t)) +end
+

cjson.safe包会在解析失败的时候返回nil

+ +
  • 还有一个是redis链接时如果host使用的是域名的话会提示“failed to connect: no resolver defined to resolve “redis.xxxxxx.com””,这里需要使用nginx的resolver指令,
    resolver 8.8.8.8 valid=3600s;

    +
  • +
  • 还有一点补充下
    就是业务在使用redis的时候使用了db的特性,所以在lua访问redis的时候也需要执行db,这里lua的redis库也支持了这个特性,可以使用instance:select(config:get(‘db’))来切换db

    +
  • +
  • 性能优化tips
    建议是尽量少使用阶段钩子,例如content_by_lua_file,*_by_lua

    +
  • +
  • 发现一个不错的openresty站点
    地址

    +
  • + +]]>
    + + nginx + + + nginx + openresty + +
    + + pcre-intro-and-a-simple-package + /2015/01/16/pcre-intro-and-a-simple-package/ + Pcre
    +

    Perl Compatible Regular Expressions (PCRE) is a regular
    expression C library inspired by the regular expression
    capabilities in the Perl programming language, written
    by Philip Hazel, starting in summer 1997.

    +
    +

    因为最近工作内容的一部分需要做字符串的识别处理,所以就顺便用上了之前在PHP中用过的正则,在C/C++中本身不包含正则库,这里使用的pcre,对MFC开发,在这里提供了静态链接库,在引入lib跟.h文件后即可使用。

    + +

    Regular Expression Syntax

    然后是一些正则语法,官方的语法文档比较科学严谨,特别是对类似于贪婪匹配等细节的说明,当然一般的使用可以在网上找到很多匹配语法,例如这个

    +

    PCRE函数介绍

    +

    pcre_compile
    原型:

    +
    +
    #include <pcre.h>
    +pcre *pcre_compile(const char *pattern, int options, const char **errptr, int *erroffset, const unsigned char *tableptr);
    +

    功能:将一个正则表达式编译成一个内部表示,在匹配多个字符串时,可以加速匹配。其同pcre_compile2功能一样只是缺少一个参数errorcodeptr。
    参数:
    pattern 正则表达式
    options 为0,或者其他参数选项
    errptr 出错消息
    erroffset 出错位置
    tableptr 指向一个字符数组的指针,可以设置为空NULL

    +
    +

    pcre_exec
    原型:

    +
    +
    #include <pcre.h>
    +int pcre_exec(const pcre *code, const pcre_extra *extra, const char *subject, int length, int startoffset, int options, int *ovector, int ovecsize)
    +

    功能:使用编译好的模式进行匹配,采用与Perl相似的算法,返回匹配串的偏移位置。
    参数:
    code 编译好的模式
    extra 指向一个pcre_extra结构体,可以为NULL
    subject 需要匹配的字符串
    length 匹配的字符串长度(Byte)
    startoffset 匹配的开始位置
    options 选项位
    ovector 指向一个结果的整型数组
    ovecsize 数组大小。

    +

    这里是两个最常用的函数的简单说明,pcre的静态库提供了一系列的函数以供使用,可以参考这个博客说明,另外对于以上函数的具体参数详细说明可以参考官网此处

    +

    一个丑陋的封装

    void COcxDemoDlg::pcre_exec_all(const pcre * re, PCRE_SPTR src, vector<pair<int, int>> &vc)
    +{
    +	int rc;
    +	int ovector[30];
    +	int i = 0;
    +	pair<int, int> pr;
    +	rc = pcre_exec(re, NULL, src, strlen(src), i, 0, ovector, 30);
    +	for (; rc > 0;)
    +	{
    +		i = ovector[1];
    +		pr.first = ovector[2];
    +		pr.second = ovector[3];
    +		vc.push_back(pr);
    +		rc = pcre_exec(re, NULL, src, strlen(src), i, 0, ovector, 30);
    +	}
    +}
    +

    vector中是全文匹配后的索引对,只是简单地用下。

    ]]>
    - Java - Mybatis + C++ - Java - Mysql - Mybatis + c++ + mfc
    @@ -10054,134 +9822,42 @@ Fatal error: Abstract function abst1::abstra1() cannot contain body in php on li - mybatis系列-sql 类的简要分析 - /2023/03/19/mybatis%E7%B3%BB%E5%88%97-sql-%E7%B1%BB%E7%9A%84%E7%AE%80%E8%A6%81%E5%88%86%E6%9E%90/ - 上次就比较简单的讲了使用,这块也比较简单,因为封装得不是很复杂,首先我们从 select 作为入口来看看,这个具体的实现,

    -
    String selectSql = new SQL() {{
    -            SELECT("id", "name");
    -            FROM("student");
    -            WHERE("id = #{id}");
    -        }}.toString();
    -

    SELECT 方法的实现,

    -
    public T SELECT(String... columns) {
    -  sql().statementType = SQLStatement.StatementType.SELECT;
    -  sql().select.addAll(Arrays.asList(columns));
    -  return getSelf();
    -}
    -

    statementType是个枚举

    -
    public enum StatementType {
    -  DELETE, INSERT, SELECT, UPDATE
    -}
    -

    那这个就是个 select 语句,然后会把参数转成 list 添加到 select 变量里,
    然后是 from 语句,这个大概也能猜到就是设置下表名,

    -
    public T FROM(String table) {
    -  sql().tables.add(table);
    -  return getSelf();
    -}
    -

    往 tables 里添加了 table,这个 tables 是什么呢
    这里也可以看下所有的变量,

    -
    StatementType statementType;
    -List<String> sets = new ArrayList<>();
    -List<String> select = new ArrayList<>();
    -List<String> tables = new ArrayList<>();
    -List<String> join = new ArrayList<>();
    -List<String> innerJoin = new ArrayList<>();
    -List<String> outerJoin = new ArrayList<>();
    -List<String> leftOuterJoin = new ArrayList<>();
    -List<String> rightOuterJoin = new ArrayList<>();
    -List<String> where = new ArrayList<>();
    -List<String> having = new ArrayList<>();
    -List<String> groupBy = new ArrayList<>();
    -List<String> orderBy = new ArrayList<>();
    -List<String> lastList = new ArrayList<>();
    -List<String> columns = new ArrayList<>();
    -List<List<String>> valuesList = new ArrayList<>();
    -

    可以看到是一堆 List 先暂存这些sql 片段,然后再拼装成 sql 语句,
    因为它重写了 toString 方法

    -
    @Override
    -public String toString() {
    -  StringBuilder sb = new StringBuilder();
    -  sql().sql(sb);
    -  return sb.toString();
    -}
    -

    调用的 sql 方法是

    -
    public String sql(Appendable a) {
    -      SafeAppendable builder = new SafeAppendable(a);
    -      if (statementType == null) {
    -        return null;
    -      }
    -
    -      String answer;
    -
    -      switch (statementType) {
    -        case DELETE:
    -          answer = deleteSQL(builder);
    -          break;
    -
    -        case INSERT:
    -          answer = insertSQL(builder);
    -          break;
    -
    -        case SELECT:
    -          answer = selectSQL(builder);
    -          break;
    -
    -        case UPDATE:
    -          answer = updateSQL(builder);
    -          break;
    -
    -        default:
    -          answer = null;
    -      }
    -
    -      return answer;
    -    }
    -

    根据上面的 statementType判断是个什么 sql,我们这个是 selectSQL 就走的 SELECT 这个分支

    -
    private String selectSQL(SafeAppendable builder) {
    -  if (distinct) {
    -    sqlClause(builder, "SELECT DISTINCT", select, "", "", ", ");
    -  } else {
    -    sqlClause(builder, "SELECT", select, "", "", ", ");
    -  }
    +    powershell 初体验
    +    /2022/11/13/powershell-%E5%88%9D%E4%BD%93%E9%AA%8C/
    +    powershell变量

    变量命名类似于php

    +
    PS C:\Users\Nicks> $a=1
    +PS C:\Users\Nicks> $b=2
    +PS C:\Users\Nicks> $a*$b
    +2
    +

    有一个比较好用的是变量交换
    一般的语言做两个变量交换一般需要一个临时变量

    +
    $tmp=$a
    +$a=$b
    +$b=$tmp
    +

    而在powershell中可以这样

    +
    $a,$b=$b,$a
    +PS C:\Users\Nicks> $a,$b=$b,$a
    +PS C:\Users\Nicks> $a
    +2
    +PS C:\Users\Nicks> $b
    +1
    +

    还可以通过这个

    +
    PS C:\Users\Nicks> ls variable:
     
    -  sqlClause(builder, "FROM", tables, "", "", ", ");
    -  joins(builder);
    -  sqlClause(builder, "WHERE", where, "(", ")", " AND ");
    -  sqlClause(builder, "GROUP BY", groupBy, "", "", ", ");
    -  sqlClause(builder, "HAVING", having, "(", ")", " AND ");
    -  sqlClause(builder, "ORDER BY", orderBy, "", "", ", ");
    -  limitingRowsStrategy.appendClause(builder, offset, limit);
    -  return builder.toString();
    -}
    -

    上面的可以看出来就是按我们常规的 sql 理解顺序来处理
    就是select ... from ... where ... 这样子
    再看下 sqlClause 的代码

    -
    private void sqlClause(SafeAppendable builder, String keyword, List<String> parts, String open, String close,
    -                           String conjunction) {
    -      if (!parts.isEmpty()) {
    -        if (!builder.isEmpty()) {
    -          builder.append("\n");
    -        }
    -        builder.append(keyword);
    -        builder.append(" ");
    -        builder.append(open);
    -        String last = "________";
    -        for (int i = 0, n = parts.size(); i < n; i++) {
    -          String part = parts.get(i);
    -          if (i > 0 && !part.equals(AND) && !part.equals(OR) && !last.equals(AND) && !last.equals(OR)) {
    -            builder.append(conjunction);
    -          }
    -          builder.append(part);
    -          last = part;
    -        }
    -        builder.append(close);
    -      }
    -    }
    -

    这里的拼接方式还需要判断 AND 和 OR 的判断逻辑,其他就没什么特别的了,只是where 语句中的 lastList 不知道是干嘛的,好像只有添加跟赋值的操作,有知道的大神也可以评论指导下

    +Name Value +---- ----- +$ $b +? True +^ $b +a 2 +args {} +b 1
    +

    查看现存的变量
    当然一般脚本都是动态类型的,
    可以通过
    gettype方法

    ]]>
    - Java - Mybatis + 语言 - Java - Mysql - Mybatis + powershell
    @@ -10207,86 +9883,469 @@ Starting node rabbit@rabbit2 集群搭建

    集群搭建的时候有个erlang vm生成的random cookie,这个是用来做集群之间认证的,相同的cookie才能连接,但是如果通过vim打开复制后在其他几点新建文件写入会多一个换行,导致集群建立是报错,所以这里最好使用scp等传输命令直接传输cookie文件,同时要注意下cookie的文件权限。
    另外在集群搭建的时候如果更改过hostname,那么要把rabbitmq的数据库删除,否则启动后会马上挂掉

    ]]> - php + php + + + php + mq + im + +
    + + redis数据结构介绍-第一部分 SDS,链表,字典 + /2019/12/26/redis%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%BB%8B%E7%BB%8D/ + redis是现在服务端很常用的缓存中间件,其实原来还有memcache之类的竞品,但是现在貌似 redis 快一统江湖,这里当然不是在吹,只是个人角度的一个感觉,不权威只是主观感觉。
    redis 主要有五种数据结构,StringsListsSetsHashesSorted Sets,这五种数据结构先简单介绍下,Strings类型的其实就是我们最常用的 key-value,实际开发中也会用的最多;Lists是列表,这个有些会用来做队列,因为 redis 目前常用的版本支持丰富的列表操作;还有是Sets集合,这个主要的特点就是集合中元素不重复,可以用在有这类需求的场景里;Hashes是叫散列,类似于 Python 中的字典结构;还有就是Sorted Sets这个是个有序集合;一眼看这些其实没啥特别的,除了最后这个有序集合,不过去了解背后的实现方式还是比较有意思的。

    +

    SDS 简单动态字符串

    先从Strings开始说,了解过 C 语言的应该知道,C 语言中的字符串其实是个 char[] 字符数组,redis 也不例外,只是最开始的版本就对这个做了一丢丢的优化,而正是这一丢丢的优化,让这个 redis 的使用效率提升了数倍

    +
    struct sdshdr {
    +    // 字符串长度
    +    int len;
    +    // 字符串空余字符数
    +    int free;
    +    // 字符串内容
    +    char buf[];
    +};
    +

    这里引用了 redis 在 github 上最早的 2.2 版本的代码,代码路径是https://github.com/antirez/redis/blob/2.2/src/sds.h,可以看到这个结构体里只有仨元素,两个 int 型和一个 char 型数组,两个 int 型其实就是我说的优化,因为 C 语言本身的字符串数组,有两个问题,一个是要知道它实际已被占用的长度,需要去遍历这个数组,第二个就是比较容易踩坑的是遍历的时候要注意它有个以\0作为结尾的特点;通过上面的两个 int 型参数,一个是知道字符串目前的长度,一个是知道字符串还剩余多少位空间,这样子坐着两个操作从 O(N)简化到了O(1)了,还有第二个 free 还有个比较重要的作用就是能防止 C 字符串的溢出问题,在存储之前可以先判断 free 长度,如果长度不够就先扩容了,先介绍到这,这个系列可以写蛮多的,慢慢介绍吧

    +

    链表

    链表是比较常见的数据结构了,但是因为 redis 是用 C 写的,所以在不依赖第三方库的情况下只能自己写一个了,redis 的链表是个有头的链表,而且是无环的,具体的结构我也找了 github 上最早版本的代码

    +
    typedef struct listNode {
    +    // 前置节点
    +    struct listNode *prev;
    +    // 后置节点
    +    struct listNode *next;
    +    // 值
    +    void *value;
    +} listNode;
    +
    +typedef struct list {
    +    // 链表表头
    +    listNode *head;
    +    // 当前节点,也可以说是最后节点
    +    listNode *tail;
    +    // 节点复制函数
    +    void *(*dup)(void *ptr);
    +    // 节点值释放函数
    +    void (*free)(void *ptr);
    +    // 节点值比较函数
    +    int (*match)(void *ptr, void *key);
    +    // 链表包含的节点数量
    +    unsigned int len;
    +} list;
    +

    代码地址是这个https://github.com/antirez/redis/blob/2.2/src/adlist.h
    可以看下节点是由listNode承载的,包括值和一个指向前节点跟一个指向后一节点的两个指针,然后值是 void 指针类型,所以可以承载不同类型的值
    然后是 list结构用来承载一个链表,包含了表头,和表尾,复制函数,释放函数和比较函数,还有链表长度,因为包含了前两个节点,找到表尾节点跟表头都是 O(1)的时间复杂度,还有节点数量,其实这个跟 SDS 是同一个做法,就是空间换时间,这也是写代码里比较常见的做法,以此让一些高频的操作提速。

    +

    字典

    字典也是个常用的数据结构,其实只是叫法不同,数据结构中叫 hash 散列,Java 中叫 Map,PHP 中是数组 array,Python 中也叫字典 dict,因为纯 C 语言本身不带这些数据结构,所以这也是个痛并快乐着的过程,享受 C 语言的高性能的同时也要接受它只提供了语言的基本功能的现实,各种轮子都需要自己造,redis 同样实现了自己的字典
    下面来看看代码

    +
    typedef struct dictEntry {
    +    void *key;
    +    void *val;
    +    struct dictEntry *next;
    +} dictEntry;
    +
    +typedef struct dictType {
    +    unsigned int (*hashFunction)(const void *key);
    +    void *(*keyDup)(void *privdata, const void *key);
    +    void *(*valDup)(void *privdata, const void *obj);
    +    int (*keyCompare)(void *privdata, const void *key1, const void *key2);
    +    void (*keyDestructor)(void *privdata, void *key);
    +    void (*valDestructor)(void *privdata, void *obj);
    +} dictType;
    +
    +/* This is our hash table structure. Every dictionary has two of this as we
    + * implement incremental rehashing, for the old to the new table. */
    +typedef struct dictht {
    +    dictEntry **table;
    +    unsigned long size;
    +    unsigned long sizemask;
    +    unsigned long used;
    +} dictht;
    +
    +typedef struct dict {
    +    dictType *type;
    +    void *privdata;
    +    dictht ht[2];
    +    int rehashidx; /* rehashing not in progress if rehashidx == -1 */
    +    int iterators; /* number of iterators currently running */
    +} dict;
    +

    看了下这个 2.2 版本的代码跟最新版的其实也差的不是很多,所以还是照旧用老代码,可以看到上面四个结构体中,其实只有三个是存储数据用的,dictType 是用来放操作函数的,那么三个存放数据的结构体分别是干嘛的,这时候感觉需要一个图来说明比较好,稍等,我去画个图~

    这个图看着应该比较清楚这些都是用来干嘛的了,dict 是我们的主体结构,它有一个指向 dictType 的指针,这里面包含了字典的操作函数,然后是一个私有数据指针,接下来是一个 dictht 的数组,包含两个dictht,这个就是用来存数据的了,然后是 rehashidx 表示重哈希的状态,当是-1 的时候表示当前没有重哈希,iterators 表示正在遍历的迭代器的数量。
    首先说说为啥需要有两个 dictht,这是因为字典 dict 这个数据结构随着数据量的增减,会需要在中途做扩容或者缩容操作,如果只有一个的话,对它进行扩容缩容时会影响正常的访问和修改操作,或者说保证正常查询,修改的正确性会比较复杂,并且因为需要高效利用空间,不能一下子申请一个非常大的空间来存很少的数据。当 dict 中 dictht 中的数据量超过 size 的时候负载就超过了 1,就需要进行扩容,这里的其实跟 Java 中的 HashMap 比较类似,超过一定的负载之后进行扩容。这里为啥 size 会超过 1 呢,可能有部分不了解这类结构的同学会比较奇怪,其实就是上图中画的,在数据结构中对于散列的冲突有几类解决方法,比如转换成链表,二次散列,找下个空槽等,这里就使用了链表法,或者说拉链法。当一个新元素通过 hashFunction 得出的 key 跟 sizemask 取模之后的值相同了,那就将其放在原来的节点之前,变成链表挂在数组 dictht.table下面,放在原有节点前是考虑到可能会优先访问。
    忘了说明下 dictht 跟 dictEntry 的关系了,dictht 就是个哈希表,它里面是个dictEntry 的二维数组,而 dictEntry 是个包含了 key-value 结构之外还有一个 next 指针,因此可以将哈希冲突的以链表的形式保存下来。
    在重点说下重哈希,可能同样写 Java 的同学对这个比较有感觉,跟 HashMap 一样,会以 2 的 N 次方进行扩容,那么扩容的方法就会比较简单,每个键重哈希要不就在原来这个槽,要不就在原来的槽加原 dictht.size 的位置;然后是重头戏,具体是怎么做扩容呢,其实这里就把第二个 ht 用上了,其实这两个hashtable 的具体作用有点类似于 jvm 中的两个 survival 区,但是又不全一样,因为 redis 在扩容的时候是采用的渐进式地重哈希,什么叫渐进式的呢,就是它不是像 jvm 那种标记复制的模式直接将一个 eden 区和原来的 survival 区存活的对象复制到另一个 survival 区,而是在每一次添加,删除,查找或者更新操作时,都会额外的帮忙搬运一部分的原 dictht 中的数据,这里会根据 rehashidx 的值来判断,如果是-1 表示并没有在重哈希中,如果是 0 表示开始重哈希了,然后rehashidx 还会随着每次的帮忙搬运往上加,但全部被搬运完成后 rehashidx 又变回了-1,又可以扯到Java 中的 Concurrent HashMap, 他在扩容的时候也使用了类似的操作。

    +]]>
    + + Redis + 数据结构 + C + 源码 + Redis + + + redis + 数据结构 + 源码 + +
    + + redis 的 rdb 和 COW 介绍 + /2021/08/15/redis-%E7%9A%84-rdb-%E5%92%8C-COW-%E4%BB%8B%E7%BB%8D/ + redis 在使用 rdb 策略进行备份时,rdb 的意思是会在开启备份的时候将开启时间点的内存数据进行备份,并且可以设置时间,这样子就是这个策略其实还是不完全可靠的,如果是在这个间隔中宕机了,或者间隔过长,不过这个不在这次的要说的内容中,如果自己去写这个 rdb 的策略可能就有点类似于 mvcc 的 redolog,需要知道这个时间点之前的数据是怎么样的,防止后面更改的干扰,但是这样一方面需要有比较复杂的 mvcc 实现,另一方面是很占用存储空间,所以 redis 在这里面使用了 COW (Copy On Write) 技术,这个技术呢以前听过,也大致了解是怎么个意思,这次稍微具体地来看下,其实 redis 的 copy-on-write 就是来自于 linux 的 cow

    +

    Linux中的CopyOnWrite

    fork()之后,kernel把父进程中所有的内存页的权限都设为read-only,然后子进程的地址空间指向父进程。当父子进程都只读内存时,相安无事。当其中某个进程写内存时,CPU硬件检测到内存页是read-only的,于是触发页异常中断(page-fault),陷入kernel的一个中断例程。中断例程中,kernel就会把触发的异常的页复制一份,于是父子进程各自持有独立的一份。这个操作其实可以类比为写屏障,正常的读取是没问题的,当有写入时就会分裂。

    +

    CopyOnWrite的好处:

    1、减少分配和复制资源时带来的瞬时延迟;
    2、减少不必要的资源分配;
    CopyOnWrite的缺点:
    1、如果父子进程都需要进行大量的写操作,会产生大量的分页错误(页异常中断page-fault);

    +

    Redis中的CopyOnWrite

    Redis在持久化时,如果是采用BGSAVE命令或者BGREWRITEAOF的方式,那Redis会fork出一个子进程来读取数据,从而写到磁盘中。
    总体来看,Redis还是读操作比较多。如果子进程存在期间,发生了大量的写操作,那可能就会出现很多的分页错误(页异常中断page-fault),这样就得耗费不少性能在复制上。
    而在rehash阶段上,写操作是无法避免的。所以Redis在fork出子进程之后,将负载因子阈值提高,尽量减少写操作,避免不必要的内存写入操作,最大限度地节约内存。这里其实更巧妙了,在细节上去优化会产生大量页异常中断的情况。

    +]]>
    + + redis + + + redis + +
    + + redis数据结构介绍三-第三部分 整数集合 + /2020/01/10/redis%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%BB%8B%E7%BB%8D%E4%B8%89/ + redis中对于 set 其实有两种处理,对于元素均为整型,并且元素数目较少时,使用 intset 作为底层数据结构,否则使用 dict 作为底层数据结构,先看一下代码先

    +
    typedef struct intset {
    +    // 编码方式
    +    uint32_t encoding;
    +    // 集合包含的元素数量
    +    uint32_t length;
    +    // 保存元素的数组
    +    int8_t contents[];
    +} intset;
    +
    +/* Note that these encodings are ordered, so:
    + * INTSET_ENC_INT16 < INTSET_ENC_INT32 < INTSET_ENC_INT64. */
    +#define INTSET_ENC_INT16 (sizeof(int16_t))
    +#define INTSET_ENC_INT32 (sizeof(int32_t))
    +#define INTSET_ENC_INT64 (sizeof(int64_t))
    +

    一眼看,为啥整型还需要编码,然后 int8_t 怎么能存下大整形呢,带着这些疑问,我们一步步分析下去,这里的编码其实指的是这个整型集合里存的究竟是多大的整型,16 位,还是 32 位,还是 64 位,结构体下面的宏定义就是表示了 encoding 的可能取值,INTSET_ENC_INT16 表示每个元素用2个字节存储,INTSET_ENC_INT32 表示每个元素用4个字节存储,INTSET_ENC_INT64 表示每个元素用8个字节存储。因此,intset中存储的整数最多只能占用64bit。length 就是正常的表示集合中元素的数量。最奇怪的应该就是这个 contents 了,是个 int8_t 的数组,那放毛线数据啊,最小的都有 16 位,这里我在看代码和《redis 设计与实现》的时候也有点懵逼,后来查了下发现这是个比较取巧的用法,这里我用自己的理解表述一下,先看看 8,16,32,64 的关系,一眼看就知道都是 2 的 N 次,并且呈两倍关系,而且 8 位刚好一个字节,所以呢其实这里的contents 不是个常规意义上的 int8_t 类型的数组,而是个柔性数组。看下 wiki 的定义

    +
    +

    Flexible array members1 were introduced in the C99 standard of the C programming language (in particular, in section §6.7.2.1, item 16, page 103).2 It is a member of a struct, which is an array without a given dimension. It must be the last member of such a struct and it must be accompanied by at least one other member, as in the following example:

    +
    +
    struct vectord {
    +    size_t len;
    +    double arr[]; // the flexible array member must be last
    +};
    +

    在初始化这个 intset 的时候,这个contents数组是不占用空间的,后面的反正用到了申请,那么这里就有一个问题,给出了三种可能的 encoding 值,他们能随便换吗,显然不行,首先在 intset 中数据的存放是有序的,这个有部分原因是方便二分查找,然后存放数据其实随着数据的大小不同会有一个升级的过程,看下图

    新创建的intset只有一个header,总共8个字节。其中encoding = 2, length = 0, 类型都是uint32_t,各占 4 字节,添加15, 5两个元素之后,因为它们是比较小的整数,都能使用2个字节表示,所以encoding不变,值还是2,也就是默认的 INTSET_ENC_INT16,当添加32768的时候,它不再能用2个字节来表示了(2个字节能表达的数据范围是-215~215-1,而32768等于215,超出范围了),因此encoding必须升级到INTSET_ENC_INT32(值为4),即用4个字节表示一个元素。在添加每个元素的过程中,intset始终保持从小到大有序。与ziplist类似,intset也是按小端(little endian)模式存储的(参见维基百科词条Endianness)。比如,在上图中intset添加完所有数据之后,表示encoding字段的4个字节应该解释成0x00000004,而第4个数据应该解释成0x00008000 = 32768

    +]]>
    + + Redis + 数据结构 + C + 源码 + Redis + + + redis + 数据结构 + 源码 + +
    + + redis数据结构介绍二-第二部分 跳表 + /2020/01/04/redis%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%BB%8B%E7%BB%8D%E4%BA%8C/ + 跳表 skiplist

    跳表是个在我们日常的代码中不太常用到的数据结构,相对来讲就没有像数组,链表,字典,散列,树等结构那么熟悉,所以就从头开始分析下,首先是链表,跳表跟链表都有个表字(太硬扯了我🤦‍♀️),注意这是个有序链表

    如上图,在这个链表里如果我要找到 23,是不是我需要从3,5,9开始一直往后找直到找到 23,也就是说时间复杂度是 O(N),N 的一次幂复杂度,那么我们来看看第二个

    这个结构跟原先有点不一样,它给链表中偶数位的节点又加了一个指针把它们链接起来,这样子当我们要寻找 23 的时候就可以从原来的一个个往下找变成跳着找,先找到 5,然后是 10,接着是 19,然后是 28,这时候发现 28 比 23 大了,那我在退回到 19,然后从下一层原来的链表往前找,

    这里毛估估是不是前面的节点我就少找了一半,有那么点二分法的意思。
    前面的其实是跳表的引子,真正的跳表其实不是这样,因为上面的其实有个比较大的问题,就是插入一个元素后需要调整每个元素的指针,在 redis 中的跳表其实是做了个随机层数的优化,因为沿着前面的例子,其实当数据量很大的时候,是不是层数越多,其查询效率越高,但是随着层数变多,要保持这种严格的层数规则其实也会增大处理复杂度,所以 redis 插入每个元素的时候都是使用随机的方式,看一眼代码

    +
    /* ZSETs use a specialized version of Skiplists */
    +typedef struct zskiplistNode {
    +    sds ele;
    +    double score;
    +    struct zskiplistNode *backward;
    +    struct zskiplistLevel {
    +        struct zskiplistNode *forward;
    +        unsigned long span;
    +    } level[];
    +} zskiplistNode;
    +
    +typedef struct zskiplist {
    +    struct zskiplistNode *header, *tail;
    +    unsigned long length;
    +    int level;
    +} zskiplist;
    +
    +typedef struct zset {
    +    dict *dict;
    +    zskiplist *zsl;
    +} zset;
    +

    忘了说了,redis 是把 skiplist 跳表用在 zset 里,zset 是个有序的集合,可以看到 zskiplist 就是个跳表的结构,里面用 header 保存跳表的表头,tail 保存表尾,还有长度和最大层级,具体的跳表节点元素使用 zskiplistNode 表示,里面包含了 sds 类型的元素值,double 类型的分值,用来排序,一个 backward 后向指针和一个 zskiplistLevel 数组,每个 level 包含了一个前向指针,和一个 span,span 表示的是跳表前向指针的跨度,这里再补充一点,前面说了为了灵活这个跳表的新增修改,redis 使用了随机层高的方式插入新节点,但是如果所有节点都随机到很高的层级或者所有都很低的话,跳表的效率优势就会减小,所以 redis 使用了个小技巧,贴下代码

    +
    #define ZSKIPLIST_P 0.25      /* Skiplist P = 1/4 */
    +int zslRandomLevel(void) {
    +    int level = 1;
    +    while ((random()&0xFFFF) < (ZSKIPLIST_P * 0xFFFF))
    +        level += 1;
    +    return (level<ZSKIPLIST_MAXLEVEL) ? level : ZSKIPLIST_MAXLEVEL;
    +}
    +

    当随机值跟0xFFFF进行与操作小于ZSKIPLIST_P * 0xFFFF时才会增大 level 的值,因此保持了一个相对递减的概率
    可以简单分析下,当 random() 的值小于 0xFFFF 的 1/4,才会 level + 1,就意味着当有 1 - 1/4也就是3/4的概率是直接跳出,所以一层的概率是3/4,也就是 1-P,二层的概率是 P*(1-P),三层的概率是 P² * (1-P) 依次递推。

    +]]>
    + + Redis + 数据结构 + C + 源码 + Redis + + + redis + 数据结构 + 源码 + +
    + + redis数据结构介绍五-第五部分 对象 + /2020/01/20/redis%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%BB%8B%E7%BB%8D%E4%BA%94/ + 前面说了这么些数据结构,其实大家对于 redis 最初的印象应该就是个 key-value 的缓存,类似于 memcache,redis 其实也是个 key-value,key 还是一样的字符串,或者说就是用 redis 自己的动态字符串实现,但是 value 其实就是前面说的那些数据结构,差不多快说完了,还有个 quicklist 后面还有一篇,这里先介绍下 redis 对于这些不同类型的 value 是怎么实现的,首先看下 redisObject 的源码头文件

    +
    /* The actual Redis Object */
    +#define OBJ_STRING 0    /* String object. */
    +#define OBJ_LIST 1      /* List object. */
    +#define OBJ_SET 2       /* Set object. */
    +#define OBJ_ZSET 3      /* Sorted set object. */
    +#define OBJ_HASH 4      /* Hash object. */
    +/*
    + * Objects encoding. Some kind of objects like Strings and Hashes can be
    + * internally represented in multiple ways. The 'encoding' field of the object
    + * is set to one of this fields for this object. */
    +#define OBJ_ENCODING_RAW 0     /* Raw representation */
    +#define OBJ_ENCODING_INT 1     /* Encoded as integer */
    +#define OBJ_ENCODING_HT 2      /* Encoded as hash table */
    +#define OBJ_ENCODING_ZIPMAP 3  /* Encoded as zipmap */
    +#define OBJ_ENCODING_LINKEDLIST 4 /* No longer used: old list encoding. */
    +#define OBJ_ENCODING_ZIPLIST 5 /* Encoded as ziplist */
    +#define OBJ_ENCODING_INTSET 6  /* Encoded as intset */
    +#define OBJ_ENCODING_SKIPLIST 7  /* Encoded as skiplist */
    +#define OBJ_ENCODING_EMBSTR 8  /* Embedded sds string encoding */
    +#define OBJ_ENCODING_QUICKLIST 9 /* Encoded as linked list of ziplists */
    +#define OBJ_ENCODING_STREAM 10 /* Encoded as a radix tree of listpacks */
    +
    +#define LRU_BITS 24
    +#define LRU_CLOCK_MAX ((1<<LRU_BITS)-1) /* Max value of obj->lru */
    +#define LRU_CLOCK_RESOLUTION 1000 /* LRU clock resolution in ms */
    +
    +#define OBJ_SHARED_REFCOUNT INT_MAX
    +typedef struct redisObject {
    +    unsigned type:4;
    +    unsigned encoding:4;
    +    unsigned lru:LRU_BITS; /* LRU time (relative to global lru_clock) or
    +                            * LFU data (least significant 8 bits frequency
    +                            * and most significant 16 bits access time). */
    +    int refcount;
    +    void *ptr;
    +} robj;
    +

    主体结构就是这个 redisObject,

    +
      +
    • type: 字段表示对象的类型,它对应的就是 redis 的对外暴露的,或者说用户可以使用的五种类型,OBJ_STRING, OBJ_LIST, OBJ_SET, OBJ_ZSET, OBJ_HASH
    • +
    • encoding: 字段表示这个对象在 redis 内部的编码方式,由OBJ_ENCODING_开头的 11 种
    • +
    • lru: 做LRU替换算法用,占24个bit
    • +
    • refcount: 引用计数。它允许robj对象在某些情况下被共享。
    • +
    • ptr: 指向底层实现数据结构的指针
      当 type 是 OBJ_STRING 时,表示类型是个 string,它的编码方式 encoding 可能有 OBJ_ENCODING_RAW,OBJ_ENCODING_INT,OBJ_ENCODING_EMBSTR 三种
      当 type 是 OBJ_LIST 时,表示类型是 list,它的编码方式 encoding 是 OBJ_ENCODING_QUICKLIST,对于早一些的版本,2.2这种可能还会使用 OBJ_ENCODING_ZIPLIST,OBJ_ENCODING_LINKEDLIST
      当 type 是 OBJ_SET 时,是个集合,但是得看具体元素的类型,有可能使用整数集合,OBJ_ENCODING_INTSET, 如果元素不全是整型或者数量超过一定限制,那么编码就是 OBJ_ENCODING_HT hash table 了
      当 type 是 OBJ_ZSET 时,是个有序集合,它底层有可能使用的是 OBJ_ENCODING_ZIPLIST 或者 OBJ_ENCODING_SKIPLIST
      当 type 是 OBJ_HASH 时,一开始也是 OBJ_ENCODING_ZIPLIST,然后当数据量大于 hash_max_ziplist_entries 时会转成 OBJ_ENCODING_HT
    • +
    +]]>
    + + Redis + 数据结构 + C + 源码 + Redis - php - mq - im + redis + 数据结构 + 源码
    - redis数据结构介绍-第一部分 SDS,链表,字典 - /2019/12/26/redis%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%BB%8B%E7%BB%8D/ - redis是现在服务端很常用的缓存中间件,其实原来还有memcache之类的竞品,但是现在貌似 redis 快一统江湖,这里当然不是在吹,只是个人角度的一个感觉,不权威只是主观感觉。
    redis 主要有五种数据结构,StringsListsSetsHashesSorted Sets,这五种数据结构先简单介绍下,Strings类型的其实就是我们最常用的 key-value,实际开发中也会用的最多;Lists是列表,这个有些会用来做队列,因为 redis 目前常用的版本支持丰富的列表操作;还有是Sets集合,这个主要的特点就是集合中元素不重复,可以用在有这类需求的场景里;Hashes是叫散列,类似于 Python 中的字典结构;还有就是Sorted Sets这个是个有序集合;一眼看这些其实没啥特别的,除了最后这个有序集合,不过去了解背后的实现方式还是比较有意思的。

    -

    SDS 简单动态字符串

    先从Strings开始说,了解过 C 语言的应该知道,C 语言中的字符串其实是个 char[] 字符数组,redis 也不例外,只是最开始的版本就对这个做了一丢丢的优化,而正是这一丢丢的优化,让这个 redis 的使用效率提升了数倍

    -
    struct sdshdr {
    -    // 字符串长度
    -    int len;
    -    // 字符串空余字符数
    -    int free;
    -    // 字符串内容
    -    char buf[];
    -};
    -

    这里引用了 redis 在 github 上最早的 2.2 版本的代码,代码路径是https://github.com/antirez/redis/blob/2.2/src/sds.h,可以看到这个结构体里只有仨元素,两个 int 型和一个 char 型数组,两个 int 型其实就是我说的优化,因为 C 语言本身的字符串数组,有两个问题,一个是要知道它实际已被占用的长度,需要去遍历这个数组,第二个就是比较容易踩坑的是遍历的时候要注意它有个以\0作为结尾的特点;通过上面的两个 int 型参数,一个是知道字符串目前的长度,一个是知道字符串还剩余多少位空间,这样子坐着两个操作从 O(N)简化到了O(1)了,还有第二个 free 还有个比较重要的作用就是能防止 C 字符串的溢出问题,在存储之前可以先判断 free 长度,如果长度不够就先扩容了,先介绍到这,这个系列可以写蛮多的,慢慢介绍吧

    -

    链表

    链表是比较常见的数据结构了,但是因为 redis 是用 C 写的,所以在不依赖第三方库的情况下只能自己写一个了,redis 的链表是个有头的链表,而且是无环的,具体的结构我也找了 github 上最早版本的代码

    -
    typedef struct listNode {
    -    // 前置节点
    -    struct listNode *prev;
    -    // 后置节点
    -    struct listNode *next;
    -    // 值
    -    void *value;
    -} listNode;
    +    redis数据结构介绍六 快表
    +    /2020/01/22/redis%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%BB%8B%E7%BB%8D%E5%85%AD/
    +    这应该是 redis 系列的最后一篇了,讲下快表,其实最前面讲的链表在早先的 redis 版本中也作为 list 的数据结构使用过,但是单纯的链表的缺陷之前也说了,插入便利,但是空间利用率低,并且不能进行二分查找等,检索效率低,ziplist 压缩表的产生也是同理,希望获得更好的性能,包括存储空间和访问性能等,原来我也不懂这个快表要怎么快,然后明白了一个道理,其实并没有什么银弹,只是大牛们会在适合的时候使用最适合的数据结构来实现性能的最大化,这里面有一招就是不同数据结构的组合调整,比如 Java 中的 HashMap,在链表节点数大于 8 时会转变成红黑树,以此提高访问效率,不费话了,回到快表,quicklist,这个数据结构主要使用在 list 类型中,如果我说其实这个 quicklist 就是个链表,可能大家不太会相信,但是事实上的确可以认为 quicklist 是个双向链表,看下代码

    +
    /* quicklistNode is a 32 byte struct describing a ziplist for a quicklist.
    + * We use bit fields keep the quicklistNode at 32 bytes.
    + * count: 16 bits, max 65536 (max zl bytes is 65k, so max count actually < 32k).
    + * encoding: 2 bits, RAW=1, LZF=2.
    + * container: 2 bits, NONE=1, ZIPLIST=2.
    + * recompress: 1 bit, bool, true if node is temporarry decompressed for usage.
    + * attempted_compress: 1 bit, boolean, used for verifying during testing.
    + * extra: 10 bits, free for future use; pads out the remainder of 32 bits */
    +typedef struct quicklistNode {
    +    struct quicklistNode *prev;
    +    struct quicklistNode *next;
    +    unsigned char *zl;
    +    unsigned int sz;             /* ziplist size in bytes */
    +    unsigned int count : 16;     /* count of items in ziplist */
    +    unsigned int encoding : 2;   /* RAW==1 or LZF==2 */
    +    unsigned int container : 2;  /* NONE==1 or ZIPLIST==2 */
    +    unsigned int recompress : 1; /* was this node previous compressed? */
    +    unsigned int attempted_compress : 1; /* node can't compress; too small */
    +    unsigned int extra : 10; /* more bits to steal for future usage */
    +} quicklistNode;
     
    -typedef struct list {
    -    // 链表表头
    -    listNode *head;
    -    // 当前节点,也可以说是最后节点
    -    listNode *tail;
    -    // 节点复制函数
    -    void *(*dup)(void *ptr);
    -    // 节点值释放函数
    -    void (*free)(void *ptr);
    -    // 节点值比较函数
    -    int (*match)(void *ptr, void *key);
    -    // 链表包含的节点数量
    -    unsigned int len;
    -} list;
    -

    代码地址是这个https://github.com/antirez/redis/blob/2.2/src/adlist.h
    可以看下节点是由listNode承载的,包括值和一个指向前节点跟一个指向后一节点的两个指针,然后值是 void 指针类型,所以可以承载不同类型的值
    然后是 list结构用来承载一个链表,包含了表头,和表尾,复制函数,释放函数和比较函数,还有链表长度,因为包含了前两个节点,找到表尾节点跟表头都是 O(1)的时间复杂度,还有节点数量,其实这个跟 SDS 是同一个做法,就是空间换时间,这也是写代码里比较常见的做法,以此让一些高频的操作提速。

    -

    字典

    字典也是个常用的数据结构,其实只是叫法不同,数据结构中叫 hash 散列,Java 中叫 Map,PHP 中是数组 array,Python 中也叫字典 dict,因为纯 C 语言本身不带这些数据结构,所以这也是个痛并快乐着的过程,享受 C 语言的高性能的同时也要接受它只提供了语言的基本功能的现实,各种轮子都需要自己造,redis 同样实现了自己的字典
    下面来看看代码

    -
    typedef struct dictEntry {
    -    void *key;
    -    void *val;
    -    struct dictEntry *next;
    -} dictEntry;
    +/* quicklistLZF is a 4+N byte struct holding 'sz' followed by 'compressed'.
    + * 'sz' is byte length of 'compressed' field.
    + * 'compressed' is LZF data with total (compressed) length 'sz'
    + * NOTE: uncompressed length is stored in quicklistNode->sz.
    + * When quicklistNode->zl is compressed, node->zl points to a quicklistLZF */
    +typedef struct quicklistLZF {
    +    unsigned int sz; /* LZF size in bytes*/
    +    char compressed[];
    +} quicklistLZF;
     
    -typedef struct dictType {
    -    unsigned int (*hashFunction)(const void *key);
    -    void *(*keyDup)(void *privdata, const void *key);
    -    void *(*valDup)(void *privdata, const void *obj);
    -    int (*keyCompare)(void *privdata, const void *key1, const void *key2);
    -    void (*keyDestructor)(void *privdata, void *key);
    -    void (*valDestructor)(void *privdata, void *obj);
    -} dictType;
    +/* quicklist is a 40 byte struct (on 64-bit systems) describing a quicklist.
    + * 'count' is the number of total entries.
    + * 'len' is the number of quicklist nodes.
    + * 'compress' is: -1 if compression disabled, otherwise it's the number
    + *                of quicklistNodes to leave uncompressed at ends of quicklist.
    + * 'fill' is the user-requested (or default) fill factor. */
    +typedef struct quicklist {
    +    quicklistNode *head;
    +    quicklistNode *tail;
    +    unsigned long count;        /* total count of all entries in all ziplists */
    +    unsigned long len;          /* number of quicklistNodes */
    +    int fill : 16;              /* fill factor for individual nodes */
    +    unsigned int compress : 16; /* depth of end nodes not to compress;0=off */
    +} quicklist;
    +

    粗略看下,quicklist 里有 head,tail, quicklistNode里有 prev,next 指针,是不是有链表的基本轮廓了,那么为啥这玩意要称为快表呢,快在哪,关键就在这个unsigned char *zl;zl 是不是前面又看到过,就是 ziplist ,这是什么鬼,链表里用压缩表,这不套娃么,先别急,回顾下前面说的 ziplist,ziplist 有哪些特点,内存利用率高,可以从表头快速定位到尾节点,节点可以从后往前找,但是有个缺点,就是从中间插入的效率比较低,需要整体往后移,这个其实是普通数组的优化版,但还是有数组的一些劣势,所以要真的快,是不是可以将链表跟数组真的结合起来。

    +

    ziplist

    这里有两个 redis 的配置参数,list-max-ziplist-sizelist-compress-depth,先来说第一个,既然快表是将链表跟压缩表数组结合起来使用,那么具体怎么用呢,比如我有一个 10 个元素的 list,那具体怎么放,每个 quicklistNode 里放多大的 ziplist,假如每个快表节点的 ziplist 只放一个元素,那么其实这就退化成了一个链表,如果 10 个元素放在一个 quicklistNode 的 ziplist 里,那就退化成了一个 ziplist,所以有了这个 list-max-ziplist-size,而且它还比较牛,能取正负值,当是正值时,对应的就是每个 quicklistNode 的 ziplist 中的元素个数,比如配置了 list-max-ziplist-size = 5,那么我刚才的 10 个元素的 list 就是一个两个 quicklistNode 组成的快表,每个 quicklistNode 中的 ziplist 包含了五个元素,当 list-max-ziplist-size取负值的时候,它限制了 ziplist 的字节数

    +
    size_t offset = (-fill) - 1;
    +if (offset < (sizeof(optimization_level) / sizeof(*optimization_level))) {
    +    if (sz <= optimization_level[offset]) {
    +        return 1;
    +    } else {
    +        return 0;
    +    }
    +} else {
    +    return 0;
    +}
    +
    +/* Optimization levels for size-based filling */
    +static const size_t optimization_level[] = {4096, 8192, 16384, 32768, 65536};
    +
    +/* Create a new quicklist.
    + * Free with quicklistRelease(). */
    +quicklist *quicklistCreate(void) {
    +    struct quicklist *quicklist;
    +
    +    quicklist = zmalloc(sizeof(*quicklist));
    +    quicklist->head = quicklist->tail = NULL;
    +    quicklist->len = 0;
    +    quicklist->count = 0;
    +    quicklist->compress = 0;
    +    quicklist->fill = -2;
    +    return quicklist;
    +}
    +

    这个 fill 就是传进来的 list-max-ziplist-size, 具体对应的就是

    +
      +
    • -5: 每个quicklist节点上的ziplist大小不能超过64 Kb。(注:1kb => 1024 bytes)
    • +
    • -4: 每个quicklist节点上的ziplist大小不能超过32 Kb。
    • +
    • -3: 每个quicklist节点上的ziplist大小不能超过16 Kb。
    • +
    • -2: 每个quicklist节点上的ziplist大小不能超过8 Kb。(-2是Redis给出的默认值)也就是上面的 quicklist->fill = -2;
    • +
    • -1: 每个quicklist节点上的ziplist大小不能超过4 Kb。
    • +
    +

    压缩

    list-compress-depth这个参数呢是用来配置压缩的,等等压缩是为啥,不是里面已经是压缩表了么,大牛们就是为了性能殚精竭虑,这里考虑到的是一个场景,一般状况下,list 都是两端的访问频率比较高,那么是不是可以对中间的数据进行压缩,那么这个参数就是用来表示

    +
    /* depth of end nodes not to compress;0=off */
    +
      +
    • 0,代表不压缩,默认值
    • +
    • 1,两端各一个节点不压缩
    • +
    • 2,两端各两个节点不压缩
    • +
    • … 依次类推
      压缩后的 ziplist 就会变成 quicklistLZF,然后替换 zl 指针,这里使用的是 LZF 压缩算法,压缩后的 quicklistLZF 中的 compressed 也是个柔性数组,压缩后的 ziplist 整个就放进这个柔性数组
    • +
    +

    插入过程

    简单说下插入元素的过程

    +
    /* Wrapper to allow argument-based switching between HEAD/TAIL pop */
    +void quicklistPush(quicklist *quicklist, void *value, const size_t sz,
    +                   int where) {
    +    if (where == QUICKLIST_HEAD) {
    +        quicklistPushHead(quicklist, value, sz);
    +    } else if (where == QUICKLIST_TAIL) {
    +        quicklistPushTail(quicklist, value, sz);
    +    }
    +}
    +
    +/* Add new entry to head node of quicklist.
    + *
    + * Returns 0 if used existing head.
    + * Returns 1 if new head created. */
    +int quicklistPushHead(quicklist *quicklist, void *value, size_t sz) {
    +    quicklistNode *orig_head = quicklist->head;
    +    if (likely(
    +            _quicklistNodeAllowInsert(quicklist->head, quicklist->fill, sz))) {
    +        quicklist->head->zl =
    +            ziplistPush(quicklist->head->zl, value, sz, ZIPLIST_HEAD);
    +        quicklistNodeUpdateSz(quicklist->head);
    +    } else {
    +        quicklistNode *node = quicklistCreateNode();
    +        node->zl = ziplistPush(ziplistNew(), value, sz, ZIPLIST_HEAD);
    +
    +        quicklistNodeUpdateSz(node);
    +        _quicklistInsertNodeBefore(quicklist, quicklist->head, node);
    +    }
    +    quicklist->count++;
    +    quicklist->head->count++;
    +    return (orig_head != quicklist->head);
    +}
    +
    +/* Add new entry to tail node of quicklist.
    + *
    + * Returns 0 if used existing tail.
    + * Returns 1 if new tail created. */
    +int quicklistPushTail(quicklist *quicklist, void *value, size_t sz) {
    +    quicklistNode *orig_tail = quicklist->tail;
    +    if (likely(
    +            _quicklistNodeAllowInsert(quicklist->tail, quicklist->fill, sz))) {
    +        quicklist->tail->zl =
    +            ziplistPush(quicklist->tail->zl, value, sz, ZIPLIST_TAIL);
    +        quicklistNodeUpdateSz(quicklist->tail);
    +    } else {
    +        quicklistNode *node = quicklistCreateNode();
    +        node->zl = ziplistPush(ziplistNew(), value, sz, ZIPLIST_TAIL);
    +
    +        quicklistNodeUpdateSz(node);
    +        _quicklistInsertNodeAfter(quicklist, quicklist->tail, node);
    +    }
    +    quicklist->count++;
    +    quicklist->tail->count++;
    +    return (orig_tail != quicklist->tail);
    +}
    +
    +/* Wrappers for node inserting around existing node. */
    +REDIS_STATIC void _quicklistInsertNodeBefore(quicklist *quicklist,
    +                                             quicklistNode *old_node,
    +                                             quicklistNode *new_node) {
    +    __quicklistInsertNode(quicklist, old_node, new_node, 0);
    +}
    +
    +REDIS_STATIC void _quicklistInsertNodeAfter(quicklist *quicklist,
    +                                            quicklistNode *old_node,
    +                                            quicklistNode *new_node) {
    +    __quicklistInsertNode(quicklist, old_node, new_node, 1);
    +}
    +
    +/* Insert 'new_node' after 'old_node' if 'after' is 1.
    + * Insert 'new_node' before 'old_node' if 'after' is 0.
    + * Note: 'new_node' is *always* uncompressed, so if we assign it to
    + *       head or tail, we do not need to uncompress it. */
    +REDIS_STATIC void __quicklistInsertNode(quicklist *quicklist,
    +                                        quicklistNode *old_node,
    +                                        quicklistNode *new_node, int after) {
    +    if (after) {
    +        new_node->prev = old_node;
    +        if (old_node) {
    +            new_node->next = old_node->next;
    +            if (old_node->next)
    +                old_node->next->prev = new_node;
    +            old_node->next = new_node;
    +        }
    +        if (quicklist->tail == old_node)
    +            quicklist->tail = new_node;
    +    } else {
    +        new_node->next = old_node;
    +        if (old_node) {
    +            new_node->prev = old_node->prev;
    +            if (old_node->prev)
    +                old_node->prev->next = new_node;
    +            old_node->prev = new_node;
    +        }
    +        if (quicklist->head == old_node)
    +            quicklist->head = new_node;
    +    }
    +    /* If this insert creates the only element so far, initialize head/tail. */
    +    if (quicklist->len == 0) {
    +        quicklist->head = quicklist->tail = new_node;
    +    }
     
    -/* This is our hash table structure. Every dictionary has two of this as we
    - * implement incremental rehashing, for the old to the new table. */
    -typedef struct dictht {
    -    dictEntry **table;
    -    unsigned long size;
    -    unsigned long sizemask;
    -    unsigned long used;
    -} dictht;
    +    if (old_node)
    +        quicklistCompress(quicklist, old_node);
     
    -typedef struct dict {
    -    dictType *type;
    -    void *privdata;
    -    dictht ht[2];
    -    int rehashidx; /* rehashing not in progress if rehashidx == -1 */
    -    int iterators; /* number of iterators currently running */
    -} dict;
    -

    看了下这个 2.2 版本的代码跟最新版的其实也差的不是很多,所以还是照旧用老代码,可以看到上面四个结构体中,其实只有三个是存储数据用的,dictType 是用来放操作函数的,那么三个存放数据的结构体分别是干嘛的,这时候感觉需要一个图来说明比较好,稍等,我去画个图~

    这个图看着应该比较清楚这些都是用来干嘛的了,dict 是我们的主体结构,它有一个指向 dictType 的指针,这里面包含了字典的操作函数,然后是一个私有数据指针,接下来是一个 dictht 的数组,包含两个dictht,这个就是用来存数据的了,然后是 rehashidx 表示重哈希的状态,当是-1 的时候表示当前没有重哈希,iterators 表示正在遍历的迭代器的数量。
    首先说说为啥需要有两个 dictht,这是因为字典 dict 这个数据结构随着数据量的增减,会需要在中途做扩容或者缩容操作,如果只有一个的话,对它进行扩容缩容时会影响正常的访问和修改操作,或者说保证正常查询,修改的正确性会比较复杂,并且因为需要高效利用空间,不能一下子申请一个非常大的空间来存很少的数据。当 dict 中 dictht 中的数据量超过 size 的时候负载就超过了 1,就需要进行扩容,这里的其实跟 Java 中的 HashMap 比较类似,超过一定的负载之后进行扩容。这里为啥 size 会超过 1 呢,可能有部分不了解这类结构的同学会比较奇怪,其实就是上图中画的,在数据结构中对于散列的冲突有几类解决方法,比如转换成链表,二次散列,找下个空槽等,这里就使用了链表法,或者说拉链法。当一个新元素通过 hashFunction 得出的 key 跟 sizemask 取模之后的值相同了,那就将其放在原来的节点之前,变成链表挂在数组 dictht.table下面,放在原有节点前是考虑到可能会优先访问。
    忘了说明下 dictht 跟 dictEntry 的关系了,dictht 就是个哈希表,它里面是个dictEntry 的二维数组,而 dictEntry 是个包含了 key-value 结构之外还有一个 next 指针,因此可以将哈希冲突的以链表的形式保存下来。
    在重点说下重哈希,可能同样写 Java 的同学对这个比较有感觉,跟 HashMap 一样,会以 2 的 N 次方进行扩容,那么扩容的方法就会比较简单,每个键重哈希要不就在原来这个槽,要不就在原来的槽加原 dictht.size 的位置;然后是重头戏,具体是怎么做扩容呢,其实这里就把第二个 ht 用上了,其实这两个hashtable 的具体作用有点类似于 jvm 中的两个 survival 区,但是又不全一样,因为 redis 在扩容的时候是采用的渐进式地重哈希,什么叫渐进式的呢,就是它不是像 jvm 那种标记复制的模式直接将一个 eden 区和原来的 survival 区存活的对象复制到另一个 survival 区,而是在每一次添加,删除,查找或者更新操作时,都会额外的帮忙搬运一部分的原 dictht 中的数据,这里会根据 rehashidx 的值来判断,如果是-1 表示并没有在重哈希中,如果是 0 表示开始重哈希了,然后rehashidx 还会随着每次的帮忙搬运往上加,但全部被搬运完成后 rehashidx 又变回了-1,又可以扯到Java 中的 Concurrent HashMap, 他在扩容的时候也使用了类似的操作。

    + quicklist->len++; +}
    +

    前面第一步先根据插入的是头还是尾选择不同的 push 函数,quicklistPushHead 或者 quicklistPushTail,举例分析下从头插入的 quicklistPushHead,先判断当前的 quicklistNode 节点还能不能允许再往 ziplist 里添加元素,如果可以就添加,如果不允许就新建一个 quicklistNode,然后调用 _quicklistInsertNodeBefore 将节点插进去,具体插入quicklist节点的操作类似链表的插入。

    ]]>
    Redis @@ -10302,570 +10361,558 @@ typedef struct dict {
    - redis 的 rdb 和 COW 介绍 - /2021/08/15/redis-%E7%9A%84-rdb-%E5%92%8C-COW-%E4%BB%8B%E7%BB%8D/ - redis 在使用 rdb 策略进行备份时,rdb 的意思是会在开启备份的时候将开启时间点的内存数据进行备份,并且可以设置时间,这样子就是这个策略其实还是不完全可靠的,如果是在这个间隔中宕机了,或者间隔过长,不过这个不在这次的要说的内容中,如果自己去写这个 rdb 的策略可能就有点类似于 mvcc 的 redolog,需要知道这个时间点之前的数据是怎么样的,防止后面更改的干扰,但是这样一方面需要有比较复杂的 mvcc 实现,另一方面是很占用存储空间,所以 redis 在这里面使用了 COW (Copy On Write) 技术,这个技术呢以前听过,也大致了解是怎么个意思,这次稍微具体地来看下,其实 redis 的 copy-on-write 就是来自于 linux 的 cow

    -

    Linux中的CopyOnWrite

    fork()之后,kernel把父进程中所有的内存页的权限都设为read-only,然后子进程的地址空间指向父进程。当父子进程都只读内存时,相安无事。当其中某个进程写内存时,CPU硬件检测到内存页是read-only的,于是触发页异常中断(page-fault),陷入kernel的一个中断例程。中断例程中,kernel就会把触发的异常的页复制一份,于是父子进程各自持有独立的一份。这个操作其实可以类比为写屏障,正常的读取是没问题的,当有写入时就会分裂。

    -

    CopyOnWrite的好处:

    1、减少分配和复制资源时带来的瞬时延迟;
    2、减少不必要的资源分配;
    CopyOnWrite的缺点:
    1、如果父子进程都需要进行大量的写操作,会产生大量的分页错误(页异常中断page-fault);

    -

    Redis中的CopyOnWrite

    Redis在持久化时,如果是采用BGSAVE命令或者BGREWRITEAOF的方式,那Redis会fork出一个子进程来读取数据,从而写到磁盘中。
    总体来看,Redis还是读操作比较多。如果子进程存在期间,发生了大量的写操作,那可能就会出现很多的分页错误(页异常中断page-fault),这样就得耗费不少性能在复制上。
    而在rehash阶段上,写操作是无法避免的。所以Redis在fork出子进程之后,将负载因子阈值提高,尽量减少写操作,避免不必要的内存写入操作,最大限度地节约内存。这里其实更巧妙了,在细节上去优化会产生大量页异常中断的情况。

    + redis数据结构介绍四-第四部分 压缩表 + /2020/01/19/redis%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%BB%8B%E7%BB%8D%E5%9B%9B/ + 在 redis 中还有一类表型数据结构叫压缩表,ziplist,它的目的是替代链表,链表是个很容易理解的数据结构,双向链表有前后指针,有带头结点的有的不带,但是链表有个比较大的问题是相对于普通的数组,它的内存不连续,碎片化的存储,内存利用效率不高,而且指针寻址相对于直接使用偏移量的话,也有一定的效率劣势,当然这不是主要的原因,ziplist 设计的主要目的是让链表的内存使用更高效

    +
    +

    The ziplist is a specially encoded dually linked list that is designed to be very memory efficient.
    这是摘自 redis 源码中ziplist.c 文件的注释,也说明了原因,它的大概结构是这样子

    +
    +
    <zlbytes> <zltail> <zllen> <entry> <entry> ... <entry> <zlend>
    +

    其中
    <zlbytes>表示 ziplist 占用的字节总数,类型是uint32_t,32 位的无符号整型,当然表示的字节数也包含自己本身占用的 4 个
    <zltail> 类型也是是uint32_t,表示ziplist表中最后一项(entry)在ziplist中的偏移字节数。<zltail>的存在,使得我们可以很方便地找到最后一项(不用遍历整个ziplist),从而可以在ziplist尾端快速地执行push或pop操作。
    <uint16_t zllen> 表示ziplist 中的数据项个数,因为是 16 位,所以当数量超过所能表示的最大的数量,它的 16 位全会置为 1,但是真实的数量需要遍历整个 ziplist 才能知道
    <entry>是具体的数据项,后面解释
    <zlend> ziplist 的最后一个字节,固定是255。
    再看一下<entry>中的具体结构,

    +
    <prevlen> <encoding> <entry-data>
    +

    首先这个<prevlen>有两种情况,一种是前面的元素的长度,如果是小于等于 253的时候就用一个uint8_t 来表示前一元素的长度,如果大于的话他将占用五个字节,第一个字节是 254,即表示这个字节已经表示不下了,需要后面的四个字节帮忙表示
    <encoding>这个就比较复杂,把源码的注释放下面先看下

    +
    * |00pppppp| - 1 byte
    +*      String value with length less than or equal to 63 bytes (6 bits).
    +*      "pppppp" represents the unsigned 6 bit length.
    +* |01pppppp|qqqqqqqq| - 2 bytes
    +*      String value with length less than or equal to 16383 bytes (14 bits).
    +*      IMPORTANT: The 14 bit number is stored in big endian.
    +* |10000000|qqqqqqqq|rrrrrrrr|ssssssss|tttttttt| - 5 bytes
    +*      String value with length greater than or equal to 16384 bytes.
    +*      Only the 4 bytes following the first byte represents the length
    +*      up to 32^2-1. The 6 lower bits of the first byte are not used and
    +*      are set to zero.
    +*      IMPORTANT: The 32 bit number is stored in big endian.
    +* |11000000| - 3 bytes
    +*      Integer encoded as int16_t (2 bytes).
    +* |11010000| - 5 bytes
    +*      Integer encoded as int32_t (4 bytes).
    +* |11100000| - 9 bytes
    +*      Integer encoded as int64_t (8 bytes).
    +* |11110000| - 4 bytes
    +*      Integer encoded as 24 bit signed (3 bytes).
    +* |11111110| - 2 bytes
    +*      Integer encoded as 8 bit signed (1 byte).
    +* |1111xxxx| - (with xxxx between 0000 and 1101) immediate 4 bit integer.
    +*      Unsigned integer from 0 to 12. The encoded value is actually from
    +*      1 to 13 because 0000 and 1111 can not be used, so 1 should be
    +*      subtracted from the encoded 4 bit value to obtain the right value.
    +* |11111111| - End of ziplist special entry.
    +

    首先如果 encoding 的前两位是 00 的话代表这个元素是个 6 位的字符串,即直接将数据保存在 encoding 中,不消耗额外的<entry-data>,如果前两位是 01 的话表示是个 14 位的字符串,如果是 10 的话表示encoding 块之后的四个字节是存放字符串类型的数据,encoding 的剩余 6 位置 0。
    如果 encoding 的前两位是 11 的话表示这是个整型,具体的如果后两位是00的话,表示后面是个2字节的 int16_t 类型,如果是01的话,后面是个4字节的int32_t,如果是10的话后面是8字节的int64_t,如果是 11 的话后面是 3 字节的有符号整型,这些都要最后 4 位都是 0 的情况噢
    剩下当是11111110时,则表示是一个1 字节的有符号数,如果是 1111xxxx,其中xxxx在0000 到 1101 表示实际的 1 到 13,为啥呢,因为 0000 前面已经用过了,而 1110 跟 1111 也都有用了。
    看个具体的例子(上下有点对不齐,将就看)

    +
    [0f 00 00 00] [0c 00 00 00] [02 00] [00 f3] [02 f6] [ff]
    +|**zlbytes***|  |***zltail***|  |*zllen*|  |entry1 entry2|  |zlend|
    +

    第一部分代表整个 ziplist 有 15 个字节,zlbytes 自己占了 4 个 zltail 表示最后一个元素的偏移量,第 13 个字节起,zllen 表示有 2 个元素,第一个元素是00f3,00表示前一个元素长度是 0,本来前面就没元素(不过不知道这个能不能优化这一字节),然后是 f3,换成二进制就是11110011,对照上面的注释,是落在|1111xxxx|这个类型里,注意这个其实是用 0001 到 1101 也就是 1到 13 来表示 0到 12,所以 f3 应该就是 2,第一个元素是 2,第二个元素呢,02 代表前一个元素也就是刚才说的这个,占用 2 字节,f6 展开也是刚才的类型,实际是 5,ff 表示 ziplist 的结尾,所以这个 ziplist 里面是两个元素,2 跟 5

    +]]>
    + + Redis + 数据结构 + C + 源码 + Redis + + + redis + 数据结构 + 源码 + +
    + + redis淘汰策略复习 + /2021/08/01/redis%E6%B7%98%E6%B1%B0%E7%AD%96%E7%95%A5%E5%A4%8D%E4%B9%A0/ + 前面复习了 redis 的过期策略,这里再复习下淘汰策略,淘汰跟过期的区别有时候会被混淆了,过期主要针对那些设置了过期时间的 key,应该说是一种逻辑策略,是主动的还是被动的加定时的,两种有各自的取舍,而淘汰也可以看成是一种保持系统稳定的策略,因为如果内存满了,不采取任何策略处理,那大概率会导致系统故障,之前其实主要从源码角度分析过redis 的 LRU 和 LFU,但这个是偏底层的实现,抠得比较细,那么具体的系统层面的配置是有哪些策略,来看下 redis labs 的介绍

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    PolicyDescription
    noeviction 不逐出Returns an error if the memory limit has been reached when trying to insert more data,插入更多数据时,如果内存达到上限了,返回错误
    allkeys-lru 所有的 key 使用 lru 逐出Evicts the least recently used keys out of all keys 在所有 key 中逐出最近最少使用的
    allkeys-lfu 所有的 key 使用 lfu 逐出Evicts the least frequently used keys out of all keys 在所有 key 中逐出最近最不频繁使用的
    allkeys-random 所有的 key 中随机逐出Randomly evicts keys out of all keys 在所有 key 中随机逐出
    volatile-lruEvicts the least recently used keys out of all keys with an “expire” field set 在设置了过期时间的 key 空间 expire 中使用 lru 策略逐出
    volatile-lfuEvicts the least frequently used keys out of all keys with an “expire” field set 在设置了过期时间的 key 空间 expire 中使用 lfu 策略逐出
    volatile-randomRandomly evicts keys with an “expire” field set 在设置了过期时间的 key 空间 expire 中随机逐出
    volatile-ttlEvicts the shortest time-to-live keys out of all keys with an “expire” field set.在设置了过期时间的 key 空间 expire 中逐出更早过期的
    +

    而在这其中默认使用的策略是 volatile-lru,对 lru 跟 lfu 想有更多的了解可以看下我之前的文章redis系列介绍八-淘汰策略

    ]]>
    redis redis + 淘汰策略 + 应用 + Evict
    - redis数据结构介绍三-第三部分 整数集合 - /2020/01/10/redis%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%BB%8B%E7%BB%8D%E4%B8%89/ - redis中对于 set 其实有两种处理,对于元素均为整型,并且元素数目较少时,使用 intset 作为底层数据结构,否则使用 dict 作为底层数据结构,先看一下代码先

    -
    typedef struct intset {
    -    // 编码方式
    -    uint32_t encoding;
    -    // 集合包含的元素数量
    -    uint32_t length;
    -    // 保存元素的数组
    -    int8_t contents[];
    -} intset;
    +    powershell 初体验二
    +    /2022/11/20/powershell-%E5%88%9D%E4%BD%93%E9%AA%8C%E4%BA%8C/
    +    powershell创建数组也很方便
    可以这样

    +
    $nums=2,0,1,2
    +

    顺便可以用下我们上次学到的gettype()

    +

    如果是想创建连续数字的数组还可以用这个方便的方法

    +
    $nums=1..5
    +


    而且数组还可以存放各种类型的数据

    +
    $array=1,"哈哈",([System.Guid]::NewGuid()),(get-date)
    +


    还有判断类型可以用-is

    创建一个空数组

    +
    $array=@()
    +


    数组添加元素

    +
    $array+="a"
    +


    数组删除元素

    +
    $a=1..4
    +$a=$a[0..1]+$a[3]
    +

    +]]>
    + + 语言 + + + powershell + + + + redis系列介绍七-过期策略 + /2020/04/12/redis%E7%B3%BB%E5%88%97%E4%BB%8B%E7%BB%8D%E4%B8%83/ + 这一篇不再是数据结构介绍了,大致的数据结构基本都介绍了,这一篇主要是查漏补缺,或者说讲一些重要且基本的概念,也可能是经常被忽略的,很多讲 redis 的系列文章可能都会忽略,学习 redis 的时候也会,因为觉得源码学习就是讲主要的数据结构和“算法”学习了就好了。
    redis 的主要应用就是拿来作为高性能的缓存,那么缓存一般有些啥需要注意的,首先是访问速度,如果取得跟数据库一样快,那就没什么存在的意义,第二个是缓存的字面意思,我只是为了让数据读取快一些,通常大部分的场景这个是需要更新过期的,这里就把我要讲的第一点引出来了(真累,

    +

    redis过期策略

    redis 是如何过期缓存的,可以猜测下,最无脑的就是每个设置了过期时间的 key 都设个定时器,过期了就删除,这种显然消耗太大,清理地最及时,还有的就是 redis 正在采用的懒汉清理策略和定期清理
    懒汉策略就是在使用的时候去检查缓存是否过期,比如 get 操作时,先判断下这个 key 是否已经过期了,如果过期了就删掉,并且返回空,如果没过期则正常返回
    主要代码是

    +
    /* This function is called when we are going to perform some operation
    + * in a given key, but such key may be already logically expired even if
    + * it still exists in the database. The main way this function is called
    + * is via lookupKey*() family of functions.
    + *
    + * The behavior of the function depends on the replication role of the
    + * instance, because slave instances do not expire keys, they wait
    + * for DELs from the master for consistency matters. However even
    + * slaves will try to have a coherent return value for the function,
    + * so that read commands executed in the slave side will be able to
    + * behave like if the key is expired even if still present (because the
    + * master has yet to propagate the DEL).
    + *
    + * In masters as a side effect of finding a key which is expired, such
    + * key will be evicted from the database. Also this may trigger the
    + * propagation of a DEL/UNLINK command in AOF / replication stream.
    + *
    + * The return value of the function is 0 if the key is still valid,
    + * otherwise the function returns 1 if the key is expired. */
    +int expireIfNeeded(redisDb *db, robj *key) {
    +    if (!keyIsExpired(db,key)) return 0;
    +
    +    /* If we are running in the context of a slave, instead of
    +     * evicting the expired key from the database, we return ASAP:
    +     * the slave key expiration is controlled by the master that will
    +     * send us synthesized DEL operations for expired keys.
    +     *
    +     * Still we try to return the right information to the caller,
    +     * that is, 0 if we think the key should be still valid, 1 if
    +     * we think the key is expired at this time. */
    +    if (server.masterhost != NULL) return 1;
    +
    +    /* Delete the key */
    +    server.stat_expiredkeys++;
    +    propagateExpire(db,key,server.lazyfree_lazy_expire);
    +    notifyKeyspaceEvent(NOTIFY_EXPIRED,
    +        "expired",key,db->id);
    +    return server.lazyfree_lazy_expire ? dbAsyncDelete(db,key) :
    +                                         dbSyncDelete(db,key);
    +}
    +
    +/* Check if the key is expired. */
    +int keyIsExpired(redisDb *db, robj *key) {
    +    mstime_t when = getExpire(db,key);
    +    mstime_t now;
    +
    +    if (when < 0) return 0; /* No expire for this key */
    +
    +    /* Don't expire anything while loading. It will be done later. */
    +    if (server.loading) return 0;
    +
    +    /* If we are in the context of a Lua script, we pretend that time is
    +     * blocked to when the Lua script started. This way a key can expire
    +     * only the first time it is accessed and not in the middle of the
    +     * script execution, making propagation to slaves / AOF consistent.
    +     * See issue #1525 on Github for more information. */
    +    if (server.lua_caller) {
    +        now = server.lua_time_start;
    +    }
    +    /* If we are in the middle of a command execution, we still want to use
    +     * a reference time that does not change: in that case we just use the
    +     * cached time, that we update before each call in the call() function.
    +     * This way we avoid that commands such as RPOPLPUSH or similar, that
    +     * may re-open the same key multiple times, can invalidate an already
    +     * open object in a next call, if the next call will see the key expired,
    +     * while the first did not. */
    +    else if (server.fixed_time_expire > 0) {
    +        now = server.mstime;
    +    }
    +    /* For the other cases, we want to use the most fresh time we have. */
    +    else {
    +        now = mstime();
    +    }
    +
    +    /* The key expired if the current (virtual or real) time is greater
    +     * than the expire time of the key. */
    +    return now > when;
    +}
    +/* Return the expire time of the specified key, or -1 if no expire
    + * is associated with this key (i.e. the key is non volatile) */
    +long long getExpire(redisDb *db, robj *key) {
    +    dictEntry *de;
     
    -/* Note that these encodings are ordered, so:
    - * INTSET_ENC_INT16 < INTSET_ENC_INT32 < INTSET_ENC_INT64. */
    -#define INTSET_ENC_INT16 (sizeof(int16_t))
    -#define INTSET_ENC_INT32 (sizeof(int32_t))
    -#define INTSET_ENC_INT64 (sizeof(int64_t))
    -

    一眼看,为啥整型还需要编码,然后 int8_t 怎么能存下大整形呢,带着这些疑问,我们一步步分析下去,这里的编码其实指的是这个整型集合里存的究竟是多大的整型,16 位,还是 32 位,还是 64 位,结构体下面的宏定义就是表示了 encoding 的可能取值,INTSET_ENC_INT16 表示每个元素用2个字节存储,INTSET_ENC_INT32 表示每个元素用4个字节存储,INTSET_ENC_INT64 表示每个元素用8个字节存储。因此,intset中存储的整数最多只能占用64bit。length 就是正常的表示集合中元素的数量。最奇怪的应该就是这个 contents 了,是个 int8_t 的数组,那放毛线数据啊,最小的都有 16 位,这里我在看代码和《redis 设计与实现》的时候也有点懵逼,后来查了下发现这是个比较取巧的用法,这里我用自己的理解表述一下,先看看 8,16,32,64 的关系,一眼看就知道都是 2 的 N 次,并且呈两倍关系,而且 8 位刚好一个字节,所以呢其实这里的contents 不是个常规意义上的 int8_t 类型的数组,而是个柔性数组。看下 wiki 的定义

    -
    -

    Flexible array members1 were introduced in the C99 standard of the C programming language (in particular, in section §6.7.2.1, item 16, page 103).2 It is a member of a struct, which is an array without a given dimension. It must be the last member of such a struct and it must be accompanied by at least one other member, as in the following example:

    -
    -
    struct vectord {
    -    size_t len;
    -    double arr[]; // the flexible array member must be last
    -};
    -

    在初始化这个 intset 的时候,这个contents数组是不占用空间的,后面的反正用到了申请,那么这里就有一个问题,给出了三种可能的 encoding 值,他们能随便换吗,显然不行,首先在 intset 中数据的存放是有序的,这个有部分原因是方便二分查找,然后存放数据其实随着数据的大小不同会有一个升级的过程,看下图

    新创建的intset只有一个header,总共8个字节。其中encoding = 2, length = 0, 类型都是uint32_t,各占 4 字节,添加15, 5两个元素之后,因为它们是比较小的整数,都能使用2个字节表示,所以encoding不变,值还是2,也就是默认的 INTSET_ENC_INT16,当添加32768的时候,它不再能用2个字节来表示了(2个字节能表达的数据范围是-215~215-1,而32768等于215,超出范围了),因此encoding必须升级到INTSET_ENC_INT32(值为4),即用4个字节表示一个元素。在添加每个元素的过程中,intset始终保持从小到大有序。与ziplist类似,intset也是按小端(little endian)模式存储的(参见维基百科词条Endianness)。比如,在上图中intset添加完所有数据之后,表示encoding字段的4个字节应该解释成0x00000004,而第4个数据应该解释成0x00008000 = 32768

    -]]>
    - - Redis - 数据结构 - C - 源码 - Redis - - - redis - 数据结构 - 源码 - -
    - - redis数据结构介绍二-第二部分 跳表 - /2020/01/04/redis%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%BB%8B%E7%BB%8D%E4%BA%8C/ - 跳表 skiplist

    跳表是个在我们日常的代码中不太常用到的数据结构,相对来讲就没有像数组,链表,字典,散列,树等结构那么熟悉,所以就从头开始分析下,首先是链表,跳表跟链表都有个表字(太硬扯了我🤦‍♀️),注意这是个有序链表

    如上图,在这个链表里如果我要找到 23,是不是我需要从3,5,9开始一直往后找直到找到 23,也就是说时间复杂度是 O(N),N 的一次幂复杂度,那么我们来看看第二个

    这个结构跟原先有点不一样,它给链表中偶数位的节点又加了一个指针把它们链接起来,这样子当我们要寻找 23 的时候就可以从原来的一个个往下找变成跳着找,先找到 5,然后是 10,接着是 19,然后是 28,这时候发现 28 比 23 大了,那我在退回到 19,然后从下一层原来的链表往前找,

    这里毛估估是不是前面的节点我就少找了一半,有那么点二分法的意思。
    前面的其实是跳表的引子,真正的跳表其实不是这样,因为上面的其实有个比较大的问题,就是插入一个元素后需要调整每个元素的指针,在 redis 中的跳表其实是做了个随机层数的优化,因为沿着前面的例子,其实当数据量很大的时候,是不是层数越多,其查询效率越高,但是随着层数变多,要保持这种严格的层数规则其实也会增大处理复杂度,所以 redis 插入每个元素的时候都是使用随机的方式,看一眼代码

    -
    /* ZSETs use a specialized version of Skiplists */
    -typedef struct zskiplistNode {
    -    sds ele;
    -    double score;
    -    struct zskiplistNode *backward;
    -    struct zskiplistLevel {
    -        struct zskiplistNode *forward;
    -        unsigned long span;
    -    } level[];
    -} zskiplistNode;
    +    /* No expire? return ASAP */
    +    if (dictSize(db->expires) == 0 ||
    +       (de = dictFind(db->expires,key->ptr)) == NULL) return -1;
     
    -typedef struct zskiplist {
    -    struct zskiplistNode *header, *tail;
    -    unsigned long length;
    -    int level;
    -} zskiplist;
    +    /* The entry was found in the expire dict, this means it should also
    +     * be present in the main dict (safety check). */
    +    serverAssertWithInfo(NULL,key,dictFind(db->dict,key->ptr) != NULL);
    +    return dictGetSignedIntegerVal(de);
    +}
    +

    这里有几点要注意的,第一是当惰性删除时会根据lazyfree_lazy_expire这个参数去判断是执行同步删除还是异步删除,另外一点是对于 slave,是不需要执行的,因为会在 master 过期时向 slave 发送 del 指令。
    光采用这个策略会有什么问题呢,假如一些key 一直未被访问,那这些 key 就不会过期了,导致一直被占用着内存,所以 redis 采取了懒汉式过期加定期过期策略,定期策略是怎么执行的呢

    +
    /* This function handles 'background' operations we are required to do
    + * incrementally in Redis databases, such as active key expiring, resizing,
    + * rehashing. */
    +void databasesCron(void) {
    +    /* Expire keys by random sampling. Not required for slaves
    +     * as master will synthesize DELs for us. */
    +    if (server.active_expire_enabled) {
    +        if (server.masterhost == NULL) {
    +            activeExpireCycle(ACTIVE_EXPIRE_CYCLE_SLOW);
    +        } else {
    +            expireSlaveKeys();
    +        }
    +    }
     
    -typedef struct zset {
    -    dict *dict;
    -    zskiplist *zsl;
    -} zset;
    -

    忘了说了,redis 是把 skiplist 跳表用在 zset 里,zset 是个有序的集合,可以看到 zskiplist 就是个跳表的结构,里面用 header 保存跳表的表头,tail 保存表尾,还有长度和最大层级,具体的跳表节点元素使用 zskiplistNode 表示,里面包含了 sds 类型的元素值,double 类型的分值,用来排序,一个 backward 后向指针和一个 zskiplistLevel 数组,每个 level 包含了一个前向指针,和一个 span,span 表示的是跳表前向指针的跨度,这里再补充一点,前面说了为了灵活这个跳表的新增修改,redis 使用了随机层高的方式插入新节点,但是如果所有节点都随机到很高的层级或者所有都很低的话,跳表的效率优势就会减小,所以 redis 使用了个小技巧,贴下代码

    -
    #define ZSKIPLIST_P 0.25      /* Skiplist P = 1/4 */
    -int zslRandomLevel(void) {
    -    int level = 1;
    -    while ((random()&0xFFFF) < (ZSKIPLIST_P * 0xFFFF))
    -        level += 1;
    -    return (level<ZSKIPLIST_MAXLEVEL) ? level : ZSKIPLIST_MAXLEVEL;
    -}
    -

    当随机值跟0xFFFF进行与操作小于ZSKIPLIST_P * 0xFFFF时才会增大 level 的值,因此保持了一个相对递减的概率
    可以简单分析下,当 random() 的值小于 0xFFFF 的 1/4,才会 level + 1,就意味着当有 1 - 1/4也就是3/4的概率是直接跳出,所以一层的概率是3/4,也就是 1-P,二层的概率是 P*(1-P),三层的概率是 P² * (1-P) 依次递推。

    -]]>
    - - Redis - 数据结构 - C - 源码 - Redis - - - redis - 数据结构 - 源码 - -
    - - mybatis系列-入门篇 - /2022/11/27/mybatis%E7%B3%BB%E5%88%97-%E5%85%A5%E9%97%A8%E7%AF%87/ - mybatis是我们比较常用的orm框架,下面是官网的介绍

    -
    -

    MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

    -
    -

    mybatis一大特点,或者说比较为人熟知的应该就是比 hibernate 是更轻量化,为国人所爱好的orm框架,对于hibernate目前还没有深入的拆解过,后续可以也写一下,在使用体验上觉得是个比较精巧的框架,看代码也比较容易,所以就想写个系列,第一篇先是介绍下使用
    根据官网的文档上我们先来尝试一下简单使用
    首先我们有个简单的配置,这个文件是mybatis-config.xml

    -
    <?xml version="1.0" encoding="UTF-8" ?>
    -<!DOCTYPE configuration
    -        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    -        "https://mybatis.org/dtd/mybatis-3-config.dtd">
    -<configuration>
    -    <!-- 需要加入的properties-->
    -    <properties resource="application-development.properties"/>
    -    <!-- 指出使用哪个环境,默认是development-->
    -    <environments default="development">
    -        <environment id="development">
    -        <!-- 指定事务管理器类型-->
    -            <transactionManager type="JDBC"/>
    -            <!-- 指定数据源类型-->
    -            <dataSource type="POOLED">
    -                <!-- 下面就是具体的参数占位了-->
    -                <property name="driver" value="${driver}"/>
    -                <property name="url" value="${url}"/>
    -                <property name="username" value="${username}"/>
    -                <property name="password" value="${password}"/>
    -            </dataSource>
    -        </environment>
    -    </environments>
    -    <mappers>
    -        <!-- 指定mapper xml的位置或文件-->
    -        <mapper resource="mapper/StudentMapper.xml"/>
    -    </mappers>
    -</configuration>
    -

    在代码里创建mybatis里重要入口

    -
    String resource = "mybatis-config.xml";
    -InputStream inputStream = Resources.getResourceAsStream(resource);
    -SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    -

    然后我们上面的StudentMapper.xml

    -
    <?xml version="1.0" encoding="UTF-8" ?>
    -<!DOCTYPE mapper
    -        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    -        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
    -<mapper namespace="com.nicksxs.mybatisdemo.StudentMapper">
    -    <select id="selectStudent" resultType="com.nicksxs.mybatisdemo.StudentDO">
    -        select * from student where id = #{id}
    -    </select>
    -</mapper>
    -

    那么我们就要使用这个mapper,

    -
    String resource = "mybatis-config.xml";
    -InputStream inputStream = Resources.getResourceAsStream(resource);
    -SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    -try (SqlSession session = sqlSessionFactory.openSession()) {
    -    StudentDO studentDO = session.selectOne("com.nicksxs.mybatisdemo.StudentMapper.selectStudent", 1);
    -    System.out.println("id is " + studentDO.getId() + " name is " +studentDO.getName());
    -} catch (Exception e) {
    -    e.printStackTrace();
    -}
    -

    sqlSessionFactory是sqlSession的工厂,我们可以通过sqlSessionFactory来创建sqlSession,而SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句。可以看到mapper.xml中有定义mapper的namespace,就可以通过session.selectOne()传入namespace+id来调用这个方法
    但是这样调用比较不合理的点,或者说按后面mybatis优化之后我们可以指定mapper接口

    -
    public interface StudentMapper {
    +    /* Defrag keys gradually. */
    +    activeDefragCycle();
    +
    +    /* Perform hash tables rehashing if needed, but only if there are no
    +     * other processes saving the DB on disk. Otherwise rehashing is bad
    +     * as will cause a lot of copy-on-write of memory pages. */
    +    if (!hasActiveChildProcess()) {
    +        /* We use global counters so if we stop the computation at a given
    +         * DB we'll be able to start from the successive in the next
    +         * cron loop iteration. */
    +        static unsigned int resize_db = 0;
    +        static unsigned int rehash_db = 0;
    +        int dbs_per_call = CRON_DBS_PER_CALL;
    +        int j;
    +
    +        /* Don't test more DBs than we have. */
    +        if (dbs_per_call > server.dbnum) dbs_per_call = server.dbnum;
    +
    +        /* Resize */
    +        for (j = 0; j < dbs_per_call; j++) {
    +            tryResizeHashTables(resize_db % server.dbnum);
    +            resize_db++;
    +        }
    +
    +        /* Rehash */
    +        if (server.activerehashing) {
    +            for (j = 0; j < dbs_per_call; j++) {
    +                int work_done = incrementallyRehash(rehash_db);
    +                if (work_done) {
    +                    /* If the function did some work, stop here, we'll do
    +                     * more at the next cron loop. */
    +                    break;
    +                } else {
    +                    /* If this db didn't need rehash, we'll try the next one. */
    +                    rehash_db++;
    +                    rehash_db %= server.dbnum;
    +                }
    +            }
    +        }
    +    }
    +}
    +/* Try to expire a few timed out keys. The algorithm used is adaptive and
    + * will use few CPU cycles if there are few expiring keys, otherwise
    + * it will get more aggressive to avoid that too much memory is used by
    + * keys that can be removed from the keyspace.
    + *
    + * Every expire cycle tests multiple databases: the next call will start
    + * again from the next db, with the exception of exists for time limit: in that
    + * case we restart again from the last database we were processing. Anyway
    + * no more than CRON_DBS_PER_CALL databases are tested at every iteration.
    + *
    + * The function can perform more or less work, depending on the "type"
    + * argument. It can execute a "fast cycle" or a "slow cycle". The slow
    + * cycle is the main way we collect expired cycles: this happens with
    + * the "server.hz" frequency (usually 10 hertz).
    + *
    + * However the slow cycle can exit for timeout, since it used too much time.
    + * For this reason the function is also invoked to perform a fast cycle
    + * at every event loop cycle, in the beforeSleep() function. The fast cycle
    + * will try to perform less work, but will do it much more often.
    + *
    + * The following are the details of the two expire cycles and their stop
    + * conditions:
    + *
    + * If type is ACTIVE_EXPIRE_CYCLE_FAST the function will try to run a
    + * "fast" expire cycle that takes no longer than EXPIRE_FAST_CYCLE_DURATION
    + * microseconds, and is not repeated again before the same amount of time.
    + * The cycle will also refuse to run at all if the latest slow cycle did not
    + * terminate because of a time limit condition.
    + *
    + * If type is ACTIVE_EXPIRE_CYCLE_SLOW, that normal expire cycle is
    + * executed, where the time limit is a percentage of the REDIS_HZ period
    + * as specified by the ACTIVE_EXPIRE_CYCLE_SLOW_TIME_PERC define. In the
    + * fast cycle, the check of every database is interrupted once the number
    + * of already expired keys in the database is estimated to be lower than
    + * a given percentage, in order to avoid doing too much work to gain too
    + * little memory.
    + *
    + * The configured expire "effort" will modify the baseline parameters in
    + * order to do more work in both the fast and slow expire cycles.
    + */
    +
    +#define ACTIVE_EXPIRE_CYCLE_KEYS_PER_LOOP 20 /* Keys for each DB loop. */
    +#define ACTIVE_EXPIRE_CYCLE_FAST_DURATION 1000 /* Microseconds. */
    +#define ACTIVE_EXPIRE_CYCLE_SLOW_TIME_PERC 25 /* Max % of CPU to use. */
    +#define ACTIVE_EXPIRE_CYCLE_ACCEPTABLE_STALE 10 /* % of stale keys after which
    +                                                   we do extra efforts. */
    +void activeExpireCycle(int type) {
    +    /* Adjust the running parameters according to the configured expire
    +     * effort. The default effort is 1, and the maximum configurable effort
    +     * is 10. */
    +    unsigned long
    +    effort = server.active_expire_effort-1, /* Rescale from 0 to 9. */
    +    config_keys_per_loop = ACTIVE_EXPIRE_CYCLE_KEYS_PER_LOOP +
    +                           ACTIVE_EXPIRE_CYCLE_KEYS_PER_LOOP/4*effort,
    +    config_cycle_fast_duration = ACTIVE_EXPIRE_CYCLE_FAST_DURATION +
    +                                 ACTIVE_EXPIRE_CYCLE_FAST_DURATION/4*effort,
    +    config_cycle_slow_time_perc = ACTIVE_EXPIRE_CYCLE_SLOW_TIME_PERC +
    +                                  2*effort,
    +    config_cycle_acceptable_stale = ACTIVE_EXPIRE_CYCLE_ACCEPTABLE_STALE-
    +                                    effort;
     
    -    public StudentDO selectStudent(Long id);
    -}
    -

    就可以可以通过mapper接口获取方法,这样就不用涉及到未知的变量转换等异常

    -
    try (SqlSession session = sqlSessionFactory.openSession()) {
    -    StudentMapper mapper = session.getMapper(StudentMapper.class);
    -    StudentDO studentDO = mapper.selectStudent(1L);
    -    System.out.println("id is " + studentDO.getId() + " name is " +studentDO.getName());
    -} catch (Exception e) {
    -    e.printStackTrace();
    -}
    -

    这一篇咱们先介绍下简单的使用,后面可以先介绍下这些的原理。

    -]]>
    - - Java - Mybatis - - - Java - Mysql - Mybatis - -
    - - redis数据结构介绍五-第五部分 对象 - /2020/01/20/redis%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%BB%8B%E7%BB%8D%E4%BA%94/ - 前面说了这么些数据结构,其实大家对于 redis 最初的印象应该就是个 key-value 的缓存,类似于 memcache,redis 其实也是个 key-value,key 还是一样的字符串,或者说就是用 redis 自己的动态字符串实现,但是 value 其实就是前面说的那些数据结构,差不多快说完了,还有个 quicklist 后面还有一篇,这里先介绍下 redis 对于这些不同类型的 value 是怎么实现的,首先看下 redisObject 的源码头文件

    -
    /* The actual Redis Object */
    -#define OBJ_STRING 0    /* String object. */
    -#define OBJ_LIST 1      /* List object. */
    -#define OBJ_SET 2       /* Set object. */
    -#define OBJ_ZSET 3      /* Sorted set object. */
    -#define OBJ_HASH 4      /* Hash object. */
    -/*
    - * Objects encoding. Some kind of objects like Strings and Hashes can be
    - * internally represented in multiple ways. The 'encoding' field of the object
    - * is set to one of this fields for this object. */
    -#define OBJ_ENCODING_RAW 0     /* Raw representation */
    -#define OBJ_ENCODING_INT 1     /* Encoded as integer */
    -#define OBJ_ENCODING_HT 2      /* Encoded as hash table */
    -#define OBJ_ENCODING_ZIPMAP 3  /* Encoded as zipmap */
    -#define OBJ_ENCODING_LINKEDLIST 4 /* No longer used: old list encoding. */
    -#define OBJ_ENCODING_ZIPLIST 5 /* Encoded as ziplist */
    -#define OBJ_ENCODING_INTSET 6  /* Encoded as intset */
    -#define OBJ_ENCODING_SKIPLIST 7  /* Encoded as skiplist */
    -#define OBJ_ENCODING_EMBSTR 8  /* Embedded sds string encoding */
    -#define OBJ_ENCODING_QUICKLIST 9 /* Encoded as linked list of ziplists */
    -#define OBJ_ENCODING_STREAM 10 /* Encoded as a radix tree of listpacks */
    +    /* This function has some global state in order to continue the work
    +     * incrementally across calls. */
    +    static unsigned int current_db = 0; /* Last DB tested. */
    +    static int timelimit_exit = 0;      /* Time limit hit in previous call? */
    +    static long long last_fast_cycle = 0; /* When last fast cycle ran. */
     
    -#define LRU_BITS 24
    -#define LRU_CLOCK_MAX ((1<<LRU_BITS)-1) /* Max value of obj->lru */
    -#define LRU_CLOCK_RESOLUTION 1000 /* LRU clock resolution in ms */
    +    int j, iteration = 0;
    +    int dbs_per_call = CRON_DBS_PER_CALL;
    +    long long start = ustime(), timelimit, elapsed;
     
    -#define OBJ_SHARED_REFCOUNT INT_MAX
    -typedef struct redisObject {
    -    unsigned type:4;
    -    unsigned encoding:4;
    -    unsigned lru:LRU_BITS; /* LRU time (relative to global lru_clock) or
    -                            * LFU data (least significant 8 bits frequency
    -                            * and most significant 16 bits access time). */
    -    int refcount;
    -    void *ptr;
    -} robj;
    -

    主体结构就是这个 redisObject,

    -
      -
    • type: 字段表示对象的类型,它对应的就是 redis 的对外暴露的,或者说用户可以使用的五种类型,OBJ_STRING, OBJ_LIST, OBJ_SET, OBJ_ZSET, OBJ_HASH
    • -
    • encoding: 字段表示这个对象在 redis 内部的编码方式,由OBJ_ENCODING_开头的 11 种
    • -
    • lru: 做LRU替换算法用,占24个bit
    • -
    • refcount: 引用计数。它允许robj对象在某些情况下被共享。
    • -
    • ptr: 指向底层实现数据结构的指针
      当 type 是 OBJ_STRING 时,表示类型是个 string,它的编码方式 encoding 可能有 OBJ_ENCODING_RAW,OBJ_ENCODING_INT,OBJ_ENCODING_EMBSTR 三种
      当 type 是 OBJ_LIST 时,表示类型是 list,它的编码方式 encoding 是 OBJ_ENCODING_QUICKLIST,对于早一些的版本,2.2这种可能还会使用 OBJ_ENCODING_ZIPLIST,OBJ_ENCODING_LINKEDLIST
      当 type 是 OBJ_SET 时,是个集合,但是得看具体元素的类型,有可能使用整数集合,OBJ_ENCODING_INTSET, 如果元素不全是整型或者数量超过一定限制,那么编码就是 OBJ_ENCODING_HT hash table 了
      当 type 是 OBJ_ZSET 时,是个有序集合,它底层有可能使用的是 OBJ_ENCODING_ZIPLIST 或者 OBJ_ENCODING_SKIPLIST
      当 type 是 OBJ_HASH 时,一开始也是 OBJ_ENCODING_ZIPLIST,然后当数据量大于 hash_max_ziplist_entries 时会转成 OBJ_ENCODING_HT
    • -
    -]]>
    - - Redis - 数据结构 - C - 源码 - Redis - - - redis - 数据结构 - 源码 - -
    - - redis淘汰策略复习 - /2021/08/01/redis%E6%B7%98%E6%B1%B0%E7%AD%96%E7%95%A5%E5%A4%8D%E4%B9%A0/ - 前面复习了 redis 的过期策略,这里再复习下淘汰策略,淘汰跟过期的区别有时候会被混淆了,过期主要针对那些设置了过期时间的 key,应该说是一种逻辑策略,是主动的还是被动的加定时的,两种有各自的取舍,而淘汰也可以看成是一种保持系统稳定的策略,因为如果内存满了,不采取任何策略处理,那大概率会导致系统故障,之前其实主要从源码角度分析过redis 的 LRU 和 LFU,但这个是偏底层的实现,抠得比较细,那么具体的系统层面的配置是有哪些策略,来看下 redis labs 的介绍

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    PolicyDescription
    noeviction 不逐出Returns an error if the memory limit has been reached when trying to insert more data,插入更多数据时,如果内存达到上限了,返回错误
    allkeys-lru 所有的 key 使用 lru 逐出Evicts the least recently used keys out of all keys 在所有 key 中逐出最近最少使用的
    allkeys-lfu 所有的 key 使用 lfu 逐出Evicts the least frequently used keys out of all keys 在所有 key 中逐出最近最不频繁使用的
    allkeys-random 所有的 key 中随机逐出Randomly evicts keys out of all keys 在所有 key 中随机逐出
    volatile-lruEvicts the least recently used keys out of all keys with an “expire” field set 在设置了过期时间的 key 空间 expire 中使用 lru 策略逐出
    volatile-lfuEvicts the least frequently used keys out of all keys with an “expire” field set 在设置了过期时间的 key 空间 expire 中使用 lfu 策略逐出
    volatile-randomRandomly evicts keys with an “expire” field set 在设置了过期时间的 key 空间 expire 中随机逐出
    volatile-ttlEvicts the shortest time-to-live keys out of all keys with an “expire” field set.在设置了过期时间的 key 空间 expire 中逐出更早过期的
    -

    而在这其中默认使用的策略是 volatile-lru,对 lru 跟 lfu 想有更多的了解可以看下我之前的文章redis系列介绍八-淘汰策略

    -]]>
    - - redis - - - redis - 淘汰策略 - 应用 - Evict - -
    - - redis数据结构介绍六 快表 - /2020/01/22/redis%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%BB%8B%E7%BB%8D%E5%85%AD/ - 这应该是 redis 系列的最后一篇了,讲下快表,其实最前面讲的链表在早先的 redis 版本中也作为 list 的数据结构使用过,但是单纯的链表的缺陷之前也说了,插入便利,但是空间利用率低,并且不能进行二分查找等,检索效率低,ziplist 压缩表的产生也是同理,希望获得更好的性能,包括存储空间和访问性能等,原来我也不懂这个快表要怎么快,然后明白了一个道理,其实并没有什么银弹,只是大牛们会在适合的时候使用最适合的数据结构来实现性能的最大化,这里面有一招就是不同数据结构的组合调整,比如 Java 中的 HashMap,在链表节点数大于 8 时会转变成红黑树,以此提高访问效率,不费话了,回到快表,quicklist,这个数据结构主要使用在 list 类型中,如果我说其实这个 quicklist 就是个链表,可能大家不太会相信,但是事实上的确可以认为 quicklist 是个双向链表,看下代码

    -
    /* quicklistNode is a 32 byte struct describing a ziplist for a quicklist.
    - * We use bit fields keep the quicklistNode at 32 bytes.
    - * count: 16 bits, max 65536 (max zl bytes is 65k, so max count actually < 32k).
    - * encoding: 2 bits, RAW=1, LZF=2.
    - * container: 2 bits, NONE=1, ZIPLIST=2.
    - * recompress: 1 bit, bool, true if node is temporarry decompressed for usage.
    - * attempted_compress: 1 bit, boolean, used for verifying during testing.
    - * extra: 10 bits, free for future use; pads out the remainder of 32 bits */
    -typedef struct quicklistNode {
    -    struct quicklistNode *prev;
    -    struct quicklistNode *next;
    -    unsigned char *zl;
    -    unsigned int sz;             /* ziplist size in bytes */
    -    unsigned int count : 16;     /* count of items in ziplist */
    -    unsigned int encoding : 2;   /* RAW==1 or LZF==2 */
    -    unsigned int container : 2;  /* NONE==1 or ZIPLIST==2 */
    -    unsigned int recompress : 1; /* was this node previous compressed? */
    -    unsigned int attempted_compress : 1; /* node can't compress; too small */
    -    unsigned int extra : 10; /* more bits to steal for future usage */
    -} quicklistNode;
    +    /* When clients are paused the dataset should be static not just from the
    +     * POV of clients not being able to write, but also from the POV of
    +     * expires and evictions of keys not being performed. */
    +    if (clientsArePaused()) return;
     
    -/* quicklistLZF is a 4+N byte struct holding 'sz' followed by 'compressed'.
    - * 'sz' is byte length of 'compressed' field.
    - * 'compressed' is LZF data with total (compressed) length 'sz'
    - * NOTE: uncompressed length is stored in quicklistNode->sz.
    - * When quicklistNode->zl is compressed, node->zl points to a quicklistLZF */
    -typedef struct quicklistLZF {
    -    unsigned int sz; /* LZF size in bytes*/
    -    char compressed[];
    -} quicklistLZF;
    +    if (type == ACTIVE_EXPIRE_CYCLE_FAST) {
    +        /* Don't start a fast cycle if the previous cycle did not exit
    +         * for time limit, unless the percentage of estimated stale keys is
    +         * too high. Also never repeat a fast cycle for the same period
    +         * as the fast cycle total duration itself. */
    +        if (!timelimit_exit &&
    +            server.stat_expired_stale_perc < config_cycle_acceptable_stale)
    +            return;
     
    -/* quicklist is a 40 byte struct (on 64-bit systems) describing a quicklist.
    - * 'count' is the number of total entries.
    - * 'len' is the number of quicklist nodes.
    - * 'compress' is: -1 if compression disabled, otherwise it's the number
    - *                of quicklistNodes to leave uncompressed at ends of quicklist.
    - * 'fill' is the user-requested (or default) fill factor. */
    -typedef struct quicklist {
    -    quicklistNode *head;
    -    quicklistNode *tail;
    -    unsigned long count;        /* total count of all entries in all ziplists */
    -    unsigned long len;          /* number of quicklistNodes */
    -    int fill : 16;              /* fill factor for individual nodes */
    -    unsigned int compress : 16; /* depth of end nodes not to compress;0=off */
    -} quicklist;
    -

    粗略看下,quicklist 里有 head,tail, quicklistNode里有 prev,next 指针,是不是有链表的基本轮廓了,那么为啥这玩意要称为快表呢,快在哪,关键就在这个unsigned char *zl;zl 是不是前面又看到过,就是 ziplist ,这是什么鬼,链表里用压缩表,这不套娃么,先别急,回顾下前面说的 ziplist,ziplist 有哪些特点,内存利用率高,可以从表头快速定位到尾节点,节点可以从后往前找,但是有个缺点,就是从中间插入的效率比较低,需要整体往后移,这个其实是普通数组的优化版,但还是有数组的一些劣势,所以要真的快,是不是可以将链表跟数组真的结合起来。

    -

    ziplist

    这里有两个 redis 的配置参数,list-max-ziplist-sizelist-compress-depth,先来说第一个,既然快表是将链表跟压缩表数组结合起来使用,那么具体怎么用呢,比如我有一个 10 个元素的 list,那具体怎么放,每个 quicklistNode 里放多大的 ziplist,假如每个快表节点的 ziplist 只放一个元素,那么其实这就退化成了一个链表,如果 10 个元素放在一个 quicklistNode 的 ziplist 里,那就退化成了一个 ziplist,所以有了这个 list-max-ziplist-size,而且它还比较牛,能取正负值,当是正值时,对应的就是每个 quicklistNode 的 ziplist 中的元素个数,比如配置了 list-max-ziplist-size = 5,那么我刚才的 10 个元素的 list 就是一个两个 quicklistNode 组成的快表,每个 quicklistNode 中的 ziplist 包含了五个元素,当 list-max-ziplist-size取负值的时候,它限制了 ziplist 的字节数

    -
    size_t offset = (-fill) - 1;
    -if (offset < (sizeof(optimization_level) / sizeof(*optimization_level))) {
    -    if (sz <= optimization_level[offset]) {
    -        return 1;
    -    } else {
    -        return 0;
    +        if (start < last_fast_cycle + (long long)config_cycle_fast_duration*2)
    +            return;
    +
    +        last_fast_cycle = start;
         }
    -} else {
    -    return 0;
    -}
     
    -/* Optimization levels for size-based filling */
    -static const size_t optimization_level[] = {4096, 8192, 16384, 32768, 65536};
    +    /* We usually should test CRON_DBS_PER_CALL per iteration, with
    +     * two exceptions:
    +     *
    +     * 1) Don't test more DBs than we have.
    +     * 2) If last time we hit the time limit, we want to scan all DBs
    +     * in this iteration, as there is work to do in some DB and we don't want
    +     * expired keys to use memory for too much time. */
    +    if (dbs_per_call > server.dbnum || timelimit_exit)
    +        dbs_per_call = server.dbnum;
    +
    +    /* We can use at max 'config_cycle_slow_time_perc' percentage of CPU
    +     * time per iteration. Since this function gets called with a frequency of
    +     * server.hz times per second, the following is the max amount of
    +     * microseconds we can spend in this function. */
    +    timelimit = config_cycle_slow_time_perc*1000000/server.hz/100;
    +    timelimit_exit = 0;
    +    if (timelimit <= 0) timelimit = 1;
    +
    +    if (type == ACTIVE_EXPIRE_CYCLE_FAST)
    +        timelimit = config_cycle_fast_duration; /* in microseconds. */
    +
    +    /* Accumulate some global stats as we expire keys, to have some idea
    +     * about the number of keys that are already logically expired, but still
    +     * existing inside the database. */
    +    long total_sampled = 0;
    +    long total_expired = 0;
    +
    +    for (j = 0; j < dbs_per_call && timelimit_exit == 0; j++) {
    +        /* Expired and checked in a single loop. */
    +        unsigned long expired, sampled;
    +
    +        redisDb *db = server.db+(current_db % server.dbnum);
     
    -/* Create a new quicklist.
    - * Free with quicklistRelease(). */
    -quicklist *quicklistCreate(void) {
    -    struct quicklist *quicklist;
    +        /* Increment the DB now so we are sure if we run out of time
    +         * in the current DB we'll restart from the next. This allows to
    +         * distribute the time evenly across DBs. */
    +        current_db++;
     
    -    quicklist = zmalloc(sizeof(*quicklist));
    -    quicklist->head = quicklist->tail = NULL;
    -    quicklist->len = 0;
    -    quicklist->count = 0;
    -    quicklist->compress = 0;
    -    quicklist->fill = -2;
    -    return quicklist;
    -}
    -

    这个 fill 就是传进来的 list-max-ziplist-size, 具体对应的就是

    -
      -
    • -5: 每个quicklist节点上的ziplist大小不能超过64 Kb。(注:1kb => 1024 bytes)
    • -
    • -4: 每个quicklist节点上的ziplist大小不能超过32 Kb。
    • -
    • -3: 每个quicklist节点上的ziplist大小不能超过16 Kb。
    • -
    • -2: 每个quicklist节点上的ziplist大小不能超过8 Kb。(-2是Redis给出的默认值)也就是上面的 quicklist->fill = -2;
    • -
    • -1: 每个quicklist节点上的ziplist大小不能超过4 Kb。
    • -
    -

    压缩

    list-compress-depth这个参数呢是用来配置压缩的,等等压缩是为啥,不是里面已经是压缩表了么,大牛们就是为了性能殚精竭虑,这里考虑到的是一个场景,一般状况下,list 都是两端的访问频率比较高,那么是不是可以对中间的数据进行压缩,那么这个参数就是用来表示

    -
    /* depth of end nodes not to compress;0=off */
    -
      -
    • 0,代表不压缩,默认值
    • -
    • 1,两端各一个节点不压缩
    • -
    • 2,两端各两个节点不压缩
    • -
    • … 依次类推
      压缩后的 ziplist 就会变成 quicklistLZF,然后替换 zl 指针,这里使用的是 LZF 压缩算法,压缩后的 quicklistLZF 中的 compressed 也是个柔性数组,压缩后的 ziplist 整个就放进这个柔性数组
    • -
    -

    插入过程

    简单说下插入元素的过程

    -
    /* Wrapper to allow argument-based switching between HEAD/TAIL pop */
    -void quicklistPush(quicklist *quicklist, void *value, const size_t sz,
    -                   int where) {
    -    if (where == QUICKLIST_HEAD) {
    -        quicklistPushHead(quicklist, value, sz);
    -    } else if (where == QUICKLIST_TAIL) {
    -        quicklistPushTail(quicklist, value, sz);
    -    }
    -}
    +        /* Continue to expire if at the end of the cycle more than 25%
    +         * of the keys were expired. */
    +        do {
    +            unsigned long num, slots;
    +            long long now, ttl_sum;
    +            int ttl_samples;
    +            iteration++;
     
    -/* Add new entry to head node of quicklist.
    - *
    - * Returns 0 if used existing head.
    - * Returns 1 if new head created. */
    -int quicklistPushHead(quicklist *quicklist, void *value, size_t sz) {
    -    quicklistNode *orig_head = quicklist->head;
    -    if (likely(
    -            _quicklistNodeAllowInsert(quicklist->head, quicklist->fill, sz))) {
    -        quicklist->head->zl =
    -            ziplistPush(quicklist->head->zl, value, sz, ZIPLIST_HEAD);
    -        quicklistNodeUpdateSz(quicklist->head);
    -    } else {
    -        quicklistNode *node = quicklistCreateNode();
    -        node->zl = ziplistPush(ziplistNew(), value, sz, ZIPLIST_HEAD);
    +            /* If there is nothing to expire try next DB ASAP. */
    +            if ((num = dictSize(db->expires)) == 0) {
    +                db->avg_ttl = 0;
    +                break;
    +            }
    +            slots = dictSlots(db->expires);
    +            now = mstime();
     
    -        quicklistNodeUpdateSz(node);
    -        _quicklistInsertNodeBefore(quicklist, quicklist->head, node);
    -    }
    -    quicklist->count++;
    -    quicklist->head->count++;
    -    return (orig_head != quicklist->head);
    -}
    +            /* When there are less than 1% filled slots, sampling the key
    +             * space is expensive, so stop here waiting for better times...
    +             * The dictionary will be resized asap. */
    +            if (num && slots > DICT_HT_INITIAL_SIZE &&
    +                (num*100/slots < 1)) break;
     
    -/* Add new entry to tail node of quicklist.
    - *
    - * Returns 0 if used existing tail.
    - * Returns 1 if new tail created. */
    -int quicklistPushTail(quicklist *quicklist, void *value, size_t sz) {
    -    quicklistNode *orig_tail = quicklist->tail;
    -    if (likely(
    -            _quicklistNodeAllowInsert(quicklist->tail, quicklist->fill, sz))) {
    -        quicklist->tail->zl =
    -            ziplistPush(quicklist->tail->zl, value, sz, ZIPLIST_TAIL);
    -        quicklistNodeUpdateSz(quicklist->tail);
    -    } else {
    -        quicklistNode *node = quicklistCreateNode();
    -        node->zl = ziplistPush(ziplistNew(), value, sz, ZIPLIST_TAIL);
    +            /* The main collection cycle. Sample random keys among keys
    +             * with an expire set, checking for expired ones. */
    +            expired = 0;
    +            sampled = 0;
    +            ttl_sum = 0;
    +            ttl_samples = 0;
     
    -        quicklistNodeUpdateSz(node);
    -        _quicklistInsertNodeAfter(quicklist, quicklist->tail, node);
    -    }
    -    quicklist->count++;
    -    quicklist->tail->count++;
    -    return (orig_tail != quicklist->tail);
    -}
    +            if (num > config_keys_per_loop)
    +                num = config_keys_per_loop;
     
    -/* Wrappers for node inserting around existing node. */
    -REDIS_STATIC void _quicklistInsertNodeBefore(quicklist *quicklist,
    -                                             quicklistNode *old_node,
    -                                             quicklistNode *new_node) {
    -    __quicklistInsertNode(quicklist, old_node, new_node, 0);
    -}
    +            /* Here we access the low level representation of the hash table
    +             * for speed concerns: this makes this code coupled with dict.c,
    +             * but it hardly changed in ten years.
    +             *
    +             * Note that certain places of the hash table may be empty,
    +             * so we want also a stop condition about the number of
    +             * buckets that we scanned. However scanning for free buckets
    +             * is very fast: we are in the cache line scanning a sequential
    +             * array of NULL pointers, so we can scan a lot more buckets
    +             * than keys in the same time. */
    +            long max_buckets = num*20;
    +            long checked_buckets = 0;
     
    -REDIS_STATIC void _quicklistInsertNodeAfter(quicklist *quicklist,
    -                                            quicklistNode *old_node,
    -                                            quicklistNode *new_node) {
    -    __quicklistInsertNode(quicklist, old_node, new_node, 1);
    -}
    +            while (sampled < num && checked_buckets < max_buckets) {
    +                for (int table = 0; table < 2; table++) {
    +                    if (table == 1 && !dictIsRehashing(db->expires)) break;
     
    -/* Insert 'new_node' after 'old_node' if 'after' is 1.
    - * Insert 'new_node' before 'old_node' if 'after' is 0.
    - * Note: 'new_node' is *always* uncompressed, so if we assign it to
    - *       head or tail, we do not need to uncompress it. */
    -REDIS_STATIC void __quicklistInsertNode(quicklist *quicklist,
    -                                        quicklistNode *old_node,
    -                                        quicklistNode *new_node, int after) {
    -    if (after) {
    -        new_node->prev = old_node;
    -        if (old_node) {
    -            new_node->next = old_node->next;
    -            if (old_node->next)
    -                old_node->next->prev = new_node;
    -            old_node->next = new_node;
    -        }
    -        if (quicklist->tail == old_node)
    -            quicklist->tail = new_node;
    -    } else {
    -        new_node->next = old_node;
    -        if (old_node) {
    -            new_node->prev = old_node->prev;
    -            if (old_node->prev)
    -                old_node->prev->next = new_node;
    -            old_node->prev = new_node;
    -        }
    -        if (quicklist->head == old_node)
    -            quicklist->head = new_node;
    -    }
    -    /* If this insert creates the only element so far, initialize head/tail. */
    -    if (quicklist->len == 0) {
    -        quicklist->head = quicklist->tail = new_node;
    -    }
    +                    unsigned long idx = db->expires_cursor;
    +                    idx &= db->expires->ht[table].sizemask;
    +                    dictEntry *de = db->expires->ht[table].table[idx];
    +                    long long ttl;
     
    -    if (old_node)
    -        quicklistCompress(quicklist, old_node);
    +                    /* Scan the current bucket of the current table. */
    +                    checked_buckets++;
    +                    while(de) {
    +                        /* Get the next entry now since this entry may get
    +                         * deleted. */
    +                        dictEntry *e = de;
    +                        de = de->next;
     
    -    quicklist->len++;
    -}
    -

    前面第一步先根据插入的是头还是尾选择不同的 push 函数,quicklistPushHead 或者 quicklistPushTail,举例分析下从头插入的 quicklistPushHead,先判断当前的 quicklistNode 节点还能不能允许再往 ziplist 里添加元素,如果可以就添加,如果不允许就新建一个 quicklistNode,然后调用 _quicklistInsertNodeBefore 将节点插进去,具体插入quicklist节点的操作类似链表的插入。

    -]]>
    - - Redis - 数据结构 - C - 源码 - Redis - - - redis - 数据结构 - 源码 - -
    - - redis数据结构介绍四-第四部分 压缩表 - /2020/01/19/redis%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%BB%8B%E7%BB%8D%E5%9B%9B/ - 在 redis 中还有一类表型数据结构叫压缩表,ziplist,它的目的是替代链表,链表是个很容易理解的数据结构,双向链表有前后指针,有带头结点的有的不带,但是链表有个比较大的问题是相对于普通的数组,它的内存不连续,碎片化的存储,内存利用效率不高,而且指针寻址相对于直接使用偏移量的话,也有一定的效率劣势,当然这不是主要的原因,ziplist 设计的主要目的是让链表的内存使用更高效

    -
    -

    The ziplist is a specially encoded dually linked list that is designed to be very memory efficient.
    这是摘自 redis 源码中ziplist.c 文件的注释,也说明了原因,它的大概结构是这样子

    -
    -
    <zlbytes> <zltail> <zllen> <entry> <entry> ... <entry> <zlend>
    -

    其中
    <zlbytes>表示 ziplist 占用的字节总数,类型是uint32_t,32 位的无符号整型,当然表示的字节数也包含自己本身占用的 4 个
    <zltail> 类型也是是uint32_t,表示ziplist表中最后一项(entry)在ziplist中的偏移字节数。<zltail>的存在,使得我们可以很方便地找到最后一项(不用遍历整个ziplist),从而可以在ziplist尾端快速地执行push或pop操作。
    <uint16_t zllen> 表示ziplist 中的数据项个数,因为是 16 位,所以当数量超过所能表示的最大的数量,它的 16 位全会置为 1,但是真实的数量需要遍历整个 ziplist 才能知道
    <entry>是具体的数据项,后面解释
    <zlend> ziplist 的最后一个字节,固定是255。
    再看一下<entry>中的具体结构,

    -
    <prevlen> <encoding> <entry-data>
    -

    首先这个<prevlen>有两种情况,一种是前面的元素的长度,如果是小于等于 253的时候就用一个uint8_t 来表示前一元素的长度,如果大于的话他将占用五个字节,第一个字节是 254,即表示这个字节已经表示不下了,需要后面的四个字节帮忙表示
    <encoding>这个就比较复杂,把源码的注释放下面先看下

    -
    * |00pppppp| - 1 byte
    -*      String value with length less than or equal to 63 bytes (6 bits).
    -*      "pppppp" represents the unsigned 6 bit length.
    -* |01pppppp|qqqqqqqq| - 2 bytes
    -*      String value with length less than or equal to 16383 bytes (14 bits).
    -*      IMPORTANT: The 14 bit number is stored in big endian.
    -* |10000000|qqqqqqqq|rrrrrrrr|ssssssss|tttttttt| - 5 bytes
    -*      String value with length greater than or equal to 16384 bytes.
    -*      Only the 4 bytes following the first byte represents the length
    -*      up to 32^2-1. The 6 lower bits of the first byte are not used and
    -*      are set to zero.
    -*      IMPORTANT: The 32 bit number is stored in big endian.
    -* |11000000| - 3 bytes
    -*      Integer encoded as int16_t (2 bytes).
    -* |11010000| - 5 bytes
    -*      Integer encoded as int32_t (4 bytes).
    -* |11100000| - 9 bytes
    -*      Integer encoded as int64_t (8 bytes).
    -* |11110000| - 4 bytes
    -*      Integer encoded as 24 bit signed (3 bytes).
    -* |11111110| - 2 bytes
    -*      Integer encoded as 8 bit signed (1 byte).
    -* |1111xxxx| - (with xxxx between 0000 and 1101) immediate 4 bit integer.
    -*      Unsigned integer from 0 to 12. The encoded value is actually from
    -*      1 to 13 because 0000 and 1111 can not be used, so 1 should be
    -*      subtracted from the encoded 4 bit value to obtain the right value.
    -* |11111111| - End of ziplist special entry.
    -

    首先如果 encoding 的前两位是 00 的话代表这个元素是个 6 位的字符串,即直接将数据保存在 encoding 中,不消耗额外的<entry-data>,如果前两位是 01 的话表示是个 14 位的字符串,如果是 10 的话表示encoding 块之后的四个字节是存放字符串类型的数据,encoding 的剩余 6 位置 0。
    如果 encoding 的前两位是 11 的话表示这是个整型,具体的如果后两位是00的话,表示后面是个2字节的 int16_t 类型,如果是01的话,后面是个4字节的int32_t,如果是10的话后面是8字节的int64_t,如果是 11 的话后面是 3 字节的有符号整型,这些都要最后 4 位都是 0 的情况噢
    剩下当是11111110时,则表示是一个1 字节的有符号数,如果是 1111xxxx,其中xxxx在0000 到 1101 表示实际的 1 到 13,为啥呢,因为 0000 前面已经用过了,而 1110 跟 1111 也都有用了。
    看个具体的例子(上下有点对不齐,将就看)

    -
    [0f 00 00 00] [0c 00 00 00] [02 00] [00 f3] [02 f6] [ff]
    -|**zlbytes***|  |***zltail***|  |*zllen*|  |entry1 entry2|  |zlend|
    -

    第一部分代表整个 ziplist 有 15 个字节,zlbytes 自己占了 4 个 zltail 表示最后一个元素的偏移量,第 13 个字节起,zllen 表示有 2 个元素,第一个元素是00f3,00表示前一个元素长度是 0,本来前面就没元素(不过不知道这个能不能优化这一字节),然后是 f3,换成二进制就是11110011,对照上面的注释,是落在|1111xxxx|这个类型里,注意这个其实是用 0001 到 1101 也就是 1到 13 来表示 0到 12,所以 f3 应该就是 2,第一个元素是 2,第二个元素呢,02 代表前一个元素也就是刚才说的这个,占用 2 字节,f6 展开也是刚才的类型,实际是 5,ff 表示 ziplist 的结尾,所以这个 ziplist 里面是两个元素,2 跟 5

    + ttl = dictGetSignedIntegerVal(e)-now; + if (activeExpireCycleTryExpire(db,e,now)) expired++; + if (ttl > 0) { + /* We want the average TTL of keys yet + * not expired. */ + ttl_sum += ttl; + ttl_samples++; + } + sampled++; + } + } + db->expires_cursor++; + } + total_expired += expired; + total_sampled += sampled; + + /* Update the average TTL stats for this database. */ + if (ttl_samples) { + long long avg_ttl = ttl_sum/ttl_samples; + + /* Do a simple running average with a few samples. + * We just use the current estimate with a weight of 2% + * and the previous estimate with a weight of 98%. */ + if (db->avg_ttl == 0) db->avg_ttl = avg_ttl; + db->avg_ttl = (db->avg_ttl/50)*49 + (avg_ttl/50); + } + + /* We can't block forever here even if there are many keys to + * expire. So after a given amount of milliseconds return to the + * caller waiting for the other active expire cycle. */ + if ((iteration & 0xf) == 0) { /* check once every 16 iterations. */ + elapsed = ustime()-start; + if (elapsed > timelimit) { + timelimit_exit = 1; + server.stat_expired_time_cap_reached_count++; + break; + } + } + /* We don't repeat the cycle for the current database if there are + * an acceptable amount of stale keys (logically expired but yet + * not reclained). */ + } while ((expired*100/sampled) > config_cycle_acceptable_stale); + } + + elapsed = ustime()-start; + server.stat_expire_cycle_time_used += elapsed; + latencyAddSampleIfNeeded("expire-cycle",elapsed/1000); + + /* Update our estimate of keys existing but yet to be expired. + * Running average with this sample accounting for 5%. */ + double current_perc; + if (total_sampled) { + current_perc = (double)total_expired/total_sampled; + } else + current_perc = 0; + server.stat_expired_stale_perc = (current_perc*0.05)+ + (server.stat_expired_stale_perc*0.95); +}
    +

    执行定期清除分成两种类型,快和慢,分别由beforeSleepdatabasesCron调用,快版有两个限制,一个是执行时长由ACTIVE_EXPIRE_CYCLE_FAST_DURATION限制,另一个是执行间隔是 2 倍的ACTIVE_EXPIRE_CYCLE_FAST_DURATION,另外这还可以由配置的server.active_expire_effort参数来控制,默认是 1,最大是 10

    +
    onfig_cycle_fast_duration = ACTIVE_EXPIRE_CYCLE_FAST_DURATION +
    +                                 ACTIVE_EXPIRE_CYCLE_FAST_DURATION/4*effort
    +

    然后会从一定数量的 db 中找出一定数量的带过期时间的 key(保存在 expires中),这里的数量是由

    +
    config_keys_per_loop = ACTIVE_EXPIRE_CYCLE_KEYS_PER_LOOP +
    +                           ACTIVE_EXPIRE_CYCLE_KEYS_PER_LOOP/4*effort
    +```                                 
    +控制,慢速的执行时长是
    +```C
    +config_cycle_slow_time_perc = ACTIVE_EXPIRE_CYCLE_SLOW_TIME_PERC +
    +                                  2*effort
    +timelimit = config_cycle_slow_time_perc*1000000/server.hz/100;
    +

    这里还有一个额外的退出条件,如果当前数据库的抽样结果已经达到我们所允许的过期 key 百分比,则下次不再处理当前 db,继续处理下个 db

    ]]>
    Redis @@ -10881,449 +10928,435 @@ REDIS_STATIC void __quicklistInsertNode(quicklist *quicklist,
    - redis系列介绍七-过期策略 - /2020/04/12/redis%E7%B3%BB%E5%88%97%E4%BB%8B%E7%BB%8D%E4%B8%83/ - 这一篇不再是数据结构介绍了,大致的数据结构基本都介绍了,这一篇主要是查漏补缺,或者说讲一些重要且基本的概念,也可能是经常被忽略的,很多讲 redis 的系列文章可能都会忽略,学习 redis 的时候也会,因为觉得源码学习就是讲主要的数据结构和“算法”学习了就好了。
    redis 的主要应用就是拿来作为高性能的缓存,那么缓存一般有些啥需要注意的,首先是访问速度,如果取得跟数据库一样快,那就没什么存在的意义,第二个是缓存的字面意思,我只是为了让数据读取快一些,通常大部分的场景这个是需要更新过期的,这里就把我要讲的第一点引出来了(真累,

    -

    redis过期策略

    redis 是如何过期缓存的,可以猜测下,最无脑的就是每个设置了过期时间的 key 都设个定时器,过期了就删除,这种显然消耗太大,清理地最及时,还有的就是 redis 正在采用的懒汉清理策略和定期清理
    懒汉策略就是在使用的时候去检查缓存是否过期,比如 get 操作时,先判断下这个 key 是否已经过期了,如果过期了就删掉,并且返回空,如果没过期则正常返回
    主要代码是

    -
    /* This function is called when we are going to perform some operation
    - * in a given key, but such key may be already logically expired even if
    - * it still exists in the database. The main way this function is called
    - * is via lookupKey*() family of functions.
    - *
    - * The behavior of the function depends on the replication role of the
    - * instance, because slave instances do not expire keys, they wait
    - * for DELs from the master for consistency matters. However even
    - * slaves will try to have a coherent return value for the function,
    - * so that read commands executed in the slave side will be able to
    - * behave like if the key is expired even if still present (because the
    - * master has yet to propagate the DEL).
    - *
    - * In masters as a side effect of finding a key which is expired, such
    - * key will be evicted from the database. Also this may trigger the
    - * propagation of a DEL/UNLINK command in AOF / replication stream.
    - *
    - * The return value of the function is 0 if the key is still valid,
    - * otherwise the function returns 1 if the key is expired. */
    -int expireIfNeeded(redisDb *db, robj *key) {
    -    if (!keyIsExpired(db,key)) return 0;
    -
    -    /* If we are running in the context of a slave, instead of
    -     * evicting the expired key from the database, we return ASAP:
    -     * the slave key expiration is controlled by the master that will
    -     * send us synthesized DEL operations for expired keys.
    -     *
    -     * Still we try to return the right information to the caller,
    -     * that is, 0 if we think the key should be still valid, 1 if
    -     * we think the key is expired at this time. */
    -    if (server.masterhost != NULL) return 1;
    -
    -    /* Delete the key */
    -    server.stat_expiredkeys++;
    -    propagateExpire(db,key,server.lazyfree_lazy_expire);
    -    notifyKeyspaceEvent(NOTIFY_EXPIRED,
    -        "expired",key,db->id);
    -    return server.lazyfree_lazy_expire ? dbAsyncDelete(db,key) :
    -                                         dbSyncDelete(db,key);
    -}
    -
    -/* Check if the key is expired. */
    -int keyIsExpired(redisDb *db, robj *key) {
    -    mstime_t when = getExpire(db,key);
    -    mstime_t now;
    -
    -    if (when < 0) return 0; /* No expire for this key */
    -
    -    /* Don't expire anything while loading. It will be done later. */
    -    if (server.loading) return 0;
    +    redis系列介绍八-淘汰策略
    +    /2020/04/18/redis%E7%B3%BB%E5%88%97%E4%BB%8B%E7%BB%8D%E5%85%AB/
    +    LRU

    说完了过期策略再说下淘汰策略,redis 使用的策略是近似的 lru 策略,为什么是近似的呢,先来看下什么是 lru,看下 wiki 的介绍
    ,图中一共有四个槽的存储空间,依次访问顺序是 A B C D E D F,
    当第一次访问 D 时刚好占满了坑,并且值是 4,这个值越小代表越先被淘汰,当 E 进来时,看了下已经存在的四个里 A 是最小的,代表是最早存在并且最早被访问的,那就先淘汰它了,E 占领了 A 的位置,并设置值为 4,然后又访问 D 了,D 已经存在了,不过又被访问到了,得更新值为 5,然后是 F 进来了,这时 B 是最老的且最近未被访问,所以就淘汰它了。以上是一个 lru 的简要说明,但是 redis 没有严格按照这个去执行,理由跟前面过期策略一致,最严格的过期策略应该是每个 key 都有对应的定时器,当超时时马上就能清除,但是问题是这样的cpu 消耗太大,所换来的内存效率不太值得,淘汰策略也是这样,类似于上图,要维护所有 key 的一个有序 lru 值,并且遍历将最小的淘汰,redis 采用的是抽样的形式,最初的实现方式是随机从 dict 抽取 5 个 key,淘汰一个 lru 最小的,这样子勉强能达到淘汰的目的,但是效果不是特别好,后面在 redis 3.0开始,将随机抽取改成了维护一个 pool,pool 的大小默认是 16,每次放入的都是按lru 值有序排列好,每一次放入的必须是 lru小于 pool 中最小的 lru 才允许放入,直到放满,后面再有新的就会将大的踢出。
    redis 针对这个策略的改进做了一个实验,这里借用下图

    首先背景是这图中的所有点都对应一个 redis 的 key,灰色部分加入后被顺序访问过一遍,然后又加入了绿色部分,那么按照理论的 lru 算法,应该是图左上中,浅灰色部分全都被淘汰,那么对比来看看图右上,左下和右下,左下表示 2.8 版本就是随机抽样 5 个 key,淘汰其中 lru 最小的一个,发现是灰色和浅灰色的都有被淘汰的,右下的 3.0 版本抽样数量不变的情况下,稍好一些,当 3.0 版本的抽样数量调整成 10 后,已经较为接近理论上的 lru 策略了,通过代码来简要分析下

    +
    typedef struct redisObject {
    +    unsigned type:4;
    +    unsigned encoding:4;
    +    unsigned lru:LRU_BITS; /* LRU time (relative to global lru_clock) or
    +                            * LFU data (least significant 8 bits frequency
    +                            * and most significant 16 bits access time). */
    +    int refcount;
    +    void *ptr;
    +} robj;
    +

    对于 lru 策略来说,lru 字段记录的就是redisObj 的LRU time,
    redis 在访问数据时,都会调用lookupKey方法

    +
    /* Low level key lookup API, not actually called directly from commands
    + * implementations that should instead rely on lookupKeyRead(),
    + * lookupKeyWrite() and lookupKeyReadWithFlags(). */
    +robj *lookupKey(redisDb *db, robj *key, int flags) {
    +    dictEntry *de = dictFind(db->dict,key->ptr);
    +    if (de) {
    +        robj *val = dictGetVal(de);
     
    -    /* If we are in the context of a Lua script, we pretend that time is
    -     * blocked to when the Lua script started. This way a key can expire
    -     * only the first time it is accessed and not in the middle of the
    -     * script execution, making propagation to slaves / AOF consistent.
    -     * See issue #1525 on Github for more information. */
    -    if (server.lua_caller) {
    -        now = server.lua_time_start;
    -    }
    -    /* If we are in the middle of a command execution, we still want to use
    -     * a reference time that does not change: in that case we just use the
    -     * cached time, that we update before each call in the call() function.
    -     * This way we avoid that commands such as RPOPLPUSH or similar, that
    -     * may re-open the same key multiple times, can invalidate an already
    -     * open object in a next call, if the next call will see the key expired,
    -     * while the first did not. */
    -    else if (server.fixed_time_expire > 0) {
    -        now = server.mstime;
    -    }
    -    /* For the other cases, we want to use the most fresh time we have. */
    -    else {
    -        now = mstime();
    +        /* Update the access time for the ageing algorithm.
    +         * Don't do it if we have a saving child, as this will trigger
    +         * a copy on write madness. */
    +        if (!hasActiveChildProcess() && !(flags & LOOKUP_NOTOUCH)){
    +            if (server.maxmemory_policy & MAXMEMORY_FLAG_LFU) {
    +                // 这个是后面一节的内容
    +                updateLFU(val);
    +            } else {
    +                //  对于这个分支,访问时就会去更新 lru 值
    +                val->lru = LRU_CLOCK();
    +            }
    +        }
    +        return val;
    +    } else {
    +        return NULL;
         }
    -
    -    /* The key expired if the current (virtual or real) time is greater
    -     * than the expire time of the key. */
    -    return now > when;
     }
    -/* Return the expire time of the specified key, or -1 if no expire
    - * is associated with this key (i.e. the key is non volatile) */
    -long long getExpire(redisDb *db, robj *key) {
    -    dictEntry *de;
    -
    -    /* No expire? return ASAP */
    -    if (dictSize(db->expires) == 0 ||
    -       (de = dictFind(db->expires,key->ptr)) == NULL) return -1;
    -
    -    /* The entry was found in the expire dict, this means it should also
    -     * be present in the main dict (safety check). */
    -    serverAssertWithInfo(NULL,key,dictFind(db->dict,key->ptr) != NULL);
    -    return dictGetSignedIntegerVal(de);
    -}
    -

    这里有几点要注意的,第一是当惰性删除时会根据lazyfree_lazy_expire这个参数去判断是执行同步删除还是异步删除,另外一点是对于 slave,是不需要执行的,因为会在 master 过期时向 slave 发送 del 指令。
    光采用这个策略会有什么问题呢,假如一些key 一直未被访问,那这些 key 就不会过期了,导致一直被占用着内存,所以 redis 采取了懒汉式过期加定期过期策略,定期策略是怎么执行的呢

    -
    /* This function handles 'background' operations we are required to do
    - * incrementally in Redis databases, such as active key expiring, resizing,
    - * rehashing. */
    -void databasesCron(void) {
    -    /* Expire keys by random sampling. Not required for slaves
    -     * as master will synthesize DELs for us. */
    -    if (server.active_expire_enabled) {
    -        if (server.masterhost == NULL) {
    -            activeExpireCycle(ACTIVE_EXPIRE_CYCLE_SLOW);
    -        } else {
    -            expireSlaveKeys();
    -        }
    +/* This function is used to obtain the current LRU clock.
    + * If the current resolution is lower than the frequency we refresh the
    + * LRU clock (as it should be in production servers) we return the
    + * precomputed value, otherwise we need to resort to a system call. */
    +unsigned int LRU_CLOCK(void) {
    +    unsigned int lruclock;
    +    if (1000/server.hz <= LRU_CLOCK_RESOLUTION) {
    +        // 如果服务器的频率server.hz大于 1 时就是用系统预设的 lruclock
    +        lruclock = server.lruclock;
    +    } else {
    +        lruclock = getLRUClock();
         }
    +    return lruclock;
    +}
    +/* Return the LRU clock, based on the clock resolution. This is a time
    + * in a reduced-bits format that can be used to set and check the
    + * object->lru field of redisObject structures. */
    +unsigned int getLRUClock(void) {
    +    return (mstime()/LRU_CLOCK_RESOLUTION) & LRU_CLOCK_MAX;
    +}
    +

    redis 处理命令是在这里processCommand

    +
    /* If this function gets called we already read a whole
    + * command, arguments are in the client argv/argc fields.
    + * processCommand() execute the command or prepare the
    + * server for a bulk read from the client.
    + *
    + * If C_OK is returned the client is still alive and valid and
    + * other operations can be performed by the caller. Otherwise
    + * if C_ERR is returned the client was destroyed (i.e. after QUIT). */
    +int processCommand(client *c) {
    +    moduleCallCommandFilters(c);
     
    -    /* Defrag keys gradually. */
    -    activeDefragCycle();
    -
    -    /* Perform hash tables rehashing if needed, but only if there are no
    -     * other processes saving the DB on disk. Otherwise rehashing is bad
    -     * as will cause a lot of copy-on-write of memory pages. */
    -    if (!hasActiveChildProcess()) {
    -        /* We use global counters so if we stop the computation at a given
    -         * DB we'll be able to start from the successive in the next
    -         * cron loop iteration. */
    -        static unsigned int resize_db = 0;
    -        static unsigned int rehash_db = 0;
    -        int dbs_per_call = CRON_DBS_PER_CALL;
    -        int j;
    -
    -        /* Don't test more DBs than we have. */
    -        if (dbs_per_call > server.dbnum) dbs_per_call = server.dbnum;
    +    
     
    -        /* Resize */
    -        for (j = 0; j < dbs_per_call; j++) {
    -            tryResizeHashTables(resize_db % server.dbnum);
    -            resize_db++;
    -        }
    +    /* Handle the maxmemory directive.
    +     *
    +     * Note that we do not want to reclaim memory if we are here re-entering
    +     * the event loop since there is a busy Lua script running in timeout
    +     * condition, to avoid mixing the propagation of scripts with the
    +     * propagation of DELs due to eviction. */
    +    if (server.maxmemory && !server.lua_timedout) {
    +        int out_of_memory = freeMemoryIfNeededAndSafe() == C_ERR;
    +        /* freeMemoryIfNeeded may flush slave output buffers. This may result
    +         * into a slave, that may be the active client, to be freed. */
    +        if (server.current_client == NULL) return C_ERR;
     
    -        /* Rehash */
    -        if (server.activerehashing) {
    -            for (j = 0; j < dbs_per_call; j++) {
    -                int work_done = incrementallyRehash(rehash_db);
    -                if (work_done) {
    -                    /* If the function did some work, stop here, we'll do
    -                     * more at the next cron loop. */
    -                    break;
    -                } else {
    -                    /* If this db didn't need rehash, we'll try the next one. */
    -                    rehash_db++;
    -                    rehash_db %= server.dbnum;
    -                }
    -            }
    +        /* It was impossible to free enough memory, and the command the client
    +         * is trying to execute is denied during OOM conditions or the client
    +         * is in MULTI/EXEC context? Error. */
    +        if (out_of_memory &&
    +            (c->cmd->flags & CMD_DENYOOM ||
    +             (c->flags & CLIENT_MULTI &&
    +              c->cmd->proc != execCommand &&
    +              c->cmd->proc != discardCommand)))
    +        {
    +            flagTransaction(c);
    +            addReply(c, shared.oomerr);
    +            return C_OK;
             }
         }
    -}
    -/* Try to expire a few timed out keys. The algorithm used is adaptive and
    - * will use few CPU cycles if there are few expiring keys, otherwise
    - * it will get more aggressive to avoid that too much memory is used by
    - * keys that can be removed from the keyspace.
    - *
    - * Every expire cycle tests multiple databases: the next call will start
    - * again from the next db, with the exception of exists for time limit: in that
    - * case we restart again from the last database we were processing. Anyway
    - * no more than CRON_DBS_PER_CALL databases are tested at every iteration.
    - *
    - * The function can perform more or less work, depending on the "type"
    - * argument. It can execute a "fast cycle" or a "slow cycle". The slow
    - * cycle is the main way we collect expired cycles: this happens with
    - * the "server.hz" frequency (usually 10 hertz).
    - *
    - * However the slow cycle can exit for timeout, since it used too much time.
    - * For this reason the function is also invoked to perform a fast cycle
    - * at every event loop cycle, in the beforeSleep() function. The fast cycle
    - * will try to perform less work, but will do it much more often.
    - *
    - * The following are the details of the two expire cycles and their stop
    - * conditions:
    - *
    - * If type is ACTIVE_EXPIRE_CYCLE_FAST the function will try to run a
    - * "fast" expire cycle that takes no longer than EXPIRE_FAST_CYCLE_DURATION
    - * microseconds, and is not repeated again before the same amount of time.
    - * The cycle will also refuse to run at all if the latest slow cycle did not
    - * terminate because of a time limit condition.
    +}
    +

    这里只摘了部分,当需要清理内存时就会调用, 然后调用了freeMemoryIfNeededAndSafe

    +
    /* This is a wrapper for freeMemoryIfNeeded() that only really calls the
    + * function if right now there are the conditions to do so safely:
      *
    - * If type is ACTIVE_EXPIRE_CYCLE_SLOW, that normal expire cycle is
    - * executed, where the time limit is a percentage of the REDIS_HZ period
    - * as specified by the ACTIVE_EXPIRE_CYCLE_SLOW_TIME_PERC define. In the
    - * fast cycle, the check of every database is interrupted once the number
    - * of already expired keys in the database is estimated to be lower than
    - * a given percentage, in order to avoid doing too much work to gain too
    - * little memory.
    + * - There must be no script in timeout condition.
    + * - Nor we are loading data right now.
      *
    - * The configured expire "effort" will modify the baseline parameters in
    - * order to do more work in both the fast and slow expire cycles.
      */
    +int freeMemoryIfNeededAndSafe(void) {
    +    if (server.lua_timedout || server.loading) return C_OK;
    +    return freeMemoryIfNeeded();
    +}
    +/* This function is periodically called to see if there is memory to free
    + * according to the current "maxmemory" settings. In case we are over the
    + * memory limit, the function will try to free some memory to return back
    + * under the limit.
    + *
    + * The function returns C_OK if we are under the memory limit or if we
    + * were over the limit, but the attempt to free memory was successful.
    + * Otehrwise if we are over the memory limit, but not enough memory
    + * was freed to return back under the limit, the function returns C_ERR. */
    +int freeMemoryIfNeeded(void) {
    +    int keys_freed = 0;
    +    /* By default replicas should ignore maxmemory
    +     * and just be masters exact copies. */
    +    if (server.masterhost && server.repl_slave_ignore_maxmemory) return C_OK;
     
    -#define ACTIVE_EXPIRE_CYCLE_KEYS_PER_LOOP 20 /* Keys for each DB loop. */
    -#define ACTIVE_EXPIRE_CYCLE_FAST_DURATION 1000 /* Microseconds. */
    -#define ACTIVE_EXPIRE_CYCLE_SLOW_TIME_PERC 25 /* Max % of CPU to use. */
    -#define ACTIVE_EXPIRE_CYCLE_ACCEPTABLE_STALE 10 /* % of stale keys after which
    -                                                   we do extra efforts. */
    -void activeExpireCycle(int type) {
    -    /* Adjust the running parameters according to the configured expire
    -     * effort. The default effort is 1, and the maximum configurable effort
    -     * is 10. */
    -    unsigned long
    -    effort = server.active_expire_effort-1, /* Rescale from 0 to 9. */
    -    config_keys_per_loop = ACTIVE_EXPIRE_CYCLE_KEYS_PER_LOOP +
    -                           ACTIVE_EXPIRE_CYCLE_KEYS_PER_LOOP/4*effort,
    -    config_cycle_fast_duration = ACTIVE_EXPIRE_CYCLE_FAST_DURATION +
    -                                 ACTIVE_EXPIRE_CYCLE_FAST_DURATION/4*effort,
    -    config_cycle_slow_time_perc = ACTIVE_EXPIRE_CYCLE_SLOW_TIME_PERC +
    -                                  2*effort,
    -    config_cycle_acceptable_stale = ACTIVE_EXPIRE_CYCLE_ACCEPTABLE_STALE-
    -                                    effort;
    -
    -    /* This function has some global state in order to continue the work
    -     * incrementally across calls. */
    -    static unsigned int current_db = 0; /* Last DB tested. */
    -    static int timelimit_exit = 0;      /* Time limit hit in previous call? */
    -    static long long last_fast_cycle = 0; /* When last fast cycle ran. */
    -
    -    int j, iteration = 0;
    -    int dbs_per_call = CRON_DBS_PER_CALL;
    -    long long start = ustime(), timelimit, elapsed;
    +    size_t mem_reported, mem_tofree, mem_freed;
    +    mstime_t latency, eviction_latency;
    +    long long delta;
    +    int slaves = listLength(server.slaves);
     
         /* When clients are paused the dataset should be static not just from the
          * POV of clients not being able to write, but also from the POV of
          * expires and evictions of keys not being performed. */
    -    if (clientsArePaused()) return;
    -
    -    if (type == ACTIVE_EXPIRE_CYCLE_FAST) {
    -        /* Don't start a fast cycle if the previous cycle did not exit
    -         * for time limit, unless the percentage of estimated stale keys is
    -         * too high. Also never repeat a fast cycle for the same period
    -         * as the fast cycle total duration itself. */
    -        if (!timelimit_exit &&
    -            server.stat_expired_stale_perc < config_cycle_acceptable_stale)
    -            return;
    +    if (clientsArePaused()) return C_OK;
    +    if (getMaxmemoryState(&mem_reported,NULL,&mem_tofree,NULL) == C_OK)
    +        return C_OK;
     
    -        if (start < last_fast_cycle + (long long)config_cycle_fast_duration*2)
    -            return;
    +    mem_freed = 0;
     
    -        last_fast_cycle = start;
    -    }
    +    if (server.maxmemory_policy == MAXMEMORY_NO_EVICTION)
    +        goto cant_free; /* We need to free memory, but policy forbids. */
     
    -    /* We usually should test CRON_DBS_PER_CALL per iteration, with
    -     * two exceptions:
    -     *
    -     * 1) Don't test more DBs than we have.
    -     * 2) If last time we hit the time limit, we want to scan all DBs
    -     * in this iteration, as there is work to do in some DB and we don't want
    -     * expired keys to use memory for too much time. */
    -    if (dbs_per_call > server.dbnum || timelimit_exit)
    -        dbs_per_call = server.dbnum;
    +    latencyStartMonitor(latency);
    +    while (mem_freed < mem_tofree) {
    +        int j, k, i;
    +        static unsigned int next_db = 0;
    +        sds bestkey = NULL;
    +        int bestdbid;
    +        redisDb *db;
    +        dict *dict;
    +        dictEntry *de;
     
    -    /* We can use at max 'config_cycle_slow_time_perc' percentage of CPU
    -     * time per iteration. Since this function gets called with a frequency of
    -     * server.hz times per second, the following is the max amount of
    -     * microseconds we can spend in this function. */
    -    timelimit = config_cycle_slow_time_perc*1000000/server.hz/100;
    -    timelimit_exit = 0;
    -    if (timelimit <= 0) timelimit = 1;
    +        if (server.maxmemory_policy & (MAXMEMORY_FLAG_LRU|MAXMEMORY_FLAG_LFU) ||
    +            server.maxmemory_policy == MAXMEMORY_VOLATILE_TTL)
    +        {
    +            struct evictionPoolEntry *pool = EvictionPoolLRU;
     
    -    if (type == ACTIVE_EXPIRE_CYCLE_FAST)
    -        timelimit = config_cycle_fast_duration; /* in microseconds. */
    +            while(bestkey == NULL) {
    +                unsigned long total_keys = 0, keys;
     
    -    /* Accumulate some global stats as we expire keys, to have some idea
    -     * about the number of keys that are already logically expired, but still
    -     * existing inside the database. */
    -    long total_sampled = 0;
    -    long total_expired = 0;
    +                /* We don't want to make local-db choices when expiring keys,
    +                 * so to start populate the eviction pool sampling keys from
    +                 * every DB. */
    +                for (i = 0; i < server.dbnum; i++) {
    +                    db = server.db+i;
    +                    dict = (server.maxmemory_policy & MAXMEMORY_FLAG_ALLKEYS) ?
    +                            db->dict : db->expires;
    +                    if ((keys = dictSize(dict)) != 0) {
    +                        evictionPoolPopulate(i, dict, db->dict, pool);
    +                        total_keys += keys;
    +                    }
    +                }
    +                if (!total_keys) break; /* No keys to evict. */
     
    -    for (j = 0; j < dbs_per_call && timelimit_exit == 0; j++) {
    -        /* Expired and checked in a single loop. */
    -        unsigned long expired, sampled;
    +                /* Go backward from best to worst element to evict. */
    +                for (k = EVPOOL_SIZE-1; k >= 0; k--) {
    +                    if (pool[k].key == NULL) continue;
    +                    bestdbid = pool[k].dbid;
     
    -        redisDb *db = server.db+(current_db % server.dbnum);
    +                    if (server.maxmemory_policy & MAXMEMORY_FLAG_ALLKEYS) {
    +                        de = dictFind(server.db[pool[k].dbid].dict,
    +                            pool[k].key);
    +                    } else {
    +                        de = dictFind(server.db[pool[k].dbid].expires,
    +                            pool[k].key);
    +                    }
     
    -        /* Increment the DB now so we are sure if we run out of time
    -         * in the current DB we'll restart from the next. This allows to
    -         * distribute the time evenly across DBs. */
    -        current_db++;
    +                    /* Remove the entry from the pool. */
    +                    if (pool[k].key != pool[k].cached)
    +                        sdsfree(pool[k].key);
    +                    pool[k].key = NULL;
    +                    pool[k].idle = 0;
     
    -        /* Continue to expire if at the end of the cycle more than 25%
    -         * of the keys were expired. */
    -        do {
    -            unsigned long num, slots;
    -            long long now, ttl_sum;
    -            int ttl_samples;
    -            iteration++;
    +                    /* If the key exists, is our pick. Otherwise it is
    +                     * a ghost and we need to try the next element. */
    +                    if (de) {
    +                        bestkey = dictGetKey(de);
    +                        break;
    +                    } else {
    +                        /* Ghost... Iterate again. */
    +                    }
    +                }
    +            }
    +        }
     
    -            /* If there is nothing to expire try next DB ASAP. */
    -            if ((num = dictSize(db->expires)) == 0) {
    -                db->avg_ttl = 0;
    -                break;
    +        /* volatile-random and allkeys-random policy */
    +        else if (server.maxmemory_policy == MAXMEMORY_ALLKEYS_RANDOM ||
    +                 server.maxmemory_policy == MAXMEMORY_VOLATILE_RANDOM)
    +        {
    +            /* When evicting a random key, we try to evict a key for
    +             * each DB, so we use the static 'next_db' variable to
    +             * incrementally visit all DBs. */
    +            for (i = 0; i < server.dbnum; i++) {
    +                j = (++next_db) % server.dbnum;
    +                db = server.db+j;
    +                dict = (server.maxmemory_policy == MAXMEMORY_ALLKEYS_RANDOM) ?
    +                        db->dict : db->expires;
    +                if (dictSize(dict) != 0) {
    +                    de = dictGetRandomKey(dict);
    +                    bestkey = dictGetKey(de);
    +                    bestdbid = j;
    +                    break;
    +                }
                 }
    -            slots = dictSlots(db->expires);
    -            now = mstime();
    +        }
     
    -            /* When there are less than 1% filled slots, sampling the key
    -             * space is expensive, so stop here waiting for better times...
    -             * The dictionary will be resized asap. */
    -            if (num && slots > DICT_HT_INITIAL_SIZE &&
    -                (num*100/slots < 1)) break;
    +        /* Finally remove the selected key. */
    +        if (bestkey) {
    +            db = server.db+bestdbid;
    +            robj *keyobj = createStringObject(bestkey,sdslen(bestkey));
    +            propagateExpire(db,keyobj,server.lazyfree_lazy_eviction);
    +            /* We compute the amount of memory freed by db*Delete() alone.
    +             * It is possible that actually the memory needed to propagate
    +             * the DEL in AOF and replication link is greater than the one
    +             * we are freeing removing the key, but we can't account for
    +             * that otherwise we would never exit the loop.
    +             *
    +             * AOF and Output buffer memory will be freed eventually so
    +             * we only care about memory used by the key space. */
    +            delta = (long long) zmalloc_used_memory();
    +            latencyStartMonitor(eviction_latency);
    +            if (server.lazyfree_lazy_eviction)
    +                dbAsyncDelete(db,keyobj);
    +            else
    +                dbSyncDelete(db,keyobj);
    +            latencyEndMonitor(eviction_latency);
    +            latencyAddSampleIfNeeded("eviction-del",eviction_latency);
    +            latencyRemoveNestedEvent(latency,eviction_latency);
    +            delta -= (long long) zmalloc_used_memory();
    +            mem_freed += delta;
    +            server.stat_evictedkeys++;
    +            notifyKeyspaceEvent(NOTIFY_EVICTED, "evicted",
    +                keyobj, db->id);
    +            decrRefCount(keyobj);
    +            keys_freed++;
     
    -            /* The main collection cycle. Sample random keys among keys
    -             * with an expire set, checking for expired ones. */
    -            expired = 0;
    -            sampled = 0;
    -            ttl_sum = 0;
    -            ttl_samples = 0;
    +            /* When the memory to free starts to be big enough, we may
    +             * start spending so much time here that is impossible to
    +             * deliver data to the slaves fast enough, so we force the
    +             * transmission here inside the loop. */
    +            if (slaves) flushSlavesOutputBuffers();
     
    -            if (num > config_keys_per_loop)
    -                num = config_keys_per_loop;
    +            /* Normally our stop condition is the ability to release
    +             * a fixed, pre-computed amount of memory. However when we
    +             * are deleting objects in another thread, it's better to
    +             * check, from time to time, if we already reached our target
    +             * memory, since the "mem_freed" amount is computed only
    +             * across the dbAsyncDelete() call, while the thread can
    +             * release the memory all the time. */
    +            if (server.lazyfree_lazy_eviction && !(keys_freed % 16)) {
    +                if (getMaxmemoryState(NULL,NULL,NULL,NULL) == C_OK) {
    +                    /* Let's satisfy our stop condition. */
    +                    mem_freed = mem_tofree;
    +                }
    +            }
    +        } else {
    +            latencyEndMonitor(latency);
    +            latencyAddSampleIfNeeded("eviction-cycle",latency);
    +            goto cant_free; /* nothing to free... */
    +        }
    +    }
    +    latencyEndMonitor(latency);
    +    latencyAddSampleIfNeeded("eviction-cycle",latency);
    +    return C_OK;
     
    -            /* Here we access the low level representation of the hash table
    -             * for speed concerns: this makes this code coupled with dict.c,
    -             * but it hardly changed in ten years.
    -             *
    -             * Note that certain places of the hash table may be empty,
    -             * so we want also a stop condition about the number of
    -             * buckets that we scanned. However scanning for free buckets
    -             * is very fast: we are in the cache line scanning a sequential
    -             * array of NULL pointers, so we can scan a lot more buckets
    -             * than keys in the same time. */
    -            long max_buckets = num*20;
    -            long checked_buckets = 0;
    +cant_free:
    +    /* We are here if we are not able to reclaim memory. There is only one
    +     * last thing we can try: check if the lazyfree thread has jobs in queue
    +     * and wait... */
    +    while(bioPendingJobsOfType(BIO_LAZY_FREE)) {
    +        if (((mem_reported - zmalloc_used_memory()) + mem_freed) >= mem_tofree)
    +            break;
    +        usleep(1000);
    +    }
    +    return C_ERR;
    +}
    +

    这里就是根据具体策略去淘汰 key,首先是要往 pool 更新 key,更新key 的方法是evictionPoolPopulate

    +
    void evictionPoolPopulate(int dbid, dict *sampledict, dict *keydict, struct evictionPoolEntry *pool) {
    +    int j, k, count;
    +    dictEntry *samples[server.maxmemory_samples];
     
    -            while (sampled < num && checked_buckets < max_buckets) {
    -                for (int table = 0; table < 2; table++) {
    -                    if (table == 1 && !dictIsRehashing(db->expires)) break;
    +    count = dictGetSomeKeys(sampledict,samples,server.maxmemory_samples);
    +    for (j = 0; j < count; j++) {
    +        unsigned long long idle;
    +        sds key;
    +        robj *o;
    +        dictEntry *de;
     
    -                    unsigned long idx = db->expires_cursor;
    -                    idx &= db->expires->ht[table].sizemask;
    -                    dictEntry *de = db->expires->ht[table].table[idx];
    -                    long long ttl;
    +        de = samples[j];
    +        key = dictGetKey(de);
     
    -                    /* Scan the current bucket of the current table. */
    -                    checked_buckets++;
    -                    while(de) {
    -                        /* Get the next entry now since this entry may get
    -                         * deleted. */
    -                        dictEntry *e = de;
    -                        de = de->next;
    +        /* If the dictionary we are sampling from is not the main
    +         * dictionary (but the expires one) we need to lookup the key
    +         * again in the key dictionary to obtain the value object. */
    +        if (server.maxmemory_policy != MAXMEMORY_VOLATILE_TTL) {
    +            if (sampledict != keydict) de = dictFind(keydict, key);
    +            o = dictGetVal(de);
    +        }
     
    -                        ttl = dictGetSignedIntegerVal(e)-now;
    -                        if (activeExpireCycleTryExpire(db,e,now)) expired++;
    -                        if (ttl > 0) {
    -                            /* We want the average TTL of keys yet
    -                             * not expired. */
    -                            ttl_sum += ttl;
    -                            ttl_samples++;
    -                        }
    -                        sampled++;
    -                    }
    -                }
    -                db->expires_cursor++;
    -            }
    -            total_expired += expired;
    -            total_sampled += sampled;
    +        /* Calculate the idle time according to the policy. This is called
    +         * idle just because the code initially handled LRU, but is in fact
    +         * just a score where an higher score means better candidate. */
    +        if (server.maxmemory_policy & MAXMEMORY_FLAG_LRU) {
    +            idle = estimateObjectIdleTime(o);
    +        } else if (server.maxmemory_policy & MAXMEMORY_FLAG_LFU) {
    +            /* When we use an LRU policy, we sort the keys by idle time
    +             * so that we expire keys starting from greater idle time.
    +             * However when the policy is an LFU one, we have a frequency
    +             * estimation, and we want to evict keys with lower frequency
    +             * first. So inside the pool we put objects using the inverted
    +             * frequency subtracting the actual frequency to the maximum
    +             * frequency of 255. */
    +            idle = 255-LFUDecrAndReturn(o);
    +        } else if (server.maxmemory_policy == MAXMEMORY_VOLATILE_TTL) {
    +            /* In this case the sooner the expire the better. */
    +            idle = ULLONG_MAX - (long)dictGetVal(de);
    +        } else {
    +            serverPanic("Unknown eviction policy in evictionPoolPopulate()");
    +        }
     
    -            /* Update the average TTL stats for this database. */
    -            if (ttl_samples) {
    -                long long avg_ttl = ttl_sum/ttl_samples;
    +        /* Insert the element inside the pool.
    +         * First, find the first empty bucket or the first populated
    +         * bucket that has an idle time smaller than our idle time. */
    +        k = 0;
    +        while (k < EVPOOL_SIZE &&
    +               pool[k].key &&
    +               pool[k].idle < idle) k++;
    +        if (k == 0 && pool[EVPOOL_SIZE-1].key != NULL) {
    +            /* Can't insert if the element is < the worst element we have
    +             * and there are no empty buckets. */
    +            continue;
    +        } else if (k < EVPOOL_SIZE && pool[k].key == NULL) {
    +            /* Inserting into empty position. No setup needed before insert. */
    +        } else {
    +            /* Inserting in the middle. Now k points to the first element
    +             * greater than the element to insert.  */
    +            if (pool[EVPOOL_SIZE-1].key == NULL) {
    +                /* Free space on the right? Insert at k shifting
    +                 * all the elements from k to end to the right. */
     
    -                /* Do a simple running average with a few samples.
    -                 * We just use the current estimate with a weight of 2%
    -                 * and the previous estimate with a weight of 98%. */
    -                if (db->avg_ttl == 0) db->avg_ttl = avg_ttl;
    -                db->avg_ttl = (db->avg_ttl/50)*49 + (avg_ttl/50);
    +                /* Save SDS before overwriting. */
    +                sds cached = pool[EVPOOL_SIZE-1].cached;
    +                memmove(pool+k+1,pool+k,
    +                    sizeof(pool[0])*(EVPOOL_SIZE-k-1));
    +                pool[k].cached = cached;
    +            } else {
    +                /* No free space on right? Insert at k-1 */
    +                k--;
    +                /* Shift all elements on the left of k (included) to the
    +                 * left, so we discard the element with smaller idle time. */
    +                sds cached = pool[0].cached; /* Save SDS before overwriting. */
    +                if (pool[0].key != pool[0].cached) sdsfree(pool[0].key);
    +                memmove(pool,pool+1,sizeof(pool[0])*k);
    +                pool[k].cached = cached;
                 }
    +        }
     
    -            /* We can't block forever here even if there are many keys to
    -             * expire. So after a given amount of milliseconds return to the
    -             * caller waiting for the other active expire cycle. */
    -            if ((iteration & 0xf) == 0) { /* check once every 16 iterations. */
    -                elapsed = ustime()-start;
    -                if (elapsed > timelimit) {
    -                    timelimit_exit = 1;
    -                    server.stat_expired_time_cap_reached_count++;
    -                    break;
    -                }
    -            }
    -            /* We don't repeat the cycle for the current database if there are
    -             * an acceptable amount of stale keys (logically expired but yet
    -             * not reclained). */
    -        } while ((expired*100/sampled) > config_cycle_acceptable_stale);
    +        /* Try to reuse the cached SDS string allocated in the pool entry,
    +         * because allocating and deallocating this object is costly
    +         * (according to the profiler, not my fantasy. Remember:
    +         * premature optimizbla bla bla bla. */
    +        int klen = sdslen(key);
    +        if (klen > EVPOOL_CACHED_SDS_SIZE) {
    +            pool[k].key = sdsdup(key);
    +        } else {
    +            memcpy(pool[k].cached,key,klen+1);
    +            sdssetlen(pool[k].cached,klen);
    +            pool[k].key = pool[k].cached;
    +        }
    +        pool[k].idle = idle;
    +        pool[k].dbid = dbid;
         }
    +}
    +

    Redis随机选择maxmemory_samples数量的key,然后计算这些key的空闲时间idle time,当满足条件时(比pool中的某些键的空闲时间还大)就可以进poolpool更新之后,就淘汰pool中空闲时间最大的键。

    +

    estimateObjectIdleTime用来计算Redis对象的空闲时间:

    +
    /* Given an object returns the min number of milliseconds the object was never
    + * requested, using an approximated LRU algorithm. */
    +unsigned long long estimateObjectIdleTime(robj *o) {
    +    unsigned long long lruclock = LRU_CLOCK();
    +    if (lruclock >= o->lru) {
    +        return (lruclock - o->lru) * LRU_CLOCK_RESOLUTION;
    +    } else {
    +        return (lruclock + (LRU_CLOCK_MAX - o->lru)) *
    +                    LRU_CLOCK_RESOLUTION;
    +    }
    +}
    +

    空闲时间第一种是 lurclock 大于对象的 lru,那么就是减一下乘以精度,因为 lruclock 有可能是已经预生成的,所以会可能走下面这个

    +

    LFU

    上面介绍了LRU 的算法,但是考虑一种场景

    +
    ~~~~~A~~~~~A~~~~~A~~~~A~~~~~A~~~~~A~~|
    +~~B~~B~~B~~B~~B~~B~~B~~B~~B~~B~~B~~B~|
    +~~~~~~~~~~C~~~~~~~~~C~~~~~~~~~C~~~~~~|
    +~~~~~D~~~~~~~~~~D~~~~~~~~~D~~~~~~~~~D|
    +

    可以发现,当采用 lru 的淘汰策略的时候,D 是最新的,会被认为是最值得保留的,但是事实上还不如 A 跟 B,然后 antirez 大神就想到了LFU (Least Frequently Used) 这个算法, 显然对于上面的四个 key 的访问频率,保留优先级应该是 B > A > C = D
    那要怎么来实现这个 LFU 算法呢,其实像LRU,理想的情况就是维护个链表,把最新访问的放到头上去,但是这个会影响访问速度,注意到前面代码的应该可以看到,redisObject 的 lru 字段其实是两用的,当策略是 LFU 时,这个字段就另作他用了,它的 24 位长度被分成两部分

    +
          16 bits      8 bits
    ++----------------+--------+
    ++ Last decr time | LOG_C  |
    ++----------------+--------+
    +

    前16位字段是最后一次递减时间,因此Redis知道 上一次计数器递减,后8位是 计数器 counter。
    LFU 的主体策略就是当这个 key 被访问的次数越多频率越高他就越容易被保留下来,并且是最近被访问的频率越高。这其实有两个事情要做,一个是在访问的时候增加计数值,在一定长时间不访问时进行衰减,所以这里用了两个值,前 16 位记录上一次衰减的时间,后 8 位记录具体的计数值。
    Redis4.0之后为maxmemory_policy淘汰策略添加了两个LFU模式:

    +

    volatile-lfu:对有过期时间的key采用LFU淘汰策略
    allkeys-lfu:对全部key采用LFU淘汰策略
    还有2个配置可以调整LFU算法:

    +
    lfu-log-factor 10
    +lfu-decay-time 1
    +```  
    +`lfu-log-factor` 可以调整计数器counter的增长速度,lfu-log-factor越大,counter增长的越慢。
     
    -    elapsed = ustime()-start;
    -    server.stat_expire_cycle_time_used += elapsed;
    -    latencyAddSampleIfNeeded("expire-cycle",elapsed/1000);
    -
    -    /* Update our estimate of keys existing but yet to be expired.
    -     * Running average with this sample accounting for 5%. */
    -    double current_perc;
    -    if (total_sampled) {
    -        current_perc = (double)total_expired/total_sampled;
    -    } else
    -        current_perc = 0;
    -    server.stat_expired_stale_perc = (current_perc*0.05)+
    -                                     (server.stat_expired_stale_perc*0.95);
    -}
    -

    执行定期清除分成两种类型,快和慢,分别由beforeSleepdatabasesCron调用,快版有两个限制,一个是执行时长由ACTIVE_EXPIRE_CYCLE_FAST_DURATION限制,另一个是执行间隔是 2 倍的ACTIVE_EXPIRE_CYCLE_FAST_DURATION,另外这还可以由配置的server.active_expire_effort参数来控制,默认是 1,最大是 10

    -
    onfig_cycle_fast_duration = ACTIVE_EXPIRE_CYCLE_FAST_DURATION +
    -                                 ACTIVE_EXPIRE_CYCLE_FAST_DURATION/4*effort
    -

    然后会从一定数量的 db 中找出一定数量的带过期时间的 key(保存在 expires中),这里的数量是由

    -
    config_keys_per_loop = ACTIVE_EXPIRE_CYCLE_KEYS_PER_LOOP +
    -                           ACTIVE_EXPIRE_CYCLE_KEYS_PER_LOOP/4*effort
    -```                                 
    -控制,慢速的执行时长是
    +`lfu-decay-time`是一个以分钟为单位的数值,可以调整counter的减少速度
    +这里有个问题是 8 位大小够计么,访问一次加 1 的话的确不够,不过大神就是大神,才不会这么简单的加一。往下看代码
     ```C
    -config_cycle_slow_time_perc = ACTIVE_EXPIRE_CYCLE_SLOW_TIME_PERC +
    -                                  2*effort
    -timelimit = config_cycle_slow_time_perc*1000000/server.hz/100;
    -

    这里还有一个额外的退出条件,如果当前数据库的抽样结果已经达到我们所允许的过期 key 百分比,则下次不再处理当前 db,继续处理下个 db

    -]]>
    - - Redis - 数据结构 - C - 源码 - Redis - - - redis - 数据结构 - 源码 - - - - redis系列介绍八-淘汰策略 - /2020/04/18/redis%E7%B3%BB%E5%88%97%E4%BB%8B%E7%BB%8D%E5%85%AB/ - LRU

    说完了过期策略再说下淘汰策略,redis 使用的策略是近似的 lru 策略,为什么是近似的呢,先来看下什么是 lru,看下 wiki 的介绍
    ,图中一共有四个槽的存储空间,依次访问顺序是 A B C D E D F,
    当第一次访问 D 时刚好占满了坑,并且值是 4,这个值越小代表越先被淘汰,当 E 进来时,看了下已经存在的四个里 A 是最小的,代表是最早存在并且最早被访问的,那就先淘汰它了,E 占领了 A 的位置,并设置值为 4,然后又访问 D 了,D 已经存在了,不过又被访问到了,得更新值为 5,然后是 F 进来了,这时 B 是最老的且最近未被访问,所以就淘汰它了。以上是一个 lru 的简要说明,但是 redis 没有严格按照这个去执行,理由跟前面过期策略一致,最严格的过期策略应该是每个 key 都有对应的定时器,当超时时马上就能清除,但是问题是这样的cpu 消耗太大,所换来的内存效率不太值得,淘汰策略也是这样,类似于上图,要维护所有 key 的一个有序 lru 值,并且遍历将最小的淘汰,redis 采用的是抽样的形式,最初的实现方式是随机从 dict 抽取 5 个 key,淘汰一个 lru 最小的,这样子勉强能达到淘汰的目的,但是效果不是特别好,后面在 redis 3.0开始,将随机抽取改成了维护一个 pool,pool 的大小默认是 16,每次放入的都是按lru 值有序排列好,每一次放入的必须是 lru小于 pool 中最小的 lru 才允许放入,直到放满,后面再有新的就会将大的踢出。
    redis 针对这个策略的改进做了一个实验,这里借用下图

    首先背景是这图中的所有点都对应一个 redis 的 key,灰色部分加入后被顺序访问过一遍,然后又加入了绿色部分,那么按照理论的 lru 算法,应该是图左上中,浅灰色部分全都被淘汰,那么对比来看看图右上,左下和右下,左下表示 2.8 版本就是随机抽样 5 个 key,淘汰其中 lru 最小的一个,发现是灰色和浅灰色的都有被淘汰的,右下的 3.0 版本抽样数量不变的情况下,稍好一些,当 3.0 版本的抽样数量调整成 10 后,已经较为接近理论上的 lru 策略了,通过代码来简要分析下

    -
    typedef struct redisObject {
    -    unsigned type:4;
    -    unsigned encoding:4;
    -    unsigned lru:LRU_BITS; /* LRU time (relative to global lru_clock) or
    -                            * LFU data (least significant 8 bits frequency
    -                            * and most significant 16 bits access time). */
    -    int refcount;
    -    void *ptr;
    -} robj;
    -

    对于 lru 策略来说,lru 字段记录的就是redisObj 的LRU time,
    redis 在访问数据时,都会调用lookupKey方法

    -
    /* Low level key lookup API, not actually called directly from commands
    +/* Low level key lookup API, not actually called directly from commands
      * implementations that should instead rely on lookupKeyRead(),
      * lookupKeyWrite() and lookupKeyReadWithFlags(). */
     robj *lookupKey(redisDb *db, robj *key, int flags) {
    @@ -11336,10 +11369,9 @@ robj *lookupKey(redisDb *db, robj *key, int flags) {
              * a copy on write madness. */
             if (!hasActiveChildProcess() && !(flags & LOOKUP_NOTOUCH)){
                 if (server.maxmemory_policy & MAXMEMORY_FLAG_LFU) {
    -                // 这个是后面一节的内容
    +                // 当淘汰策略是 LFU 时,就会调用这个updateLFU
                     updateLFU(val);
                 } else {
    -                //  对于这个分支,访问时就会去更新 lru 值
                     val->lru = LRU_CLOCK();
                 }
             }
    @@ -11347,708 +11379,637 @@ robj *lookupKey(redisDb *db, robj *key, int flags) {
         } else {
             return NULL;
         }
    -}
    -/* This function is used to obtain the current LRU clock.
    - * If the current resolution is lower than the frequency we refresh the
    - * LRU clock (as it should be in production servers) we return the
    - * precomputed value, otherwise we need to resort to a system call. */
    -unsigned int LRU_CLOCK(void) {
    -    unsigned int lruclock;
    -    if (1000/server.hz <= LRU_CLOCK_RESOLUTION) {
    -        // 如果服务器的频率server.hz大于 1 时就是用系统预设的 lruclock
    -        lruclock = server.lruclock;
    -    } else {
    -        lruclock = getLRUClock();
    -    }
    -    return lruclock;
    -}
    -/* Return the LRU clock, based on the clock resolution. This is a time
    - * in a reduced-bits format that can be used to set and check the
    - * object->lru field of redisObject structures. */
    -unsigned int getLRUClock(void) {
    -    return (mstime()/LRU_CLOCK_RESOLUTION) & LRU_CLOCK_MAX;
    -}
    -

    redis 处理命令是在这里processCommand

    -
    /* If this function gets called we already read a whole
    - * command, arguments are in the client argv/argc fields.
    - * processCommand() execute the command or prepare the
    - * server for a bulk read from the client.
    +}
    +

    updateLFU 这个其实个入口,调用了两个重要的方法

    +
    /* Update LFU when an object is accessed.
    + * Firstly, decrement the counter if the decrement time is reached.
    + * Then logarithmically increment the counter, and update the access time. */
    +void updateLFU(robj *val) {
    +    unsigned long counter = LFUDecrAndReturn(val);
    +    counter = LFULogIncr(counter);
    +    val->lru = (LFUGetTimeInMinutes()<<8) | counter;
    +}
    +

    首先来看看LFUDecrAndReturn,这个方法的作用是根据上一次衰减时间和系统配置的 lfu-decay-time 参数来确定需要将 counter 减去多少

    +
    /* If the object decrement time is reached decrement the LFU counter but
    + * do not update LFU fields of the object, we update the access time
    + * and counter in an explicit way when the object is really accessed.
    + * And we will times halve the counter according to the times of
    + * elapsed time than server.lfu_decay_time.
    + * Return the object frequency counter.
      *
    - * If C_OK is returned the client is still alive and valid and
    - * other operations can be performed by the caller. Otherwise
    - * if C_ERR is returned the client was destroyed (i.e. after QUIT). */
    -int processCommand(client *c) {
    -    moduleCallCommandFilters(c);
    + * This function is used in order to scan the dataset for the best object
    + * to fit: as we check for the candidate, we incrementally decrement the
    + * counter of the scanned objects if needed. */
    +unsigned long LFUDecrAndReturn(robj *o) {
    +    // 右移 8 位,拿到上次衰减时间
    +    unsigned long ldt = o->lru >> 8;
    +    // 对 255 做与操作,拿到 counter 值
    +    unsigned long counter = o->lru & 255;
    +    // 根据lfu_decay_time来算出过了多少个衰减周期
    +    unsigned long num_periods = server.lfu_decay_time ? LFUTimeElapsed(ldt) / server.lfu_decay_time : 0;
    +    if (num_periods)
    +        counter = (num_periods > counter) ? 0 : counter - num_periods;
    +    return counter;
    +}
    +

    然后是加,调用了LFULogIncr

    +
    /* Logarithmically increment a counter. The greater is the current counter value
    + * the less likely is that it gets really implemented. Saturate it at 255. */
    +uint8_t LFULogIncr(uint8_t counter) {
    +    // 最大值就是 255,到顶了就不加了
    +    if (counter == 255) return 255;
    +    // 生成个随机小数
    +    double r = (double)rand()/RAND_MAX;
    +    // 减去个基础值,LFU_INIT_VAL = 5,防止刚进来就被逐出
    +    double baseval = counter - LFU_INIT_VAL;
    +    // 如果是小于 0,
    +    if (baseval < 0) baseval = 0;
    +    // 如果 baseval 是 0,那么 p 就是 1了,后面 counter 直接加一,如果不是的话,得看系统参数lfu_log_factor,这个越大,除出来的 p 越小,那么 counter++的可能性也越小,这样子就把前面的疑问给解决了,不是直接+1 的
    +    double p = 1.0/(baseval*server.lfu_log_factor+1);
    +    if (r < p) counter++;
    +    return counter;
    +}
    +

    大概的变化速度可以参考

    +
    +--------+------------+------------+------------+------------+------------+
    +| factor | 100 hits   | 1000 hits  | 100K hits  | 1M hits    | 10M hits   |
    ++--------+------------+------------+------------+------------+------------+
    +| 0      | 104        | 255        | 255        | 255        | 255        |
    ++--------+------------+------------+------------+------------+------------+
    +| 1      | 18         | 49         | 255        | 255        | 255        |
    ++--------+------------+------------+------------+------------+------------+
    +| 10     | 10         | 18         | 142        | 255        | 255        |
    ++--------+------------+------------+------------+------------+------------+
    +| 100    | 8          | 11         | 49         | 143        | 255        |
    ++--------+------------+------------+------------+------------+------------+
    +

    简而言之就是 lfu_log_factor 越大变化的越慢

    +

    总结

    总结一下,redis 实现了近似的 lru 淘汰策略,通过增加了淘汰 key 的池子(pool),并且增大每次抽样的 key 的数量来将淘汰效果更进一步地接近于 lru,这是 lru 策略,但是对于前面举的一个例子,其实 lru 并不能保证 key 的淘汰就如我们预期,所以在后期又引入了 lfu 的策略,lfu的策略比较巧妙,复用了 redis 对象的 lru 字段,并且使用了factor 参数来控制计数器递增的速度,防止 8 位的计数器太早溢出。

    +]]>
    + + Redis + 数据结构 + C + 源码 + Redis + + + redis + 数据结构 + 源码 + +
    + + redis过期策略复习 + /2021/07/25/redis%E8%BF%87%E6%9C%9F%E7%AD%96%E7%95%A5%E5%A4%8D%E4%B9%A0/ + redis过期策略复习

    之前其实写过redis的过期的一些原理,这次主要是记录下,一些使用上的概念,主要是redis使用的过期策略是懒过期和定时清除,懒过期的其实比较简单,即是在key被访问的时候会顺带着判断下这个key是否已过期了,如果已经过期了,就不返回了,但是这种策略有个漏洞是如果有些key之后一直不会被访问了,就等于沉在池底了,所以需要有一个定时的清理机制,去从设置了过期的key池子(expires)里随机地捞key,具体的策略我们看下官网的解释

    +
      +
    1. Test 20 random keys from the set of keys with an associated expire.
    2. +
    3. Delete all the keys found expired.
    4. +
    5. If more than 25% of keys were expired, start again from step 1.
    6. +
    +

    从池子里随机获取20个key,将其中过期的key删掉,如果这其中有超过25%的key已经过期了,那就再来一次,以此保持过期的key不超过25%(左右),并且这个定时策略可以在redis的配置文件

    +
    # Redis calls an internal function to perform many background tasks, like
    +# closing connections of clients in timeout, purging expired keys that are
    +# never requested, and so forth.
    +#
    +# Not all tasks are performed with the same frequency, but Redis checks for
    +# tasks to perform according to the specified "hz" value.
    +#
    +# By default "hz" is set to 10. Raising the value will use more CPU when
    +# Redis is idle, but at the same time will make Redis more responsive when
    +# there are many keys expiring at the same time, and timeouts may be
    +# handled with more precision.
    +#
    +# The range is between 1 and 500, however a value over 100 is usually not
    +# a good idea. Most users should use the default of 10 and raise this up to
    +# 100 only in environments where very low latency is required.
    +hz 10
    - +

    可以配置这个hz的值,代表的含义是每秒的执行次数,默认是10,其实也用了hz的普遍含义。有兴趣可以看看之前写的一篇文章redis系列介绍七-过期策略

    +]]>
    + + redis + + + redis + 应用 + 过期策略 + +
    + + rust学习笔记-所有权三之切片 + /2021/05/16/rust%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0-%E6%89%80%E6%9C%89%E6%9D%83%E4%B8%89%E4%B9%8B%E5%88%87%E7%89%87/ + 除了引用,Rust 还有另外一种不持有所有权的数据类型:切片(slice)。切片允许我们引用集合中某一段连续的元素序列,而不是整个集合。
    例如代码

    +
    fn main() {
    +    let mut s = String::from("hello world");
     
    -    /* Handle the maxmemory directive.
    -     *
    -     * Note that we do not want to reclaim memory if we are here re-entering
    -     * the event loop since there is a busy Lua script running in timeout
    -     * condition, to avoid mixing the propagation of scripts with the
    -     * propagation of DELs due to eviction. */
    -    if (server.maxmemory && !server.lua_timedout) {
    -        int out_of_memory = freeMemoryIfNeededAndSafe() == C_ERR;
    -        /* freeMemoryIfNeeded may flush slave output buffers. This may result
    -         * into a slave, that may be the active client, to be freed. */
    -        if (server.current_client == NULL) return C_ERR;
    +    let word = first_word(&s);
    +
    +    s.clear();
    +
    +    // 这时候虽然 word 还是 5,但是 s 已经被清除了,所以就没存在的意义
    +}
    +

    这里其实我们就需要关注 s 的存在性,代码的逻辑合理性就需要额外去维护,此时我们就可以用切片

    +
    let s = String::from("hello world")
    +
    +let hello = &s[0..5];
    +let world = &s[6..11];
    +

    其实跟 Python 的list 之类的语法有点类似,当然里面还有些语法糖,比如可以直接用省略后面的数字表示直接引用到结尾

    +
    let hello = &s[0..];
    +

    甚至再进一步

    +
    let hello = &s[..];
    +

    使用了切片之后

    +
    fn first_word(s: &String) -> &str {
    +    let bytes = s.as_bytes();
     
    -        /* It was impossible to free enough memory, and the command the client
    -         * is trying to execute is denied during OOM conditions or the client
    -         * is in MULTI/EXEC context? Error. */
    -        if (out_of_memory &&
    -            (c->cmd->flags & CMD_DENYOOM ||
    -             (c->flags & CLIENT_MULTI &&
    -              c->cmd->proc != execCommand &&
    -              c->cmd->proc != discardCommand)))
    -        {
    -            flagTransaction(c);
    -            addReply(c, shared.oomerr);
    -            return C_OK;
    -        }
    -    }
    -}
    -

    这里只摘了部分,当需要清理内存时就会调用, 然后调用了freeMemoryIfNeededAndSafe

    -
    /* This is a wrapper for freeMemoryIfNeeded() that only really calls the
    - * function if right now there are the conditions to do so safely:
    - *
    - * - There must be no script in timeout condition.
    - * - Nor we are loading data right now.
    - *
    - */
    -int freeMemoryIfNeededAndSafe(void) {
    -    if (server.lua_timedout || server.loading) return C_OK;
    -    return freeMemoryIfNeeded();
    -}
    -/* This function is periodically called to see if there is memory to free
    - * according to the current "maxmemory" settings. In case we are over the
    - * memory limit, the function will try to free some memory to return back
    - * under the limit.
    - *
    - * The function returns C_OK if we are under the memory limit or if we
    - * were over the limit, but the attempt to free memory was successful.
    - * Otehrwise if we are over the memory limit, but not enough memory
    - * was freed to return back under the limit, the function returns C_ERR. */
    -int freeMemoryIfNeeded(void) {
    -    int keys_freed = 0;
    -    /* By default replicas should ignore maxmemory
    -     * and just be masters exact copies. */
    -    if (server.masterhost && server.repl_slave_ignore_maxmemory) return C_OK;
    +    for (i, &item) in bytes.iter().enumerate() {
    +        if item == b' ' {
    +            return &s[0..i];
    +        }
    +    }
     
    -    size_t mem_reported, mem_tofree, mem_freed;
    -    mstime_t latency, eviction_latency;
    -    long long delta;
    -    int slaves = listLength(server.slaves);
    +    &s[..]
    +}
    +fn main() {
    +    let mut s = String::from("hello world");
     
    -    /* When clients are paused the dataset should be static not just from the
    -     * POV of clients not being able to write, but also from the POV of
    -     * expires and evictions of keys not being performed. */
    -    if (clientsArePaused()) return C_OK;
    -    if (getMaxmemoryState(&mem_reported,NULL,&mem_tofree,NULL) == C_OK)
    -        return C_OK;
    +    let word = first_word(&s);
     
    -    mem_freed = 0;
    +    s.clear(); // error!
     
    -    if (server.maxmemory_policy == MAXMEMORY_NO_EVICTION)
    -        goto cant_free; /* We need to free memory, but policy forbids. */
    +    println!("the first word is: {}", word);
    +}
    +

    那再执行 main 函数的时候就会抛错,因为 word 还是个切片,需要保证 s 的有效性,并且其实我们可以将函数申明成

    +
    fn first_word(s: &str) -> &str {
    +

    这样就既能处理&String 的情况,就是当成完整字符串的切片,也能处理普通的切片。
    其他类型的切片

    +
    let a = [1, 2, 3, 4, 5];
    +let slice = &a[1..3];
    +

    简单记录下,具体可以去看看这本书

    +]]>
    + + 语言 + Rust + + + Rust + 所有权 + 内存分布 + 新语言 + 可变引用 + 不可变引用 + 切片 + +
    + + rust学习笔记-所有权一 + /2021/04/18/rust%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/ + 最近在看 《rust 权威指南》,还是难度比较大的,它里面的一些概念跟之前的用过的都有比较大的差别
    比起有 gc 的虚拟机语言,跟像 C 和 C++这种主动释放内存的,rust 有他的独特点,主要是有三条

    +
      +
    • Rust中的每一个值都有一个对应的变量作为它的所有者。
    • +
    • 在同一时间内,值有且只有一个所有者。
    • +
    • 当所有者离开自己的作用域时,它持有的值就会被释放掉。

      这里有两个重点:
    • +
    • s 在进入作用域后才变得有效
    • +
    • 它会保持自己的有效性直到自己离开作用域为止
    • +
    +

    然后看个案例

    +
    let x = 5;
    +let y = x;
    +

    这个其实有两种,一般可以认为比较多实现的会使用 copy on write 之类的,先让两个都指向同一个快 5 的存储,在发生变更后开始正式拷贝,但是涉及到内存处理的便利性,对于这类简单类型,可以直接拷贝
    但是对于非基础类型

    +
    let s1 = String::from("hello");
    +let s2 = s1;
     
    -    latencyStartMonitor(latency);
    -    while (mem_freed < mem_tofree) {
    -        int j, k, i;
    -        static unsigned int next_db = 0;
    -        sds bestkey = NULL;
    -        int bestdbid;
    -        redisDb *db;
    -        dict *dict;
    -        dictEntry *de;
    +println!("{}, world!", s1);
    +

    有可能认为有两种内存分布可能
    先看下 string 的内存结构

    第一种可能是

    第二种是

    我们来尝试编译下

    发现有这个错误,其实在 rust 中let y = x这个行为的实质是移动,在赋值给 y 之后 x 就无效了

    这样子就不会造成脱离作用域时,对同一块内存区域的二次释放,如果需要复制,可以使用 clone 方法

    +
    let s1 = String::from("hello");
    +let s2 = s1.clone();
     
    -        if (server.maxmemory_policy & (MAXMEMORY_FLAG_LRU|MAXMEMORY_FLAG_LFU) ||
    -            server.maxmemory_policy == MAXMEMORY_VOLATILE_TTL)
    -        {
    -            struct evictionPoolEntry *pool = EvictionPoolLRU;
    +println!("s1 = {}, s2 = {}", s1, s2);
    +

    这里其实会有点疑惑,为什么前面的x, y 的行为跟 s1, s2 的不一样,其实主要是基本类型和 string 这类的不定大小的类型的内存分配方式不同,x, y这类整型可以直接确定大小,可以直接在栈上分配,而像 string 和其他的变体结构体,其大小都是不能在编译时确定,所以需要在堆上进行分配

    +]]>
    + + 语言 + Rust + + + Rust + 所有权 + 内存分布 + 新语言 + +
    + + mybatis系列-第一条sql的细节 + /2022/12/11/mybatis%E7%B3%BB%E5%88%97-%E7%AC%AC%E4%B8%80%E6%9D%A1sql%E7%9A%84%E7%BB%86%E8%8A%82/ + 先补充两个点,
    第一是前面我们说了
    使用org.apache.ibatis.builder.xml.XMLConfigBuilder 创建了parser解析器,那么解析的结果是什么
    看这个方法的返回值

    +
    public Configuration parse() {
    +  if (parsed) {
    +    throw new BuilderException("Each XMLConfigBuilder can only be used once.");
    +  }
    +  parsed = true;
    +  parseConfiguration(parser.evalNode("/configuration"));
    +  return configuration;
    +}
    - while(bestkey == NULL) { - unsigned long total_keys = 0, keys; +

    返回的是 org.apache.ibatis.session.Configuration , 而这个 Configuration 也是 mybatis 中特别重要的配置核心类,贴一下里面的成员变量,

    +
    public class Configuration {
     
    -                /* We don't want to make local-db choices when expiring keys,
    -                 * so to start populate the eviction pool sampling keys from
    -                 * every DB. */
    -                for (i = 0; i < server.dbnum; i++) {
    -                    db = server.db+i;
    -                    dict = (server.maxmemory_policy & MAXMEMORY_FLAG_ALLKEYS) ?
    -                            db->dict : db->expires;
    -                    if ((keys = dictSize(dict)) != 0) {
    -                        evictionPoolPopulate(i, dict, db->dict, pool);
    -                        total_keys += keys;
    -                    }
    -                }
    -                if (!total_keys) break; /* No keys to evict. */
    +  protected Environment environment;
     
    -                /* Go backward from best to worst element to evict. */
    -                for (k = EVPOOL_SIZE-1; k >= 0; k--) {
    -                    if (pool[k].key == NULL) continue;
    -                    bestdbid = pool[k].dbid;
    +  protected boolean safeRowBoundsEnabled;
    +  protected boolean safeResultHandlerEnabled = true;
    +  protected boolean mapUnderscoreToCamelCase;
    +  protected boolean aggressiveLazyLoading;
    +  protected boolean multipleResultSetsEnabled = true;
    +  protected boolean useGeneratedKeys;
    +  protected boolean useColumnLabel = true;
    +  protected boolean cacheEnabled = true;
    +  protected boolean callSettersOnNulls;
    +  protected boolean useActualParamName = true;
    +  protected boolean returnInstanceForEmptyRow;
    +  protected boolean shrinkWhitespacesInSql;
    +  protected boolean nullableOnForEach;
    +  protected boolean argNameBasedConstructorAutoMapping;
     
    -                    if (server.maxmemory_policy & MAXMEMORY_FLAG_ALLKEYS) {
    -                        de = dictFind(server.db[pool[k].dbid].dict,
    -                            pool[k].key);
    -                    } else {
    -                        de = dictFind(server.db[pool[k].dbid].expires,
    -                            pool[k].key);
    -                    }
    +  protected String logPrefix;
    +  protected Class<? extends Log> logImpl;
    +  protected Class<? extends VFS> vfsImpl;
    +  protected Class<?> defaultSqlProviderType;
    +  protected LocalCacheScope localCacheScope = LocalCacheScope.SESSION;
    +  protected JdbcType jdbcTypeForNull = JdbcType.OTHER;
    +  protected Set<String> lazyLoadTriggerMethods = new HashSet<>(Arrays.asList("equals", "clone", "hashCode", "toString"));
    +  protected Integer defaultStatementTimeout;
    +  protected Integer defaultFetchSize;
    +  protected ResultSetType defaultResultSetType;
    +  protected ExecutorType defaultExecutorType = ExecutorType.SIMPLE;
    +  protected AutoMappingBehavior autoMappingBehavior = AutoMappingBehavior.PARTIAL;
    +  protected AutoMappingUnknownColumnBehavior autoMappingUnknownColumnBehavior = AutoMappingUnknownColumnBehavior.NONE;
     
    -                    /* Remove the entry from the pool. */
    -                    if (pool[k].key != pool[k].cached)
    -                        sdsfree(pool[k].key);
    -                    pool[k].key = NULL;
    -                    pool[k].idle = 0;
    +  protected Properties variables = new Properties();
    +  protected ReflectorFactory reflectorFactory = new DefaultReflectorFactory();
    +  protected ObjectFactory objectFactory = new DefaultObjectFactory();
    +  protected ObjectWrapperFactory objectWrapperFactory = new DefaultObjectWrapperFactory();
     
    -                    /* If the key exists, is our pick. Otherwise it is
    -                     * a ghost and we need to try the next element. */
    -                    if (de) {
    -                        bestkey = dictGetKey(de);
    -                        break;
    -                    } else {
    -                        /* Ghost... Iterate again. */
    -                    }
    -                }
    -            }
    -        }
    +  protected boolean lazyLoadingEnabled = false;
    +  protected ProxyFactory proxyFactory = new JavassistProxyFactory(); // #224 Using internal Javassist instead of OGNL
     
    -        /* volatile-random and allkeys-random policy */
    -        else if (server.maxmemory_policy == MAXMEMORY_ALLKEYS_RANDOM ||
    -                 server.maxmemory_policy == MAXMEMORY_VOLATILE_RANDOM)
    -        {
    -            /* When evicting a random key, we try to evict a key for
    -             * each DB, so we use the static 'next_db' variable to
    -             * incrementally visit all DBs. */
    -            for (i = 0; i < server.dbnum; i++) {
    -                j = (++next_db) % server.dbnum;
    -                db = server.db+j;
    -                dict = (server.maxmemory_policy == MAXMEMORY_ALLKEYS_RANDOM) ?
    -                        db->dict : db->expires;
    -                if (dictSize(dict) != 0) {
    -                    de = dictGetRandomKey(dict);
    -                    bestkey = dictGetKey(de);
    -                    bestdbid = j;
    -                    break;
    -                }
    -            }
    -        }
    +  protected String databaseId;
    +  /**
    +   * Configuration factory class.
    +   * Used to create Configuration for loading deserialized unread properties.
    +   *
    +   * @see <a href='https://github.com/mybatis/old-google-code-issues/issues/300'>Issue 300 (google code)</a>
    +   */
    +  protected Class<?> configurationFactory;
     
    -        /* Finally remove the selected key. */
    -        if (bestkey) {
    -            db = server.db+bestdbid;
    -            robj *keyobj = createStringObject(bestkey,sdslen(bestkey));
    -            propagateExpire(db,keyobj,server.lazyfree_lazy_eviction);
    -            /* We compute the amount of memory freed by db*Delete() alone.
    -             * It is possible that actually the memory needed to propagate
    -             * the DEL in AOF and replication link is greater than the one
    -             * we are freeing removing the key, but we can't account for
    -             * that otherwise we would never exit the loop.
    -             *
    -             * AOF and Output buffer memory will be freed eventually so
    -             * we only care about memory used by the key space. */
    -            delta = (long long) zmalloc_used_memory();
    -            latencyStartMonitor(eviction_latency);
    -            if (server.lazyfree_lazy_eviction)
    -                dbAsyncDelete(db,keyobj);
    -            else
    -                dbSyncDelete(db,keyobj);
    -            latencyEndMonitor(eviction_latency);
    -            latencyAddSampleIfNeeded("eviction-del",eviction_latency);
    -            latencyRemoveNestedEvent(latency,eviction_latency);
    -            delta -= (long long) zmalloc_used_memory();
    -            mem_freed += delta;
    -            server.stat_evictedkeys++;
    -            notifyKeyspaceEvent(NOTIFY_EVICTED, "evicted",
    -                keyobj, db->id);
    -            decrRefCount(keyobj);
    -            keys_freed++;
    +  protected final MapperRegistry mapperRegistry = new MapperRegistry(this);
    +  protected final InterceptorChain interceptorChain = new InterceptorChain();
    +  protected final TypeHandlerRegistry typeHandlerRegistry = new TypeHandlerRegistry(this);
    +  protected final TypeAliasRegistry typeAliasRegistry = new TypeAliasRegistry();
    +  protected final LanguageDriverRegistry languageRegistry = new LanguageDriverRegistry();
     
    -            /* When the memory to free starts to be big enough, we may
    -             * start spending so much time here that is impossible to
    -             * deliver data to the slaves fast enough, so we force the
    -             * transmission here inside the loop. */
    -            if (slaves) flushSlavesOutputBuffers();
    +  protected final Map<String, MappedStatement> mappedStatements = new StrictMap<MappedStatement>("Mapped Statements collection")
    +      .conflictMessageProducer((savedValue, targetValue) ->
    +          ". please check " + savedValue.getResource() + " and " + targetValue.getResource());
    +  protected final Map<String, Cache> caches = new StrictMap<>("Caches collection");
    +  protected final Map<String, ResultMap> resultMaps = new StrictMap<>("Result Maps collection");
    +  protected final Map<String, ParameterMap> parameterMaps = new StrictMap<>("Parameter Maps collection");
    +  protected final Map<String, KeyGenerator> keyGenerators = new StrictMap<>("Key Generators collection");
     
    -            /* Normally our stop condition is the ability to release
    -             * a fixed, pre-computed amount of memory. However when we
    -             * are deleting objects in another thread, it's better to
    -             * check, from time to time, if we already reached our target
    -             * memory, since the "mem_freed" amount is computed only
    -             * across the dbAsyncDelete() call, while the thread can
    -             * release the memory all the time. */
    -            if (server.lazyfree_lazy_eviction && !(keys_freed % 16)) {
    -                if (getMaxmemoryState(NULL,NULL,NULL,NULL) == C_OK) {
    -                    /* Let's satisfy our stop condition. */
    -                    mem_freed = mem_tofree;
    -                }
    -            }
    -        } else {
    -            latencyEndMonitor(latency);
    -            latencyAddSampleIfNeeded("eviction-cycle",latency);
    -            goto cant_free; /* nothing to free... */
    -        }
    -    }
    -    latencyEndMonitor(latency);
    -    latencyAddSampleIfNeeded("eviction-cycle",latency);
    -    return C_OK;
    +  protected final Set<String> loadedResources = new HashSet<>();
    +  protected final Map<String, XNode> sqlFragments = new StrictMap<>("XML fragments parsed from previous mappers");
     
    -cant_free:
    -    /* We are here if we are not able to reclaim memory. There is only one
    -     * last thing we can try: check if the lazyfree thread has jobs in queue
    -     * and wait... */
    -    while(bioPendingJobsOfType(BIO_LAZY_FREE)) {
    -        if (((mem_reported - zmalloc_used_memory()) + mem_freed) >= mem_tofree)
    -            break;
    -        usleep(1000);
    -    }
    -    return C_ERR;
    -}
    -

    这里就是根据具体策略去淘汰 key,首先是要往 pool 更新 key,更新key 的方法是evictionPoolPopulate

    -
    void evictionPoolPopulate(int dbid, dict *sampledict, dict *keydict, struct evictionPoolEntry *pool) {
    -    int j, k, count;
    -    dictEntry *samples[server.maxmemory_samples];
    +  protected final Collection<XMLStatementBuilder> incompleteStatements = new LinkedList<>();
    +  protected final Collection<CacheRefResolver> incompleteCacheRefs = new LinkedList<>();
    +  protected final Collection<ResultMapResolver> incompleteResultMaps = new LinkedList<>();
    +  protected final Collection<MethodResolver> incompleteMethods = new LinkedList<>();
    - count = dictGetSomeKeys(sampledict,samples,server.maxmemory_samples); - for (j = 0; j < count; j++) { - unsigned long long idle; - sds key; - robj *o; - dictEntry *de; +

    这么多成员变量,先不一一解释作用,但是其中的几个参数我们应该是已经知道了的,第一个就是 mappedStatements ,上一篇我们知道被解析的mapper就是放在这里,后面的 resultMapsparameterMaps 也比较常用的就是我们参数和结果的映射map,这里跟我之前有一篇解释为啥我们一些变量的使用会比较特殊,比如list,可以参考这篇keyGenerators是在我们需要定义主键生成器的时候使用。
    然后第二点是我们创建的 org.apache.ibatis.session.SqlSessionFactory 是哪个,

    +
    public SqlSessionFactory build(Configuration config) {
    +  return new DefaultSqlSessionFactory(config);
    +}
    - de = samples[j]; - key = dictGetKey(de); +

    是这个 DefaultSqlSessionFactory ,这是其中一个 SqlSessionFactory 的实现
    接下来我们看看 openSession 里干了啥

    +
    public SqlSession openSession() {
    +  return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
    +}
    - /* If the dictionary we are sampling from is not the main - * dictionary (but the expires one) we need to lookup the key - * again in the key dictionary to obtain the value object. */ - if (server.maxmemory_policy != MAXMEMORY_VOLATILE_TTL) { - if (sampledict != keydict) de = dictFind(keydict, key); - o = dictGetVal(de); - } +

    这边有几个参数,第一个是默认的执行器类型,往上找找上面贴着的 Configuration 的成员变量里可以看到默认是
    protected ExecutorType defaultExecutorType = ExecutorType.SIMPLE;

    +

    因为没有指明特殊的执行逻辑,所以默认我们也就用简单类型的,第二个参数是是事务级别,第三个是是否自动提交

    +
    private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
    +  Transaction tx = null;
    +  try {
    +    final Environment environment = configuration.getEnvironment();
    +    final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
    +    tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
    +    // --------> 先关注这里
    +    final Executor executor = configuration.newExecutor(tx, execType);
    +    return new DefaultSqlSession(configuration, executor, autoCommit);
    +  } catch (Exception e) {
    +    closeTransaction(tx); // may have fetched a connection so lets call close()
    +    throw ExceptionFactory.wrapException("Error opening session.  Cause: " + e, e);
    +  } finally {
    +    ErrorContext.instance().reset();
    +  }
    +}
    - /* Calculate the idle time according to the policy. This is called - * idle just because the code initially handled LRU, but is in fact - * just a score where an higher score means better candidate. */ - if (server.maxmemory_policy & MAXMEMORY_FLAG_LRU) { - idle = estimateObjectIdleTime(o); - } else if (server.maxmemory_policy & MAXMEMORY_FLAG_LFU) { - /* When we use an LRU policy, we sort the keys by idle time - * so that we expire keys starting from greater idle time. - * However when the policy is an LFU one, we have a frequency - * estimation, and we want to evict keys with lower frequency - * first. So inside the pool we put objects using the inverted - * frequency subtracting the actual frequency to the maximum - * frequency of 255. */ - idle = 255-LFUDecrAndReturn(o); - } else if (server.maxmemory_policy == MAXMEMORY_VOLATILE_TTL) { - /* In this case the sooner the expire the better. */ - idle = ULLONG_MAX - (long)dictGetVal(de); - } else { - serverPanic("Unknown eviction policy in evictionPoolPopulate()"); - } +

    具体是调用了 Configuration 的这个方法

    +
    public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
    +  executorType = executorType == null ? defaultExecutorType : executorType;
    +  Executor executor;
    +  if (ExecutorType.BATCH == executorType) {
    +    executor = new BatchExecutor(this, transaction);
    +  } else if (ExecutorType.REUSE == executorType) {
    +    executor = new ReuseExecutor(this, transaction);
    +  } else {
    +    // ---------> 会走到这个分支
    +    executor = new SimpleExecutor(this, transaction);
    +  }
    +  if (cacheEnabled) {
    +    executor = new CachingExecutor(executor);
    +  }
    +  executor = (Executor) interceptorChain.pluginAll(executor);
    +  return executor;
    +}
    - /* Insert the element inside the pool. - * First, find the first empty bucket or the first populated - * bucket that has an idle time smaller than our idle time. */ - k = 0; - while (k < EVPOOL_SIZE && - pool[k].key && - pool[k].idle < idle) k++; - if (k == 0 && pool[EVPOOL_SIZE-1].key != NULL) { - /* Can't insert if the element is < the worst element we have - * and there are no empty buckets. */ - continue; - } else if (k < EVPOOL_SIZE && pool[k].key == NULL) { - /* Inserting into empty position. No setup needed before insert. */ - } else { - /* Inserting in the middle. Now k points to the first element - * greater than the element to insert. */ - if (pool[EVPOOL_SIZE-1].key == NULL) { - /* Free space on the right? Insert at k shifting - * all the elements from k to end to the right. */ +

    上面传入的 executorTypeConfiguration 的默认类型,也就是 simple 类型,并且 cacheEnabledConfiguration 默认为 true,所以会包装成CachingExecutor ,然后后面就是插件了,这块我们先不展开
    然后我们的openSession返回的就是创建了DefaultSqlSession

    +
    public DefaultSqlSession(Configuration configuration, Executor executor, boolean autoCommit) {
    +    this.configuration = configuration;
    +    this.executor = executor;
    +    this.dirty = false;
    +    this.autoCommit = autoCommit;
    +  }
    + +

    然后就是调用 selectOne, 因为前面已经把这部分代码说过了,就直接跳转过来
    org.apache.ibatis.session.defaults.DefaultSqlSession#selectList(java.lang.String, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.session.ResultHandler)

    +
    private <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) {
    +  try {
    +    MappedStatement ms = configuration.getMappedStatement(statement);
    +    return executor.query(ms, wrapCollection(parameter), rowBounds, handler);
    +  } catch (Exception e) {
    +    throw ExceptionFactory.wrapException("Error querying database.  Cause: " + e, e);
    +  } finally {
    +    ErrorContext.instance().reset();
    +  }
    +}
    + +

    因为前面说了 executor 包装了 CachingExecutor ,所以会先调用

    +
    @Override
    +public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
    +  BoundSql boundSql = ms.getBoundSql(parameterObject);
    +  CacheKey key = createCacheKey(ms, parameterObject, rowBounds, boundSql);
    +  return query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
    +}
    + +

    然后是调用的真实的query方法

    +
    @Override
    +public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)
    +    throws SQLException {
    +  Cache cache = ms.getCache();
    +  if (cache != null) {
    +    flushCacheIfRequired(ms);
    +    if (ms.isUseCache() && resultHandler == null) {
    +      ensureNoOutParams(ms, boundSql);
    +      @SuppressWarnings("unchecked")
    +      List<E> list = (List<E>) tcm.getObject(cache, key);
    +      if (list == null) {
    +        list = delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
    +        tcm.putObject(cache, key, list); // issue #578 and #116
    +      }
    +      return list;
    +    }
    +  }
    +  return delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
    +}
    + +

    这里是第一次查询,没有缓存就先到最后一行,继续是调用到 org.apache.ibatis.executor.BaseExecutor#queryFromDatabase

    +
    @Override
    +  public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
    +    ErrorContext.instance().resource(ms.getResource()).activity("executing a query").object(ms.getId());
    +    if (closed) {
    +      throw new ExecutorException("Executor was closed.");
    +    }
    +    if (queryStack == 0 && ms.isFlushCacheRequired()) {
    +      clearLocalCache();
    +    }
    +    List<E> list;
    +    try {
    +      queryStack++;
    +      list = resultHandler == null ? (List<E>) localCache.getObject(key) : null;
    +      if (list != null) {
    +        handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);
    +      } else {
    +        // ----------->会走到这里
    +        list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);
    +      }
    +    } finally {
    +      queryStack--;
    +    }
    +    if (queryStack == 0) {
    +      for (DeferredLoad deferredLoad : deferredLoads) {
    +        deferredLoad.load();
    +      }
    +      // issue #601
    +      deferredLoads.clear();
    +      if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) {
    +        // issue #482
    +        clearLocalCache();
    +      }
    +    }
    +    return list;
    +  }
    - /* Save SDS before overwriting. */ - sds cached = pool[EVPOOL_SIZE-1].cached; - memmove(pool+k+1,pool+k, - sizeof(pool[0])*(EVPOOL_SIZE-k-1)); - pool[k].cached = cached; - } else { - /* No free space on right? Insert at k-1 */ - k--; - /* Shift all elements on the left of k (included) to the - * left, so we discard the element with smaller idle time. */ - sds cached = pool[0].cached; /* Save SDS before overwriting. */ - if (pool[0].key != pool[0].cached) sdsfree(pool[0].key); - memmove(pool,pool+1,sizeof(pool[0])*k); - pool[k].cached = cached; - } - } +

    然后是

    +
    private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
    +  List<E> list;
    +  localCache.putObject(key, EXECUTION_PLACEHOLDER);
    +  try {
    +    list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);
    +  } finally {
    +    localCache.removeObject(key);
    +  }
    +  localCache.putObject(key, list);
    +  if (ms.getStatementType() == StatementType.CALLABLE) {
    +    localOutputParameterCache.putObject(key, parameter);
    +  }
    +  return list;
    +}
    - /* Try to reuse the cached SDS string allocated in the pool entry, - * because allocating and deallocating this object is costly - * (according to the profiler, not my fantasy. Remember: - * premature optimizbla bla bla bla. */ - int klen = sdslen(key); - if (klen > EVPOOL_CACHED_SDS_SIZE) { - pool[k].key = sdsdup(key); - } else { - memcpy(pool[k].cached,key,klen+1); - sdssetlen(pool[k].cached,klen); - pool[k].key = pool[k].cached; - } - pool[k].idle = idle; - pool[k].dbid = dbid; - } -}
    -

    Redis随机选择maxmemory_samples数量的key,然后计算这些key的空闲时间idle time,当满足条件时(比pool中的某些键的空闲时间还大)就可以进poolpool更新之后,就淘汰pool中空闲时间最大的键。

    -

    estimateObjectIdleTime用来计算Redis对象的空闲时间:

    -
    /* Given an object returns the min number of milliseconds the object was never
    - * requested, using an approximated LRU algorithm. */
    -unsigned long long estimateObjectIdleTime(robj *o) {
    -    unsigned long long lruclock = LRU_CLOCK();
    -    if (lruclock >= o->lru) {
    -        return (lruclock - o->lru) * LRU_CLOCK_RESOLUTION;
    -    } else {
    -        return (lruclock + (LRU_CLOCK_MAX - o->lru)) *
    -                    LRU_CLOCK_RESOLUTION;
    -    }
    -}
    -

    空闲时间第一种是 lurclock 大于对象的 lru,那么就是减一下乘以精度,因为 lruclock 有可能是已经预生成的,所以会可能走下面这个

    -

    LFU

    上面介绍了LRU 的算法,但是考虑一种场景

    -
    ~~~~~A~~~~~A~~~~~A~~~~A~~~~~A~~~~~A~~|
    -~~B~~B~~B~~B~~B~~B~~B~~B~~B~~B~~B~~B~|
    -~~~~~~~~~~C~~~~~~~~~C~~~~~~~~~C~~~~~~|
    -~~~~~D~~~~~~~~~~D~~~~~~~~~D~~~~~~~~~D|
    -

    可以发现,当采用 lru 的淘汰策略的时候,D 是最新的,会被认为是最值得保留的,但是事实上还不如 A 跟 B,然后 antirez 大神就想到了LFU (Least Frequently Used) 这个算法, 显然对于上面的四个 key 的访问频率,保留优先级应该是 B > A > C = D
    那要怎么来实现这个 LFU 算法呢,其实像LRU,理想的情况就是维护个链表,把最新访问的放到头上去,但是这个会影响访问速度,注意到前面代码的应该可以看到,redisObject 的 lru 字段其实是两用的,当策略是 LFU 时,这个字段就另作他用了,它的 24 位长度被分成两部分

    -
          16 bits      8 bits
    -+----------------+--------+
    -+ Last decr time | LOG_C  |
    -+----------------+--------+
    -

    前16位字段是最后一次递减时间,因此Redis知道 上一次计数器递减,后8位是 计数器 counter。
    LFU 的主体策略就是当这个 key 被访问的次数越多频率越高他就越容易被保留下来,并且是最近被访问的频率越高。这其实有两个事情要做,一个是在访问的时候增加计数值,在一定长时间不访问时进行衰减,所以这里用了两个值,前 16 位记录上一次衰减的时间,后 8 位记录具体的计数值。
    Redis4.0之后为maxmemory_policy淘汰策略添加了两个LFU模式:

    -

    volatile-lfu:对有过期时间的key采用LFU淘汰策略
    allkeys-lfu:对全部key采用LFU淘汰策略
    还有2个配置可以调整LFU算法:

    -
    lfu-log-factor 10
    -lfu-decay-time 1
    -```  
    -`lfu-log-factor` 可以调整计数器counter的增长速度,lfu-log-factor越大,counter增长的越慢。
    +

    然后就是 simpleExecutor 的执行过程

    +
    @Override
    +public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
    +  Statement stmt = null;
    +  try {
    +    Configuration configuration = ms.getConfiguration();
    +    StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
    +    stmt = prepareStatement(handler, ms.getStatementLog());
    +    return handler.query(stmt, resultHandler);
    +  } finally {
    +    closeStatement(stmt);
    +  }
    +}
    -`lfu-decay-time`是一个以分钟为单位的数值,可以调整counter的减少速度 -这里有个问题是 8 位大小够计么,访问一次加 1 的话的确不够,不过大神就是大神,才不会这么简单的加一。往下看代码 -```C -/* Low level key lookup API, not actually called directly from commands - * implementations that should instead rely on lookupKeyRead(), - * lookupKeyWrite() and lookupKeyReadWithFlags(). */ -robj *lookupKey(redisDb *db, robj *key, int flags) { - dictEntry *de = dictFind(db->dict,key->ptr); - if (de) { - robj *val = dictGetVal(de); +

    接下去其实就是跟jdbc交互了

    +
    @Override
    +public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
    +  PreparedStatement ps = (PreparedStatement) statement;
    +  ps.execute();
    +  return resultSetHandler.handleResultSets(ps);
    +}
    - /* Update the access time for the ageing algorithm. - * Don't do it if we have a saving child, as this will trigger - * a copy on write madness. */ - if (!hasActiveChildProcess() && !(flags & LOOKUP_NOTOUCH)){ - if (server.maxmemory_policy & MAXMEMORY_FLAG_LFU) { - // 当淘汰策略是 LFU 时,就会调用这个updateLFU - updateLFU(val); - } else { - val->lru = LRU_CLOCK(); - } - } - return val; - } else { - return NULL; - } -}
    -

    updateLFU 这个其实个入口,调用了两个重要的方法

    -
    /* Update LFU when an object is accessed.
    - * Firstly, decrement the counter if the decrement time is reached.
    - * Then logarithmically increment the counter, and update the access time. */
    -void updateLFU(robj *val) {
    -    unsigned long counter = LFUDecrAndReturn(val);
    -    counter = LFULogIncr(counter);
    -    val->lru = (LFUGetTimeInMinutes()<<8) | counter;
    -}
    -

    首先来看看LFUDecrAndReturn,这个方法的作用是根据上一次衰减时间和系统配置的 lfu-decay-time 参数来确定需要将 counter 减去多少

    -
    /* If the object decrement time is reached decrement the LFU counter but
    - * do not update LFU fields of the object, we update the access time
    - * and counter in an explicit way when the object is really accessed.
    - * And we will times halve the counter according to the times of
    - * elapsed time than server.lfu_decay_time.
    - * Return the object frequency counter.
    - *
    - * This function is used in order to scan the dataset for the best object
    - * to fit: as we check for the candidate, we incrementally decrement the
    - * counter of the scanned objects if needed. */
    -unsigned long LFUDecrAndReturn(robj *o) {
    -    // 右移 8 位,拿到上次衰减时间
    -    unsigned long ldt = o->lru >> 8;
    -    // 对 255 做与操作,拿到 counter 值
    -    unsigned long counter = o->lru & 255;
    -    // 根据lfu_decay_time来算出过了多少个衰减周期
    -    unsigned long num_periods = server.lfu_decay_time ? LFUTimeElapsed(ldt) / server.lfu_decay_time : 0;
    -    if (num_periods)
    -        counter = (num_periods > counter) ? 0 : counter - num_periods;
    -    return counter;
    -}
    -

    然后是加,调用了LFULogIncr

    -
    /* Logarithmically increment a counter. The greater is the current counter value
    - * the less likely is that it gets really implemented. Saturate it at 255. */
    -uint8_t LFULogIncr(uint8_t counter) {
    -    // 最大值就是 255,到顶了就不加了
    -    if (counter == 255) return 255;
    -    // 生成个随机小数
    -    double r = (double)rand()/RAND_MAX;
    -    // 减去个基础值,LFU_INIT_VAL = 5,防止刚进来就被逐出
    -    double baseval = counter - LFU_INIT_VAL;
    -    // 如果是小于 0,
    -    if (baseval < 0) baseval = 0;
    -    // 如果 baseval 是 0,那么 p 就是 1了,后面 counter 直接加一,如果不是的话,得看系统参数lfu_log_factor,这个越大,除出来的 p 越小,那么 counter++的可能性也越小,这样子就把前面的疑问给解决了,不是直接+1 的
    -    double p = 1.0/(baseval*server.lfu_log_factor+1);
    -    if (r < p) counter++;
    -    return counter;
    -}
    -

    大概的变化速度可以参考

    -
    +--------+------------+------------+------------+------------+------------+
    -| factor | 100 hits   | 1000 hits  | 100K hits  | 1M hits    | 10M hits   |
    -+--------+------------+------------+------------+------------+------------+
    -| 0      | 104        | 255        | 255        | 255        | 255        |
    -+--------+------------+------------+------------+------------+------------+
    -| 1      | 18         | 49         | 255        | 255        | 255        |
    -+--------+------------+------------+------------+------------+------------+
    -| 10     | 10         | 18         | 142        | 255        | 255        |
    -+--------+------------+------------+------------+------------+------------+
    -| 100    | 8          | 11         | 49         | 143        | 255        |
    -+--------+------------+------------+------------+------------+------------+
    -

    简而言之就是 lfu_log_factor 越大变化的越慢

    -

    总结

    总结一下,redis 实现了近似的 lru 淘汰策略,通过增加了淘汰 key 的池子(pool),并且增大每次抽样的 key 的数量来将淘汰效果更进一步地接近于 lru,这是 lru 策略,但是对于前面举的一个例子,其实 lru 并不能保证 key 的淘汰就如我们预期,所以在后期又引入了 lfu 的策略,lfu的策略比较巧妙,复用了 redis 对象的 lru 字段,并且使用了factor 参数来控制计数器递增的速度,防止 8 位的计数器太早溢出。

    -]]>
    - - Redis - 数据结构 - C - 源码 - Redis - - - redis - 数据结构 - 源码 - -
    - - redis过期策略复习 - /2021/07/25/redis%E8%BF%87%E6%9C%9F%E7%AD%96%E7%95%A5%E5%A4%8D%E4%B9%A0/ - redis过期策略复习

    之前其实写过redis的过期的一些原理,这次主要是记录下,一些使用上的概念,主要是redis使用的过期策略是懒过期和定时清除,懒过期的其实比较简单,即是在key被访问的时候会顺带着判断下这个key是否已过期了,如果已经过期了,就不返回了,但是这种策略有个漏洞是如果有些key之后一直不会被访问了,就等于沉在池底了,所以需要有一个定时的清理机制,去从设置了过期的key池子(expires)里随机地捞key,具体的策略我们看下官网的解释

    -
      -
    1. Test 20 random keys from the set of keys with an associated expire.
    2. -
    3. Delete all the keys found expired.
    4. -
    5. If more than 25% of keys were expired, start again from step 1.
    6. -
    -

    从池子里随机获取20个key,将其中过期的key删掉,如果这其中有超过25%的key已经过期了,那就再来一次,以此保持过期的key不超过25%(左右),并且这个定时策略可以在redis的配置文件

    -
    # Redis calls an internal function to perform many background tasks, like
    -# closing connections of clients in timeout, purging expired keys that are
    -# never requested, and so forth.
    -#
    -# Not all tasks are performed with the same frequency, but Redis checks for
    -# tasks to perform according to the specified "hz" value.
    -#
    -# By default "hz" is set to 10. Raising the value will use more CPU when
    -# Redis is idle, but at the same time will make Redis more responsive when
    -# there are many keys expiring at the same time, and timeouts may be
    -# handled with more precision.
    -#
    -# The range is between 1 and 500, however a value over 100 is usually not
    -# a good idea. Most users should use the default of 10 and raise this up to
    -# 100 only in environments where very low latency is required.
    -hz 10
    +

    com.mysql.cj.jdbc.ClientPreparedStatement#execute

    +
    public boolean execute() throws SQLException {
    +        try {
    +            synchronized(this.checkClosed().getConnectionMutex()) {
    +                JdbcConnection locallyScopedConn = this.connection;
    +                if (!this.doPingInstead && !this.checkReadOnlySafeStatement()) {
    +                    throw SQLError.createSQLException(Messages.getString("PreparedStatement.20") + Messages.getString("PreparedStatement.21"), "S1009", this.exceptionInterceptor);
    +                } else {
    +                    ResultSetInternalMethods rs = null;
    +                    this.lastQueryIsOnDupKeyUpdate = false;
    +                    if (this.retrieveGeneratedKeys) {
    +                        this.lastQueryIsOnDupKeyUpdate = this.containsOnDuplicateKeyUpdate();
    +                    }
    +
    +                    this.batchedGeneratedKeys = null;
    +                    this.resetCancelledState();
    +                    this.implicitlyCloseAllOpenResults();
    +                    this.clearWarnings();
    +                    if (this.doPingInstead) {
    +                        this.doPingInstead();
    +                        return true;
    +                    } else {
    +                        this.setupStreamingTimeout(locallyScopedConn);
    +                        Message sendPacket = ((PreparedQuery)this.query).fillSendPacket(((PreparedQuery)this.query).getQueryBindings());
    +                        String oldDb = null;
    +                        if (!locallyScopedConn.getDatabase().equals(this.getCurrentDatabase())) {
    +                            oldDb = locallyScopedConn.getDatabase();
    +                            locallyScopedConn.setDatabase(this.getCurrentDatabase());
    +                        }
     
    -

    可以配置这个hz的值,代表的含义是每秒的执行次数,默认是10,其实也用了hz的普遍含义。有兴趣可以看看之前写的一篇文章redis系列介绍七-过期策略

    -]]> - - redis - - - redis - 应用 - 过期策略 - - - - rust学习笔记-所有权二 - /2021/04/18/rust%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0-%E6%89%80%E6%9C%89%E6%9D%83%E4%BA%8C/ - 这里需要说道函数和返回值了
    可以看书上的这个例子

    对于这种情况,当进入函数内部时,会把传入的变量的所有权转移进函数内部,如果最后还是要返回该变量,但是如果此时还要返回别的计算结果,就可能需要笨拙地使用元组

    -

    引用

    此时我们就可以用引用来解决这个问题

    -
    fn main() {
    -    let s1 = String::from("hello");
    -    let len = calculate_length(&s1);
    +                        CachedResultSetMetaData cachedMetadata = null;
    +                        boolean cacheResultSetMetadata = (Boolean)locallyScopedConn.getPropertySet().getBooleanProperty(PropertyKey.cacheResultSetMetadata).getValue();
    +                        if (cacheResultSetMetadata) {
    +                            cachedMetadata = locallyScopedConn.getCachedMetaData(((PreparedQuery)this.query).getOriginalSql());
    +                        }
     
    -    println!("The length of '{}' is {}", s1, len);
    -}
    -fn calculate_length(s: &String) -> usize {
    -    s.len()
    -}
    -

    这里的&符号就是引用的语义,它们允许你在不获得所有权的前提下使用值

    由于引用不持有值的所有权,所以当引用离开当前作用域时,它指向的值也不会被丢弃

    -

    可变引用

    而当我们尝试对引用的字符串进行修改时

    -
    fn main() {
    -    let s1 = String::from("hello");
    -    change(&s1);
    -}
    -fn change(s: &String) {
    -    s.push_str(", world");
    -}
    -

    就会有以下报错,

    其实也很容易发现,毕竟没有 mut 指出这是可变引用,同时需要将 s1 改成 mut 可变的

    -
    fn main() {
    -    let mut s1 = String::from("hello");
    -    change(&mut s1);
    -}
    +                        locallyScopedConn.setSessionMaxRows(this.getQueryInfo().getFirstStmtChar() == 'S' ? this.maxRows : -1);
    +                        rs = this.executeInternal(this.maxRows, sendPacket, this.createStreamingResultSet(), this.getQueryInfo().getFirstStmtChar() == 'S', cachedMetadata, false);
    +                        if (cachedMetadata != null) {
    +                            locallyScopedConn.initializeResultsMetadataFromCache(((PreparedQuery)this.query).getOriginalSql(), cachedMetadata, rs);
    +                        } else if (rs.hasRows() && cacheResultSetMetadata) {
    +                            locallyScopedConn.initializeResultsMetadataFromCache(((PreparedQuery)this.query).getOriginalSql(), (CachedResultSetMetaData)null, rs);
    +                        }
     
    +                        if (this.retrieveGeneratedKeys) {
    +                            rs.setFirstCharOfQuery(this.getQueryInfo().getFirstStmtChar());
    +                        }
     
    -fn change(s: &mut String) {
    -    s.push_str(", world");
    -}
    -

    再看一个例子

    -
    fn main() {
    -    let mut s1 = String::from("hello");
    -    let r1 = &mut s1;
    -    let r2 = &mut s1;
    -}
    -

    这个例子在书里是会报错的,因为同时存在一个以上的可变引用,但是在我运行的版本里前面这段没有报错,只有当我真的要去更改的时候

    -
    fn main() {
    -    let mut s1 = String::from("hello");
    -    let mut r1 = &mut s1;
    -    let mut r2 = &mut s1;
    -    change(&mut r1);
    -    change(&mut r2);
    -}
    +                        if (oldDb != null) {
    +                            locallyScopedConn.setDatabase(oldDb);
    +                        }
     
    +                        if (rs != null) {
    +                            this.lastInsertId = rs.getUpdateID();
    +                            this.results = rs;
    +                        }
     
    -fn change(s: &mut String) {
    -    s.push_str(", world");
    -}
    -


    这里可能就是具体版本在实现上的一个差异,我用的 rustc 是 1.44.0 版本
    其实上面的主要是由 rust 想要避免这类多重可变更导致的异常问题,总结下就是三个点

    -
      -
    • 两个或两个以上的指针同时同时访问同一空间
    • -
    • 其中至少有一个指针会想空间中写入数据
    • -
    • 没有同步数据访问的机制
      并且我们不能在拥有不可变引用的情况下创建可变引用
    • -
    -

    悬垂引用

    还有一点需要注意的就是悬垂引用

    -
    fn main() {
    -    let reference_to_nothing = dangle();
    -}
    +                        return rs != null && rs.hasRows();
    +                    }
    +                }
    +            }
    +        } catch (CJException var11) {
    +            throw SQLExceptionsMapping.translateException(var11, this.getExceptionInterceptor());
    +        }
    +    }
    -fn dangle() -> &String { - let s = String::from("hello"); - &s -}
    -

    这里可以看到其实在 dangle函数返回后,这里的 s 理论上就离开了作用域,但是由于返回了 s 的引用,在 main 函数中就会拿着这个引用,就会出现如下错误

    -

    总结

    最后总结下

    -
      -
    • 在任何一个段给定的时间里,你要么只能拥有一个可变引用,要么只能拥有任意数量的不可变引用。
    • -
    • 引用总是有效的。
    • -
    ]]>
    - 语言 - Rust + Java + Mybatis - Rust - 所有权 - 内存分布 - 新语言 - 可变引用 - 不可变引用 + Java + Mysql + Mybatis
    - spark-little-tips - /2017/03/28/spark-little-tips/ - spark 的一些粗浅使用经验

    工作中学习使用了一下Spark做数据分析,主要是用spark的python接口,首先是pyspark.SparkContext(appName=xxx),这是初始化一个Spark应用实例或者说会话,不能重复,
    返回的实例句柄就可以调用textFile(path)读取文本文件,这里的文本文件可以是HDFS上的文本文件,也可以普通文本文件,但是需要在Spark的所有集群上都存在,否则会
    读取失败,parallelize则可以将python生成的集合数据读取后转换成rdd(A Resilient Distributed Dataset (RDD),一种spark下的基本抽象数据集),基于这个RDD就可以做
    数据的流式计算,例如map reduce,在Spark中可以非常方便地实现

    -

    简单的mapreduce word count示例

    textFile = sc.parallelize([(1,1), (2,1), (3,1), (4,1), (5,1),(1,1), (2,1), (3,1), (4,1), (5,1)])
    -data = textFile.reduceByKey(lambda x, y: x + y).collect()
    -for _ in data:
    -    print(_)
    - + mybatis系列-sql 类的简单使用 + /2023/03/12/mybatis%E7%B3%BB%E5%88%97-sql-%E7%B1%BB%E7%9A%84%E7%AE%80%E5%8D%95%E4%BD%BF%E7%94%A8/ + mybatis 还有个比较有趣的功能,就是使用 SQL 类生成 sql,有点类似于 hibernate 或者像 php 的 laravel 框架等的,就是把sql 这种放在 xml 里或者代码里直接写 sql 用对象的形式

    +

    select语句

    比如这样

    +
    public static void main(String[] args) {
    +    String selectSql = new SQL() {{
    +        SELECT("id", "name");
    +        FROM("student");
    +        WHERE("id = #{id}");
    +    }}.toString();
    +    System.out.println(selectSql);
    +}
    +

    打印出来就是

    +
    SELECT id, name
    +FROM student
    +WHERE (id = #{id})
    +

    应付简单的 sql 查询基本都可以这么解决,如果习惯这种模式,还是不错的,
    其实以面向对象的编程模式来说,这样是比较符合面向对象的,先不深入的解析这块的源码,先从使用角度讲一下

    +

    比如 update 语句

    String updateSql = new SQL() {{
    +            UPDATE("student");
    +            SET("name = #{name}");
    +            WHERE("id = #{id}");
    +        }}.toString();
    +

    打印输出就是

    +
    UPDATE student
    +SET name = #{name}
    +WHERE (id = #{id})
    -

    结果

    (3, 2)
    -(1, 2)
    -(4, 2)
    -(2, 2)
    -(5, 2)
    +

    insert 语句

    String insertSql = new SQL() {{
    +            INSERT_INTO("student");
    +            VALUES("name", "#{name}");
    +            VALUES("age", "#{age}");
    +        }}.toString();
    +        System.out.println(insertSql);
    +

    打印输出

    +
    INSERT INTO student
    + (name, age)
    +VALUES (#{name}, #{age})
    +

    delete语句

    String deleteSql = new SQL() {{
    +            DELETE_FROM("student");
    +            WHERE("id = #{id}");
    +        }}.toString();
    +        System.out.println(deleteSql);
    +

    打印输出

    +
    DELETE FROM student
    +WHERE (id = #{id})
    ]]>
    - data analysis + Java + Mybatis - spark - python + Java + Mysql + Mybatis
    - rust学习笔记-所有权三之切片 - /2021/05/16/rust%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0-%E6%89%80%E6%9C%89%E6%9D%83%E4%B8%89%E4%B9%8B%E5%88%87%E7%89%87/ - 除了引用,Rust 还有另外一种不持有所有权的数据类型:切片(slice)。切片允许我们引用集合中某一段连续的元素序列,而不是整个集合。
    例如代码

    -
    fn main() {
    -    let mut s = String::from("hello world");
    -
    -    let word = first_word(&s);
    -
    -    s.clear();
    -
    -    // 这时候虽然 word 还是 5,但是 s 已经被清除了,所以就没存在的意义
    -}
    -

    这里其实我们就需要关注 s 的存在性,代码的逻辑合理性就需要额外去维护,此时我们就可以用切片

    -
    let s = String::from("hello world")
    -
    -let hello = &s[0..5];
    -let world = &s[6..11];
    -

    其实跟 Python 的list 之类的语法有点类似,当然里面还有些语法糖,比如可以直接用省略后面的数字表示直接引用到结尾

    -
    let hello = &s[0..];
    -

    甚至再进一步

    -
    let hello = &s[..];
    -

    使用了切片之后

    -
    fn first_word(s: &String) -> &str {
    -    let bytes = s.as_bytes();
    -
    -    for (i, &item) in bytes.iter().enumerate() {
    -        if item == b' ' {
    -            return &s[0..i];
    -        }
    -    }
    -
    -    &s[..]
    -}
    -fn main() {
    -    let mut s = String::from("hello world");
    -
    -    let word = first_word(&s);
    -
    -    s.clear(); // error!
    +    spring boot中的 http 接口返回 json 形式的小注意点
    +    /2023/06/25/spring-boot%E4%B8%AD%E7%9A%84-http-%E6%8E%A5%E5%8F%A3%E8%BF%94%E5%9B%9E-json-%E5%BD%A2%E5%BC%8F%E7%9A%84%E5%B0%8F%E6%B3%A8%E6%84%8F%E7%82%B9/
    +    这个可能是个很简单的点,不过之前碰到了就记录下,我们常规的应用都是使用统一的请求响应转换器去处理请求和响应返回,但是对于有文件上传或者返回的是文件的情况,一般都是不使用统一的处理,但是在响应返回的时候可能会存在这样的情况,如果文件正常被处理那就返回文件,如果处理异常需要给前端返回 json类型的响应,里面能够取到响应码错误描述等

    +

    比如在请求中参数就使用 httpRequest(HttpServletRequest request, HttpServletResponse response)
    然后在返回的时候就使用 response.getOutputStream().write(result),而如果是要返回 json 形式的话就可以像这个文章说明的
    链接

    +
    Employee employee = new Employee(1, "Karan", "IT", 5000);
    +String employeeJsonString = this.gson.toJson(employee);
     
    -    println!("the first word is: {}", word);
    -}
    -

    那再执行 main 函数的时候就会抛错,因为 word 还是个切片,需要保证 s 的有效性,并且其实我们可以将函数申明成

    -
    fn first_word(s: &str) -> &str {
    -

    这样就既能处理&String 的情况,就是当成完整字符串的切片,也能处理普通的切片。
    其他类型的切片

    -
    let a = [1, 2, 3, 4, 5];
    -let slice = &a[1..3];
    -

    简单记录下,具体可以去看看这本书

    +PrintWriter out = response.getWriter(); +response.setContentType("application/json"); +response.setCharacterEncoding("UTF-8"); +out.print(employeeJsonString); +out.flush();
    +

    一开始我也是这么一搜就用了,后来发现返回的一直是乱码,仔细看了下发现了个问题,就是这个 response 设置 contentType 是在getWriter之后的,这样自然就不会起作用了,所以要在设置 setContentTypesetCharacterEncoding 之后再 getWriter,之后就可以正常返回了。

    ]]>
    - 语言 - Rust + Java + SpringBoot - Rust - 所有权 - 内存分布 - 新语言 - 可变引用 - 不可变引用 - 切片 + Java + Spring + SpringBoot
    @@ -12152,56 +12113,78 @@ for _ in data: - powershell 初体验二 - /2022/11/20/powershell-%E5%88%9D%E4%BD%93%E9%AA%8C%E4%BA%8C/ - powershell创建数组也很方便
    可以这样

    -
    $nums=2,0,1,2
    -

    顺便可以用下我们上次学到的gettype()

    -

    如果是想创建连续数字的数组还可以用这个方便的方法

    -
    $nums=1..5
    -


    而且数组还可以存放各种类型的数据

    -
    $array=1,"哈哈",([System.Guid]::NewGuid()),(get-date)
    -


    还有判断类型可以用-is

    创建一个空数组

    -
    $array=@()
    -


    数组添加元素

    -
    $array+="a"
    -


    数组删除元素

    -
    $a=1..4
    -$a=$a[0..1]+$a[3]
    -

    -]]>
    - - 语言 - - - powershell - -
    - - rust学习笔记-所有权一 - /2021/04/18/rust%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/ - 最近在看 《rust 权威指南》,还是难度比较大的,它里面的一些概念跟之前的用过的都有比较大的差别
    比起有 gc 的虚拟机语言,跟像 C 和 C++这种主动释放内存的,rust 有他的独特点,主要是有三条

    + rust学习笔记-所有权二 + /2021/04/18/rust%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0-%E6%89%80%E6%9C%89%E6%9D%83%E4%BA%8C/ + 这里需要说道函数和返回值了
    可以看书上的这个例子

    对于这种情况,当进入函数内部时,会把传入的变量的所有权转移进函数内部,如果最后还是要返回该变量,但是如果此时还要返回别的计算结果,就可能需要笨拙地使用元组

    +

    引用

    此时我们就可以用引用来解决这个问题

    +
    fn main() {
    +    let s1 = String::from("hello");
    +    let len = calculate_length(&s1);
    +
    +    println!("The length of '{}' is {}", s1, len);
    +}
    +fn calculate_length(s: &String) -> usize {
    +    s.len()
    +}
    +

    这里的&符号就是引用的语义,它们允许你在不获得所有权的前提下使用值

    由于引用不持有值的所有权,所以当引用离开当前作用域时,它指向的值也不会被丢弃

    +

    可变引用

    而当我们尝试对引用的字符串进行修改时

    +
    fn main() {
    +    let s1 = String::from("hello");
    +    change(&s1);
    +}
    +fn change(s: &String) {
    +    s.push_str(", world");
    +}
    +

    就会有以下报错,

    其实也很容易发现,毕竟没有 mut 指出这是可变引用,同时需要将 s1 改成 mut 可变的

    +
    fn main() {
    +    let mut s1 = String::from("hello");
    +    change(&mut s1);
    +}
    +
    +
    +fn change(s: &mut String) {
    +    s.push_str(", world");
    +}
    +

    再看一个例子

    +
    fn main() {
    +    let mut s1 = String::from("hello");
    +    let r1 = &mut s1;
    +    let r2 = &mut s1;
    +}
    +

    这个例子在书里是会报错的,因为同时存在一个以上的可变引用,但是在我运行的版本里前面这段没有报错,只有当我真的要去更改的时候

    +
    fn main() {
    +    let mut s1 = String::from("hello");
    +    let mut r1 = &mut s1;
    +    let mut r2 = &mut s1;
    +    change(&mut r1);
    +    change(&mut r2);
    +}
    +
    +
    +fn change(s: &mut String) {
    +    s.push_str(", world");
    +}
    +


    这里可能就是具体版本在实现上的一个差异,我用的 rustc 是 1.44.0 版本
    其实上面的主要是由 rust 想要避免这类多重可变更导致的异常问题,总结下就是三个点

      -
    • Rust中的每一个值都有一个对应的变量作为它的所有者。
    • -
    • 在同一时间内,值有且只有一个所有者。
    • -
    • 当所有者离开自己的作用域时,它持有的值就会被释放掉。

      这里有两个重点:
    • -
    • s 在进入作用域后才变得有效
    • -
    • 它会保持自己的有效性直到自己离开作用域为止
    • +
    • 两个或两个以上的指针同时同时访问同一空间
    • +
    • 其中至少有一个指针会想空间中写入数据
    • +
    • 没有同步数据访问的机制
      并且我们不能在拥有不可变引用的情况下创建可变引用
    -

    然后看个案例

    -
    let x = 5;
    -let y = x;
    -

    这个其实有两种,一般可以认为比较多实现的会使用 copy on write 之类的,先让两个都指向同一个快 5 的存储,在发生变更后开始正式拷贝,但是涉及到内存处理的便利性,对于这类简单类型,可以直接拷贝
    但是对于非基础类型

    -
    let s1 = String::from("hello");
    -let s2 = s1;
    -
    -println!("{}, world!", s1);
    -

    有可能认为有两种内存分布可能
    先看下 string 的内存结构

    第一种可能是

    第二种是

    我们来尝试编译下

    发现有这个错误,其实在 rust 中let y = x这个行为的实质是移动,在赋值给 y 之后 x 就无效了

    这样子就不会造成脱离作用域时,对同一块内存区域的二次释放,如果需要复制,可以使用 clone 方法

    -
    let s1 = String::from("hello");
    -let s2 = s1.clone();
    +

    悬垂引用

    还有一点需要注意的就是悬垂引用

    +
    fn main() {
    +    let reference_to_nothing = dangle();
    +}
     
    -println!("s1 = {}, s2 = {}", s1, s2);
    -

    这里其实会有点疑惑,为什么前面的x, y 的行为跟 s1, s2 的不一样,其实主要是基本类型和 string 这类的不定大小的类型的内存分配方式不同,x, y这类整型可以直接确定大小,可以直接在栈上分配,而像 string 和其他的变体结构体,其大小都是不能在编译时确定,所以需要在堆上进行分配

    +fn dangle() -> &String { + let s = String::from("hello"); + &s +}
    +

    这里可以看到其实在 dangle函数返回后,这里的 s 理论上就离开了作用域,但是由于返回了 s 的引用,在 main 函数中就会拿着这个引用,就会出现如下错误

    +

    总结

    最后总结下

    +
      +
    • 在任何一个段给定的时间里,你要么只能拥有一个可变引用,要么只能拥有任意数量的不可变引用。
    • +
    • 引用总是有效的。
    • +
    ]]>
    语言 @@ -12212,45 +12195,141 @@ for _ in data: 所有权 内存分布 新语言 + 可变引用 + 不可变引用
    - powershell 初体验 - /2022/11/13/powershell-%E5%88%9D%E4%BD%93%E9%AA%8C/ - powershell变量

    变量命名类似于php

    -
    PS C:\Users\Nicks> $a=1
    -PS C:\Users\Nicks> $b=2
    -PS C:\Users\Nicks> $a*$b
    -2
    -

    有一个比较好用的是变量交换
    一般的语言做两个变量交换一般需要一个临时变量

    -
    $tmp=$a
    -$a=$b
    -$b=$tmp
    -

    而在powershell中可以这样

    -
    $a,$b=$b,$a
    -PS C:\Users\Nicks> $a,$b=$b,$a
    -PS C:\Users\Nicks> $a
    -2
    -PS C:\Users\Nicks> $b
    -1
    -

    还可以通过这个

    -
    PS C:\Users\Nicks> ls variable:
    +    springboot 处理请求的小分支-跳转 & cookie
    +    /2023/09/03/springboot-%E5%A4%84%E7%90%86%E8%AF%B7%E6%B1%82%E7%9A%84%E5%B0%8F%E5%88%86%E6%94%AF-%E8%B7%B3%E8%BD%AC-cookie/
    +    首先是跳转,应该说设置状态,其中跳转是其中一个状态,

    +
    @RequestMapping(value = "request1", method = RequestMethod.GET)
    +    public void request1(HttpServletRequest request, HttpServletResponse response) {
    +        response.setStatus(HttpServletResponse.SC_OK);
    +    }
    +

    200 状态就很简单,如果想做跳转可以使用 302 并设置 location

    +
    @RequestMapping(value = "request2", method = RequestMethod.GET)
    +public void request2(HttpServletRequest request, HttpServletResponse response) {
    +    response.setHeader("Location", "https://baidu.com");
    +    response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
    +}
    +

    这里如果设置了 302,但没设置跳转 location,就是 302 found

    +
    int SC_MOVED_TEMPORARILY = 302;
    +int SC_FOUND = 302;
    + +

    而如果是 301 跳转,代表原地址不可用了,永久跳转

    +
    @RequestMapping(value = "request3", method = RequestMethod.GET)
    +    public void request3(HttpServletRequest request, HttpServletResponse response) {
    +        response.setHeader("Location", "https://baidu.com");
    +        response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
    +    }
    +

    另一个问题是设置 cookie

    @RequestMapping(value = "request4", method = RequestMethod.GET)
    +    public void request4(HttpServletRequest request, HttpServletResponse response) {
    +        Cookie cookie = new Cookie("a", "b");
    +        response.addCookie(cookie);
    +        response.setStatus(HttpServletResponse.SC_OK);
    +    }
    +

    这样的设置就能成功设定 cookie,而随着目前的浏览器 cookie 策略,如果要跳转后设置的话,估计是会越来越难,包括

    +
    response.addHeader("Set-Cookie", "a=b; domain=baidu.com; SameSite=none;Secure");
    +

    这样的方式也没法实现。

    +]]>
    + + Java + SpringBoot + + + Java + SpringBoot + + + + springboot 获取 web 应用中所有的接口 url + /2023/08/06/springboot-%E8%8E%B7%E5%8F%96-web-%E5%BA%94%E7%94%A8%E4%B8%AD%E6%89%80%E6%9C%89%E7%9A%84%E6%8E%A5%E5%8F%A3-url/ + 最近有个小需求,要把我们一个 springboot 应用的 request mapping 给导出来,这么说已经是转化过了的,应该是要整理这个应用所有的接口路径,比如我有一个 api.baidu1.com 作为接口域名,然后这个域名下有很多个接口提供服务,这些接口都是写在一个 springboot 应用里,如果本身有网关管理这些接口转发的其实可以通过网关的数据输出,这里就介绍下通过代码来获取

    +
    RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class);
    +Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
    +for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : map.entrySet()) {
    +    Set<String> urlSet = entry.getKey().getPatternsCondition().getPatterns();
    +    for (String url : urlSet) {
    +        System.out.println(url);
    +    }
    +}
    +

    第一行

    逐行来解析下,第一行就是从上下文中获取 RequestMappingHandlerMapping 这个 bean,

    +

    第二行

    然后调用了 getHandlerMethods,
    这里面具体执行了

    +
    public Map<T, HandlerMethod> getHandlerMethods() {
    +		this.mappingRegistry.acquireReadLock();
    +		try {
    +			return Collections.unmodifiableMap(this.mappingRegistry.getMappings());
    +		}
    +		finally {
    +			this.mappingRegistry.releaseReadLock();
    +		}
    +	}
    +

    前后加了锁,重要的就是从 mappingRegistry 中获取 mappings, 这里获取的就是
    org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.MappingRegistry#getMappings 具体的代码

    +
    public Map<T, HandlerMethod> getMappings() {
    +	return this.mappingLookup;
    +}
    +

    而这个 mappingLookup 再来看下

    +
    class MappingRegistry {
    +
    +	private final Map<T, MappingRegistration<T>> registry = new HashMap<>();
    +
    +	private final Map<T, HandlerMethod> mappingLookup = new LinkedHashMap<>();
    +

    可以看到就是在 MappingRegistry 中的一个变量,至于这个变量是怎么来的,简单的考虑下 springboot 处理请求的流程,就是从 Mapping 去找到对应的 Handler,所以就需要提前将这个对应关系存到这个变量里,
    具体可以看这 org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.MappingRegistry#register

    +
    public void register(T mapping, Object handler, Method method) {
    +			// Assert that the handler method is not a suspending one.
    +			if (KotlinDetector.isKotlinType(method.getDeclaringClass())) {
    +				Class<?>[] parameterTypes = method.getParameterTypes();
    +				if ((parameterTypes.length > 0) && "kotlin.coroutines.Continuation".equals(parameterTypes[parameterTypes.length - 1].getName())) {
    +					throw new IllegalStateException("Unsupported suspending handler method detected: " + method);
    +				}
    +			}
    +			this.readWriteLock.writeLock().lock();
    +			try {
    +				HandlerMethod handlerMethod = createHandlerMethod(handler, method);
    +				validateMethodMapping(handlerMethod, mapping);
    +				this.mappingLookup.put(mapping, handlerMethod); 
    +

    就是在这里会把 mapping 和 handleMethod 对应关系存进去

    +

    第三行

    这里拿的是上面的 map 里的 key,也就是 RequestMappingInfo 也就是 org.springframework.web.servlet.mvc.method.RequestMappingInfo
    而真的 url 就存在 org.springframework.web.servlet.mvc.condition.PatternsRequestCondition
    最终这里面的patterns就是我们要的路径

    +
    public class PatternsRequestCondition extends AbstractRequestCondition<PatternsRequestCondition> {
    +
    +	private final static Set<String> EMPTY_PATH_PATTERN = Collections.singleton("");
    +
    +
    +	private final Set<String> patterns;
    +

    写到这下一篇是不是可以介绍下 mapping 的具体注册逻辑

    +]]>
    + + Java + SpringBoot + + + Java + SpringBoot + +
    + + spark-little-tips + /2017/03/28/spark-little-tips/ + spark 的一些粗浅使用经验

    工作中学习使用了一下Spark做数据分析,主要是用spark的python接口,首先是pyspark.SparkContext(appName=xxx),这是初始化一个Spark应用实例或者说会话,不能重复,
    返回的实例句柄就可以调用textFile(path)读取文本文件,这里的文本文件可以是HDFS上的文本文件,也可以普通文本文件,但是需要在Spark的所有集群上都存在,否则会
    读取失败,parallelize则可以将python生成的集合数据读取后转换成rdd(A Resilient Distributed Dataset (RDD),一种spark下的基本抽象数据集),基于这个RDD就可以做
    数据的流式计算,例如map reduce,在Spark中可以非常方便地实现

    +

    简单的mapreduce word count示例

    textFile = sc.parallelize([(1,1), (2,1), (3,1), (4,1), (5,1),(1,1), (2,1), (3,1), (4,1), (5,1)])
    +data = textFile.reduceByKey(lambda x, y: x + y).collect()
    +for _ in data:
    +    print(_)
    -Name Value ----- ----- -$ $b -? True -^ $b -a 2 -args {} -b 1
    -

    查看现存的变量
    当然一般脚本都是动态类型的,
    可以通过
    gettype方法

    + +

    结果

    (3, 2)
    +(1, 2)
    +(4, 2)
    +(2, 2)
    +(5, 2)
    ]]>
    - 语言 + data analysis - powershell + spark + python
    @@ -12375,299 +12454,28 @@ b 1.mappingLookup.put(mapping, handlerMethod); List<String> directUrls = getDirectUrls(mapping); - for (String url : directUrls) { - this.urlLookup.add(url, mapping); - } - - String name = null; - if (getNamingStrategy() != null) { - name = getNamingStrategy().getName(handlerMethod, mapping); - addMappingName(name, handlerMethod); - } - - CorsConfiguration corsConfig = initCorsConfiguration(handler, method, mapping); - if (corsConfig != null) { - this.corsLookup.put(handlerMethod, corsConfig); - } - - this.registry.put(mapping, new MappingRegistration<>(mapping, handlerMethod, directUrls, name)); - } - finally { - this.readWriteLock.writeLock().unlock(); - } - }
    -

    底层的存储就是上一篇说的 mappingLookup 来存储信息

    -]]> - - Java - SpringBoot - - - Java - SpringBoot - - - - springboot 请求响应处理流程 - /2023/08/27/springboot-%E8%AF%B7%E6%B1%82%E5%93%8D%E5%BA%94%E5%A4%84%E7%90%86%E6%B5%81%E7%A8%8B/ - Tomcat 会把请求委托到
    org.springframework.web.servlet.DispatcherServlet#doService

    -
    protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
    -		logRequest(request);
    -
    -        // 省略前面的代码
    -		try {
    -			doDispatch(request, response);
    -		}
    -

    然后就是调用
    org.springframework.web.servlet.DispatcherServlet#doDispatch

    -
    protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
    -
    -	try {
    -		ModelAndView mv = null;
    -		Exception dispatchException = null;
    -
    -		try {
    -			processedRequest = checkMultipart(request);
    -			multipartRequestParsed = (processedRequest != request);
    -
    -               // 去获取处理器
    -			// Determine handler for the current request.
    -			mappedHandler = getHandler(processedRequest);
    -			if (mappedHandler == null) {
    -				noHandlerFound(processedRequest, response);
    -				return;
    -			}
    -
    -			// Determine handler adapter for the current request.
    -			HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
    -
    -			// Process last-modified header, if supported by the handler.
    -			String method = request.getMethod();
    -			boolean isGet = HttpMethod.GET.matches(method);
    -			if (isGet || HttpMethod.HEAD.matches(method)) {
    -				long lastModified = ha.getLastModified(request, mappedHandler.getHandler());
    -				if (new ServletWebRequest(request, response).checkNotModified(lastModified) && isGet) {
    -					return;
    -				}
    -			}
    -
    -			if (!mappedHandler.applyPreHandle(processedRequest, response)) {
    -				return;
    -			}
    -
    -			// Actually invoke the handler.
    -			mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
    -
    -

    看下这里的逻辑

    -
    @Nullable
    -protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
    -	if (this.handlerMappings != null) {
    -		for (HandlerMapping mapping : this.handlerMappings) {
    -			HandlerExecutionChain handler = mapping.getHandler(request);
    -			if (handler != null) {
    -				return handler;
    -			}
    -		}
    -	}
    -	return null;
    -}
    -

    可以看到有这些 HandlerMapping

    而这里面就是前面提到过的
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping
    从这就能找到具体的 Handler
    com.nicksxs.spbdemo.controller.DemoController#test()
    这就是我简单的示例代码

    -
    @RequestMapping(value = "/test", method = RequestMethod.GET)
    -@ResponseBody
    -public DemoResponse test() {
    -    String item = "{\"id\": 1, \"name\": \"nick\"}";
    -    ParserConfig parserConfig = ParserConfig.getGlobalInstance();
    -    parserConfig.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
    -    DemoResponse response = JSON.parseObject(item, DemoResponse.class, parserConfig);
    -    return response;
    -}
    -

    下一步是再获取处理器的适配器,
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter

    -
    protected HandlerAdapter getHandlerAdapter(Object handler) throws ServletException {
    -		if (this.handlerAdapters != null) {
    -			for (HandlerAdapter adapter : this.handlerAdapters) {
    -				if (adapter.supports(handler)) {
    -					return adapter;
    -				}
    -			}
    -		}
    -		throw new ServletException("No adapter for handler [" + handler +
    -				"]: The DispatcherServlet configuration needs to include a HandlerAdapter that supports this handler");
    -	}
    -

    正好这个适配器是调用的父类的 supports 方法

    -
    @Override
    -public final boolean supports(Object handler) {
    -	return (handler instanceof HandlerMethod && supportsInternal((HandlerMethod) handler));
    -}
    -

    而我这个com.nicksxs.spbdemo.controller.DemoController#test()
    就是个包装好的 HandlerMethod
    然后就是调用 hahandle 方法,也是通过模板方法,实际调用的是
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter#handle

    -
    @Override
    -@Nullable
    -public final ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler)
    -		throws Exception {
    -
    -	return handleInternal(request, response, (HandlerMethod) handler);
    -}
    -

    然后调用
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#handleInternal

    -
    @Override
    -	protected ModelAndView handleInternal(HttpServletRequest request,
    -			HttpServletResponse response, HandlerMethod handlerMethod) throws Exception {
    -
    -		ModelAndView mav;
    -		checkRequest(request);
    -
    -		// Execute invokeHandlerMethod in synchronized block if required.
    -		if (this.synchronizeOnSession) {
    -			HttpSession session = request.getSession(false);
    -			if (session != null) {
    -				Object mutex = WebUtils.getSessionMutex(session);
    -				synchronized (mutex) {
    -					mav = invokeHandlerMethod(request, response, handlerMethod);
    -				}
    -			}
    -			else {
    -				// No HttpSession available -> no mutex necessary
    -				mav = invokeHandlerMethod(request, response, handlerMethod);
    -			}
    -		}
    -		else {
    -            // 是否要锁定 session,否则走到这
    -			// No synchronization on session demanded at all...
    -			mav = invokeHandlerMethod(request, response, handlerMethod);
    -		}
    - -

    继续调用
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#invokeHandlerMethod

    -
    @Nullable
    -	protected ModelAndView invokeHandlerMethod(HttpServletRequest request,
    -			HttpServletResponse response, HandlerMethod handlerMethod) throws Exception {
    -
    -		ServletWebRequest webRequest = new ServletWebRequest(request, response);
    -		try {
    -			WebDataBinderFactory binderFactory = getDataBinderFactory(handlerMethod);
    -			ModelFactory modelFactory = getModelFactory(handlerMethod, binderFactory);
    -
    -            // 包装调用方法,
    -			ServletInvocableHandlerMethod invocableMethod = createInvocableHandlerMethod(handlerMethod);
    -			// 省略一部分非本次关注核心代码
    -            // 然后是调用到这
    -			invocableMethod.invokeAndHandle(webRequest, mavContainer);
    -			if (asyncManager.isConcurrentHandlingStarted()) {
    -				return null;
    -			}
    -
    -			return getModelAndView(mavContainer, modelFactory, webRequest);
    -		}
    -		finally {
    -			webRequest.requestCompleted();
    -		}
    -	}
    -

    稍微再看一眼
    第一步是
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#createInvocableHandlerMethod

    -
    protected ServletInvocableHandlerMethod createInvocableHandlerMethod(HandlerMethod handlerMethod) {
    -	return new ServletInvocableHandlerMethod(handlerMethod);
    -}
    -

    第二步是
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod#ServletInvocableHandlerMethod(org.springframework.web.method.HandlerMethod)

    -
       public ServletInvocableHandlerMethod(HandlerMethod handlerMethod) {
    -	super(handlerMethod);
    -}
    -

    第三步是
    org.springframework.web.method.support.InvocableHandlerMethod#InvocableHandlerMethod(org.springframework.web.method.HandlerMethod)

    -
       public InvocableHandlerMethod(HandlerMethod handlerMethod) {
    -	super(handlerMethod);
    -}
    -

    第四步是
    org.springframework.web.method.HandlerMethod#HandlerMethod(org.springframework.web.method.HandlerMethod)

    -
    protected HandlerMethod(HandlerMethod handlerMethod) {
    -	Assert.notNull(handlerMethod, "HandlerMethod is required");
    -	this.bean = handlerMethod.bean;
    -	this.beanFactory = handlerMethod.beanFactory;
    -	this.beanType = handlerMethod.beanType;
    -	this.method = handlerMethod.method;
    -	this.bridgedMethod = handlerMethod.bridgedMethod;
    -	this.parameters = handlerMethod.parameters;
    -	this.responseStatus = handlerMethod.responseStatus;
    -	this.responseStatusReason = handlerMethod.responseStatusReason;
    -	this.description = handlerMethod.description;
    -	this.resolvedFromHandlerMethod = handlerMethod.resolvedFromHandlerMethod;
    -}
    -

    这是个继承关系,一直调用到最顶层的父类的构造方法,其实就是拷贝,然后继续调用
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod#invokeAndHandle

    -
    public void invokeAndHandle(ServletWebRequest webRequest, ModelAndViewContainer mavContainer,
    -			Object... providedArgs) throws Exception {
    -
    -        // 调用请求
    -		Object returnValue = invokeForRequest(webRequest, mavContainer, providedArgs);
    -		// 稍微忽略下后面的代码
    -	}
    -

    继续调用
    org.springframework.web.method.support.InvocableHandlerMethod#invokeForRequest

    -
    @Nullable
    -public Object invokeForRequest(NativeWebRequest request, @Nullable ModelAndViewContainer mavContainer,
    -		Object... providedArgs) throws Exception {
    +				for (String url : directUrls) {
    +					this.urlLookup.add(url, mapping);
    +				}
     
    -	Object[] args = getMethodArgumentValues(request, mavContainer, providedArgs);
    -	if (logger.isTraceEnabled()) {
    -		logger.trace("Arguments: " + Arrays.toString(args));
    -	}
    -	return doInvoke(args);
    -}
    -

    来到了最核心处
    org.springframework.web.method.support.InvocableHandlerMethod#doInvoke

    -
    @Nullable
    -protected Object doInvoke(Object... args) throws Exception {
    -	Method method = getBridgedMethod();
    -	ReflectionUtils.makeAccessible(method);
    -	try {
    -		if (KotlinDetector.isSuspendingFunction(method)) {
    -			return CoroutinesUtils.invokeSuspendingFunction(method, getBean(), args);
    -		}
    -           // 会走到这里,获取到 bean,而这个 bean 就是前面构造方法里赋值的,最开始被放在 handler 里面,然后调用方法
    -		return method.invoke(getBean(), args);
    -	}
    -]]>
    - - Java - SpringBoot - - - Java - SpringBoot - -
    - - summary-ranges-228 - /2016/10/12/summary-ranges-228/ - problem

    Given a sorted integer array without duplicates, return the summary of its ranges.

    -

    For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"].

    -

    题解

    每一个区间的起点nums[i]加上j是否等于nums[i+j]
    参考

    -

    Code

    class Solution {
    -public:
    -    vector<string> summaryRanges(vector<int>& nums) {
    -        int i = 0, j = 1, n;
    -        vector<string> res;
    -        n = nums.size();
    -        while(i < n){
    -            j = 1;
    -            while(j < n && nums[i+j] - nums[i] == j) j++;
    -            res.push_back(j <= 1 ? to_string(nums[i]) : to_string(nums[i]) + "->" + to_string(nums[i + j - 1]));
    -            i += j;
    -        }
    -        return res;
    -    }
    -};
    ]]>
    - - leetcode - - - leetcode - c++ - -
    - - spring boot中的 http 接口返回 json 形式的小注意点 - /2023/06/25/spring-boot%E4%B8%AD%E7%9A%84-http-%E6%8E%A5%E5%8F%A3%E8%BF%94%E5%9B%9E-json-%E5%BD%A2%E5%BC%8F%E7%9A%84%E5%B0%8F%E6%B3%A8%E6%84%8F%E7%82%B9/ - 这个可能是个很简单的点,不过之前碰到了就记录下,我们常规的应用都是使用统一的请求响应转换器去处理请求和响应返回,但是对于有文件上传或者返回的是文件的情况,一般都是不使用统一的处理,但是在响应返回的时候可能会存在这样的情况,如果文件正常被处理那就返回文件,如果处理异常需要给前端返回 json类型的响应,里面能够取到响应码错误描述等

    -

    比如在请求中参数就使用 httpRequest(HttpServletRequest request, HttpServletResponse response)
    然后在返回的时候就使用 response.getOutputStream().write(result),而如果是要返回 json 形式的话就可以像这个文章说明的
    链接

    -
    Employee employee = new Employee(1, "Karan", "IT", 5000);
    -String employeeJsonString = this.gson.toJson(employee);
    +				String name = null;
    +				if (getNamingStrategy() != null) {
    +					name = getNamingStrategy().getName(handlerMethod, mapping);
    +					addMappingName(name, handlerMethod);
    +				}
     
    -PrintWriter out = response.getWriter();
    -response.setContentType("application/json");
    -response.setCharacterEncoding("UTF-8");
    -out.print(employeeJsonString);
    -out.flush();   
    -

    一开始我也是这么一搜就用了,后来发现返回的一直是乱码,仔细看了下发现了个问题,就是这个 response 设置 contentType 是在getWriter之后的,这样自然就不会起作用了,所以要在设置 setContentTypesetCharacterEncoding 之后再 getWriter,之后就可以正常返回了。

    + CorsConfiguration corsConfig = initCorsConfiguration(handler, method, mapping); + if (corsConfig != null) { + this.corsLookup.put(handlerMethod, corsConfig); + } + + this.registry.put(mapping, new MappingRegistration<>(mapping, handlerMethod, directUrls, name)); + } + finally { + this.readWriteLock.writeLock().unlock(); + } + }
    +

    底层的存储就是上一篇说的 mappingLookup 来存储信息

    ]]> Java @@ -12675,7 +12483,6 @@ out.flush Java - Spring SpringBoot @@ -12881,68 +12688,32 @@ out.flush - springboot 处理请求的小分支-跳转 & cookie - /2023/09/03/springboot-%E5%A4%84%E7%90%86%E8%AF%B7%E6%B1%82%E7%9A%84%E5%B0%8F%E5%88%86%E6%94%AF-%E8%B7%B3%E8%BD%AC-cookie/ - 首先是跳转,应该说设置状态,其中跳转是其中一个状态,

    -
    @RequestMapping(value = "request1", method = RequestMethod.GET)
    -    public void request1(HttpServletRequest request, HttpServletResponse response) {
    -        response.setStatus(HttpServletResponse.SC_OK);
    -    }
    -

    200 状态就很简单,如果想做跳转可以使用 302 并设置 location

    -
    @RequestMapping(value = "request2", method = RequestMethod.GET)
    -public void request2(HttpServletRequest request, HttpServletResponse response) {
    -    response.setHeader("Location", "https://baidu.com");
    -    response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
    -}
    -

    这里如果设置了 302,但没设置跳转 location,就是 302 found

    -
    int SC_MOVED_TEMPORARILY = 302;
    -int SC_FOUND = 302;
    - -

    而如果是 301 跳转,代表原地址不可用了,永久跳转

    -
    @RequestMapping(value = "request3", method = RequestMethod.GET)
    -    public void request3(HttpServletRequest request, HttpServletResponse response) {
    -        response.setHeader("Location", "https://baidu.com");
    -        response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
    -    }
    -

    另一个问题是设置 cookie

    @RequestMapping(value = "request4", method = RequestMethod.GET)
    -    public void request4(HttpServletRequest request, HttpServletResponse response) {
    -        Cookie cookie = new Cookie("a", "b");
    -        response.addCookie(cookie);
    -        response.setStatus(HttpServletResponse.SC_OK);
    -    }
    -

    这样的设置就能成功设定 cookie,而随着目前的浏览器 cookie 策略,如果要跳转后设置的话,估计是会越来越难,包括

    -
    response.addHeader("Set-Cookie", "a=b; domain=baidu.com; SameSite=none;Secure");
    -

    这样的方式也没法实现。

    -]]>
    - - Java - SpringBoot - - - Java - SpringBoot - -
    - - 《垃圾回收算法手册读书》笔记之整理算法 - /2021/03/07/%E3%80%8A%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6%E7%AE%97%E6%B3%95%E6%89%8B%E5%86%8C%E8%AF%BB%E4%B9%A6%E3%80%8B%E7%AC%94%E8%AE%B0%E4%B9%8B%E6%95%B4%E7%90%86%E7%AE%97%E6%B3%95/ - 最近看了下这本垃圾回收算法手册,看到了第三章的标记-整理回收算法,做个简单的读书笔记

    -

    双指针整理算法

    对于一块待整理区域,通过两个指针,free 在区域的起始端,scan 指针在区域的末端,free 指针从前往后知道找到空闲区域,scan 从后往前一直找到存活对象,当 free 指针未与 scan 指针交叉时,会给 scan 位置的对象特定位置标记上 free 的地址,即将要转移的地址,不过这里有个限制,这种整理算法一般会用于对象大小统一的情况,否则 free 指针扫描时还需要匹配scan 指针扫描到的存活对象的大小。

    -

    Lisp 2 整理算法

    需要三次完整遍历堆区域
    第一遍是遍历后将计算出所有对象的最终地址(转发地址)
    第二遍是使用转发地址更新赋值器线程根以及被标记对象中的引用,该操作将确保它们指向对象的新位置
    第三次遍历是relocate最终将存活对象移动到其新的目标位置

    -

    引线整理算法

    这个真的长见识了,

    可以看到,原来是 A,B,C 对象引用了 N,这里会在第一次遍历的时候把这种引用反过来,让 N 的对象头部保存下 A 的地址,表示这类引用,然后在遍历到 B 的时候在链起来,到最后就会把所有引用了 N 对象的所有对象通过引线链起来,在第二次遍历的时候就把更新A,B,C 对象引用的 N 地址,并且移动 N 对象

    -

    单次遍历算法

    这个一直提到过位图的实现方式,

    可以看到在第一步会先通过位图标记,标记的方式是位图的每一位对应的堆内存的一个字(这里可能指的是 byte 吧),然后将一个存活对象的内存区域的第一个字跟最后一个字标记,这里如果在通过普通的方式就还需要一个地方在存转发地址,但是因为具体的位置可以通过位图算出来,也就不需要额外记录了

    -]]>
    + summary-ranges-228 + /2016/10/12/summary-ranges-228/ + problem

    Given a sorted integer array without duplicates, return the summary of its ranges.

    +

    For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"].

    +

    题解

    每一个区间的起点nums[i]加上j是否等于nums[i+j]
    参考

    +

    Code

    class Solution {
    +public:
    +    vector<string> summaryRanges(vector<int>& nums) {
    +        int i = 0, j = 1, n;
    +        vector<string> res;
    +        n = nums.size();
    +        while(i < n){
    +            j = 1;
    +            while(j < n && nums[i+j] - nums[i] == j) j++;
    +            res.push_back(j <= 1 ? to_string(nums[i]) : to_string(nums[i]) + "->" + to_string(nums[i + j - 1]));
    +            i += j;
    +        }
    +        return res;
    +    }
    +};
    ]]>
    - Java - gc - jvm + leetcode - java - gc - 标记整理 - 垃圾回收 - jvm + leetcode + c++
    @@ -13071,28 +12842,41 @@ user3: - ssh 小技巧-端口转发 - /2023/03/26/ssh-%E5%B0%8F%E6%8A%80%E5%B7%A7-%E7%AB%AF%E5%8F%A3%E8%BD%AC%E5%8F%91/ - 我们在使用 ssh 连接的使用有一个很好用功能,就是端口转发,而且使用的方式也很多样,比如我们经常用 vscode 来做远程开发的话,一般远程连接就可以基于 ssh,前面也介绍过 vscode 的端口转发,并且可以配置到 .ssh/config 配置文件里,只不过最近在一次使用的过程中发现了一个问题,就是在一台 Ubuntu 的某云服务器上想 ssh 到另一台服务器上,并且做下端口映射,但是发现报了个错,

    -
    bind: Cannot assign requested address
    -

    查了下这个问题,猜测是不是端口已经被占用了,查了下并不是,然后想到是不是端口是系统保留的,

    -
    sysctl -a |grep port_range
    -

    结果中

    -
    net.ipv4.ip_local_port_range = 50000    65000      -----意味着50000~65000端口可用
    -

    发现也不是,没有限制,最后才查到这个原因是默认如果有 ipv6 的话会使用 ipv6 的地址做映射
    所以如果是命令连接做端口转发的话,

    -
    ssh -4 -L 11234:localhost:1234 x.x.x.x
    -

    使用-4来制定通过 ipv4 地址来做映射
    如果是在 .ssh/config 中配置的话可以直接指定所有的连接都走 ipv4

    -
    Host *
    -    AddressFamily inet
    -

    inet代表 ipv4,inet6代表 ipv6
    AddressFamily 的所有取值范围是:”any”(默认)、”inet”(仅IPv4)、”inet6”(仅IPv6)。
    另外此类问题还可以通过 ssh -v 来打印更具体的信息

    + wordpress 忘记密码的一种解决方法 + /2021/12/05/wordpress-%E5%BF%98%E8%AE%B0%E5%AF%86%E7%A0%81%E7%9A%84%E4%B8%80%E7%A7%8D%E8%A7%A3%E5%86%B3%E6%96%B9%E6%B3%95/ + 前阵子搭了个 WordPress,但是没怎么用,前两天发现忘了登录密码了,最近不知道是什么情况,chrome 的记住密码跟历史记录感觉有点问题,历史记录丢了不少东西,可能是时间太久了,但是理论上应该有 LRU 这种策略的,有些还比较常用,还有记住密码,因为个人域名都是用子域名分配给各个服务,有些记住了,有些又没记住密码,略蛋疼,所以就找了下这个方案。
    当然这个方案不是最优的,有很多限制,首先就是要能够登陆 WordPress 的数据库,不然这个方法是没用的。
    首先不管用什么方式(别违法)先登陆数据库,选择 WordPress 的数据库,可以看到里面有几个表,我们的目标就是 wp_users 表,用 select 查询看下可以看到有用户的数据,如果是像我这样搭着玩的没有创建其他用户的话应该就只有一个用户,那我们的表里的用户数据就只会有一条,当然多条的话可以通过用户名来找

    然后可能我这个版本是这样,没有装额外的插件,密码只是经过了 MD5 的单向哈希,所以我们可以设定一个新密码,然后用 MD5 编码后直接更新进去

    +
    UPDATE wp_users SET user_pass = MD5('123456') WHERE ID = 1;
    + +

    然后就能用自己的账户跟刚才更新的密码登录了。

    ]]>
    - ssh - 技巧 + 小技巧 - ssh - 端口转发 + WordPress + 小技巧 + +
    + + 《垃圾回收算法手册读书》笔记之整理算法 + /2021/03/07/%E3%80%8A%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6%E7%AE%97%E6%B3%95%E6%89%8B%E5%86%8C%E8%AF%BB%E4%B9%A6%E3%80%8B%E7%AC%94%E8%AE%B0%E4%B9%8B%E6%95%B4%E7%90%86%E7%AE%97%E6%B3%95/ + 最近看了下这本垃圾回收算法手册,看到了第三章的标记-整理回收算法,做个简单的读书笔记

    +

    双指针整理算法

    对于一块待整理区域,通过两个指针,free 在区域的起始端,scan 指针在区域的末端,free 指针从前往后知道找到空闲区域,scan 从后往前一直找到存活对象,当 free 指针未与 scan 指针交叉时,会给 scan 位置的对象特定位置标记上 free 的地址,即将要转移的地址,不过这里有个限制,这种整理算法一般会用于对象大小统一的情况,否则 free 指针扫描时还需要匹配scan 指针扫描到的存活对象的大小。

    +

    Lisp 2 整理算法

    需要三次完整遍历堆区域
    第一遍是遍历后将计算出所有对象的最终地址(转发地址)
    第二遍是使用转发地址更新赋值器线程根以及被标记对象中的引用,该操作将确保它们指向对象的新位置
    第三次遍历是relocate最终将存活对象移动到其新的目标位置

    +

    引线整理算法

    这个真的长见识了,

    可以看到,原来是 A,B,C 对象引用了 N,这里会在第一次遍历的时候把这种引用反过来,让 N 的对象头部保存下 A 的地址,表示这类引用,然后在遍历到 B 的时候在链起来,到最后就会把所有引用了 N 对象的所有对象通过引线链起来,在第二次遍历的时候就把更新A,B,C 对象引用的 N 地址,并且移动 N 对象

    +

    单次遍历算法

    这个一直提到过位图的实现方式,

    可以看到在第一步会先通过位图标记,标记的方式是位图的每一位对应的堆内存的一个字(这里可能指的是 byte 吧),然后将一个存活对象的内存区域的第一个字跟最后一个字标记,这里如果在通过普通的方式就还需要一个地方在存转发地址,但是因为具体的位置可以通过位图算出来,也就不需要额外记录了

    +]]>
    + + Java + gc + jvm + + + java + gc + 标记整理 + 垃圾回收 + jvm
    @@ -13101,12 +12885,50 @@ user3: 断断续续地看完了马伯庸老师的《长安的荔枝》,一开始是看这本书在排行榜排得很高,又是马伯庸的,之前看过他的《古董局中局》,还是很有意思的,而且正好是比较短的,不过前后也拖了蛮久才看完,看完后读了下马老师自己写的后记,就特别有感触。
    整个故事是围绕一个上林署监事李善德被委任一项给贵妃送荔枝的差事展开,“长安回望绣成堆,山顶千门次第开,一骑红尘妃子笑,无人知是荔枝来”,以前没细究过这个送荔枝的过程,但是以以前的运输速度和保鲜条件,感觉也不是太现实,所以主人公一开始就以为只是像以往一样是送荔枝干这种,能比较方便运输,不容易变质的,结果发现其实是同僚在坑他,这次是要在贵妃生辰的时候给贵妃送来新鲜的岭南荔枝,用比较时兴的词来说,这就是个送命题啊,鲜荔枝一日色变,两日香变,三日味变,同僚的还有杜甫跟韩承,都觉得老李可以直接写休书了,保全家人,不然就是全家送命,李善德也觉得基本算是判刑了,而且其实是这事被转了几次,最后到老李所在的上林署,主管为了骗他接下这个活还特意在文书上把荔枝鲜的“鲜”字贴住,那会叫做“贴黄”,变成了荔枝“煎”,所以说官场险恶,大家都想把这烫手山芋丢出去,结果丢到了我们老实的老李头上,但是从接到这个通知到贵妃的生辰六月初一还有挺长的时间,其实这个活虽然送命,但是在前期这个“荔枝使”也基本就是类似带着尚方宝剑,御赐黄马褂的职位,随便申请经费,不必像常规的部门费用需要定预算,申请后再层层审批,而是特事特批特办的耍赖做法,所以在这段时间是能够潇洒挥霍一下的。其实可以好好地捞一波给妻女,然后写下和离,在自己死后能让她们过的好一些,但最后还是在杜甫的一番劝导下做出了尝试一番的决定,因为也没其他办法,既是退无可退,何不向前拼死一搏,其实说到这,我觉得看这本书感觉有所收获的第一点,有时候总觉得事情没戏了,想躺平放弃了,但是这样其实这个结果是不会变好的,尝试努力,拼尽全力搏一搏,说不定会有所改观,至少不会变更坏了。

    ]]>
    - 读后感 - 生活 + 读后感 + 生活 + + + 读后感 + 生活 + +
    + + 《寻羊历险记》读后感 + /2023/07/23/%E3%80%8A%E5%AF%BB%E7%BE%8A%E5%8E%86%E9%99%A9%E8%AE%B0%E3%80%8B%E8%AF%BB%E5%90%8E%E6%84%9F/ + 最近本来是在读《舞舞舞》,然后看到有介绍说,这个跟《寻羊历险记》是有情节上的关联,所以就先去看了《寻羊历险记》,《寻羊历险记》也是村上春树的第一本成规模的长篇小说,也可以认为是《舞舞舞》的前篇。
    最开始这个情节跟之前的刺杀骑士团长还是哪本有点类似,都有跟老婆离婚了,主角应该是个跟朋友一起开翻译社的,后面也开始做广告相关的,做到了经济收益还不错的阶段,也有一些挺哲学的对话,朋友觉得这么赚钱不地道(可能也是觉得这样忘了初心),在离婚以后又结交了一个耳朵很好看的女友,这个女友也是个比较抽象的存在,描述中给人感觉是一个外貌很普通的女孩,但是耳朵漂亮的惊为天人,不知道是不是有什么隐喻,感觉现实中没见过这样的人,女友平时把耳朵遮起来不轻易露出来,只有在跟主角做爱的时候才露出来
    主体剧情是因为男主在广告中用了一张一位叫“鼠”的朋友寄给他的一张包含一只特殊的羊的照片,就有个政界大佬的秘书找过来,逼迫主角要找到照片上的羊,这只羊背上有星纹,基本不可能属于在日本当时可能存在的羊的品种,因为这位政界大佬快病危了,所以要求主角必须在一个月内找到这只羊,因为这里把这只神秘的羊塑造成神一样的存在,这位政界大佬在年轻时被这只羊上身,后面就开始在政治事业上大展宏图,就基本成了能左右整个日本走向的巨佬,但近期随着巨佬,身体状态慢慢变差,这只羊就从他身上消失了,所以秘书要主角必须找到这只羊,不然基本会让主角的翻译社完蛋,这样主角就会面临破产赔偿等严重后果,只是说主角本来也一直是这种丧气存在,再说这么茫茫人海找个人都难,还要找这么一只玄乎的不太可能真实存在的羊,所以基本是想要放弃的,结果刚才说的耳朵很漂亮的女友却有着神乎其神的直觉,就觉得能找到,然后他们就踏上了巡羊的旅程,一开始到了札幌,寻找一无所获,然后神奇的是女友推荐一定要住的海豚宾馆,恰恰是一切线索的源头,宾馆老板的父亲正好是羊博士,在年轻的时候被羊上身过,后面离开后就去了那位巨佬身上,让巨佬成了真正控制日本的地下帝国的王,跟羊博士咨询后知道羊可能在十二瀑镇的牧场出现过,所以一路找寻,发现其实这个牧场中有个别墅正好是主角朋友“鼠”的,到了别墅后出现了个神秘的羊男,这个羊男真的不太明白是怎么个存在,就是让主角的女友回去了,然后最后一个肉体承载着“鼠”的灵魂跟主角有了一次接触,主角呆在这个别墅过着百无聊赖的生活,在才到有一次羊男来跟他交流的时候其实是承载着鼠的灵魂,就觉得是不是一切都是在忽悠他,离一个月期限也越来越近了,而在发怒之后,“鼠”真的出现后,但是不是真的“鼠”,而是只有他的灵魂,因为“鼠”已经死了,因为不想被“羊”附身,成为羊壳,并且让主角设定好时钟后的装置后尽快下山,第二天主角离开上了火车后山上牧场就传来爆炸声,“鼠”已经跟羊同归于尽了,免得再有其他人被羊附身,主角也很难过,回到故乡在四周大海已经被填掉了的旧防波堤上大哭悼念逝去的“鼠”。
    其实对于没什么时代概念或者对村上一直以来的观念不是特别敏感的,对这本书讲了啥有点云里雾里,后面看了一些简单的解释就是羊其实代表日本帝国主义和资本主义,可能是村上本人反帝国主义,军国主义和资本主义的一个表征,想来也有些道理,不然“鼠”的牺牲就感觉比较没意义,但是另一方面我的理解也可能是对自由的向往的表达,被羊控制,虽然可以成就“伟大”的事业,但是也丧失了自我。

    +]]>
    + + 读后感 + 生活 + + + 读后感 + +
    + + ssh 小技巧-端口转发 + /2023/03/26/ssh-%E5%B0%8F%E6%8A%80%E5%B7%A7-%E7%AB%AF%E5%8F%A3%E8%BD%AC%E5%8F%91/ + 我们在使用 ssh 连接的使用有一个很好用功能,就是端口转发,而且使用的方式也很多样,比如我们经常用 vscode 来做远程开发的话,一般远程连接就可以基于 ssh,前面也介绍过 vscode 的端口转发,并且可以配置到 .ssh/config 配置文件里,只不过最近在一次使用的过程中发现了一个问题,就是在一台 Ubuntu 的某云服务器上想 ssh 到另一台服务器上,并且做下端口映射,但是发现报了个错,

    +
    bind: Cannot assign requested address
    +

    查了下这个问题,猜测是不是端口已经被占用了,查了下并不是,然后想到是不是端口是系统保留的,

    +
    sysctl -a |grep port_range
    +

    结果中

    +
    net.ipv4.ip_local_port_range = 50000    65000      -----意味着50000~65000端口可用
    +

    发现也不是,没有限制,最后才查到这个原因是默认如果有 ipv6 的话会使用 ipv6 的地址做映射
    所以如果是命令连接做端口转发的话,

    +
    ssh -4 -L 11234:localhost:1234 x.x.x.x
    +

    使用-4来制定通过 ipv4 地址来做映射
    如果是在 .ssh/config 中配置的话可以直接指定所有的连接都走 ipv4

    +
    Host *
    +    AddressFamily inet
    +

    inet代表 ipv4,inet6代表 ipv6
    AddressFamily 的所有取值范围是:”any”(默认)、”inet”(仅IPv4)、”inet6”(仅IPv6)。
    另外此类问题还可以通过 ssh -v 来打印更具体的信息

    +]]>
    + + ssh + 技巧 - 生活 - 读后感 + ssh + 端口转发
    @@ -13157,125 +12979,6 @@ user3: 生活 - - wordpress 忘记密码的一种解决方法 - /2021/12/05/wordpress-%E5%BF%98%E8%AE%B0%E5%AF%86%E7%A0%81%E7%9A%84%E4%B8%80%E7%A7%8D%E8%A7%A3%E5%86%B3%E6%96%B9%E6%B3%95/ - 前阵子搭了个 WordPress,但是没怎么用,前两天发现忘了登录密码了,最近不知道是什么情况,chrome 的记住密码跟历史记录感觉有点问题,历史记录丢了不少东西,可能是时间太久了,但是理论上应该有 LRU 这种策略的,有些还比较常用,还有记住密码,因为个人域名都是用子域名分配给各个服务,有些记住了,有些又没记住密码,略蛋疼,所以就找了下这个方案。
    当然这个方案不是最优的,有很多限制,首先就是要能够登陆 WordPress 的数据库,不然这个方法是没用的。
    首先不管用什么方式(别违法)先登陆数据库,选择 WordPress 的数据库,可以看到里面有几个表,我们的目标就是 wp_users 表,用 select 查询看下可以看到有用户的数据,如果是像我这样搭着玩的没有创建其他用户的话应该就只有一个用户,那我们的表里的用户数据就只会有一条,当然多条的话可以通过用户名来找

    然后可能我这个版本是这样,没有装额外的插件,密码只是经过了 MD5 的单向哈希,所以我们可以设定一个新密码,然后用 MD5 编码后直接更新进去

    -
    UPDATE wp_users SET user_pass = MD5('123456') WHERE ID = 1;
    - -

    然后就能用自己的账户跟刚才更新的密码登录了。

    -]]>
    - - 小技巧 - - - WordPress - 小技巧 - -
    - - 介绍下最近比较实用的端口转发 - /2021/11/14/%E4%BB%8B%E7%BB%8D%E4%B8%8B%E6%9C%80%E8%BF%91%E6%AF%94%E8%BE%83%E5%AE%9E%E7%94%A8%E7%9A%84%E7%AB%AF%E5%8F%A3%E8%BD%AC%E5%8F%91/ - vscode 扩展转发

    在日常使用云服务器的时候,如果要访问上面自建的 mysql,一般要不直接开对应的端口,然后需要对本地 ip 进行授权,但是这个方案会有比较多的限制,比如本地 ip 变了,比如是非固定出口 ip 的家用宽带,或者要在家里跟公司都要访问,如果对所有 ip 都授权的话会不安全,这个时候其实是用 ssh 端口转发是个比较安全方便的方式。
    原来在这个之前其实对这块内容不太了解,后面是听朋友说的,vscode 的 Remote - SSH 扩展可以很方便的使用端口转发,在使用该扩展的时候,会在控制台位置里都出现一个”端口” tab

    如图中所示,我就是将一个服务器上的 mysql 的 3306 端口转发到本地的 3307 端口,至于为什么不用 3306 是因为本地我也有个 mysql 已经使用了 3306 端口,这个方法是使用的 vscode 的这个扩展,

    -

    ssh 命令转发

    还有个方式是直接使用 ssh 命令
    命令可以如此

    -
    ssh -CfNg -L 3307:127.0.0.1:3306 user1@199.199.199.199
    -

    简单介绍下这个命令
    -C 表示的是压缩数据包
    -f 表示后台执行命令
    -N 是表示不执行具体命令只用于端口转发
    -g 表示允许远程主机连接本地转发端口
    -L 则是具体端口转发的映射配置
    上面的命令就是将远程主机的 127.0.0.1:3306 对应转发到本地 3307
    而后面的用户则就是登录主机的用户名user1和ip地址199.199.199.199,当然这个配置也不是唯一的

    -

    ssh config 配置转发

    还可以在ssh 的 config 配置中加对应的配置

    -
    Host host1
    -  HostName 199.199.199.199
    -  User user1
    -  IdentityFile  /Users/user1/.ssh/id_rsa
    -  ServerAliveInterval 60
    -  LocalForward 3310 127.0.0.1:3306
    -

    然后通过 ssh host1 连接服务器的时候就能顺带做端口转发

    -]]>
    - - ssh - 技巧 - - - ssh - 端口转发 - -
    - - springboot 获取 web 应用中所有的接口 url - /2023/08/06/springboot-%E8%8E%B7%E5%8F%96-web-%E5%BA%94%E7%94%A8%E4%B8%AD%E6%89%80%E6%9C%89%E7%9A%84%E6%8E%A5%E5%8F%A3-url/ - 最近有个小需求,要把我们一个 springboot 应用的 request mapping 给导出来,这么说已经是转化过了的,应该是要整理这个应用所有的接口路径,比如我有一个 api.baidu1.com 作为接口域名,然后这个域名下有很多个接口提供服务,这些接口都是写在一个 springboot 应用里,如果本身有网关管理这些接口转发的其实可以通过网关的数据输出,这里就介绍下通过代码来获取

    -
    RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class);
    -Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
    -for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : map.entrySet()) {
    -    Set<String> urlSet = entry.getKey().getPatternsCondition().getPatterns();
    -    for (String url : urlSet) {
    -        System.out.println(url);
    -    }
    -}
    -

    第一行

    逐行来解析下,第一行就是从上下文中获取 RequestMappingHandlerMapping 这个 bean,

    -

    第二行

    然后调用了 getHandlerMethods,
    这里面具体执行了

    -
    public Map<T, HandlerMethod> getHandlerMethods() {
    -		this.mappingRegistry.acquireReadLock();
    -		try {
    -			return Collections.unmodifiableMap(this.mappingRegistry.getMappings());
    -		}
    -		finally {
    -			this.mappingRegistry.releaseReadLock();
    -		}
    -	}
    -

    前后加了锁,重要的就是从 mappingRegistry 中获取 mappings, 这里获取的就是
    org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.MappingRegistry#getMappings 具体的代码

    -
    public Map<T, HandlerMethod> getMappings() {
    -	return this.mappingLookup;
    -}
    -

    而这个 mappingLookup 再来看下

    -
    class MappingRegistry {
    -
    -	private final Map<T, MappingRegistration<T>> registry = new HashMap<>();
    -
    -	private final Map<T, HandlerMethod> mappingLookup = new LinkedHashMap<>();
    -

    可以看到就是在 MappingRegistry 中的一个变量,至于这个变量是怎么来的,简单的考虑下 springboot 处理请求的流程,就是从 Mapping 去找到对应的 Handler,所以就需要提前将这个对应关系存到这个变量里,
    具体可以看这 org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.MappingRegistry#register

    -
    public void register(T mapping, Object handler, Method method) {
    -			// Assert that the handler method is not a suspending one.
    -			if (KotlinDetector.isKotlinType(method.getDeclaringClass())) {
    -				Class<?>[] parameterTypes = method.getParameterTypes();
    -				if ((parameterTypes.length > 0) && "kotlin.coroutines.Continuation".equals(parameterTypes[parameterTypes.length - 1].getName())) {
    -					throw new IllegalStateException("Unsupported suspending handler method detected: " + method);
    -				}
    -			}
    -			this.readWriteLock.writeLock().lock();
    -			try {
    -				HandlerMethod handlerMethod = createHandlerMethod(handler, method);
    -				validateMethodMapping(handlerMethod, mapping);
    -				this.mappingLookup.put(mapping, handlerMethod); 
    -

    就是在这里会把 mapping 和 handleMethod 对应关系存进去

    -

    第三行

    这里拿的是上面的 map 里的 key,也就是 RequestMappingInfo 也就是 org.springframework.web.servlet.mvc.method.RequestMappingInfo
    而真的 url 就存在 org.springframework.web.servlet.mvc.condition.PatternsRequestCondition
    最终这里面的patterns就是我们要的路径

    -
    public class PatternsRequestCondition extends AbstractRequestCondition<PatternsRequestCondition> {
    -
    -	private final static Set<String> EMPTY_PATH_PATTERN = Collections.singleton("");
    -
    -
    -	private final Set<String> patterns;
    -

    写到这下一篇是不是可以介绍下 mapping 的具体注册逻辑

    -]]>
    - - Java - SpringBoot - - - Java - SpringBoot - -
    - - win 下 vmware 虚拟机搭建黑裙 nas 的小思路 - /2023/06/04/win-%E4%B8%8B-vmware-%E8%99%9A%E6%8B%9F%E6%9C%BA%E6%90%AD%E5%BB%BA%E9%BB%91%E8%A3%99-nas-%E7%9A%84%E5%B0%8F%E6%80%9D%E8%B7%AF/ - 上次说 nas 的方案我是在 win10 下使用vmware workstation 搭建的黑裙虚拟机,采用 sata 物理磁盘直通的方式,算是跑通了黑裙的基础使用模式,但是后来发现的一个问题是之前没考虑到的,我买了不带 f 的处理器就是为了核显能做硬解,但是因为 cpu 是通过 vmware 虚拟的,目前看来是没法直通核显的,我是使用的 jellyfin 套件,一开始使用是默认的刮削方式,而且把电视剧当成了电影在刮削,所以基本不能看,后面使用了 tmm 作为刮削工具,可以手动填写 imdb 的id 来进行搜索,一般比较正式的剧都可以在豆瓣上找到的,然后让 jellyfin 只作为媒体管理器,但是前面的问题还是没解决,所以考虑了下可以在win10 下直接运行 jellyfin,媒体目录使用挂载在 nas 里的盘,这样 jellyfin 就能直接调用核显了,也算是把 win10 本身给利用起来了,并且文件的管理还是在黑裙中。
    现在想来其实我这个方案还是不太合理,cpu 性能有点过剩想通过虚拟机的形式进行隔离使用,但是购买带核显的 cpu 最大的目的却没有实现,如果是直接裸机部署黑裙的话,真的是觉得 cpu 有点太浪费了,毕竟 passmark评分有 1w3 的cpu,只用来跑黑裙,所以网上的很多建议也是合理的,不过我可能是 win10 用的比较多了,还是习惯有 win 的环境。

    -]]>
    - - nas - - - nas - -
    介绍一下 RocketMQ /2020/06/21/%E4%BB%8B%E7%BB%8D%E4%B8%80%E4%B8%8B-RocketMQ/ @@ -13345,6 +13048,43 @@ user3: 中间件 + + 介绍下最近比较实用的端口转发 + /2021/11/14/%E4%BB%8B%E7%BB%8D%E4%B8%8B%E6%9C%80%E8%BF%91%E6%AF%94%E8%BE%83%E5%AE%9E%E7%94%A8%E7%9A%84%E7%AB%AF%E5%8F%A3%E8%BD%AC%E5%8F%91/ + vscode 扩展转发

    在日常使用云服务器的时候,如果要访问上面自建的 mysql,一般要不直接开对应的端口,然后需要对本地 ip 进行授权,但是这个方案会有比较多的限制,比如本地 ip 变了,比如是非固定出口 ip 的家用宽带,或者要在家里跟公司都要访问,如果对所有 ip 都授权的话会不安全,这个时候其实是用 ssh 端口转发是个比较安全方便的方式。
    原来在这个之前其实对这块内容不太了解,后面是听朋友说的,vscode 的 Remote - SSH 扩展可以很方便的使用端口转发,在使用该扩展的时候,会在控制台位置里都出现一个”端口” tab

    如图中所示,我就是将一个服务器上的 mysql 的 3306 端口转发到本地的 3307 端口,至于为什么不用 3306 是因为本地我也有个 mysql 已经使用了 3306 端口,这个方法是使用的 vscode 的这个扩展,

    +

    ssh 命令转发

    还有个方式是直接使用 ssh 命令
    命令可以如此

    +
    ssh -CfNg -L 3307:127.0.0.1:3306 user1@199.199.199.199
    +

    简单介绍下这个命令
    -C 表示的是压缩数据包
    -f 表示后台执行命令
    -N 是表示不执行具体命令只用于端口转发
    -g 表示允许远程主机连接本地转发端口
    -L 则是具体端口转发的映射配置
    上面的命令就是将远程主机的 127.0.0.1:3306 对应转发到本地 3307
    而后面的用户则就是登录主机的用户名user1和ip地址199.199.199.199,当然这个配置也不是唯一的

    +

    ssh config 配置转发

    还可以在ssh 的 config 配置中加对应的配置

    +
    Host host1
    +  HostName 199.199.199.199
    +  User user1
    +  IdentityFile  /Users/user1/.ssh/id_rsa
    +  ServerAliveInterval 60
    +  LocalForward 3310 127.0.0.1:3306
    +

    然后通过 ssh host1 连接服务器的时候就能顺带做端口转发

    +]]>
    + + ssh + 技巧 + + + ssh + 端口转发 + +
    + + win 下 vmware 虚拟机搭建黑裙 nas 的小思路 + /2023/06/04/win-%E4%B8%8B-vmware-%E8%99%9A%E6%8B%9F%E6%9C%BA%E6%90%AD%E5%BB%BA%E9%BB%91%E8%A3%99-nas-%E7%9A%84%E5%B0%8F%E6%80%9D%E8%B7%AF/ + 上次说 nas 的方案我是在 win10 下使用vmware workstation 搭建的黑裙虚拟机,采用 sata 物理磁盘直通的方式,算是跑通了黑裙的基础使用模式,但是后来发现的一个问题是之前没考虑到的,我买了不带 f 的处理器就是为了核显能做硬解,但是因为 cpu 是通过 vmware 虚拟的,目前看来是没法直通核显的,我是使用的 jellyfin 套件,一开始使用是默认的刮削方式,而且把电视剧当成了电影在刮削,所以基本不能看,后面使用了 tmm 作为刮削工具,可以手动填写 imdb 的id 来进行搜索,一般比较正式的剧都可以在豆瓣上找到的,然后让 jellyfin 只作为媒体管理器,但是前面的问题还是没解决,所以考虑了下可以在win10 下直接运行 jellyfin,媒体目录使用挂载在 nas 里的盘,这样 jellyfin 就能直接调用核显了,也算是把 win10 本身给利用起来了,并且文件的管理还是在黑裙中。
    现在想来其实我这个方案还是不太合理,cpu 性能有点过剩想通过虚拟机的形式进行隔离使用,但是购买带核显的 cpu 最大的目的却没有实现,如果是直接裸机部署黑裙的话,真的是觉得 cpu 有点太浪费了,毕竟 passmark评分有 1w3 的cpu,只用来跑黑裙,所以网上的很多建议也是合理的,不过我可能是 win10 用的比较多了,还是习惯有 win 的环境。

    +]]>
    + + nas + + + nas + +
    从丁仲礼被美国制裁聊点啥 /2020/12/20/%E4%BB%8E%E4%B8%81%E4%BB%B2%E7%A4%BC%E8%A2%AB%E7%BE%8E%E5%9B%BD%E5%88%B6%E8%A3%81%E8%81%8A%E7%82%B9%E5%95%A5/ @@ -13365,6 +13105,48 @@ user3: 美国 + + 从清华美院学姐聊聊我们身边的恶人 + /2020/11/29/%E4%BB%8E%E6%B8%85%E5%8D%8E%E7%BE%8E%E9%99%A2%E5%AD%A6%E5%A7%90%E8%81%8A%E8%81%8A%E6%88%91%E4%BB%AC%E8%BA%AB%E8%BE%B9%E7%9A%84%E6%81%B6%E4%BA%BA/ + 前几天清华美院学姐的热点火了,然后仔细看了下,其实是个学姐诬陷以为其貌不扬的男同学摸她屁股

    然后还在朋友圈发文想让他社死,我也是挺晚才知道这个词什么意思,然后后面我看到了这个图片,挺有意思的

    本来其实也没什么想聊这个的,是在 B 站看了个吐槽这个的,然后刚好晚上乘公交的时候又碰到了有点类似的问题
    故事描述下,我们从始发站做了公交,这辆公交司机上次碰到过一回,就是会比较关注乘客的佩戴情况,主要考虑到目前国内疫情,然后这次在差不多人都坐满的情况下,可能在提示了三次让车内乘客戴好口罩,但是他指的那个中年女性还是没有反应,司机就转头比较大声指着这个乘客(中年女性)让戴好口罩,然后这个乘客(中年女性)就大声的说“我口罩是滑下来了,你指着我干嘛,你态度这么差,要吃了我一样,我要投诉你”等等,然后可能跟她一块的一个中年女性也是这么帮腔指责司机,比较基本的理解,车子里这么多乘客,假如是处于这位乘客口罩滑下来了而不自知的情况下,司机在提示了三次以后回头指着她说,我想的是没什么问题的,但是这位却反而指责这位司机指着她,并且说是态度差,要吃了她,完全是不可理喻的,并且一直喋喋不休说她口罩滑掉了有什么错,要投诉这个司机,让他可以提前退休了,在其他乘客的劝说下司机准备继续开车时,又口吐芬芳“你个傻,你来打我呀”,真的是让我再次体会到了所谓的恶人先告状的又一完美呈现,后面还有个乘客还是表示要打死司机这个傻,让我有点不明所以,俗话说有人是得理不饶人,前提是得理,这种理亏不饶人真的是挺让人长见识的,试想下,司机在提示三次后,这位乘客还是没有把口罩戴好,如何在不指着这位乘客的情况下能准确的提示到她呢,并且觉得语气态度不好,司机要载着一车的人,因为你这一个乘客不戴好口罩而不能正常出发,有些着急应该很正常吧,可能是平时自己在家里耀武扬威的使唤别人习惯了吧,别人不敢这么大声跟她说话,其实想想这位中年女性应该年纪不会很大,还比较时髦的吧,像一些常见的中年杭州本地人可能是不会说傻*这个词的吧。
    杭州的公交可能是在二月份疫情还比较严重的时候是要求上车出示健康码,后面比较缓和以后只要求佩戴好口罩,但是在我们小绍兴,目前还是一律要求检验健康码和佩戴口罩,对于疫情中,并且目前阶段国内也时有报出小范围的疫情的情况下,司机尽职要求佩戴好口罩其实也是为了乘客着想,另一种情况如果司机不严格要求,万一车上有个感染者,这位中年女性被传染了,如果能找到这个司机的话,是不是想“打死”这个司机,竟然让感染者上了车,反正她自己是不可能有错的,上来就是对方态度差,要投诉,自己不戴好口罩啥都没错,我就想知道如果因为自己没戴好口罩被感染了,是不是也是司机的错,毕竟没有像仆人那样点头哈腰求着她戴好口罩。
    再说回来,整个车就她一个人没戴好口罩,并且还有个细节,其实这个乘客是上了车之后就没戴好了,本来上车的时候是戴好的,这种比较有可能是觉得上车的时候司机那看一眼就好了,如果好好戴着口罩,一点事情都没有,唉,纯粹是太气愤了,调理逻辑什么的就忽略吧

    +]]>
    + + 生活 + 吐槽 + 疫情 + 口罩 + + + 生活 + 吐槽 + 疫情 + 公交车 + 口罩 + 杀人诛心 + +
    + + 关于公共交通再吐个槽 + /2021/03/21/%E5%85%B3%E4%BA%8E%E5%85%AC%E5%85%B1%E4%BA%A4%E9%80%9A%E5%86%8D%E5%90%90%E4%B8%AA%E6%A7%BD/ + 事情源于周末来回家发生的两件事情,先是回去的时候从高铁下车要坐公交,现在算是有个比较好的临时候车点了,但是可能由于疫情好转,晚上都不用检查健康码就可以进候车点,但是上公交的时候还是需要看健康码,一般情况下从高铁下来的,各个地方的人都有,而且也不太清楚这边上公交车需要查验健康码,我的一个看法是候车的时候就应该放个横幅告示,或者再配合喇叭循环播放,请提前准备好健康码,上车前需要查验,因为像这周的情况,我乘坐的那辆车是间隔时间比较长,而且终点是工业开发区,可能是比较多外来务工人员的目的地,正好这部分人可能对于操作手机检验健康码这个事情不太熟悉,所以结果就是头上几个不知道怎么搞出来健康码,然后让几乎有满满一整车的人在后面堵着,司机又非常厌烦那些没有提前出示健康码的,有位乘客搞得久了点,还被误以为没刷卡买票,差点吵起来,其实公共交通或者高铁站负责的在公交指引路线上多写一句上车前需要查验健康码,可能就能改善比较多,还有就是那个积水的路,这个吐槽起来就一大坨了,整个绍兴像 dayuejin 一样到处都是破路。
    第二个就是来杭州的时候,经过人行横道,远处车道的公交车停下来等我们了,为了少添麻烦总想快点穿过去,但是这时靠近我们的车道(晚上光线较暗,可见度不佳)有一辆从远处来的奥迪 A4 还是 A5 这种的车反而想加速冲过去,如果少看一下可能我已经残了,交规考的靠近人行道要减速好像基本都是个摆设了,杭州也只有公交车因为一些考核指标原因会主动礼让,人其实需要有同理心,虽然可能有些人是开车多于骑车走路的,但是总也不可能永远不穿人行道吧,甚至这些人可能还会在人行道红灯的时候走过去。这个事情不是吐槽公共交通的,只是也有些许关系,想起来还有一件事也是刚才来杭州的时候看到的,等公交的时候看到有辆路虎要加塞,而目标车道刚好是辆大货车,大货车看到按了喇叭,路虎犹豫了下还是挤进去了,可能是对路虎的扛撞性能非常自信吧,反正我是挺后怕的,这种级别的车,被撞了的话估计还是鸡蛋撞石头,吨位惯性在那,这里再延伸下,挺多开豪车的人好像都觉得这路上路权更大一些,谁谁都得让着他,可能实际吃亏的不多,所以越加巩固了这种思维,当真的碰到不管的可能就会明白了,路权这个事情在天朝也基本没啥人重视,也没想说个结论,就到这吧

    +]]>
    + + 生活 + 公交 + + + 生活 + 开车 + 加塞 + 糟心事 + 规则 + 公交 + 路政规划 + 基础设施 + 杭州 + 健康码 + +
    nas 中使用 tmm 刮削视频 /2023/07/02/%E4%BD%BF%E7%94%A8-tmm-%E5%88%AE%E5%89%8A%E8%A7%86%E9%A2%91/ @@ -13383,8 +13165,8 @@ user3: 最近群里大佬发起了一个读书打卡活动,需要每天读一会书,在群里打卡分享感悟,争取一个月能读完一本书,说实话一天十分钟的读书时间倒是问题不大,不过每天都要打卡,而且一个月要读完一本书,其实难度还是有点大的,不过也想试试看。
    之前某某老大给自己立了个 flag,说要读一百本书,这对我来说挺难实现的,一则我也不喜欢书只读一小半,二则感觉对于喜欢看的内容范围还是比较有限制,可能也算是比较矫情,不爱追热门的各类东西,因为往往会有一些跟大众不一致的观点看法,显得格格不入。所以还是这个打卡活动可能会比较适合我,书是人类进步的阶梯。
    到现在是打卡了三天了,读的主要是白岩松的《幸福了吗》,对于白岩松,我们这一代人是比较熟悉,并且整体印象比较不错的一个央视主持人,从《焦点访谈》开始,到疫情期间的各类一线节目,可能对我来说是个三观比较正,敢于说一些真话的主持人,这中间其实是有个空档期,没怎么看电视,也不太关注了,只是在疫情期间的节目,还是一如既往地给人一种可靠的感觉,正好有一次偶然微信读书推荐了白岩松的这本书,就看了一部分,正好这次继续往下看,因为相对来讲不会很晦涩,并且从这位知名央视主持人的角度分享他的过往和想法看法,还是比较有意思的。
    从对汶川地震,08 年奥运等往事的回忆和一些细节的呈现,也让我了解比较多当时所不知道的,特别是汶川地震,那时的我还在读高中,真的是看着电视,作为“猛男”都忍不住泪目了,共和国之殇,多难兴邦,但是这对于当事人来说,都是一场醒不过来的噩梦。
    然后是对于足球的热爱,其实光这个就能掰扯很多,因为我不爱足球,只爱篮球,其中原因有的没的也挺多可以说的,但是看了他的书,才能比较深入的了解一个足球迷,对足球,对中国足球,对世界杯,对阿根廷的感情。
    接下去还是想能继续坚持下去,加油!

    ]]>
    - 生活 读后感 + 生活 白岩松 幸福了吗 @@ -13396,26 +13178,6 @@ user3: 足球
    - - 从清华美院学姐聊聊我们身边的恶人 - /2020/11/29/%E4%BB%8E%E6%B8%85%E5%8D%8E%E7%BE%8E%E9%99%A2%E5%AD%A6%E5%A7%90%E8%81%8A%E8%81%8A%E6%88%91%E4%BB%AC%E8%BA%AB%E8%BE%B9%E7%9A%84%E6%81%B6%E4%BA%BA/ - 前几天清华美院学姐的热点火了,然后仔细看了下,其实是个学姐诬陷以为其貌不扬的男同学摸她屁股

    然后还在朋友圈发文想让他社死,我也是挺晚才知道这个词什么意思,然后后面我看到了这个图片,挺有意思的

    本来其实也没什么想聊这个的,是在 B 站看了个吐槽这个的,然后刚好晚上乘公交的时候又碰到了有点类似的问题
    故事描述下,我们从始发站做了公交,这辆公交司机上次碰到过一回,就是会比较关注乘客的佩戴情况,主要考虑到目前国内疫情,然后这次在差不多人都坐满的情况下,可能在提示了三次让车内乘客戴好口罩,但是他指的那个中年女性还是没有反应,司机就转头比较大声指着这个乘客(中年女性)让戴好口罩,然后这个乘客(中年女性)就大声的说“我口罩是滑下来了,你指着我干嘛,你态度这么差,要吃了我一样,我要投诉你”等等,然后可能跟她一块的一个中年女性也是这么帮腔指责司机,比较基本的理解,车子里这么多乘客,假如是处于这位乘客口罩滑下来了而不自知的情况下,司机在提示了三次以后回头指着她说,我想的是没什么问题的,但是这位却反而指责这位司机指着她,并且说是态度差,要吃了她,完全是不可理喻的,并且一直喋喋不休说她口罩滑掉了有什么错,要投诉这个司机,让他可以提前退休了,在其他乘客的劝说下司机准备继续开车时,又口吐芬芳“你个傻,你来打我呀”,真的是让我再次体会到了所谓的恶人先告状的又一完美呈现,后面还有个乘客还是表示要打死司机这个傻,让我有点不明所以,俗话说有人是得理不饶人,前提是得理,这种理亏不饶人真的是挺让人长见识的,试想下,司机在提示三次后,这位乘客还是没有把口罩戴好,如何在不指着这位乘客的情况下能准确的提示到她呢,并且觉得语气态度不好,司机要载着一车的人,因为你这一个乘客不戴好口罩而不能正常出发,有些着急应该很正常吧,可能是平时自己在家里耀武扬威的使唤别人习惯了吧,别人不敢这么大声跟她说话,其实想想这位中年女性应该年纪不会很大,还比较时髦的吧,像一些常见的中年杭州本地人可能是不会说傻*这个词的吧。
    杭州的公交可能是在二月份疫情还比较严重的时候是要求上车出示健康码,后面比较缓和以后只要求佩戴好口罩,但是在我们小绍兴,目前还是一律要求检验健康码和佩戴口罩,对于疫情中,并且目前阶段国内也时有报出小范围的疫情的情况下,司机尽职要求佩戴好口罩其实也是为了乘客着想,另一种情况如果司机不严格要求,万一车上有个感染者,这位中年女性被传染了,如果能找到这个司机的话,是不是想“打死”这个司机,竟然让感染者上了车,反正她自己是不可能有错的,上来就是对方态度差,要投诉,自己不戴好口罩啥都没错,我就想知道如果因为自己没戴好口罩被感染了,是不是也是司机的错,毕竟没有像仆人那样点头哈腰求着她戴好口罩。
    再说回来,整个车就她一个人没戴好口罩,并且还有个细节,其实这个乘客是上了车之后就没戴好了,本来上车的时候是戴好的,这种比较有可能是觉得上车的时候司机那看一眼就好了,如果好好戴着口罩,一点事情都没有,唉,纯粹是太气愤了,调理逻辑什么的就忽略吧

    -]]>
    - - 生活 - 吐槽 - 疫情 - 口罩 - - - 生活 - 吐槽 - 疫情 - 公交车 - 口罩 - 杀人诛心 - -
    关于 npe 的一个小记忆点 /2023/07/16/%E5%85%B3%E4%BA%8E-npe-%E7%9A%84%E4%B8%80%E4%B8%AA%E5%B0%8F%E8%AE%B0%E5%BF%86%E7%82%B9/ @@ -13435,13 +13197,9 @@ user3: - 分享一次比较诡异的 Windows 下 U盘无法退出的经历 - /2023/01/29/%E5%88%86%E4%BA%AB%E4%B8%80%E6%AC%A1%E6%AF%94%E8%BE%83%E8%AF%A1%E5%BC%82%E7%9A%84-Windows-%E4%B8%8B-U%E7%9B%98%E6%97%A0%E6%B3%95%E9%80%80%E5%87%BA%E7%9A%84%E7%BB%8F%E5%8E%86/ - 作为一个 Windows 的老用户,并且也算是 Windows 系统的半个粉丝,但是秉承一贯的优缺点都应该说的原则,Windows 系统有一点缺点是真的挺难受,相信 Windows 用过比较久的都会经历过,就是 U盘无法退出的问题,在比较远古时代,这个问题似乎能采取的措施不多,关机再拔 U盘的方式是一种比较保险的方式,其他貌似有 360这种可以解除占用的,但是需要安装 360 软件,对于目前的使用环境来说有点得不偿失,也是比较流氓的一类软件了,目前在 Windows 环境我主要就安装了个火绒,或者就用 Windows 自带的 defender。

    -

    第一种

    最近这次经历也是有火绒的一定责任,在我尝试推出 U盘的时候提示了我被另一个大流氓软件,XlibabaProtect.exe 占用了,这个流氓软件真的是充分展示了某里的技术实力,试过 N 多种办法都关不掉也删不掉,尝试了很多种办法也没办法删除,但是后面换了种思路,一般这种情况肯定是有进程在占用 U盘里的内容,最新版本的 Powertoys 会在文件的右键菜单里添加一个叫 File Locksmith 的功能,可以用于检查正在使用哪些文件以及由哪些进程使用,但是可能是我的使用姿势不对,没有仔细看文档,它里面有个”以管理员身份重启”,可能会有用。
    这算是第一种方式,

    -

    第二种

    第二种方式是 Windows 任务管理器中性能 tab 下的”打开资源监视器”,
    ,假如我的 U 盘的盘符是F:
    就可以搜索到占用这个盘符下文件的进程,这里千万小心‼️‼️,不可轻易杀掉这些进程,有些系统进程如果轻易杀掉会导致蓝屏等问题,不可轻易尝试,除非能确认这些进程的作用。
    对于前两种方式对我来说都无效,

    -

    第三种

    所以尝试了第三种,
    就是磁盘脱机的方式,在”计算机”右键管理,点击”磁盘管理”,可以找到 U 盘盘符右键,点击”脱机”,然后再”推出”,这个对我来说也不行

    -

    第四种

    这种是唯一对我有效的,在开始菜单搜索”event”,可以搜到”事件查看器”,
    ,这个可以看到当前最近 Windows 发生的事件,打开这个后就点击U盘推出,因为推不出来也是一种错误事件,点击下刷新就能在这看到具体是因为什么推出不了,具体的进程信息
    最后发现是英特尔的驱动管理程序的一个进程,关掉就退出了,虽然前面说的某里的进程是流氓,但这边是真的冤枉它了

    + 分享一次折腾老旧笔记本的体验-续续篇 + /2023/02/26/%E5%88%86%E4%BA%AB%E4%B8%80%E6%AC%A1%E6%8A%98%E8%85%BE%E8%80%81%E6%97%A7%E7%AC%94%E8%AE%B0%E6%9C%AC%E7%9A%84%E4%BD%93%E9%AA%8C-%E7%BB%AD%E7%BB%AD%E7%AF%87/ + 上周因为一些事情没回去,买好了内存条这周才回去用,结果不知道是 U 盘的问题还是什么其他原因原来装的那个系统起不来,然后想用之前一直用的 LD 的笔记本,结果 LD 的老笔记本也起不来了,一直卡在启动界面,猜测可能是本身也比较老了,用的机械硬盘会不会被我一直动而损坏了,所以就想搞个老毛桃跟新搞一个启动盘,结果这周最大的坑就在这了,在我的 15 寸 mbp 上用etcher做了个 win10 的启动盘,可能是分区表格式是 GUID,不是 MBR 的,老电脑不能识别,就像装个虚拟机来做启动盘,结果像老毛桃不支持这种用虚拟机的,需要本地磁盘,然后我就有用 bootcamp 安装了个 win10,又没网络,查了下网络需要用 bootcamp 下载 Windows Support 软件,下了好久一直没下完,后来又提示连不上苹果服务器,好不容易下完了,开启 win10 后,安装到一半就蓝屏了,真的是够操蛋的,在这个时候真的很需要有一个 Windows 机器的支持,LD 的那个笔记本也跟我差不多老了,虽然比较慢但之前好歹也还可以用,结果这下也被我弄坏了,家里就没有其他机器可以支持了,有点巧妇难为无米之炊的赶脚,而且还是想再折腾下我的老电脑,后面看看打算做几个 U 盘,分工职责明确,一个老毛桃的PE 盘,老毛桃的虽然不是很纯净的,但是是我一直以来用过内置工具比较全,修复启动功能比较强大的一个 pe,没用过 winpe,后续可以考虑使用下,一个 win7 的启动盘,因为是老电脑,如果后面是新的电脑可以考虑是 win10,一个 win to go 盘,这样我的 mbp 就可以直接用 win10 了,不过想来也还是要有一台 win 机器才比较好,不然很多时候都是在折腾工具,工欲善其事必先利其器,后面也可以考虑能够更深入的去了解主板的一些问题,我原来的那个主板可能是一些小的电阻等问题,如果能自己学习解决就更好了,有时候研究下还是有意思的。

    ]]>
    Windows @@ -13452,16 +13210,29 @@ user3:
    - 《寻羊历险记》读后感 - /2023/07/23/%E3%80%8A%E5%AF%BB%E7%BE%8A%E5%8E%86%E9%99%A9%E8%AE%B0%E3%80%8B%E8%AF%BB%E5%90%8E%E6%84%9F/ - 最近本来是在读《舞舞舞》,然后看到有介绍说,这个跟《寻羊历险记》是有情节上的关联,所以就先去看了《寻羊历险记》,《寻羊历险记》也是村上春树的第一本成规模的长篇小说,也可以认为是《舞舞舞》的前篇。
    最开始这个情节跟之前的刺杀骑士团长还是哪本有点类似,都有跟老婆离婚了,主角应该是个跟朋友一起开翻译社的,后面也开始做广告相关的,做到了经济收益还不错的阶段,也有一些挺哲学的对话,朋友觉得这么赚钱不地道(可能也是觉得这样忘了初心),在离婚以后又结交了一个耳朵很好看的女友,这个女友也是个比较抽象的存在,描述中给人感觉是一个外貌很普通的女孩,但是耳朵漂亮的惊为天人,不知道是不是有什么隐喻,感觉现实中没见过这样的人,女友平时把耳朵遮起来不轻易露出来,只有在跟主角做爱的时候才露出来
    主体剧情是因为男主在广告中用了一张一位叫“鼠”的朋友寄给他的一张包含一只特殊的羊的照片,就有个政界大佬的秘书找过来,逼迫主角要找到照片上的羊,这只羊背上有星纹,基本不可能属于在日本当时可能存在的羊的品种,因为这位政界大佬快病危了,所以要求主角必须在一个月内找到这只羊,因为这里把这只神秘的羊塑造成神一样的存在,这位政界大佬在年轻时被这只羊上身,后面就开始在政治事业上大展宏图,就基本成了能左右整个日本走向的巨佬,但近期随着巨佬,身体状态慢慢变差,这只羊就从他身上消失了,所以秘书要主角必须找到这只羊,不然基本会让主角的翻译社完蛋,这样主角就会面临破产赔偿等严重后果,只是说主角本来也一直是这种丧气存在,再说这么茫茫人海找个人都难,还要找这么一只玄乎的不太可能真实存在的羊,所以基本是想要放弃的,结果刚才说的耳朵很漂亮的女友却有着神乎其神的直觉,就觉得能找到,然后他们就踏上了巡羊的旅程,一开始到了札幌,寻找一无所获,然后神奇的是女友推荐一定要住的海豚宾馆,恰恰是一切线索的源头,宾馆老板的父亲正好是羊博士,在年轻的时候被羊上身过,后面离开后就去了那位巨佬身上,让巨佬成了真正控制日本的地下帝国的王,跟羊博士咨询后知道羊可能在十二瀑镇的牧场出现过,所以一路找寻,发现其实这个牧场中有个别墅正好是主角朋友“鼠”的,到了别墅后出现了个神秘的羊男,这个羊男真的不太明白是怎么个存在,就是让主角的女友回去了,然后最后一个肉体承载着“鼠”的灵魂跟主角有了一次接触,主角呆在这个别墅过着百无聊赖的生活,在才到有一次羊男来跟他交流的时候其实是承载着鼠的灵魂,就觉得是不是一切都是在忽悠他,离一个月期限也越来越近了,而在发怒之后,“鼠”真的出现后,但是不是真的“鼠”,而是只有他的灵魂,因为“鼠”已经死了,因为不想被“羊”附身,成为羊壳,并且让主角设定好时钟后的装置后尽快下山,第二天主角离开上了火车后山上牧场就传来爆炸声,“鼠”已经跟羊同归于尽了,免得再有其他人被羊附身,主角也很难过,回到故乡在四周大海已经被填掉了的旧防波堤上大哭悼念逝去的“鼠”。
    其实对于没什么时代概念或者对村上一直以来的观念不是特别敏感的,对这本书讲了啥有点云里雾里,后面看了一些简单的解释就是羊其实代表日本帝国主义和资本主义,可能是村上本人反帝国主义,军国主义和资本主义的一个表征,想来也有些道理,不然“鼠”的牺牲就感觉比较没意义,但是另一方面我的理解也可能是对自由的向往的表达,被羊控制,虽然可以成就“伟大”的事业,但是也丧失了自我。

    + 分享一次折腾老旧笔记本的体验 + /2023/02/05/%E5%88%86%E4%BA%AB%E4%B8%80%E6%AC%A1%E6%8A%98%E8%85%BE%E8%80%81%E6%97%A7%E7%AC%94%E8%AE%B0%E6%9C%AC%E7%9A%84%E4%BD%93%E9%AA%8C/ + 上大学的时候买了第一个笔记本,是联想的小y,y460,配置应该是 i5+2g 内存,500g 硬盘,ati 5650 的显卡,那时候还是比较时髦的带有集显和独显切换的,一些人也觉得它算是一代“神机”,陪我度过了大学四年,还有毕业后的第一年,记得中间还用的比较曲折,差不多第一学期末的时候硬盘感觉有时候会文件操作卡住,去售后看了下,果然硬盘出问题了,还在当场把硬盘的东西都拷贝到新买的移动硬盘里,不过联想的售后还是比较不错的,在保内可以直接免费换,如果出保了估计就要修不起了,后面出了个很大的问题,就是屏幕花屏了,而且它的花屏是横着的会有那种上升的变化,一开始感觉跟湿度还有温度有点关系,天气冷了就很容易出现,天气热了就好一点,出现的概率小一点,而且是合盖后再开会好,过一会又会上升,只是这么度过了保修期,去售后问了下,修一下要两千多,后来是在玉泉学校里面的维修店,好像是花了六百多,省是省了很多,但是后面使用的时候发现有点漏光,而且两三个亮点,总归还是给我那不富裕的经济条件带来了一个正常屏幕,不过是挺影响使用,严格来说都没法用了,后面基本是大半个屏幕花掉,接近整个屏幕花掉,至此大学就是这么用过去了。
    噢对了,中间在大二的时候加了一条 2g 的内存,因为像操作系统课需要用虚拟机,2g 内存不太够,不过那会用的都是 32 位的 win7 系统,实际使用用不到 4g 内存,得使用破解补丁才能识别到,后来在大学毕业后由于收入也低,想换其他电脑,特别是 mac,买不起,电脑在那会还会玩玩 DNF,但是风扇声很大,也想优化下,就买了个 msata 的固态硬盘,因为刚好有个口子留着,在那之前一直搜到的是把光驱位拆掉换上 sata 固态硬盘,这对于那会的我来说操作难度实在有点大,换上了msata 固态之后还是有比较大的提升的,把操作系统装到固态硬盘后其他盘就只放数据了,后面还装过黑苹果,只是不小心被室友强制关机了,之后就起不来了,也不知道啥原因,后续想继续按原来的操作装,也没成功,再往后就配了一台台式机,这个笔记本就放在那没啥用了,后面偶尔会拿出来用一下,特别是疫情那会充当了 LD 的临时使用机器。
    最近一次就是想把行车记录仪里的视频导出来,结果上传的时候我点了下 win10 的更新,重启后这个机器就起不来了,一开始以为顶多是个重装系统,结果重装也不行,就进不去,插着 U 盘也起不来,一开始还能进 BIOS,后面就直接进不去了,像内存条脏了,擦下金手指什么的,都没搞定,想着也只可能是主板上的部件坏了,所以就开始了这趟半作死之旅,买了块主板来换,拆这个笔记本是真的够难的,开机键那一条是真的拆不开,后面还把两个扣子扳坏了,里面的排线插口还几个也拔坏了,幸好用买来的主板装上还能用,但是后面就很奇怪了,因为这个电脑装了 Ubuntu 跟 win10 的双系统,Ubuntu 能正常起来,但是 win10 就是起不来,插上老毛桃或者 win10 的启动盘都是起不来,老毛桃是能起来,但是进不了 pe,插启动盘又报 0xc00000e9 错误码,现在想着是不是这个固态硬盘有点问题或者还是内存问题,只能后续再看了,拆机的时候也找不到视频,机器实在是太老了,后面再试试看。

    +]]>
    + + Windows + 小技巧 + + + Windows + +
    + + 分享一次折腾老旧笔记本的体验-续篇 + /2023/02/12/%E5%88%86%E4%BA%AB%E4%B8%80%E6%AC%A1%E6%8A%98%E8%85%BE%E8%80%81%E6%97%A7%E7%AC%94%E8%AE%B0%E6%9C%AC%E7%9A%84%E4%BD%93%E9%AA%8C-%E7%BB%AD%E7%AF%87/ + 接着上一篇的折腾记,因为这周又尝试了一些新的措施和方法,想继续记录分享下,上周的整体情况大概是 Ubuntu 系统能进去了,但是 Windows 进不去,PE 也进不去,Windows 启动盘也进不去,因为我的机器加过一个 msata 的固态,Windows 是装在 msata 固态硬盘里的,Ubuntu 是装在机械硬盘里的,所以有了一种猜测就是可能这个固态硬盘有点问题,还有就是还是怀疑内存的问题,正好家里还有个msata 的固态硬盘,是以前想给LD 的旧笔记本换上的,因为买回来放在那没有及时装,后面会又找不到,直到很后面才找到,LD 也不怎么用那个笔记本了,所以就一直放着了,这次我就想拿来换上。
    周末回家我就开始尝试了,换上了新的固态硬盘后,插上 Windows 启动 U 盘,这次一开始看起来有点顺利,在 BIOS 选择 U 盘启动,进入了 Windows 安装界面,但是装到一半,后面重启了之后就一直说硬盘有问题,让重启,但是重启并没有解决问题,变成了一直无效地重复重启,再想进 U 盘启动,就又进不去了,这时候怎么说呢,感觉硬盘不是没有问题,但是呢,问题应该不完全出在这,所以按着总体的逻辑来讲,主板带着cpu 跟显卡,都换掉了,硬盘也换掉了,剩下的就是内存了,可是内存我也尝试过把后面加的那条金士顿拔掉,可还是一样,也尝试过用橡皮擦金手指,这里感觉也很奇怪了,找了一圈了都感觉没啥明确的原因,比如其实我的猜测,主板电池的问题,一些电阻坏掉了,但是主板是换过的,那如果内存有问题,照理我用原装的那条应该会没问题,也有一种非常小的可能,就是两条内存都坏了,或者说这也是一种不太可能的可能,所以最后的办法就打算试试把两条内存都换掉,不过现在网上都找不到这个内存的确切信息了,只能根据大致的型号去买来试试,就怕买来的还是坏的,其实也怕是这个买来的主板因为也是别的拆机下来的,不一定保证完全没问题,要是有类似的问题或者也有别的问题导致开不起来就很尴尬,也没有很多专业的仪器可以排查原因,比如主板有没有什么短路的,对了还有一个就是电源问题,但是电源的问题也就可能是从充电器插的口子到主板的连线,因为 LD 的电源跟我的口子一样,也试过,但是结果还是一样,顺着正常逻辑排查,目前也没有剩下很明确的方向了,只能再尝试下看看。

    ]]>
    - 读后感 - 生活 + Windows + 小技巧 - 读后感 + Windows
    @@ -13484,25 +13255,22 @@ user3: - 关于公共交通再吐个槽 - /2021/03/21/%E5%85%B3%E4%BA%8E%E5%85%AC%E5%85%B1%E4%BA%A4%E9%80%9A%E5%86%8D%E5%90%90%E4%B8%AA%E6%A7%BD/ - 事情源于周末来回家发生的两件事情,先是回去的时候从高铁下车要坐公交,现在算是有个比较好的临时候车点了,但是可能由于疫情好转,晚上都不用检查健康码就可以进候车点,但是上公交的时候还是需要看健康码,一般情况下从高铁下来的,各个地方的人都有,而且也不太清楚这边上公交车需要查验健康码,我的一个看法是候车的时候就应该放个横幅告示,或者再配合喇叭循环播放,请提前准备好健康码,上车前需要查验,因为像这周的情况,我乘坐的那辆车是间隔时间比较长,而且终点是工业开发区,可能是比较多外来务工人员的目的地,正好这部分人可能对于操作手机检验健康码这个事情不太熟悉,所以结果就是头上几个不知道怎么搞出来健康码,然后让几乎有满满一整车的人在后面堵着,司机又非常厌烦那些没有提前出示健康码的,有位乘客搞得久了点,还被误以为没刷卡买票,差点吵起来,其实公共交通或者高铁站负责的在公交指引路线上多写一句上车前需要查验健康码,可能就能改善比较多,还有就是那个积水的路,这个吐槽起来就一大坨了,整个绍兴像 dayuejin 一样到处都是破路。
    第二个就是来杭州的时候,经过人行横道,远处车道的公交车停下来等我们了,为了少添麻烦总想快点穿过去,但是这时靠近我们的车道(晚上光线较暗,可见度不佳)有一辆从远处来的奥迪 A4 还是 A5 这种的车反而想加速冲过去,如果少看一下可能我已经残了,交规考的靠近人行道要减速好像基本都是个摆设了,杭州也只有公交车因为一些考核指标原因会主动礼让,人其实需要有同理心,虽然可能有些人是开车多于骑车走路的,但是总也不可能永远不穿人行道吧,甚至这些人可能还会在人行道红灯的时候走过去。这个事情不是吐槽公共交通的,只是也有些许关系,想起来还有一件事也是刚才来杭州的时候看到的,等公交的时候看到有辆路虎要加塞,而目标车道刚好是辆大货车,大货车看到按了喇叭,路虎犹豫了下还是挤进去了,可能是对路虎的扛撞性能非常自信吧,反正我是挺后怕的,这种级别的车,被撞了的话估计还是鸡蛋撞石头,吨位惯性在那,这里再延伸下,挺多开豪车的人好像都觉得这路上路权更大一些,谁谁都得让着他,可能实际吃亏的不多,所以越加巩固了这种思维,当真的碰到不管的可能就会明白了,路权这个事情在天朝也基本没啥人重视,也没想说个结论,就到这吧

    + 分享记录一下一个 scp 操作方法 + /2022/02/06/%E5%88%86%E4%BA%AB%E8%AE%B0%E5%BD%95%E4%B8%80%E4%B8%8B%E4%B8%80%E4%B8%AA-scp-%E6%93%8D%E4%BD%9C%E6%96%B9%E6%B3%95/ + scp 是个在服务器之间拷贝文件的一个常用命令,有时候有个场景是比如我们需要拷贝一些带有共同前缀的文件,但是有一个问题是比如我们有使用 zsh 的话,会出现一个报错,

    +
    zsh: no matches found: root@100.100.100.100://root/prefix*
    +

    这里就比较奇怪了,这个前缀的文件肯定是有的,这里其实是由于 zsh 会对 * 进行展开,这个可以在例如 ls 命令在使用中就可以发现 zsh 有这个特性
    需要使用双引号或单引号将路径包起来或者在*之前加反斜杠\来阻止对*展开和转义

    +
    scp root@100.100.100.100://root/prefix* .
    +

    通过使用双引号"进行转义

    +
    scp root@100.100.100.100:"//root/prefix*" .
    +

    或者可以将 shell 从 zsh 切换成 bash

    ]]>
    - 生活 - 公交 + shell + 小技巧 - 生活 - 开车 - 加塞 - 糟心事 - 规则 - 公交 - 路政规划 - 基础设施 - 杭州 - 健康码 + scp
    @@ -13525,41 +13293,60 @@ user3: - 分享记录一下一个 scp 操作方法 - /2022/02/06/%E5%88%86%E4%BA%AB%E8%AE%B0%E5%BD%95%E4%B8%80%E4%B8%8B%E4%B8%80%E4%B8%AA-scp-%E6%93%8D%E4%BD%9C%E6%96%B9%E6%B3%95/ - scp 是个在服务器之间拷贝文件的一个常用命令,有时候有个场景是比如我们需要拷贝一些带有共同前缀的文件,但是有一个问题是比如我们有使用 zsh 的话,会出现一个报错,

    -
    zsh: no matches found: root@100.100.100.100://root/prefix*
    -

    这里就比较奇怪了,这个前缀的文件肯定是有的,这里其实是由于 zsh 会对 * 进行展开,这个可以在例如 ls 命令在使用中就可以发现 zsh 有这个特性
    需要使用双引号或单引号将路径包起来或者在*之前加反斜杠\来阻止对*展开和转义

    -
    scp root@100.100.100.100://root/prefix* .
    -

    通过使用双引号"进行转义

    -
    scp root@100.100.100.100:"//root/prefix*" .
    -

    或者可以将 shell 从 zsh 切换成 bash

    + 在 wsl 2 中开启 ssh 连接 + /2023/04/23/%E5%9C%A8-wsl-2-%E4%B8%AD%E5%BC%80%E5%90%AF-ssh-%E8%BF%9E%E6%8E%A5/ + 之前在 wsl 1 中开启 ssh 其实很方便,只要把 sshd 服务起来就好了,但是在 wsl 2 中就不太一样了,
    我这边使用的是 wsl 2 中的 Ubuntu 20.04,直接启动 sshd 服务是没法让其他机器连接的,而且都没有 ifconfig 命令可以查看 ip
    不过可以用直接用 ip a来查看,可以看到这个 ip 是172网段的,而在 wsl 1 中可以看到 ip 就是 win 的 ip,
    所以需要做一些操作,首先要安装 openssl-server

    +
    sudo apt update
    +sudo apt install openssh-server
    +

    另外如果需要提高安全性,可以wsl 中配置 hosts.allow

    +
    sshd:192.168.xx.
    +

    先定一个子网段,然后对于ssh的配置,可以做以下修改

    +
    Port 22
    +PasswordAuthentication yes
    +

    在进行重启

    +
    sudo service ssh --full-restart
    +

    配置以后发现上面的问题,没法远程登录,因为 wsl 2 是基于 hyper-v 虚拟机实现的,并且 ip 使用的是一个虚拟出来的子网 ip,所以需要在 Windows 这一层配置端口的转发,可以通过命令netsh interface portproxy show v4tov4看到

    截图是我已经添加好了的,先把原来的删除,再进行添加

    +
    netsh interface portproxy delete v4tov4 listenaddress=0.0.0.0 listenport=22
    +netsh interface portproxy add v4tov4 listenaddress=0.0.0.0 listenport=22 connectaddress=172.19.129.207 connectport=22
    +

    也可以全量删除

    +
    netsh int portproxy reset all
    +

    但是这样也不能直接访问了,还需要开启防火墙

    +
    netsh advfirewall firewall add rule name="WSL SSH" dir=in action=allow protocol=TCP localport=22
    + + + ]]>
    - shell - 小技巧 + wsl - scp + wsl
    - 分享一次折腾老旧笔记本的体验-续续篇 - /2023/02/26/%E5%88%86%E4%BA%AB%E4%B8%80%E6%AC%A1%E6%8A%98%E8%85%BE%E8%80%81%E6%97%A7%E7%AC%94%E8%AE%B0%E6%9C%AC%E7%9A%84%E4%BD%93%E9%AA%8C-%E7%BB%AD%E7%BB%AD%E7%AF%87/ - 上周因为一些事情没回去,买好了内存条这周才回去用,结果不知道是 U 盘的问题还是什么其他原因原来装的那个系统起不来,然后想用之前一直用的 LD 的笔记本,结果 LD 的老笔记本也起不来了,一直卡在启动界面,猜测可能是本身也比较老了,用的机械硬盘会不会被我一直动而损坏了,所以就想搞个老毛桃跟新搞一个启动盘,结果这周最大的坑就在这了,在我的 15 寸 mbp 上用etcher做了个 win10 的启动盘,可能是分区表格式是 GUID,不是 MBR 的,老电脑不能识别,就像装个虚拟机来做启动盘,结果像老毛桃不支持这种用虚拟机的,需要本地磁盘,然后我就有用 bootcamp 安装了个 win10,又没网络,查了下网络需要用 bootcamp 下载 Windows Support 软件,下了好久一直没下完,后来又提示连不上苹果服务器,好不容易下完了,开启 win10 后,安装到一半就蓝屏了,真的是够操蛋的,在这个时候真的很需要有一个 Windows 机器的支持,LD 的那个笔记本也跟我差不多老了,虽然比较慢但之前好歹也还可以用,结果这下也被我弄坏了,家里就没有其他机器可以支持了,有点巧妇难为无米之炊的赶脚,而且还是想再折腾下我的老电脑,后面看看打算做几个 U 盘,分工职责明确,一个老毛桃的PE 盘,老毛桃的虽然不是很纯净的,但是是我一直以来用过内置工具比较全,修复启动功能比较强大的一个 pe,没用过 winpe,后续可以考虑使用下,一个 win7 的启动盘,因为是老电脑,如果后面是新的电脑可以考虑是 win10,一个 win to go 盘,这样我的 mbp 就可以直接用 win10 了,不过想来也还是要有一台 win 机器才比较好,不然很多时候都是在折腾工具,工欲善其事必先利其器,后面也可以考虑能够更深入的去了解主板的一些问题,我原来的那个主板可能是一些小的电阻等问题,如果能自己学习解决就更好了,有时候研究下还是有意思的。

    + 在老丈人家的小工记三 + /2020/09/13/%E5%9C%A8%E8%80%81%E4%B8%88%E4%BA%BA%E5%AE%B6%E7%9A%84%E5%B0%8F%E5%B7%A5%E8%AE%B0%E4%B8%89/ + 小工记三

    前面这两周周末也都去老丈人家帮忙了,上上周周六先是去了那个在装修的旧房子那,把三楼收拾了下,因为要搬进来住,来不及等二楼装修好,就要把三楼里的东西都整理干净,这个活感觉是比较 easy,原来是就准备把三楼当放东西仓储的地方了,我们乡下大部分三层楼都是这么用的,这次也是没办法,之前搬进来的木头什么的都搬出去,主要是这上面灰尘太多,后面清理鼻孔的时候都是黑色的了,把东西都搬出去以后主要是地还是很脏,就扫了地拖了地,因为是水泥地,灰尘又太多了,拖起来都是会灰尘扬起来,整个脱完了的确干净很多,然而这会就出了个大乌龙,我们清理的是三楼的西边一间,结果老丈人上来说要住东边那间的🤦‍♂️,不过其实西边的也得清理,因为还是要放被子什么的,不算是白费功夫,接着清理东边那间,之前这个房子做过群租房,里面有个高低铺的床,当时觉得可以用在放被子什么的就没扔,只是拆掉了放旁边,我们就把它擦干净了又装好,发现螺丝🔩少了几个,亘古不变的真理,拆了以后装要不就多几个要不就少几个,不是很牢靠,不过用来放放被子省得放地上总还是可以的,对了前面还做了个事情就是铺地毯,其实也不是地毯,就是类似于墙布雨篷布那种,别人不用了送给我们的,三楼水泥地也不会铺瓷砖地板了就放一下,干净好看点,不过大小不合适要裁一下,那把剪刀是真的太难用了,我手都要抽筋了,它就是刀口只有一小个点是能剪下来的,其他都是钝的,后来还是用刀片直接裁,铺好以后,真的感觉也不太一样了,焕然一新的感觉
    差不多中午了就去吃饭了,之前两次是去了一家小饭店,还是还比较干净,但是店里菜不好吃,还死贵,这次去了一家小快餐店,口味好,便宜,味道是真的不错,带鱼跟黄鱼都好吃,一点都不腥,我对这类比较腥的鱼真的是很挑剔的,基本上除了家里做的很少吃外面的,那天抱着试试的态度吃了下,真的还不错,后来丈母娘说好像这家老板是给别人结婚喜事酒席当厨师的,怪不得做的好吃,其实本来是有一点小抗拒,怕不干净什么的,后来发现菜很好吃,而且可能是老丈人跟干活的师傅去吃的比较多,老板很客气,我们吃完饭,还给我们买了葡萄吃,不过这家店有一个槽点,就是饭比较不好吃,有时候会夹生,不过后面聊起来其实是这种小菜馆饭点的通病,烧的太早太多容易多出来浪费,烧的迟了不够吃,而且大的电饭锅比较不容易烧好。
    下午前面还是在处理三楼的,窗户上各种钉子,实在是太多了,我后面在走廊上排了一排🤦‍♂️,有些是直接断了,有些是就撬了出来,感觉我在杭州租房也没有这样子各种钉钉子,挂下衣服什么的也不用这么多吧,比较不能理解,搞得到处都是钉子。那天我爸也去帮忙了,主要是在卫生间里做白缝,其实也是个技术活,印象中好像我小时候自己家里也做过这个事情,但是比较模糊了,后面我们三楼搞完了就去帮我爸了,前面是我老婆二爹在那先刷上白缝,这里叫白缝,有些考究的也叫美缝,就是瓷砖铺完之后的缝,如果不去弄的话,里面水泥的颜色就露出来了,而且容易渗水,所以就要用白水泥加胶水搅拌之后糊在缝上,但是也不是直接糊,先要把缝抠一抠,因为铺瓷砖的还不会仔细到每个缝里的水泥都是一样满,而且也需要一些空间糊上去,不然就太表面的一层很容易被水直接冲掉了,然后这次其实也不是用的白水泥,而是直接现成买来就已经配好的用来填缝的,兑水搅拌均匀就好了,后面就主要是我跟我爸在搞,那个时候真的觉得我实在是太胖了,蹲下去真的没一会就受不了了,膝盖什么的太难受了,后面我跪着刷,然后膝盖又疼,也是比较不容易,不过我爸动作很快,我中间跪累了休息一会,我爸就能搞一大片,后面其实我也没做多少(谦虚一下),总体来讲这次不是很累,就是蹲着跪着腿有点受不了,是应该好好减肥了。

    ]]>
    - Windows - 小技巧 + 生活 + 运动 + 跑步 + 干活 - Windows + 生活 + 小技巧 + 运动 + 减肥 + 跑步 + 干活
    - 在老丈人家的小工记三 - /2020/09/13/%E5%9C%A8%E8%80%81%E4%B8%88%E4%BA%BA%E5%AE%B6%E7%9A%84%E5%B0%8F%E5%B7%A5%E8%AE%B0%E4%B8%89/ - 小工记三

    前面这两周周末也都去老丈人家帮忙了,上上周周六先是去了那个在装修的旧房子那,把三楼收拾了下,因为要搬进来住,来不及等二楼装修好,就要把三楼里的东西都整理干净,这个活感觉是比较 easy,原来是就准备把三楼当放东西仓储的地方了,我们乡下大部分三层楼都是这么用的,这次也是没办法,之前搬进来的木头什么的都搬出去,主要是这上面灰尘太多,后面清理鼻孔的时候都是黑色的了,把东西都搬出去以后主要是地还是很脏,就扫了地拖了地,因为是水泥地,灰尘又太多了,拖起来都是会灰尘扬起来,整个脱完了的确干净很多,然而这会就出了个大乌龙,我们清理的是三楼的西边一间,结果老丈人上来说要住东边那间的🤦‍♂️,不过其实西边的也得清理,因为还是要放被子什么的,不算是白费功夫,接着清理东边那间,之前这个房子做过群租房,里面有个高低铺的床,当时觉得可以用在放被子什么的就没扔,只是拆掉了放旁边,我们就把它擦干净了又装好,发现螺丝🔩少了几个,亘古不变的真理,拆了以后装要不就多几个要不就少几个,不是很牢靠,不过用来放放被子省得放地上总还是可以的,对了前面还做了个事情就是铺地毯,其实也不是地毯,就是类似于墙布雨篷布那种,别人不用了送给我们的,三楼水泥地也不会铺瓷砖地板了就放一下,干净好看点,不过大小不合适要裁一下,那把剪刀是真的太难用了,我手都要抽筋了,它就是刀口只有一小个点是能剪下来的,其他都是钝的,后来还是用刀片直接裁,铺好以后,真的感觉也不太一样了,焕然一新的感觉
    差不多中午了就去吃饭了,之前两次是去了一家小饭店,还是还比较干净,但是店里菜不好吃,还死贵,这次去了一家小快餐店,口味好,便宜,味道是真的不错,带鱼跟黄鱼都好吃,一点都不腥,我对这类比较腥的鱼真的是很挑剔的,基本上除了家里做的很少吃外面的,那天抱着试试的态度吃了下,真的还不错,后来丈母娘说好像这家老板是给别人结婚喜事酒席当厨师的,怪不得做的好吃,其实本来是有一点小抗拒,怕不干净什么的,后来发现菜很好吃,而且可能是老丈人跟干活的师傅去吃的比较多,老板很客气,我们吃完饭,还给我们买了葡萄吃,不过这家店有一个槽点,就是饭比较不好吃,有时候会夹生,不过后面聊起来其实是这种小菜馆饭点的通病,烧的太早太多容易多出来浪费,烧的迟了不够吃,而且大的电饭锅比较不容易烧好。
    下午前面还是在处理三楼的,窗户上各种钉子,实在是太多了,我后面在走廊上排了一排🤦‍♂️,有些是直接断了,有些是就撬了出来,感觉我在杭州租房也没有这样子各种钉钉子,挂下衣服什么的也不用这么多吧,比较不能理解,搞得到处都是钉子。那天我爸也去帮忙了,主要是在卫生间里做白缝,其实也是个技术活,印象中好像我小时候自己家里也做过这个事情,但是比较模糊了,后面我们三楼搞完了就去帮我爸了,前面是我老婆二爹在那先刷上白缝,这里叫白缝,有些考究的也叫美缝,就是瓷砖铺完之后的缝,如果不去弄的话,里面水泥的颜色就露出来了,而且容易渗水,所以就要用白水泥加胶水搅拌之后糊在缝上,但是也不是直接糊,先要把缝抠一抠,因为铺瓷砖的还不会仔细到每个缝里的水泥都是一样满,而且也需要一些空间糊上去,不然就太表面的一层很容易被水直接冲掉了,然后这次其实也不是用的白水泥,而是直接现成买来就已经配好的用来填缝的,兑水搅拌均匀就好了,后面就主要是我跟我爸在搞,那个时候真的觉得我实在是太胖了,蹲下去真的没一会就受不了了,膝盖什么的太难受了,后面我跪着刷,然后膝盖又疼,也是比较不容易,不过我爸动作很快,我中间跪累了休息一会,我爸就能搞一大片,后面其实我也没做多少(谦虚一下),总体来讲这次不是很累,就是蹲着跪着腿有点受不了,是应该好好减肥了。

    + 在老丈人家的小工记五 + /2020/10/18/%E5%9C%A8%E8%80%81%E4%B8%88%E4%BA%BA%E5%AE%B6%E7%9A%84%E5%B0%8F%E5%B7%A5%E8%AE%B0%E4%BA%94/ + 终于回忆起来了,年纪大了写这种东西真的要立马写,不然很容易想不起来,那天应该是 9 月 12 日,也就是上周六,因为我爸也去了,而且娘亲(丈母娘,LD 这么叫,我也就随了她这么叫,当然是背后,当面就叫妈)也在那,早上一到那二爹就给我爸指挥了活,要挖一条院子的出水道,自己想出来的词,因为觉得下水道是竖的,在那稍稍帮了一会会忙,然后我还是比较惯例的跟着 LD 还有娘亲去住的家里,主要是老丈人可能也不太想让我干太累的活,因为上次已经差不多把三楼都整理干净了,然后就是二楼了,二楼说实话我也帮不上什么忙,主要是衣服被子什么的,正好是有张以前小孩子睡过的那种摇篮床,看上去虽然有一些破损,整体还是不错的,所以打算拿过去,我就负责把它拆掉了,比较简单的是只要拧螺丝就行了,但是其实是用了好多好多工具才搞定的,一开始只要螺丝刀就行了,但是因为年代久了,后面的螺帽也有点锈住或者本身就会串着会一起动,所以拿来了个扳手,大部分的其实都被这两个工具给搞定了,但是后期大概还剩下四分之一的时候,有一颗完全锈住,并且螺纹跟之前那些都不一样,但是这个已经是最大的螺丝刀了,也没办法换个大的了,所以又去找来个一字的,因为十字的不是也可以用一字的拧嘛,结果可能是我买的工具箱里的一字螺丝刀太新了,口子那很锋利,直接把螺丝花纹给划掉了,大的小的都划掉,然后真的变成凹进去一个圆柱体了,然后就想能不能隔一层布去拧,然而因为的确是已经变成圆柱体了,布也不太给力,不放弃的我又去找来了个老虎钳,妄图把划掉的螺丝用老虎钳钳住,另一端用扳手拧开螺帽,但是这个螺丝跟螺帽真的是生锈的太严重了,外加上钳不太牢,完全是两边一起转,实在是没办法了,在征得同意之后,直接掰断了,火死了,一颗螺丝折腾得比我拆一张床还久,那天因为早上去的也比较晚了,然后就快吃午饭了,正好想着带一点东西过去,就把一些脸盆,泡脚桶啥的拿过去了,先是去吃了饭,还是在那家快餐店,菜的口味还是依然不错,就是人比较多,我爸旁边都是素菜,都没怎么吃远一点的荤菜,下次要早点去,把荤菜放我爸旁边😄(PS:他们家饭还是依然尴尬,需要等),吃完就开到在修的房子那把东西拿了出来,我爸已经动作很快的打了一小半的地沟了,说实话那玩意真的是很重,我之前把它从三楼拿下来,就觉得这个太重了,这次还要用起来,感觉我的手会分分钟废掉,不过一开始我还是跟着LD去了住的家里,惯例睡了午觉,那天睡得比较踏实,竟然睡了一个小时,醒了想了下,其实LD她们收拾也用不上我(没啥力气活),我还是去帮我爸他们,跟LD说了下就去了在修的老房子那,两位老爹在一起钻地,看着就很累,我连忙上去想换一会他们,因为刚好是钻到混凝土地线,特别难,力道不够就会滑开,用蛮力就是钻进去拔不出来,原理是因为本身浇的时候就是很紧实的,需要边钻边动,那家伙实在是太重了,真的是汗如雨下,基本是三个人轮流来,我是个添乱的,经常卡住,然后把地线,其实就是一条混凝土横梁,里面还有14跟18的钢筋,需要割断,这个割断也是很有技巧,钢筋本身在里面是受到挤压的,直接用切割的,到快断掉的时候就会崩一下,非常危险,还是老丈人比较有经验,要留一点点,然后直接用榔头敲断就好了,本来以为这个是最难的了,结果下面是一块非常大的青基石,而且也是石头跟石头挤一块,边上一点点打钻有点杯水车薪,后来是用那种螺旋的钻,钻四个洞,相对位置大概是个长方形,这样子把中间这个长方形钻出来就比较容易地能拿出来了,后面的也容易搞出来了,后面的其实难度不是特别大了,主要是地沟打好之后得看看高低是不是符合要求的,不能本来是往外排水的反而外面高,这个怎么看就又很有技巧了,一般在地上的只要侧着看一下就好了,考究点就用下水平尺,但是在地下的,不用水平尺,其实可以借助于地沟里正要放进去的水管,放点水进去,看水往哪流就行了,铺好水管后,就剩填埋的活了,不是太麻烦了,那天真的是累到了,打那个混凝土的时候我真的是把我整个人压上去了,不过也挺爽的,有点把平时无处发泄的蛮力发泄出去了。

    ]]>
    生活 @@ -13576,6 +13363,23 @@ user3: 干活
    + + 小工周记一 + /2023/03/05/%E5%B0%8F%E5%B7%A5%E5%91%A8%E8%AE%B0%E4%B8%80/ + 开始修老房子又可以更新这个系列了,比较无聊,就是帮着干点零活的记录,这次过去起的比较早,前几天是在翻新瓦片,到这次周六是收尾了,到了的时候先是继续筛了沙子,上周也筛了,就是只筛了一点点,筛沙子的那个像纱窗一样的还是用一扇中空的中间有一根竖档的门钉上铁丝网做的,就是沙子一直放在外面,原来是有袋子装好的,后来是风吹雨打在上面的都已经破掉,还夹杂了很多树叶什么的,需要过下筛,并且前面都是下雨天,沙子都是湿的,不太像我以前看村里有人造房子筛沙子那样,用铲子铲上去就自己都下去的,湿的就是会在一坨,所以需要铲得比较少,然后撒的比较开,这个需要一点经验,然后如果有人一起的话就可以用扫把按住扫一下,这样就会筛得比较有效,不至于都滑下去,沙子本来大部分是可以筛出来的,还有一点就是这种情况网筛需要放得坡度小一点,不然就更容易直接往下调,袋子没破的就不用过筛了,只是湿掉了的是真的重,筛完了那些破掉了的袋子里的沙子,就没有特别的事情要做了,看到大工在那打墙,有一些敲下来的好的砖头就留着,需要削一下上面的混凝土,据大工说现在砖头要七八毛一块了,后面能够重新利用还是挺值钱的,我跟 LD 就用泥刀和铁锹的在那慢慢削,砖头上的泥灰有的比较牢固有的就像直接是沙子,泥刀刮一下就下来了,有的就结合得比较牢固,不过据说以前的砖头工艺上还比较落后,这个房子差不多是三十年前了的,砖头表面都是有点不平,甚至变形,那时候可能砖头是手工烧制的,现在的砖头比较工艺可好多了,不过可能也贵了很多,后来老丈人也过来了,指导了我们拌泥灰,就是水泥和黄沙混合,以前小时候可喜欢玩这个了,可是就也搞不清楚这个是怎么搅拌的,只看见是水泥跟黄沙围城一圈,中间放水,然后一点点搬进去,首先需要先把干的水泥跟黄沙进行混合,具体的比例是老丈人说的,拌的方式有点像堆沙堆,把水泥黄沙铲起来堆起来,就一直要往这个混合堆的尖尖上堆,这样子它自己滑下来能更好地混合,来回两趟就基本混合均匀了,然后就是跟以前看过的,中间扒拉出一个空间放水,然后慢慢把周围的混合好的泥沙推进去,需要注意不要太着急,旁边的推进去太多太快就会漏水出来,一个是会把旁边的地给弄脏,另一个也铲不回水,然后就是推完所有的都混合水了,就铲起来倒一下,再将铲子翻过来捣几下,后面我们就去吃饭了,去了一家叫金记的,又贵又不太好吃的店,就是离得比较近,六七个人只有六七个菜,吃完要四百多,也是有点离谱了。
    下午是重头戏,其实本来倒没啥事,就说帮忙搞下靠背(就是踢脚线上面到窗台附近的用木头还有其他材料的装饰性的),都撬撬掉,但是真的是有点离谱了,首先是撬棒真的很重,20 斤的重量(网上查的,没有真的查过),抡起来还要用力地铲进去,因为就是破坏性的要把整个都撬掉,对于我这种又没技巧又没力气的非专业选手,抡起撬棍铲两下手就开始痛了,只是也比较犟,不想刚开始弄就说太重了要休息,后面都完全靠的一点倔强劲撑着,看着里面的工艺感觉也是不容易的,直着横着的木条有好多,竖的一整条,每隔三五十公分,横着的就是三五十公分,每根都要用钉子钉起来,然后外层好像是贴上去,在同一个面的开了头之后就能靠着蛮力往下撬,但是到了转角就又要重新开头,而且最上面一根横条跟紧邻的那一块,大概十几公分,是横着的三条钉在一起,真的是大力都出不了奇迹了,用撬棍的一头用力地敲打都很震手,要从下面往上铲进去撬开一点,然后再从上面往下敲打,这里比较重要的是要小心钉子,我这次运气比较好,踩下去已经扎到了,不过正好在脚趾缝里,没有扎到脚,还是要小心的,做完这个我的手真的是差不多废了,上臂的疼痛已经动一下就受不了了,后面有撬下了最下面当踢脚线的小瓷砖,这个房子估计中间修过一次,两批水泥糊的,新的那批粘的特别牢,敲敲打打了半天才下来一点点,锤子敲上去跟一整块石头一样,震手又没有进展,整个搞完,楼上又在敲墙了,下面的灰尘也是从没见过,我一直在那洒水都完全没有缓解,就上去跟 LD 一起拣砖头,手痛到只能抬两块砖头都会痛了。
    回到家里开始越来越痛,两个手就完全没法动了,应该也是肌肉拉伤了,我这样是没足够的力气也不会什么技巧,像大工说的,他们也累也难,只是为了赚钱,不过他们有了经验跟技巧,会注意怎么使力不容易受伤,怎么样比较省力,还有一点就是即使这么累,他们一般也下午五点半就下班了,真的很累了,至少还有不少时间可以回家休息,而我们的职业呢,就像 LD 说的回家就像住酒店,就只是来洗澡睡个觉,希望能改善吧

    +]]>
    + + 生活 + + + 生活 + 小技巧 + 运动 + 减肥 + 跑步 + 干活 + +
    在老丈人家的小工记四 /2020/09/26/%E5%9C%A8%E8%80%81%E4%B8%88%E4%BA%BA%E5%AE%B6%E7%9A%84%E5%B0%8F%E5%B7%A5%E8%AE%B0%E5%9B%9B/ @@ -13597,9 +13401,13 @@ user3: - 分享一次折腾老旧笔记本的体验-续篇 - /2023/02/12/%E5%88%86%E4%BA%AB%E4%B8%80%E6%AC%A1%E6%8A%98%E8%85%BE%E8%80%81%E6%97%A7%E7%AC%94%E8%AE%B0%E6%9C%AC%E7%9A%84%E4%BD%93%E9%AA%8C-%E7%BB%AD%E7%AF%87/ - 接着上一篇的折腾记,因为这周又尝试了一些新的措施和方法,想继续记录分享下,上周的整体情况大概是 Ubuntu 系统能进去了,但是 Windows 进不去,PE 也进不去,Windows 启动盘也进不去,因为我的机器加过一个 msata 的固态,Windows 是装在 msata 固态硬盘里的,Ubuntu 是装在机械硬盘里的,所以有了一种猜测就是可能这个固态硬盘有点问题,还有就是还是怀疑内存的问题,正好家里还有个msata 的固态硬盘,是以前想给LD 的旧笔记本换上的,因为买回来放在那没有及时装,后面会又找不到,直到很后面才找到,LD 也不怎么用那个笔记本了,所以就一直放着了,这次我就想拿来换上。
    周末回家我就开始尝试了,换上了新的固态硬盘后,插上 Windows 启动 U 盘,这次一开始看起来有点顺利,在 BIOS 选择 U 盘启动,进入了 Windows 安装界面,但是装到一半,后面重启了之后就一直说硬盘有问题,让重启,但是重启并没有解决问题,变成了一直无效地重复重启,再想进 U 盘启动,就又进不去了,这时候怎么说呢,感觉硬盘不是没有问题,但是呢,问题应该不完全出在这,所以按着总体的逻辑来讲,主板带着cpu 跟显卡,都换掉了,硬盘也换掉了,剩下的就是内存了,可是内存我也尝试过把后面加的那条金士顿拔掉,可还是一样,也尝试过用橡皮擦金手指,这里感觉也很奇怪了,找了一圈了都感觉没啥明确的原因,比如其实我的猜测,主板电池的问题,一些电阻坏掉了,但是主板是换过的,那如果内存有问题,照理我用原装的那条应该会没问题,也有一种非常小的可能,就是两条内存都坏了,或者说这也是一种不太可能的可能,所以最后的办法就打算试试把两条内存都换掉,不过现在网上都找不到这个内存的确切信息了,只能根据大致的型号去买来试试,就怕买来的还是坏的,其实也怕是这个买来的主板因为也是别的拆机下来的,不一定保证完全没问题,要是有类似的问题或者也有别的问题导致开不起来就很尴尬,也没有很多专业的仪器可以排查原因,比如主板有没有什么短路的,对了还有一个就是电源问题,但是电源的问题也就可能是从充电器插的口子到主板的连线,因为 LD 的电源跟我的口子一样,也试过,但是结果还是一样,顺着正常逻辑排查,目前也没有剩下很明确的方向了,只能再尝试下看看。

    + 分享一次比较诡异的 Windows 下 U盘无法退出的经历 + /2023/01/29/%E5%88%86%E4%BA%AB%E4%B8%80%E6%AC%A1%E6%AF%94%E8%BE%83%E8%AF%A1%E5%BC%82%E7%9A%84-Windows-%E4%B8%8B-U%E7%9B%98%E6%97%A0%E6%B3%95%E9%80%80%E5%87%BA%E7%9A%84%E7%BB%8F%E5%8E%86/ + 作为一个 Windows 的老用户,并且也算是 Windows 系统的半个粉丝,但是秉承一贯的优缺点都应该说的原则,Windows 系统有一点缺点是真的挺难受,相信 Windows 用过比较久的都会经历过,就是 U盘无法退出的问题,在比较远古时代,这个问题似乎能采取的措施不多,关机再拔 U盘的方式是一种比较保险的方式,其他貌似有 360这种可以解除占用的,但是需要安装 360 软件,对于目前的使用环境来说有点得不偿失,也是比较流氓的一类软件了,目前在 Windows 环境我主要就安装了个火绒,或者就用 Windows 自带的 defender。

    +

    第一种

    最近这次经历也是有火绒的一定责任,在我尝试推出 U盘的时候提示了我被另一个大流氓软件,XlibabaProtect.exe 占用了,这个流氓软件真的是充分展示了某里的技术实力,试过 N 多种办法都关不掉也删不掉,尝试了很多种办法也没办法删除,但是后面换了种思路,一般这种情况肯定是有进程在占用 U盘里的内容,最新版本的 Powertoys 会在文件的右键菜单里添加一个叫 File Locksmith 的功能,可以用于检查正在使用哪些文件以及由哪些进程使用,但是可能是我的使用姿势不对,没有仔细看文档,它里面有个”以管理员身份重启”,可能会有用。
    这算是第一种方式,

    +

    第二种

    第二种方式是 Windows 任务管理器中性能 tab 下的”打开资源监视器”,
    ,假如我的 U 盘的盘符是F:
    就可以搜索到占用这个盘符下文件的进程,这里千万小心‼️‼️,不可轻易杀掉这些进程,有些系统进程如果轻易杀掉会导致蓝屏等问题,不可轻易尝试,除非能确认这些进程的作用。
    对于前两种方式对我来说都无效,

    +

    第三种

    所以尝试了第三种,
    就是磁盘脱机的方式,在”计算机”右键管理,点击”磁盘管理”,可以找到 U 盘盘符右键,点击”脱机”,然后再”推出”,这个对我来说也不行

    +

    第四种

    这种是唯一对我有效的,在开始菜单搜索”event”,可以搜到”事件查看器”,
    ,这个可以看到当前最近 Windows 发生的事件,打开这个后就点击U盘推出,因为推不出来也是一种错误事件,点击下刷新就能在这看到具体是因为什么推出不了,具体的进程信息
    最后发现是英特尔的驱动管理程序的一个进程,关掉就退出了,虽然前面说的某里的进程是流氓,但这边是真的冤枉它了

    ]]>
    Windows @@ -13610,189 +13418,300 @@ user3:
    - 在老丈人家的小工记五 - /2020/10/18/%E5%9C%A8%E8%80%81%E4%B8%88%E4%BA%BA%E5%AE%B6%E7%9A%84%E5%B0%8F%E5%B7%A5%E8%AE%B0%E4%BA%94/ - 终于回忆起来了,年纪大了写这种东西真的要立马写,不然很容易想不起来,那天应该是 9 月 12 日,也就是上周六,因为我爸也去了,而且娘亲(丈母娘,LD 这么叫,我也就随了她这么叫,当然是背后,当面就叫妈)也在那,早上一到那二爹就给我爸指挥了活,要挖一条院子的出水道,自己想出来的词,因为觉得下水道是竖的,在那稍稍帮了一会会忙,然后我还是比较惯例的跟着 LD 还有娘亲去住的家里,主要是老丈人可能也不太想让我干太累的活,因为上次已经差不多把三楼都整理干净了,然后就是二楼了,二楼说实话我也帮不上什么忙,主要是衣服被子什么的,正好是有张以前小孩子睡过的那种摇篮床,看上去虽然有一些破损,整体还是不错的,所以打算拿过去,我就负责把它拆掉了,比较简单的是只要拧螺丝就行了,但是其实是用了好多好多工具才搞定的,一开始只要螺丝刀就行了,但是因为年代久了,后面的螺帽也有点锈住或者本身就会串着会一起动,所以拿来了个扳手,大部分的其实都被这两个工具给搞定了,但是后期大概还剩下四分之一的时候,有一颗完全锈住,并且螺纹跟之前那些都不一样,但是这个已经是最大的螺丝刀了,也没办法换个大的了,所以又去找来个一字的,因为十字的不是也可以用一字的拧嘛,结果可能是我买的工具箱里的一字螺丝刀太新了,口子那很锋利,直接把螺丝花纹给划掉了,大的小的都划掉,然后真的变成凹进去一个圆柱体了,然后就想能不能隔一层布去拧,然而因为的确是已经变成圆柱体了,布也不太给力,不放弃的我又去找来了个老虎钳,妄图把划掉的螺丝用老虎钳钳住,另一端用扳手拧开螺帽,但是这个螺丝跟螺帽真的是生锈的太严重了,外加上钳不太牢,完全是两边一起转,实在是没办法了,在征得同意之后,直接掰断了,火死了,一颗螺丝折腾得比我拆一张床还久,那天因为早上去的也比较晚了,然后就快吃午饭了,正好想着带一点东西过去,就把一些脸盆,泡脚桶啥的拿过去了,先是去吃了饭,还是在那家快餐店,菜的口味还是依然不错,就是人比较多,我爸旁边都是素菜,都没怎么吃远一点的荤菜,下次要早点去,把荤菜放我爸旁边😄(PS:他们家饭还是依然尴尬,需要等),吃完就开到在修的房子那把东西拿了出来,我爸已经动作很快的打了一小半的地沟了,说实话那玩意真的是很重,我之前把它从三楼拿下来,就觉得这个太重了,这次还要用起来,感觉我的手会分分钟废掉,不过一开始我还是跟着LD去了住的家里,惯例睡了午觉,那天睡得比较踏实,竟然睡了一个小时,醒了想了下,其实LD她们收拾也用不上我(没啥力气活),我还是去帮我爸他们,跟LD说了下就去了在修的老房子那,两位老爹在一起钻地,看着就很累,我连忙上去想换一会他们,因为刚好是钻到混凝土地线,特别难,力道不够就会滑开,用蛮力就是钻进去拔不出来,原理是因为本身浇的时候就是很紧实的,需要边钻边动,那家伙实在是太重了,真的是汗如雨下,基本是三个人轮流来,我是个添乱的,经常卡住,然后把地线,其实就是一条混凝土横梁,里面还有14跟18的钢筋,需要割断,这个割断也是很有技巧,钢筋本身在里面是受到挤压的,直接用切割的,到快断掉的时候就会崩一下,非常危险,还是老丈人比较有经验,要留一点点,然后直接用榔头敲断就好了,本来以为这个是最难的了,结果下面是一块非常大的青基石,而且也是石头跟石头挤一块,边上一点点打钻有点杯水车薪,后来是用那种螺旋的钻,钻四个洞,相对位置大概是个长方形,这样子把中间这个长方形钻出来就比较容易地能拿出来了,后面的也容易搞出来了,后面的其实难度不是特别大了,主要是地沟打好之后得看看高低是不是符合要求的,不能本来是往外排水的反而外面高,这个怎么看就又很有技巧了,一般在地上的只要侧着看一下就好了,考究点就用下水平尺,但是在地下的,不用水平尺,其实可以借助于地沟里正要放进去的水管,放点水进去,看水往哪流就行了,铺好水管后,就剩填埋的活了,不是太麻烦了,那天真的是累到了,打那个混凝土的时候我真的是把我整个人压上去了,不过也挺爽的,有点把平时无处发泄的蛮力发泄出去了。

    + 寄生虫观后感 + /2020/03/01/%E5%AF%84%E7%94%9F%E8%99%AB%E8%A7%82%E5%90%8E%E6%84%9F/ + 寄生虫这部电影在获得奥斯卡之前就有关注了,豆瓣评分很高,一开始看到这个片名以为是像《铁线虫入侵》那种灾难片,后来看到男主,宋康昊,也是老面孔了,从高中时候在学校操场组织看的《汉江怪物》,有点二的感觉,后来在大学寝室电脑上重新看的时候,室友跟我说是韩国国宝级演员,真人不可貌相,感觉是个呆子的形象。

    +

    但是你说这不是个灾难片,而是个反映社会问题的,就业比较容易往这个方向猜,只是剧情会是怎么样的,一时也没啥头绪,后来不知道哪里看了下一个剧情透露,是一个穷人给富人做家教,然后把自己一家都带进富人家,如果是这样的话可能会把这个怎么带进去作为一个主线,不过事实告诉我,这没那么重要,从第一步朋友的介绍,就显得无比顺利,要去当家教了,作为一个穷成这样的人,瞬间转变成一个衣着得体,言行举止都没让富人家看出破绽的延世大学学生,这真的挺难让人理解,所谓江山易改,本性难移,还有就是这人也正好有那么好能力去辅导,并且诡异的是,多惠也是瞬间就喜欢上了男主,多惠跟将男主介绍给她做家教,也就是多惠原来的家教敏赫,应该也有不少的相处时间,这变了有点大了吧,当然这里也可能因为时长需要,如果说这一点是因为时长,那可能我所有的槽点都是因为这个吧,因为我理解的应该是把家里的人如何一步步地带进富人家,这应该是整个剧情的一个需要更多铺垫去克服这个矛盾点,有时候也想过如果我去当导演,是能拍出个啥,没这个机会,可能有也会是很扯淡的,当然这也不能阻拦我谈谈对这个点的一些看法,毕竟评价一台电冰箱不是说我必须得自己会制冷对吧,这大概是我觉得这个电影的第一个槽点,接下去接二连三的,就是我说的这个最核心的矛盾点,不知道谁说过,这种影视剧应该是源自于生活又高于生活,越是好的作品,越要接近生活,这样子才更能有感同身受。

    +

    接下去的点是金基宇介绍金基婷去给多颂当美术家教,这一步又是我理解的败笔吧,就怎么说呢,没什么铺垫,突然从一个社会底层的穷姑娘,转变成一个气场爆表,把富人家太太唬得一愣一愣的,如果说富太太是比较简单无脑的,那富人自己应该是比较有见识而且是做 IT 的,给自己儿子女儿做家教的,查查底细也很正常吧,但是啥都没有,然后呢,她又开始耍司机的心机了,真的是莫名其妙了,司机真的很惨,窈窕淑女君子好逑,而且这个操作也让我摸不着头脑,这是多腹黑并且有经验才会这么操作,脱内裤真的是让我看得一愣愣的,更看得我一愣一愣的,富人竟然也完全按着这个思路去想了,完全没有别的可能呢,甚至可以去查下行车记录仪或者怎样的,或者有没有毛发体液啥的去检验下,毕竟金基婷也乘坐过这辆车,但是最最让我不懂的还是脱内裤这个操作,究竟是什么样的人才会的呢,值得思考。

    +

    金基泽和忠淑的点也是比较奇怪,首先是金基泽,引起最后那个杀人事件的一个由头,大部分观点都是人为朴社长在之前跟老婆啪啪啪的时候说金基泽的身上有股乘地铁的人的味道,简而言之就是穷人的味道,还有去雯光丈夫身下拿钥匙是对金基泽和雯光丈夫身上的味道的鄙夷,可是这个原因真的站不住脚,即使是同样经济水平,如果身上有比较重的异味,背后讨论下,或者闻到了比较重的味道,有不适的表情和动作很正常吧,像雯光丈夫,在地下室里呆了那么久,身上有异味并且比较重太正常了,就跟在厕所呆久了不会觉得味道大,但是从没味道的地方一进有点味道的厕所就会觉得异样,略尴尬的理由;再说忠淑呢,感觉是太厉害了,能胜任这么一家有钱人的各种挑剔的饮食口味要求的保姆职位,也是让人看懵逼了,看到了不禁想到一个问题,这家人开头是那么地穷,不堪,突然转变成这么地像骗子家族,如果有这么好的骗人能力,应该不会到这种地步吧,如果真的是那么穷,没能力,没志气,又怎么会突然变成这么厉害呢,一家人各司其职,把富人家唬得团团转,而这个前提是,这些人的确能胜任这四个位置,这就是我非常不能理解的点。

    +

    然后说回这个标题,寄生虫,不知道是不是翻译过来不准确,如果真的是叫寄生虫的话,这个寄生虫智商未免也太低了,没有像新冠那样机制,致死率低一点,传染能力强一点,潜伏期也能传染,这个寄生虫第一次受到免疫系统的攻击就自爆了;还有呢,作为一个社会比较低层的打工者,乡下人,对这个审题也是不太审的清,是指这一家人是社会的寄生虫,不思进取,并且死的应该,富人是傻白甜,又有钱又善良,这是给有钱人洗地了还是啥,这个奥斯卡真不知道是怎么得的,总觉得奥斯卡,甚至低一点,豆瓣,得奖的,评分高的都是被一群“精英党”把持的,有黑人主角的,得分高;有同性恋的,得分高;结局惨的,得分高;看不懂的,得分高;就像肖申克的救赎,真不知道是哪里好了,最近看了关于明朝那些事的三杨,杨溥的经历应该比这个厉害吧,可是外国人看不懂,就像外国人不懂中国为什么有反分裂国家法,经历了鸦片战争,八国联军,抗日战争等等,其实跟外国对于黑人的权益的问题,因为有南北战争,所以极度重视这个问题,相应的中国也有自己的历史,请理解。

    +

    简而言之我对寄生虫的评分大概 5~6 分吧。

    +]]>
    + + 生活 + 影评 + 2020 + + + 生活 + 影评 + 寄生虫 + +
    + + 屯菜惊魂记 + /2022/04/24/%E5%B1%AF%E8%8F%9C%E6%83%8A%E9%AD%82%E8%AE%B0/ + 因某国际大都市的给力表现,昨儿旁边行政区启动应急响应,同事早上就在群里说要去超市买菜了,到了超市人还特别多,由于来的就是我们经常去的那家超市,一方面为了安全,另一方面是怕已经抢不到了,就去了另一家比较远的超市,开车怕没车位就骑了小电驴,还下着小雨,结果到了超市差不多 12 点多,超市里出来的人都是推着一整车一整车的物资,有些比较像我,整箱的泡面,好几提纸巾,还有各种吃的,都是整箱整箱的,进了超市发现结账包括自助结账的都排很长的队,到了蔬菜货架附近,差点哼起那首歌“空空如也~”,新鲜蔬菜基本已被抢空,只剩下一些卖相不太好的土豆番薯之类的,也算是意料之外情理之中了,本来以为这家超市稍微离封控区远一些会空一点,结果就是所谓的某大都市封控了等物资,杭州市是屯了物资等封控,新鲜蔬菜没了我们也只能买点其他的,神奇的是水果基本都在,可能困难时期水果不算必需品了?还是水果基本人人都已经储备了很多,不太能理解,虽然水果还在,但是称重的地方也还有好多人排队,我们采取了并行策略,LD 在那排队,遥控指挥我去拿其他物资,拿了点碱水面,黑米,那黑米的时候还闹了个乌龙,因为前面就是散装鸡蛋的堆货的地方,结果我们以为是在那后面排队,结果称重那个在那散步了,我们还在那排队,看到后面排队,那几个挑的人也该提醒下吧,几个鸡蛋挑了半天,看看人家大妈,直接拿了四盘,看了下牛奶货架也比较空,不过还有致优跟优倍,不过不算很实惠,本来想买,只是后来赶着去结账,就给忘了,称好了黑米去看了下肉,结果肉也没了,都在买猪蹄,我们也不太爱吃猪蹄,就买了点鸡胸肉,整体看起来我们买的东西真的有点格格不入,不买泡面(因为 LD 不让买了),也不屯啥米和鸡蛋,其实鸡蛋已经买了,米也买了,其他的本身冰箱小也放不下太多东西,我是觉得还可能在屯一点这那的,LD 觉得太多了,基本的米面油有了,其他调味品什么也有了。后面就是排队结账,我去排的时候刚好前面一个小伙子跟大妈在争执,大妈说我们差不多时间来的,你要排前面就前面,小伙子有点不高兴,觉得她就是插队,哈哈,平时一般这种剧情都是发生在我身上的,这会看着前面的吵起来还是很开心的,终于有跟我一样较真的人了,有时候总觉得我是个很纠结,很较真的人,但是我现在慢慢认可了这种较真,如果没有人指出来这种是插队行为,是不对的,就会有越来越多的人觉得是可以随意插队的,正确的事应该要坚持,很多情况大家总是觉得多一事不如少一事,鸡毛蒜皮的没什么好计较的,正是这种想法,那么多人才不管任何规则,反而搞得像遵守规则都是傻 X 似的。回到屯物资,后面结账排到队了也没来得及买原来想买的花生牛奶什么的,毕竟那么多人排着队,回家后因为没有蔬菜,结果就只能吃干菜汤和饭了

    +]]>
    + + 生活 + + + 生活 + 囤物资 + +
    + + 我是如何走上跑步这条不归路的 + /2020/07/26/%E6%88%91%E6%98%AF%E5%A6%82%E4%BD%95%E8%B5%B0%E4%B8%8A%E8%B7%91%E6%AD%A5%E8%BF%99%E6%9D%A1%E4%B8%8D%E5%BD%92%E8%B7%AF%E7%9A%84/ + 这周因为没有准备技术方面的内容加之之前有想分享下我和跑步的一些事情,我从小学开始就是个体育渣,因为体重大非常胖,小学的时候要做仰卧起坐,基本是一个都起不来,然后那时候跑步也是要我命那种,跟另外一个比较胖的同学在跑步队尾苟延残喘,只有立定跳远还行。

    +

    时光飞逝,我在初中高中的时候因为爱打篮球,以为自己体质已经有了质的变化,所以在体育课跑步的时候妄图跟一位体育非常好的同学一起跑,结果跟的快断气了,最终还是确认了自己是个体育渣,特别是到了大学的第一次体测跑一千米,跑完直接吐了,一则是大学太宅不运动,二则的确是底子不好。那么怎么会去跑步了呢,其实也没什么特殊的原因,就是工作以后因为运动得更少,体质差,而且越来越胖,所以就想运动下,加之跑步也是我觉得成本最低的运动了,刚好那时候17 年租的地方附近小区周围的路车不太多,一圈刚好一公里多,就觉得开始跑跑看,其实想想以前觉得一千米是非常远的,学校塑胶跑道才 400 米,一千米要两圈半,太难了,但是后来在这个小区周围跑的时候好像跑了一圈以后还能再跑一点,最后跑了两圈,可把自己牛坏了,我都能跑两千米了,哈哈,这是个什么概念呢,大学里最让我绝望的两项体育相关的内容就是一千米和十二分钟跑,一千米把我跑吐了,十二分钟跑及格五圈半也能让我跑完花一周时间恢复以及提前一周心理压力爆炸,虽然我那时候跑的不快,但是已经能跑两千米了,瞬间让自己自信心爆炸,并且跑完步出完汗的感觉是非常棒的,毕竟吃奶茶鸡排都能心安理得了,谁叫我跑步了呢😄,其实现在回去看,那时候跑得还算快的,因为还比较瘦,现在要跑得那么快心跳就太快了,关于心跳什么的后面说,开始建立起自信心之后,对跑步这件事就开始不那么排斥跟害怕了,毕竟我能跑两千米了,然后试试三公里,哇,也可以了呢,三公里是什么概念呢,我大学里跑过最多的一次是十二分钟跑五圈半还是六圈,也就是两公里多,不到三公里,几乎是生涯最长了,一时间产生了一些我可能是个被埋没的运动天才的错觉,其实细想下也能明白,只是速度足够慢了就能跑多一点,毕竟提测一千米是要跑进四分钟才及格,自己跑的时候一千米跑六分多钟已经算不慢了(对我自己来说),但是即使是这样还是对把跑步坚持下去这件事有了很大的正面激励作用,并且由于那时候上下班骑车,整个体重控制的比较理想,导致一时间误会跑步就能非常快的减肥(其实这是我跑步历程中比较大的误区之一),因为会在跑步前后称下体重,如果跑个五公里(后面可以跑五公里了),可能体重就能降 0.5 千克,但实际上这只是这五公里跑步身体流失的水分,喝杯水就回来了,那时候能控制体重主要是骑车跟跑步一起的作用,并且工作压力相对来讲比较小,没有过劳肥。

    +

    后面其实跑步慢慢变得一个比较习惯的运动了,从三公里,到五公里,到七公里,再到十公里,十公里差不多对我来说是个坎,一直还不能比较轻松的跑十公里,可能近一两年好了一些(原谅我只是跟自己比较,跟那些大神比差得不知道多远),其实对我来说每次都是个突破,因为其实与他人比较没有特别大意义,比较顶尖的差得太远,比较普通的也不行,都会打击自信心,比较比我差的就更没意义了,所以其实能挑战自己,能把自己的上限提高才是最有意义的,这也是我看着朋友圈里的一些大神的速度除了佩服赞叹之外没什么其他的惭愧或者说嫌弃自己的感觉(阿 Q 精神😄)。

    +

    一直感性地觉得,跑步能解压,跑完浑身汗,有种把身体的负能量都排出去的感觉,也把吃太多的罪恶感排解掉了🤦‍♂️,之前朋友有看一本书,书名差不多叫越跑越接近自己,这个也是我觉得挺准确的一句话,当跑到接近极限了,还想再继续再跑一点,再跑一点就能突破自己上一次的最远记录了,再跑一点就能又一次突破自己了,成人以后,毕业以后,进入社会以后,世事总是难以件件顺遂,磕磕绊绊的往前走,总觉得要崩溃了,但是还是得坚持,再熬一下,再拼一下,可能还是失败,但人生呢,运气好的人和事总是小概率的,唯有面对挫折,还是日拱一卒,来日方长,我们再坚持下,没准下一次,没准再跑一会,就能突破自己,达到新的境界。

    +

    另外个人后期对跑步的一些知识和理解也变得深入一些,比如伤膝盖,其实跑步的确伤膝盖,需要做一些准备和防护,最好的是适合自己的跑鞋和比较好的路(最好的是塑胶跑道了),也要注意热身跟跑后的拉伸(虽然我做的很差),还有就是注意心率,每个人有自己的适宜心率,我这就不冒充科普达人了,可以自行搜索关键字,先说到这吧~

    ]]>
    生活 运动 跑步 - 干活 生活 - 小技巧 运动 减肥 跑步 - 干活
    - 分享一次折腾老旧笔记本的体验 - /2023/02/05/%E5%88%86%E4%BA%AB%E4%B8%80%E6%AC%A1%E6%8A%98%E8%85%BE%E8%80%81%E6%97%A7%E7%AC%94%E8%AE%B0%E6%9C%AC%E7%9A%84%E4%BD%93%E9%AA%8C/ - 上大学的时候买了第一个笔记本,是联想的小y,y460,配置应该是 i5+2g 内存,500g 硬盘,ati 5650 的显卡,那时候还是比较时髦的带有集显和独显切换的,一些人也觉得它算是一代“神机”,陪我度过了大学四年,还有毕业后的第一年,记得中间还用的比较曲折,差不多第一学期末的时候硬盘感觉有时候会文件操作卡住,去售后看了下,果然硬盘出问题了,还在当场把硬盘的东西都拷贝到新买的移动硬盘里,不过联想的售后还是比较不错的,在保内可以直接免费换,如果出保了估计就要修不起了,后面出了个很大的问题,就是屏幕花屏了,而且它的花屏是横着的会有那种上升的变化,一开始感觉跟湿度还有温度有点关系,天气冷了就很容易出现,天气热了就好一点,出现的概率小一点,而且是合盖后再开会好,过一会又会上升,只是这么度过了保修期,去售后问了下,修一下要两千多,后来是在玉泉学校里面的维修店,好像是花了六百多,省是省了很多,但是后面使用的时候发现有点漏光,而且两三个亮点,总归还是给我那不富裕的经济条件带来了一个正常屏幕,不过是挺影响使用,严格来说都没法用了,后面基本是大半个屏幕花掉,接近整个屏幕花掉,至此大学就是这么用过去了。
    噢对了,中间在大二的时候加了一条 2g 的内存,因为像操作系统课需要用虚拟机,2g 内存不太够,不过那会用的都是 32 位的 win7 系统,实际使用用不到 4g 内存,得使用破解补丁才能识别到,后来在大学毕业后由于收入也低,想换其他电脑,特别是 mac,买不起,电脑在那会还会玩玩 DNF,但是风扇声很大,也想优化下,就买了个 msata 的固态硬盘,因为刚好有个口子留着,在那之前一直搜到的是把光驱位拆掉换上 sata 固态硬盘,这对于那会的我来说操作难度实在有点大,换上了msata 固态之后还是有比较大的提升的,把操作系统装到固态硬盘后其他盘就只放数据了,后面还装过黑苹果,只是不小心被室友强制关机了,之后就起不来了,也不知道啥原因,后续想继续按原来的操作装,也没成功,再往后就配了一台台式机,这个笔记本就放在那没啥用了,后面偶尔会拿出来用一下,特别是疫情那会充当了 LD 的临时使用机器。
    最近一次就是想把行车记录仪里的视频导出来,结果上传的时候我点了下 win10 的更新,重启后这个机器就起不来了,一开始以为顶多是个重装系统,结果重装也不行,就进不去,插着 U 盘也起不来,一开始还能进 BIOS,后面就直接进不去了,像内存条脏了,擦下金手指什么的,都没搞定,想着也只可能是主板上的部件坏了,所以就开始了这趟半作死之旅,买了块主板来换,拆这个笔记本是真的够难的,开机键那一条是真的拆不开,后面还把两个扣子扳坏了,里面的排线插口还几个也拔坏了,幸好用买来的主板装上还能用,但是后面就很奇怪了,因为这个电脑装了 Ubuntu 跟 win10 的双系统,Ubuntu 能正常起来,但是 win10 就是起不来,插上老毛桃或者 win10 的启动盘都是起不来,老毛桃是能起来,但是进不了 pe,插启动盘又报 0xc00000e9 错误码,现在想着是不是这个固态硬盘有点问题或者还是内存问题,只能后续再看了,拆机的时候也找不到视频,机器实在是太老了,后面再试试看。

    + 深度学习入门初认识 + /2023/04/30/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0%E5%85%A5%E9%97%A8%E5%88%9D%E8%AE%A4%E8%AF%86/ + 对于深度学习只能说我是个门外汉,开始学习,不过很多还搞不懂,做个记录和分享,基于《深度学习入门:基于 Python 的理论与实现》,
    第一章 Python 入门就不介绍了,不是重点,不过完全没有 Python 基础的可以看下,我之前算是学过一点点,
    第二章我觉得入门的方式比较不错,从感知机入手,有一些顾名思义,感知一些状态(输入),来做出反应,简单的就是比如通电了,我的灯就亮起来了,并且往后就是延伸到了计算机的最基础组成,与或门,与门与或门是最基础的,配合非门进行组成,可以作为计算机基础单元ALU 的组成基础,而更复杂的也可以由此进行搭建,这是个比较通俗的解释,根据书中的定义,感知机是具有输入和输出的算法。给定一个输入后,将输出一个既定的值,单层的感知机无法实现更复杂的异或门,但是可以通过 2 层感知机来实现,也就是一个与非门,一个或门,作为第一层的感知机,他们的输出作为与门的输入,就可以成为一个异或门。理论上多层感知机可以表示计算机。
    而后第三章引出了激活函数,也就是在前面的与或门和基础的感知机的基础上加上了输出的条件,前面与门或门都是最基础的 0,1 游戏,现在可以加上更复杂的判断条件,在输入的基础上配以权重,再加上偏置参数,表示被激活的容易程度,这种激活函数可以被称为阶跃函数,如果超过了一定的值就代表被激活,没有则不激活,但是实际在神经元中被使用的主要是用 sigmoid 函数,相比阶跃函数,sigmoid 函数是一个平滑的曲线,随着输入变化而连续变化,因为相对感知机,神经元需要的信号是连续的实数值信号,再往后则是对输出层的介绍,如果是回归问题,也就是根据输入预测一个(连续的)数值的问题,属于回归问题,可以用恒等函数,而对于分类问题,则使用 softmax 函数,这个函数的一个重要的点在于也是区分于简单的二元分类器,softmax 是将多个结果概率进行数值处理(归一化),也叫做归一化指数函数,对于不同的结果概率是将概率最大的进行放大,凸显其中最大的值并抑制远低于最大值的其他分量。使得其他概率值也能够被使用,但是减弱其份额权重。

    ]]>
    - Windows - 小技巧 + 深度学习 - Windows + 深度学习
    - 在 wsl 2 中开启 ssh 连接 - /2023/04/23/%E5%9C%A8-wsl-2-%E4%B8%AD%E5%BC%80%E5%90%AF-ssh-%E8%BF%9E%E6%8E%A5/ - 之前在 wsl 1 中开启 ssh 其实很方便,只要把 sshd 服务起来就好了,但是在 wsl 2 中就不太一样了,
    我这边使用的是 wsl 2 中的 Ubuntu 20.04,直接启动 sshd 服务是没法让其他机器连接的,而且都没有 ifconfig 命令可以查看 ip
    不过可以用直接用 ip a来查看,可以看到这个 ip 是172网段的,而在 wsl 1 中可以看到 ip 就是 win 的 ip,
    所以需要做一些操作,首先要安装 openssl-server

    -
    sudo apt update
    -sudo apt install openssh-server
    -

    另外如果需要提高安全性,可以wsl 中配置 hosts.allow

    -
    sshd:192.168.xx.
    -

    先定一个子网段,然后对于ssh的配置,可以做以下修改

    -
    Port 22
    -PasswordAuthentication yes
    -

    在进行重启

    -
    sudo service ssh --full-restart
    -

    配置以后发现上面的问题,没法远程登录,因为 wsl 2 是基于 hyper-v 虚拟机实现的,并且 ip 使用的是一个虚拟出来的子网 ip,所以需要在 Windows 这一层配置端口的转发,可以通过命令netsh interface portproxy show v4tov4看到

    截图是我已经添加好了的,先把原来的删除,再进行添加

    -
    netsh interface portproxy delete v4tov4 listenaddress=0.0.0.0 listenport=22
    -netsh interface portproxy add v4tov4 listenaddress=0.0.0.0 listenport=22 connectaddress=172.19.129.207 connectport=22
    -

    也可以全量删除

    -
    netsh int portproxy reset all
    -

    但是这样也不能直接访问了,还需要开启防火墙

    -
    netsh advfirewall firewall add rule name="WSL SSH" dir=in action=allow protocol=TCP localport=22
    + springboot 请求响应处理流程 + /2023/08/27/springboot-%E8%AF%B7%E6%B1%82%E5%93%8D%E5%BA%94%E5%A4%84%E7%90%86%E6%B5%81%E7%A8%8B/ + Tomcat 会把请求委托到
    org.springframework.web.servlet.DispatcherServlet#doService

    +
    protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
    +		logRequest(request);
    +
    +        // 省略前面的代码
    +		try {
    +			doDispatch(request, response);
    +		}
    +

    然后就是调用
    org.springframework.web.servlet.DispatcherServlet#doDispatch

    +
    protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
    +
    +	try {
    +		ModelAndView mv = null;
    +		Exception dispatchException = null;
    +
    +		try {
    +			processedRequest = checkMultipart(request);
    +			multipartRequestParsed = (processedRequest != request);
    +
    +               // 去获取处理器
    +			// Determine handler for the current request.
    +			mappedHandler = getHandler(processedRequest);
    +			if (mappedHandler == null) {
    +				noHandlerFound(processedRequest, response);
    +				return;
    +			}
    +
    +			// Determine handler adapter for the current request.
    +			HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
    +
    +			// Process last-modified header, if supported by the handler.
    +			String method = request.getMethod();
    +			boolean isGet = HttpMethod.GET.matches(method);
    +			if (isGet || HttpMethod.HEAD.matches(method)) {
    +				long lastModified = ha.getLastModified(request, mappedHandler.getHandler());
    +				if (new ServletWebRequest(request, response).checkNotModified(lastModified) && isGet) {
    +					return;
    +				}
    +			}
    +
    +			if (!mappedHandler.applyPreHandle(processedRequest, response)) {
    +				return;
    +			}
    +
    +			// Actually invoke the handler.
    +			mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
    +
    +

    看下这里的逻辑

    +
    @Nullable
    +protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
    +	if (this.handlerMappings != null) {
    +		for (HandlerMapping mapping : this.handlerMappings) {
    +			HandlerExecutionChain handler = mapping.getHandler(request);
    +			if (handler != null) {
    +				return handler;
    +			}
    +		}
    +	}
    +	return null;
    +}
    +

    可以看到有这些 HandlerMapping

    而这里面就是前面提到过的
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping
    从这就能找到具体的 Handler
    com.nicksxs.spbdemo.controller.DemoController#test()
    这就是我简单的示例代码

    +
    @RequestMapping(value = "/test", method = RequestMethod.GET)
    +@ResponseBody
    +public DemoResponse test() {
    +    String item = "{\"id\": 1, \"name\": \"nick\"}";
    +    ParserConfig parserConfig = ParserConfig.getGlobalInstance();
    +    parserConfig.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
    +    DemoResponse response = JSON.parseObject(item, DemoResponse.class, parserConfig);
    +    return response;
    +}
    +

    下一步是再获取处理器的适配器,
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter

    +
    protected HandlerAdapter getHandlerAdapter(Object handler) throws ServletException {
    +		if (this.handlerAdapters != null) {
    +			for (HandlerAdapter adapter : this.handlerAdapters) {
    +				if (adapter.supports(handler)) {
    +					return adapter;
    +				}
    +			}
    +		}
    +		throw new ServletException("No adapter for handler [" + handler +
    +				"]: The DispatcherServlet configuration needs to include a HandlerAdapter that supports this handler");
    +	}
    +

    正好这个适配器是调用的父类的 supports 方法

    +
    @Override
    +public final boolean supports(Object handler) {
    +	return (handler instanceof HandlerMethod && supportsInternal((HandlerMethod) handler));
    +}
    +

    而我这个com.nicksxs.spbdemo.controller.DemoController#test()
    就是个包装好的 HandlerMethod
    然后就是调用 hahandle 方法,也是通过模板方法,实际调用的是
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter#handle

    +
    @Override
    +@Nullable
    +public final ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler)
    +		throws Exception {
     
    +	return handleInternal(request, response, (HandlerMethod) handler);
    +}
    +

    然后调用
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#handleInternal

    +
    @Override
    +	protected ModelAndView handleInternal(HttpServletRequest request,
    +			HttpServletResponse response, HandlerMethod handlerMethod) throws Exception {
     
    +		ModelAndView mav;
    +		checkRequest(request);
     
    +		// Execute invokeHandlerMethod in synchronized block if required.
    +		if (this.synchronizeOnSession) {
    +			HttpSession session = request.getSession(false);
    +			if (session != null) {
    +				Object mutex = WebUtils.getSessionMutex(session);
    +				synchronized (mutex) {
    +					mav = invokeHandlerMethod(request, response, handlerMethod);
    +				}
    +			}
    +			else {
    +				// No HttpSession available -> no mutex necessary
    +				mav = invokeHandlerMethod(request, response, handlerMethod);
    +			}
    +		}
    +		else {
    +            // 是否要锁定 session,否则走到这
    +			// No synchronization on session demanded at all...
    +			mav = invokeHandlerMethod(request, response, handlerMethod);
    +		}
    + +

    继续调用
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#invokeHandlerMethod

    +
    @Nullable
    +	protected ModelAndView invokeHandlerMethod(HttpServletRequest request,
    +			HttpServletResponse response, HandlerMethod handlerMethod) throws Exception {
    +
    +		ServletWebRequest webRequest = new ServletWebRequest(request, response);
    +		try {
    +			WebDataBinderFactory binderFactory = getDataBinderFactory(handlerMethod);
    +			ModelFactory modelFactory = getModelFactory(handlerMethod, binderFactory);
    +
    +            // 包装调用方法,
    +			ServletInvocableHandlerMethod invocableMethod = createInvocableHandlerMethod(handlerMethod);
    +			// 省略一部分非本次关注核心代码
    +            // 然后是调用到这
    +			invocableMethod.invokeAndHandle(webRequest, mavContainer);
    +			if (asyncManager.isConcurrentHandlingStarted()) {
    +				return null;
    +			}
    +
    +			return getModelAndView(mavContainer, modelFactory, webRequest);
    +		}
    +		finally {
    +			webRequest.requestCompleted();
    +		}
    +	}
    +

    稍微再看一眼
    第一步是
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#createInvocableHandlerMethod

    +
    protected ServletInvocableHandlerMethod createInvocableHandlerMethod(HandlerMethod handlerMethod) {
    +	return new ServletInvocableHandlerMethod(handlerMethod);
    +}
    +

    第二步是
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod#ServletInvocableHandlerMethod(org.springframework.web.method.HandlerMethod)

    +
       public ServletInvocableHandlerMethod(HandlerMethod handlerMethod) {
    +	super(handlerMethod);
    +}
    +

    第三步是
    org.springframework.web.method.support.InvocableHandlerMethod#InvocableHandlerMethod(org.springframework.web.method.HandlerMethod)

    +
       public InvocableHandlerMethod(HandlerMethod handlerMethod) {
    +	super(handlerMethod);
    +}
    +

    第四步是
    org.springframework.web.method.HandlerMethod#HandlerMethod(org.springframework.web.method.HandlerMethod)

    +
    protected HandlerMethod(HandlerMethod handlerMethod) {
    +	Assert.notNull(handlerMethod, "HandlerMethod is required");
    +	this.bean = handlerMethod.bean;
    +	this.beanFactory = handlerMethod.beanFactory;
    +	this.beanType = handlerMethod.beanType;
    +	this.method = handlerMethod.method;
    +	this.bridgedMethod = handlerMethod.bridgedMethod;
    +	this.parameters = handlerMethod.parameters;
    +	this.responseStatus = handlerMethod.responseStatus;
    +	this.responseStatusReason = handlerMethod.responseStatusReason;
    +	this.description = handlerMethod.description;
    +	this.resolvedFromHandlerMethod = handlerMethod.resolvedFromHandlerMethod;
    +}
    +

    这是个继承关系,一直调用到最顶层的父类的构造方法,其实就是拷贝,然后继续调用
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod#invokeAndHandle

    +
    public void invokeAndHandle(ServletWebRequest webRequest, ModelAndViewContainer mavContainer,
    +			Object... providedArgs) throws Exception {
    +
    +        // 调用请求
    +		Object returnValue = invokeForRequest(webRequest, mavContainer, providedArgs);
    +		// 稍微忽略下后面的代码
    +	}
    +

    继续调用
    org.springframework.web.method.support.InvocableHandlerMethod#invokeForRequest

    +
    @Nullable
    +public Object invokeForRequest(NativeWebRequest request, @Nullable ModelAndViewContainer mavContainer,
    +		Object... providedArgs) throws Exception {
    +
    +	Object[] args = getMethodArgumentValues(request, mavContainer, providedArgs);
    +	if (logger.isTraceEnabled()) {
    +		logger.trace("Arguments: " + Arrays.toString(args));
    +	}
    +	return doInvoke(args);
    +}
    +

    来到了最核心处
    org.springframework.web.method.support.InvocableHandlerMethod#doInvoke

    +
    @Nullable
    +protected Object doInvoke(Object... args) throws Exception {
    +	Method method = getBridgedMethod();
    +	ReflectionUtils.makeAccessible(method);
    +	try {
    +		if (KotlinDetector.isSuspendingFunction(method)) {
    +			return CoroutinesUtils.invokeSuspendingFunction(method, getBean(), args);
    +		}
    +           // 会走到这里,获取到 bean,而这个 bean 就是前面构造方法里赋值的,最开始被放在 handler 里面,然后调用方法
    +		return method.invoke(getBean(), args);
    +	}
    ]]>
    - wsl - - - wsl - -
    - - 寄生虫观后感 - /2020/03/01/%E5%AF%84%E7%94%9F%E8%99%AB%E8%A7%82%E5%90%8E%E6%84%9F/ - 寄生虫这部电影在获得奥斯卡之前就有关注了,豆瓣评分很高,一开始看到这个片名以为是像《铁线虫入侵》那种灾难片,后来看到男主,宋康昊,也是老面孔了,从高中时候在学校操场组织看的《汉江怪物》,有点二的感觉,后来在大学寝室电脑上重新看的时候,室友跟我说是韩国国宝级演员,真人不可貌相,感觉是个呆子的形象。

    -

    但是你说这不是个灾难片,而是个反映社会问题的,就业比较容易往这个方向猜,只是剧情会是怎么样的,一时也没啥头绪,后来不知道哪里看了下一个剧情透露,是一个穷人给富人做家教,然后把自己一家都带进富人家,如果是这样的话可能会把这个怎么带进去作为一个主线,不过事实告诉我,这没那么重要,从第一步朋友的介绍,就显得无比顺利,要去当家教了,作为一个穷成这样的人,瞬间转变成一个衣着得体,言行举止都没让富人家看出破绽的延世大学学生,这真的挺难让人理解,所谓江山易改,本性难移,还有就是这人也正好有那么好能力去辅导,并且诡异的是,多惠也是瞬间就喜欢上了男主,多惠跟将男主介绍给她做家教,也就是多惠原来的家教敏赫,应该也有不少的相处时间,这变了有点大了吧,当然这里也可能因为时长需要,如果说这一点是因为时长,那可能我所有的槽点都是因为这个吧,因为我理解的应该是把家里的人如何一步步地带进富人家,这应该是整个剧情的一个需要更多铺垫去克服这个矛盾点,有时候也想过如果我去当导演,是能拍出个啥,没这个机会,可能有也会是很扯淡的,当然这也不能阻拦我谈谈对这个点的一些看法,毕竟评价一台电冰箱不是说我必须得自己会制冷对吧,这大概是我觉得这个电影的第一个槽点,接下去接二连三的,就是我说的这个最核心的矛盾点,不知道谁说过,这种影视剧应该是源自于生活又高于生活,越是好的作品,越要接近生活,这样子才更能有感同身受。

    -

    接下去的点是金基宇介绍金基婷去给多颂当美术家教,这一步又是我理解的败笔吧,就怎么说呢,没什么铺垫,突然从一个社会底层的穷姑娘,转变成一个气场爆表,把富人家太太唬得一愣一愣的,如果说富太太是比较简单无脑的,那富人自己应该是比较有见识而且是做 IT 的,给自己儿子女儿做家教的,查查底细也很正常吧,但是啥都没有,然后呢,她又开始耍司机的心机了,真的是莫名其妙了,司机真的很惨,窈窕淑女君子好逑,而且这个操作也让我摸不着头脑,这是多腹黑并且有经验才会这么操作,脱内裤真的是让我看得一愣愣的,更看得我一愣一愣的,富人竟然也完全按着这个思路去想了,完全没有别的可能呢,甚至可以去查下行车记录仪或者怎样的,或者有没有毛发体液啥的去检验下,毕竟金基婷也乘坐过这辆车,但是最最让我不懂的还是脱内裤这个操作,究竟是什么样的人才会的呢,值得思考。

    -

    金基泽和忠淑的点也是比较奇怪,首先是金基泽,引起最后那个杀人事件的一个由头,大部分观点都是人为朴社长在之前跟老婆啪啪啪的时候说金基泽的身上有股乘地铁的人的味道,简而言之就是穷人的味道,还有去雯光丈夫身下拿钥匙是对金基泽和雯光丈夫身上的味道的鄙夷,可是这个原因真的站不住脚,即使是同样经济水平,如果身上有比较重的异味,背后讨论下,或者闻到了比较重的味道,有不适的表情和动作很正常吧,像雯光丈夫,在地下室里呆了那么久,身上有异味并且比较重太正常了,就跟在厕所呆久了不会觉得味道大,但是从没味道的地方一进有点味道的厕所就会觉得异样,略尴尬的理由;再说忠淑呢,感觉是太厉害了,能胜任这么一家有钱人的各种挑剔的饮食口味要求的保姆职位,也是让人看懵逼了,看到了不禁想到一个问题,这家人开头是那么地穷,不堪,突然转变成这么地像骗子家族,如果有这么好的骗人能力,应该不会到这种地步吧,如果真的是那么穷,没能力,没志气,又怎么会突然变成这么厉害呢,一家人各司其职,把富人家唬得团团转,而这个前提是,这些人的确能胜任这四个位置,这就是我非常不能理解的点。

    -

    然后说回这个标题,寄生虫,不知道是不是翻译过来不准确,如果真的是叫寄生虫的话,这个寄生虫智商未免也太低了,没有像新冠那样机制,致死率低一点,传染能力强一点,潜伏期也能传染,这个寄生虫第一次受到免疫系统的攻击就自爆了;还有呢,作为一个社会比较低层的打工者,乡下人,对这个审题也是不太审的清,是指这一家人是社会的寄生虫,不思进取,并且死的应该,富人是傻白甜,又有钱又善良,这是给有钱人洗地了还是啥,这个奥斯卡真不知道是怎么得的,总觉得奥斯卡,甚至低一点,豆瓣,得奖的,评分高的都是被一群“精英党”把持的,有黑人主角的,得分高;有同性恋的,得分高;结局惨的,得分高;看不懂的,得分高;就像肖申克的救赎,真不知道是哪里好了,最近看了关于明朝那些事的三杨,杨溥的经历应该比这个厉害吧,可是外国人看不懂,就像外国人不懂中国为什么有反分裂国家法,经历了鸦片战争,八国联军,抗日战争等等,其实跟外国对于黑人的权益的问题,因为有南北战争,所以极度重视这个问题,相应的中国也有自己的历史,请理解。

    -

    简而言之我对寄生虫的评分大概 5~6 分吧。

    -]]>
    - - 生活 - 影评 - 2020 - - - 生活 - 影评 - 寄生虫 - -
    - - 屯菜惊魂记 - /2022/04/24/%E5%B1%AF%E8%8F%9C%E6%83%8A%E9%AD%82%E8%AE%B0/ - 因某国际大都市的给力表现,昨儿旁边行政区启动应急响应,同事早上就在群里说要去超市买菜了,到了超市人还特别多,由于来的就是我们经常去的那家超市,一方面为了安全,另一方面是怕已经抢不到了,就去了另一家比较远的超市,开车怕没车位就骑了小电驴,还下着小雨,结果到了超市差不多 12 点多,超市里出来的人都是推着一整车一整车的物资,有些比较像我,整箱的泡面,好几提纸巾,还有各种吃的,都是整箱整箱的,进了超市发现结账包括自助结账的都排很长的队,到了蔬菜货架附近,差点哼起那首歌“空空如也~”,新鲜蔬菜基本已被抢空,只剩下一些卖相不太好的土豆番薯之类的,也算是意料之外情理之中了,本来以为这家超市稍微离封控区远一些会空一点,结果就是所谓的某大都市封控了等物资,杭州市是屯了物资等封控,新鲜蔬菜没了我们也只能买点其他的,神奇的是水果基本都在,可能困难时期水果不算必需品了?还是水果基本人人都已经储备了很多,不太能理解,虽然水果还在,但是称重的地方也还有好多人排队,我们采取了并行策略,LD 在那排队,遥控指挥我去拿其他物资,拿了点碱水面,黑米,那黑米的时候还闹了个乌龙,因为前面就是散装鸡蛋的堆货的地方,结果我们以为是在那后面排队,结果称重那个在那散步了,我们还在那排队,看到后面排队,那几个挑的人也该提醒下吧,几个鸡蛋挑了半天,看看人家大妈,直接拿了四盘,看了下牛奶货架也比较空,不过还有致优跟优倍,不过不算很实惠,本来想买,只是后来赶着去结账,就给忘了,称好了黑米去看了下肉,结果肉也没了,都在买猪蹄,我们也不太爱吃猪蹄,就买了点鸡胸肉,整体看起来我们买的东西真的有点格格不入,不买泡面(因为 LD 不让买了),也不屯啥米和鸡蛋,其实鸡蛋已经买了,米也买了,其他的本身冰箱小也放不下太多东西,我是觉得还可能在屯一点这那的,LD 觉得太多了,基本的米面油有了,其他调味品什么也有了。后面就是排队结账,我去排的时候刚好前面一个小伙子跟大妈在争执,大妈说我们差不多时间来的,你要排前面就前面,小伙子有点不高兴,觉得她就是插队,哈哈,平时一般这种剧情都是发生在我身上的,这会看着前面的吵起来还是很开心的,终于有跟我一样较真的人了,有时候总觉得我是个很纠结,很较真的人,但是我现在慢慢认可了这种较真,如果没有人指出来这种是插队行为,是不对的,就会有越来越多的人觉得是可以随意插队的,正确的事应该要坚持,很多情况大家总是觉得多一事不如少一事,鸡毛蒜皮的没什么好计较的,正是这种想法,那么多人才不管任何规则,反而搞得像遵守规则都是傻 X 似的。回到屯物资,后面结账排到队了也没来得及买原来想买的花生牛奶什么的,毕竟那么多人排着队,回家后因为没有蔬菜,结果就只能吃干菜汤和饭了

    -]]>
    - - 生活 - - - 生活 - 囤物资 - -
    - - 搬运两个 StackOverflow 上的 Mysql 编码相关的问题解答 - /2022/01/16/%E6%90%AC%E8%BF%90%E4%B8%A4%E4%B8%AA-StackOverflow-%E4%B8%8A%E7%9A%84-Mysql-%E7%BC%96%E7%A0%81%E7%9B%B8%E5%85%B3%E7%9A%84%E9%97%AE%E9%A2%98%E8%A7%A3%E7%AD%94/ - Mysql 字符编码和排序规则

    这个一直是属于一知半解的状态,知道 utf8 跟 utf8mb4 的区别主要是能不能支持 emoji,但是具体后面配置的排序规则是用来干嘛,或者有什么区别,应该使用哪个,所以在 stackoverflow 上找了下,有两个比较不错的解答,就搬过来并且配合机翻做了点修改

    -

    原文

    For those people still arriving at this question in 2020 or later, there are newer options that may be better than both of these. For example, utf8mb4_0900_ai_ci.

    -

    All these collations are for the UTF-8 character encoding. The differences are in how text is sorted and compared.

    -

    _unicode_ci and _general_ci are two different sets of rules for sorting and comparing text according to the way we expect. Newer versions of MySQL introduce new sets of rules, too, such as _0900_ai_ci for equivalent rules based on Unicode 9.0 - and with no equivalent _general_ci variant. People reading this now should probably use one of these newer collations instead of either _unicode_ci or _general_ci. The description of those older collations below is provided for interest only.

    -

    MySQL is currently transitioning away from an older, flawed UTF-8 implementation. For now, you need to use utf8mb4 instead of utf8 for the character encoding part, to ensure you are getting the fixed version. The flawed version remains for backward compatibility, though it is being deprecated.

    -

    Key differences

    -

    utf8mb4_unicode_ci is based on the official Unicode rules for universal sorting and comparison, which sorts accurately in a wide range of languages.

    -

    utf8mb4_general_ci is a simplified set of sorting rules which aims to do as well as it can while taking many short-cuts designed to improve speed. It does not follow the Unicode rules and will result in undesirable sorting or comparison in some situations, such as when using particular languages or characters.

    -

    On modern servers, this performance boost will be all but negligible. It was devised in a time when servers had a tiny fraction of the CPU performance of today’s computers.

    -

    Benefits of utf8mb4_unicode_ci over utf8mb4_general_ci

    -

    utf8mb4_unicode_ci, which uses the Unicode rules for sorting and comparison, employs a fairly complex algorithm for correct sorting in a wide range of languages and when using a wide range of special characters. These rules need to take into account language-specific conventions; not everybody sorts their characters in what we would call ‘alphabetical order’.

    -

    As far as Latin (ie “European”) languages go, there is not much difference between the Unicode sorting and the simplified utf8mb4_general_cisorting in MySQL, but there are still a few differences:

    -

    For examples, the Unicode collation sorts “ß” like “ss”, and “Œ” like “OE” as people using those characters would normally want, whereas utf8mb4_general_cisorts them as single characters (presumably like “s” and “e” respectively).

    -

    Some Unicode characters are defined as ignorable, which means they shouldn’t count toward the sort order and the comparison should move on to the next character instead. utf8mb4_unicode_cihandles these properly.

    -

    In non-latin languages, such as Asian languages or languages with different alphabets, there may be a lot more differences between Unicode sorting and the simplified utf8mb4_general_cisorting. The suitability of utf8mb4_general_ciwill depend heavily on the language used. For some languages, it’ll be quite inadequate.

    -

    What should you use?

    -

    There is almost certainly no reason to use utf8mb4_general_cianymore, as we have left behind the point where CPU speed is low enough that the performance difference would be important. Your database will almost certainly be limited by other bottlenecks than this.

    -

    In the past, some people recommended to use utf8mb4_general_ciexcept when accurate sorting was going to be important enough to justify the performance cost. Today, that performance cost has all but disappeared, and developers are treating internationalization more seriously.

    -

    There’s an argument to be made that if speed is more important to you than accuracy, you may as well not do any sorting at all. It’s trivial to make an algorithm faster if you do not need it to be accurate. So, utf8mb4_general_ciis a compromise that’s probably not needed for speed reasons and probably also not suitable for accuracy reasons.

    -

    One other thing I’ll add is that even if you know your application only supports the English language, it may still need to deal with people’s names, which can often contain characters used in other languages in which it is just as important to sort correctly. Using the Unicode rules for everything helps add peace of mind that the very smart Unicode people have worked very hard to make sorting work properly.

    -

    What the parts mean

    -

    Firstly, ci is for case-insensitive sorting and comparison. This means it’s suitable for textual data, and case is not important. The other types of collation are cs (case-sensitive) for textual data where case is important, and bin, for where the encoding needs to match, bit for bit, which is suitable for fields which are really encoded binary data (including, for example, Base64). Case-sensitive sorting leads to some weird results and case-sensitive comparison can result in duplicate values differing only in letter case, so case-sensitive collations are falling out of favor for textual data - if case is significant to you, then otherwise ignorable punctuation and so on is probably also significant, and a binary collation might be more appropriate.

    -

    Next, unicode or general refers to the specific sorting and comparison rules - in particular, the way text is normalized or compared. There are many different sets of rules for the utf8mb4 character encoding, with unicode and general being two that attempt to work well in all possible languages rather than one specific one. The differences between these two sets of rules are the subject of this answer. Note that unicode uses rules from Unicode 4.0. Recent versions of MySQL add the rulesets unicode_520 using rules from Unicode 5.2, and 0900 (dropping the “unicode_” part) using rules from Unicode 9.0.

    -

    And lastly, utf8mb4 is of course the character encoding used internally. In this answer I’m talking only about Unicode based encodings.

    -

    翻译

    对于那些在 2020 年或之后仍会遇到这个问题的人,有可能比这两个更好的新选项。例如,utf8mb4_0900_ai_ci

    -

    所有这些排序规则都用于 UTF-8 字符编码。不同之处在于文本的排序和比较方式。

    -

    _unicode_ci_general_ci是两组不同的规则,用于按照我们期望的方式对文本进行排序和比较。较新版本的 MySQL 也引入了新的规则集,例如 _0900_ai_ci用于基于 Unicode 9.0 的等效规则 - 并且没有等效的 _general_ci变体。现在阅读本文的人可能应该使用这些较新的排序规则之一,而不是 _unicode_ci_general_ci。下面对那些较旧的排序规则的描述仅供参考。

    -

    MySQL 目前正在从旧的、有缺陷的 UTF-8 实现过渡。现在,您需要使用 utf8mb4 而不是 utf8作为字符编码部分,以确保您获得的是固定版本。有缺陷的版本仍然是为了向后兼容,尽管它已被弃用。

    -

    主要区别

    -

    utf8mb4_unicode_ci基于官方 Unicode 规则进行通用排序和比较,可在多种语言中准确排序。

    -

    utf8mb4_general_ci是一组简化的排序规则,旨在尽其所能,同时采用许多旨在提高速度的捷径。它不遵循 Unicode 规则,并且在某些情况下会导致不希望的排序或比较,例如在使用特定语言或字符时。

    -

    在现代服务器上,这种性能提升几乎可以忽略不计。它是在服务器的 CPU 性能只有当今计算机的一小部分时设计的。

    -

    utf8mb4_unicode_ci 相对于 utf8mb4_general_ci的优势

    -

    utf8mb4_unicode_ci使用 Unicode 规则进行排序和比较,采用相当复杂的算法在多种语言中以及在使用多种特殊字符时进行正确排序。这些规则需要考虑特定语言的约定;不是每个人都按照我们所说的“字母顺序”对他们的字符进行排序。

    -

    就拉丁语(即“欧洲”)语言而言,Unicode 排序和 MySQL 中简化的 utf8mb4_general_ci排序没有太大区别,但仍有一些区别:

    -

    例如,Unicode 排序规则将“ß”排序为“ss”,将“Œ”排序为“OE”,因为使用这些字符的人通常需要这些字符,而 utf8mb4_general_ci将它们排序为单个字符(大概分别像“s”和“e” )。

    -

    一些 Unicode 字符被定义为可忽略,这意味着它们不应该计入排序顺序,并且比较应该转到下一个字符。 utf8mb4_unicode_ci正确处理这些。

    -

    在非拉丁语言中,例如亚洲语言或具有不同字母的语言,Unicode 排序和简化的 utf8mb4_general_ci排序之间可能存在更多差异。 utf8mb4_general_ci的适用性在很大程度上取决于所使用的语言。对于某些语言,这将是非常不充分的。

    -

    你应该用什么?

    -

    几乎可以肯定没有理由再使用 utf8mb4_general_ci,因为我们已经将 CPU 速度低到会严重影响性能表现的时代远抛在脑后了。您的数据库几乎肯定会受到除此之外的其他瓶颈的限制。

    -

    过去,有些人建议使用 utf8mb4_general_ci,除非准确排序足够重要以证明性能成本是合理的。如今,这种性能成本几乎消失了,开发人员正在更加认真地对待国际化。

    -

    有一个论点是,如果速度对您来说比准确性更重要,那么您可能根本不进行任何排序。如果您不需要准确的算法,那么使算法更快是微不足道的。因此,utf8mb4_general_ci是一种折衷方案,出于速度原因可能不需要,也可能出于准确性原因也不适合。

    -

    我要补充的另一件事是,即使您知道您的应用程序仅支持英语,它可能仍需要处理人名,这些人名通常包含其他语言中使用的字符,在这些语言中正确排序同样重要.对所有事情都使用 Unicode 规则有助于让您更加安心,因为非常聪明的 Unicode 人员已经非常努力地工作以使排序正常工作。

    -

    其余各个部分是什么意思

    -

    首先, ci 用于不区分大小写的排序和比较。这意味着它适用于文本数据,大小写并不重要。其他类型的排序规则是 cs(区分大小写),用于区分大小写的文本数据,以及 bin,用于编码需要匹配的地方,逐位匹配,适用于真正编码二进制数据的字段(包括,用于例如,Base64)。区分大小写的排序会导致一些奇怪的结果,区分大小写的比较可能会导致重复值仅在字母大小写上有所不同,因此区分大小写的排序规则对文本数据不受欢迎 - 如果大小写对您很重要,那么标点符号就可以忽略等等可能也很重要,二进制排序规则可能更合适。

    -

    接下来,unicode 或general 指的是具体的排序和比较规则——特别是文本被规范化或比较的方式。 utf8mb4 字符编码有许多不同的规则集,其中 unicode 和 general 是两种,它们试图在所有可能的语言中都很好地工作,而不是在一种特定的语言中。这两组规则之间的差异是此答案的主题。请注意,unicode 使用 Unicode 4.0 中的规则。 MySQL 的最新版本使用 Unicode 5.2 的规则添加规则集 unicode_520,使用 Unicode 9.0 的规则添加 0900(删除“unicode_”部分)。

    -

    最后,utf8mb4 当然是内部使用的字符编码。在这个答案中,我只谈论基于 Unicode 的编码。

    -

    utf8 和 utf8mb4 编码有什么区别

    原文

    UTF-8is a variable-length encoding. In the case of UTF-8, this means that storing one code point requires one to four bytes. However, MySQL’s encoding called “utf8” (alias of “utf8mb3”) only stores a maximum of three bytes per code point.

    -

    So the character set “utf8”/“utf8mb3” cannot store all Unicode code points: it only supports the range 0x000 to 0xFFFF, which is called the “Basic Multilingual Plane“. See also Comparison of Unicode encodings.

    -

    This is what (a previous version of the same page at)the MySQL documentationhas to say about it:

    -
    -

    The character set named utf8[/utf8mb3] uses a maximum of three bytes per character and contains only BMP characters. As of MySQL 5.5.3, the utf8mb4 character set uses a maximum of four bytes per character supports supplemental characters:

    -
      -
    • For a BMP character, utf8[/utf8mb3] and utf8mb4 have identical storage characteristics: same code values, same encoding, same length.
    • -
    • For a supplementary character, utf8[/utf8mb3] cannot store the character at all, while utf8mb4 requires four bytes to store it. Since utf8[/utf8mb3] cannot store the character at all, you do not have any supplementary characters in utf8[/utf8mb3] columns and you need not worry about converting characters or losing data when upgrading utf8[/utf8mb3] data from older versions of MySQL.
    • -
    -
    -

    So if you want your column to support storing characters lying outside the BMP (and you usually want to), such as emoji, use “utf8mb4”. See also What are the most common non-BMP Unicode characters in actual use?.

    -

    译文

    UTF-8 是一种可变长度编码。对于 UTF-8,这意味着存储一个代码点需要一到四个字节。但是,MySQL 的编码称为“utf8”(“utf8mb3”的别名)每个代码点最多只能存储三个字节。

    -

    所以字符集“utf8”/“utf8mb3”不能存储所有的Unicode码位:它只支持0x000到0xFFFF的范围,被称为“基本多语言平面”。另请参阅 Unicode 编码比较

    -

    这就是(同一页面的先前版本)MySQL 文档 不得不说的:

    -
    -

    名为 utf8[/utf8mb3] 的字符集每个字符最多使用三个字节,并且仅包含 BMP 字符。从 MySQL 5.5.3 开始,utf8mb4 字符集每个字符最多使用四个字节,支持补充字符:

    -
      -
    • 对于 BMP 字符,utf8[/utf8mb3] 和 utf8mb4 具有相同的存储特性:相同的代码值、相同的编码、相同的长度。
    • -
    • 对于补充字符,utf8[/utf8mb3] 根本无法存储该字符,而 utf8mb4 需要四个字节来存储它。由于 utf8[/utf8mb3] 根本无法存储字符,因此您在 utf8[/utf8mb3] 列中没有任何补充字符,您不必担心从旧版本升级 utf8[/utf8mb3] 数据时转换字符或丢失数据mysql。
    • -
    -
    -

    因此,如果您希望您的列支持存储位于 BMP 之外的字符(并且您通常希望这样做),例如 emoji,请使用“utf8mb4”。另请参阅

    -

    实际使用中最常见的非 BMP Unicode 字符是什么?

    -]]>
    - - Mysql + Java + SpringBoot - mysql - 字符集 - 编码 - utf8 - utf8mb4 - utf8mb4_0900_ai_ci - utf8mb4_unicode_ci - utf8mb4_general_ci + Java + SpringBoot + +
    + + 是何原因竟让两人深夜奔袭十公里 + /2022/06/05/%E6%98%AF%E4%BD%95%E5%8E%9F%E5%9B%A0%E7%AB%9F%E8%AE%A9%E4%B8%A4%E4%BA%BA%E6%B7%B1%E5%A4%9C%E5%A5%94%E8%A2%AD%E5%8D%81%E5%85%AC%E9%87%8C/ + 偶尔来个标题党,不过也是一次比较神奇的经历
    上周五下班后跟 LD 约好去吃牛蛙,某个朋友好像对这类都不太能接受,我以前小时候也不常吃,但是这类其实都是口味比较重,没有那种肉本身的腥味,而且肉质比较特殊,吃过几次以后就有点爱上了,这次刚好是 LD 买的新店开业券,比较优惠(我们俩都是有点勤俭持家的,想着小电驴还有三格电,这家店又有点远,骑车单趟大概要 10 公里左右,有点担心,LD 说应该可以的,就一起骑了过去(跟她轮换着骑电驴和共享单车),结果大概离吃牛蛙的店还有一辆公里的时候,电量就报警了,只有最后一个红色的了,一共是五格,最后一格是红色的,提示我们该充电了,这样子是真的有点慌了,之前开了几个月都是还有一两格电的时候就充电了,没有试验过究竟这最后一格电能开多远,总之先到了再说。
    这家牛蛙没想到还挺热闹的,我们到那已经快八点了,还有十几个排队的,有个人还想插队(向来是不惯着这种,一边去),旁边刚好是有些商店就逛了下,就跟常规的商业中心差不多,开业的比较早也算是这一边比较核心的商业综合体了,各种品牌都有,而且还有彩票售卖点的,只是不太理解现在的彩票都是兑图案的,而且要 10 块钱一张,我的概念里还是以前 2 块钱一张的双色球,偶尔能中个五块十块的。排队还剩四五个的时候我们就去门口坐着等了,又等了大概二十分钟才排到我们,靠近我们等的里面的位置,好像好几个小女生在那还叫了外卖奶茶,然后各种拍照,小朋友的生活还是丰富多彩的,我们到了就点了蒜蓉的,没有点传说中紫苏的,菜单上画了 N 个🌶,LD 还是想体验下说下次人多点可以试试,我们俩吃怕太辣了吃不消,口味还是不错的,这家貌似是 LD 闺蜜推荐的,口碑有保证。两个人光吃一个蛙锅就差不多了,本来还想再点个其他的,后面实在吃不下了就没点,吃完还是惯例点了个奶茶,不过是真的不好找,太大了。
    本来是就回个家的事了,结果就因为前面铺垫的小电驴已经只有一格电了,标题的深夜奔袭十公里就出现了,这个电驴估计续航也虚标挺严重的,电量也是这样,骑的时候显示只有一格电,关掉再开起来又有三格,然后我们回去骑了没一公里就没电了,这下是真的完球了,觉得车子也比较新,直接停外面也不放心,就开始了深夜的十公里推电驴奔袭,LD 看我太累还帮我中间推了一段,虽然是跑过十公里的,但是推着个没电的电驴,还是着实不容易的,LD 也是陪我推着车走,中间好几次说我们把电驴停着打车回去,把电池带回去充满了明天再过来骑车,可能是心态已经转变了,这应该算是一次很特殊的体验,从我们吃完出来大概十点,到最后我们推到小区,大概是过了两个小时的样子,说句深夜也不太过分,把这次这么推车看成了一种意志力的考验,很多事情也都是怕坚持,或者说怕不能坚持,想走得远,没有持续的努力坚持肯定是不行的,所以还是坚持着把车推回来(好吧,我其实主要是怕车被偷,毕竟刚来杭州上学没多久就被偷了自行车留下了阴影),中间感谢 LD,跟我轮着推了一段路,有些下坡的时候还在那坐着用脚蹬一下,离家里大概还有一公里的时候,有个骑电瓶车的大叔还停下来问我们是车破了还是没电了,应该是出于好意吧,最后快到的时候真的非常渴,买了2.5 升的水被我一口气喝了大半瓶,奶茶已经不能起到解渴的作用了,本来以为这样能消耗很多,结果第二天一称还重了,(我的称一定有问题 233

    +]]>
    + + 生活 + + + 生活
    @@ -13812,9 +13731,11 @@ netsh interface portproxy add v4tov4 listenaddress=0 - 给小电驴上牌 - /2022/03/20/%E7%BB%99%E5%B0%8F%E7%94%B5%E9%A9%B4%E4%B8%8A%E7%89%8C/ - 三八节活动的时候下决心买了个小电驴,主要是上下班路上现在通勤条件越来越恶劣了,之前都是觉得坐公交就行了,实际路程就比较短,但是现在或者说大概是年前那两个月差不多就开始了,基本是堵一路,个人感觉是天目山路那边在修地铁,而且蚂蚁的几个空间都在那,上班的时间点都差不多,前一个修地铁感觉挺久了,机动车保有量也越来越多,总体是古墩路就越来越堵,还有个原因就是早上上班的点共享单车都被骑走了,有时候整整走一路都没一辆,有时候孤零零地有一辆基本都是破的;走路其实也是一种选择,但是因为要赶着上班,走得太慢就要很久,可能要 45 分钟这样,走得比较快就一身汗挺难受的。所以考虑自行车和电动车,这里还有一点就是不管是乘公交还是骑共享单车,其实都要从楼下走出去蛮远,公司回来也是,也就是这种通勤方式在准备阶段就花了比较多时间,比如总的从下班到到家的时间是半小时,可能在骑共享单车和公交车上的时间都不到十分钟,就比较难受。觉得这种比例太浪费时间,如果能有这种比较点对点的方式,估计能省时省力不少,前面说的骑共享单车的方式其实在之前是比较可行的,但是后来越来越少车,基本都是每周的前几天,周一到周三都是没有车,走路到公司再冷的天都是走出一身的汗,下雨天就更难受,本来下雨天应该是优先选择坐公交,但是一般下雨天堵车会更严重,而且车子到我上车的那个站,下雨天就挤得不行,总体说下来感觉事情都不打,但是几年下来,还是会挺不爽的。

    -

    电驴看的比较草率,主要是考虑续航,然后锂电池外加 48v 和 24AH,这样一般来讲还是价格比较高的,只是原来没预料到这个限速,以为现在的车子都比较快,但是现在的新国标车子都是 25km/h 的限速,然后 15km/h 都是会要提醒,虽然说有一些特殊的解除限速的方法,但是解了也就 35km/h ,差距不是特别大,而且现在的车子都是比较小,也不太能载东西,特别是上下班路程也不远的情况下,其实不是那么需要速度,就像我朋友说的,可能骑车的时间还不如等红绿灯多,所以就还好,也不打算解除限速,只是品牌上也仔细看,后来选了绿源,目前大部分还是雅迪,爱玛,台羚,绿源,小牛等,路上看的话还是雅迪比较多,不过价格也比较贵一点,还有就是小牛了,是比较新兴的品牌,手机 App 什么的做得比较好,而且也比较贵,最后以相对比较便宜的价格买了个锂电 48V24AH 的小车子,后来发现还是有点不方便的点就是没有比较大的筐,也不好装,这样就是下雨天雨衣什么的比较不方便放。

    -

    聊回来主题上牌这个事情,这个事情也是颇费心力,提车的时候店里的让我跟他早上一起去,但是因为不确定时间,也比较远就没跟着去,因为我是线上买的,线下自提,线下的店可能没啥利润可以拿,就不肯帮忙代上牌,朋友说在线下店里买是可以代上的,自己上牌过程也比较曲折,一开始是头盔没到,然后是等开发票,主要的东西就是需要骑着车子去车管所,不能只自己去,然后需要预约,附近比较近的都是提前一周就预约完了号了,要提前在支付宝上进行预约,比较空的就是店里推荐的景区大队,但是随之而来就是比较蛋疼的,这个景区大队太远了,看下骑车距离有十几公里,所以就有点拖延症,但是总归要上的,不然一直不能开是白买了,上牌的材料主要是车辆合格证,发票,然后车子上的浙品码,在车架上和电池上,然后车架号什么的都要跟合格证上完全对应,整体车子要跟合格证上一毛一样,如果有额外的反光镜,后面副座都需要拆掉,脚踏板要装上,到了那其实还比较顺利,就是十几公里外加那天比较冷,吹得头疼。

    + 搬运两个 StackOverflow 上的 Mysql 编码相关的问题解答 + /2022/01/16/%E6%90%AC%E8%BF%90%E4%B8%A4%E4%B8%AA-StackOverflow-%E4%B8%8A%E7%9A%84-Mysql-%E7%BC%96%E7%A0%81%E7%9B%B8%E5%85%B3%E7%9A%84%E9%97%AE%E9%A2%98%E8%A7%A3%E7%AD%94/ + Mysql 字符编码和排序规则

    这个一直是属于一知半解的状态,知道 utf8 跟 utf8mb4 的区别主要是能不能支持 emoji,但是具体后面配置的排序规则是用来干嘛,或者有什么区别,应该使用哪个,所以在 stackoverflow 上找了下,有两个比较不错的解答,就搬过来并且配合机翻做了点修改

    +

    原文

    For those people still arriving at this question in 2020 or later, there are newer options that may be better than both of these. For example, utf8mb4_0900_ai_ci.

    +

    All these collations are for the UTF-8 character encoding. The differences are in how text is sorted and compared.

    +

    _unicode_ci and _general_ci are two different sets of rules for sorting and comparing text according to the way we expect. Newer versions of MySQL introduce new sets of rules, too, such as _0900_ai_ci for equivalent rules based on Unicode 9.0 - and with no equivalent _general_ci variant. People reading this now should probably use one of these newer collations instead of either _unicode_ci or _general_ci. The description of those older collations below is provided for interest only.

    +

    MySQL is currently transitioning away from an older, flawed UTF-8 implementation. For now, you need to use utf8mb4 instead of utf8 for the character encoding part, to ensure you are getting the fixed version. The flawed version remains for backward compatibility, though it is being deprecated.

    +

    Key differences

    +

    utf8mb4_unicode_ci is based on the official Unicode rules for universal sorting and comparison, which sorts accurately in a wide range of languages.

    +

    utf8mb4_general_ci is a simplified set of sorting rules which aims to do as well as it can while taking many short-cuts designed to improve speed. It does not follow the Unicode rules and will result in undesirable sorting or comparison in some situations, such as when using particular languages or characters.

    +

    On modern servers, this performance boost will be all but negligible. It was devised in a time when servers had a tiny fraction of the CPU performance of today’s computers.

    +

    Benefits of utf8mb4_unicode_ci over utf8mb4_general_ci

    +

    utf8mb4_unicode_ci, which uses the Unicode rules for sorting and comparison, employs a fairly complex algorithm for correct sorting in a wide range of languages and when using a wide range of special characters. These rules need to take into account language-specific conventions; not everybody sorts their characters in what we would call ‘alphabetical order’.

    +

    As far as Latin (ie “European”) languages go, there is not much difference between the Unicode sorting and the simplified utf8mb4_general_cisorting in MySQL, but there are still a few differences:

    +

    For examples, the Unicode collation sorts “ß” like “ss”, and “Œ” like “OE” as people using those characters would normally want, whereas utf8mb4_general_cisorts them as single characters (presumably like “s” and “e” respectively).

    +

    Some Unicode characters are defined as ignorable, which means they shouldn’t count toward the sort order and the comparison should move on to the next character instead. utf8mb4_unicode_cihandles these properly.

    +

    In non-latin languages, such as Asian languages or languages with different alphabets, there may be a lot more differences between Unicode sorting and the simplified utf8mb4_general_cisorting. The suitability of utf8mb4_general_ciwill depend heavily on the language used. For some languages, it’ll be quite inadequate.

    +

    What should you use?

    +

    There is almost certainly no reason to use utf8mb4_general_cianymore, as we have left behind the point where CPU speed is low enough that the performance difference would be important. Your database will almost certainly be limited by other bottlenecks than this.

    +

    In the past, some people recommended to use utf8mb4_general_ciexcept when accurate sorting was going to be important enough to justify the performance cost. Today, that performance cost has all but disappeared, and developers are treating internationalization more seriously.

    +

    There’s an argument to be made that if speed is more important to you than accuracy, you may as well not do any sorting at all. It’s trivial to make an algorithm faster if you do not need it to be accurate. So, utf8mb4_general_ciis a compromise that’s probably not needed for speed reasons and probably also not suitable for accuracy reasons.

    +

    One other thing I’ll add is that even if you know your application only supports the English language, it may still need to deal with people’s names, which can often contain characters used in other languages in which it is just as important to sort correctly. Using the Unicode rules for everything helps add peace of mind that the very smart Unicode people have worked very hard to make sorting work properly.

    +

    What the parts mean

    +

    Firstly, ci is for case-insensitive sorting and comparison. This means it’s suitable for textual data, and case is not important. The other types of collation are cs (case-sensitive) for textual data where case is important, and bin, for where the encoding needs to match, bit for bit, which is suitable for fields which are really encoded binary data (including, for example, Base64). Case-sensitive sorting leads to some weird results and case-sensitive comparison can result in duplicate values differing only in letter case, so case-sensitive collations are falling out of favor for textual data - if case is significant to you, then otherwise ignorable punctuation and so on is probably also significant, and a binary collation might be more appropriate.

    +

    Next, unicode or general refers to the specific sorting and comparison rules - in particular, the way text is normalized or compared. There are many different sets of rules for the utf8mb4 character encoding, with unicode and general being two that attempt to work well in all possible languages rather than one specific one. The differences between these two sets of rules are the subject of this answer. Note that unicode uses rules from Unicode 4.0. Recent versions of MySQL add the rulesets unicode_520 using rules from Unicode 5.2, and 0900 (dropping the “unicode_” part) using rules from Unicode 9.0.

    +

    And lastly, utf8mb4 is of course the character encoding used internally. In this answer I’m talking only about Unicode based encodings.

    +

    翻译

    对于那些在 2020 年或之后仍会遇到这个问题的人,有可能比这两个更好的新选项。例如,utf8mb4_0900_ai_ci

    +

    所有这些排序规则都用于 UTF-8 字符编码。不同之处在于文本的排序和比较方式。

    +

    _unicode_ci_general_ci是两组不同的规则,用于按照我们期望的方式对文本进行排序和比较。较新版本的 MySQL 也引入了新的规则集,例如 _0900_ai_ci用于基于 Unicode 9.0 的等效规则 - 并且没有等效的 _general_ci变体。现在阅读本文的人可能应该使用这些较新的排序规则之一,而不是 _unicode_ci_general_ci。下面对那些较旧的排序规则的描述仅供参考。

    +

    MySQL 目前正在从旧的、有缺陷的 UTF-8 实现过渡。现在,您需要使用 utf8mb4 而不是 utf8作为字符编码部分,以确保您获得的是固定版本。有缺陷的版本仍然是为了向后兼容,尽管它已被弃用。

    +

    主要区别

    +

    utf8mb4_unicode_ci基于官方 Unicode 规则进行通用排序和比较,可在多种语言中准确排序。

    +

    utf8mb4_general_ci是一组简化的排序规则,旨在尽其所能,同时采用许多旨在提高速度的捷径。它不遵循 Unicode 规则,并且在某些情况下会导致不希望的排序或比较,例如在使用特定语言或字符时。

    +

    在现代服务器上,这种性能提升几乎可以忽略不计。它是在服务器的 CPU 性能只有当今计算机的一小部分时设计的。

    +

    utf8mb4_unicode_ci 相对于 utf8mb4_general_ci的优势

    +

    utf8mb4_unicode_ci使用 Unicode 规则进行排序和比较,采用相当复杂的算法在多种语言中以及在使用多种特殊字符时进行正确排序。这些规则需要考虑特定语言的约定;不是每个人都按照我们所说的“字母顺序”对他们的字符进行排序。

    +

    就拉丁语(即“欧洲”)语言而言,Unicode 排序和 MySQL 中简化的 utf8mb4_general_ci排序没有太大区别,但仍有一些区别:

    +

    例如,Unicode 排序规则将“ß”排序为“ss”,将“Œ”排序为“OE”,因为使用这些字符的人通常需要这些字符,而 utf8mb4_general_ci将它们排序为单个字符(大概分别像“s”和“e” )。

    +

    一些 Unicode 字符被定义为可忽略,这意味着它们不应该计入排序顺序,并且比较应该转到下一个字符。 utf8mb4_unicode_ci正确处理这些。

    +

    在非拉丁语言中,例如亚洲语言或具有不同字母的语言,Unicode 排序和简化的 utf8mb4_general_ci排序之间可能存在更多差异。 utf8mb4_general_ci的适用性在很大程度上取决于所使用的语言。对于某些语言,这将是非常不充分的。

    +

    你应该用什么?

    +

    几乎可以肯定没有理由再使用 utf8mb4_general_ci,因为我们已经将 CPU 速度低到会严重影响性能表现的时代远抛在脑后了。您的数据库几乎肯定会受到除此之外的其他瓶颈的限制。

    +

    过去,有些人建议使用 utf8mb4_general_ci,除非准确排序足够重要以证明性能成本是合理的。如今,这种性能成本几乎消失了,开发人员正在更加认真地对待国际化。

    +

    有一个论点是,如果速度对您来说比准确性更重要,那么您可能根本不进行任何排序。如果您不需要准确的算法,那么使算法更快是微不足道的。因此,utf8mb4_general_ci是一种折衷方案,出于速度原因可能不需要,也可能出于准确性原因也不适合。

    +

    我要补充的另一件事是,即使您知道您的应用程序仅支持英语,它可能仍需要处理人名,这些人名通常包含其他语言中使用的字符,在这些语言中正确排序同样重要.对所有事情都使用 Unicode 规则有助于让您更加安心,因为非常聪明的 Unicode 人员已经非常努力地工作以使排序正常工作。

    +

    其余各个部分是什么意思

    +

    首先, ci 用于不区分大小写的排序和比较。这意味着它适用于文本数据,大小写并不重要。其他类型的排序规则是 cs(区分大小写),用于区分大小写的文本数据,以及 bin,用于编码需要匹配的地方,逐位匹配,适用于真正编码二进制数据的字段(包括,用于例如,Base64)。区分大小写的排序会导致一些奇怪的结果,区分大小写的比较可能会导致重复值仅在字母大小写上有所不同,因此区分大小写的排序规则对文本数据不受欢迎 - 如果大小写对您很重要,那么标点符号就可以忽略等等可能也很重要,二进制排序规则可能更合适。

    +

    接下来,unicode 或general 指的是具体的排序和比较规则——特别是文本被规范化或比较的方式。 utf8mb4 字符编码有许多不同的规则集,其中 unicode 和 general 是两种,它们试图在所有可能的语言中都很好地工作,而不是在一种特定的语言中。这两组规则之间的差异是此答案的主题。请注意,unicode 使用 Unicode 4.0 中的规则。 MySQL 的最新版本使用 Unicode 5.2 的规则添加规则集 unicode_520,使用 Unicode 9.0 的规则添加 0900(删除“unicode_”部分)。

    +

    最后,utf8mb4 当然是内部使用的字符编码。在这个答案中,我只谈论基于 Unicode 的编码。

    +

    utf8 和 utf8mb4 编码有什么区别

    原文

    UTF-8is a variable-length encoding. In the case of UTF-8, this means that storing one code point requires one to four bytes. However, MySQL’s encoding called “utf8” (alias of “utf8mb3”) only stores a maximum of three bytes per code point.

    +

    So the character set “utf8”/“utf8mb3” cannot store all Unicode code points: it only supports the range 0x000 to 0xFFFF, which is called the “Basic Multilingual Plane“. See also Comparison of Unicode encodings.

    +

    This is what (a previous version of the same page at)the MySQL documentationhas to say about it:

    +
    +

    The character set named utf8[/utf8mb3] uses a maximum of three bytes per character and contains only BMP characters. As of MySQL 5.5.3, the utf8mb4 character set uses a maximum of four bytes per character supports supplemental characters:

    +
      +
    • For a BMP character, utf8[/utf8mb3] and utf8mb4 have identical storage characteristics: same code values, same encoding, same length.
    • +
    • For a supplementary character, utf8[/utf8mb3] cannot store the character at all, while utf8mb4 requires four bytes to store it. Since utf8[/utf8mb3] cannot store the character at all, you do not have any supplementary characters in utf8[/utf8mb3] columns and you need not worry about converting characters or losing data when upgrading utf8[/utf8mb3] data from older versions of MySQL.
    • +
    +
    +

    So if you want your column to support storing characters lying outside the BMP (and you usually want to), such as emoji, use “utf8mb4”. See also What are the most common non-BMP Unicode characters in actual use?.

    +

    译文

    UTF-8 是一种可变长度编码。对于 UTF-8,这意味着存储一个代码点需要一到四个字节。但是,MySQL 的编码称为“utf8”(“utf8mb3”的别名)每个代码点最多只能存储三个字节。

    +

    所以字符集“utf8”/“utf8mb3”不能存储所有的Unicode码位:它只支持0x000到0xFFFF的范围,被称为“基本多语言平面”。另请参阅 Unicode 编码比较

    +

    这就是(同一页面的先前版本)MySQL 文档 不得不说的:

    +
    +

    名为 utf8[/utf8mb3] 的字符集每个字符最多使用三个字节,并且仅包含 BMP 字符。从 MySQL 5.5.3 开始,utf8mb4 字符集每个字符最多使用四个字节,支持补充字符:

    +
      +
    • 对于 BMP 字符,utf8[/utf8mb3] 和 utf8mb4 具有相同的存储特性:相同的代码值、相同的编码、相同的长度。
    • +
    • 对于补充字符,utf8[/utf8mb3] 根本无法存储该字符,而 utf8mb4 需要四个字节来存储它。由于 utf8[/utf8mb3] 根本无法存储字符,因此您在 utf8[/utf8mb3] 列中没有任何补充字符,您不必担心从旧版本升级 utf8[/utf8mb3] 数据时转换字符或丢失数据mysql。
    • +
    +
    +

    因此,如果您希望您的列支持存储位于 BMP 之外的字符(并且您通常希望这样做),例如 emoji,请使用“utf8mb4”。另请参阅

    +

    实际使用中最常见的非 BMP Unicode 字符是什么?

    ]]>
    - 生活 + Mysql - 生活 + mysql + 字符集 + 编码 + utf8 + utf8mb4 + utf8mb4_0900_ai_ci + utf8mb4_unicode_ci + utf8mb4_general_ci
    @@ -15257,84 +15252,6 @@ netsh interface portproxy add v4tov4 listenaddress=0这篇文章,个人感觉写得非常好,在 rocketmq 中,最大的一块存储就是消息存储,也就是 CommitLog ,当然还有 ConsumeQueue 和 IndexFile,以及其他一些文件,CommitLog 的存储是以一个 1G 大小的文件作为存储单位,写完了就再建一个,那么如何提高这 1G 文件的读写效率呢,就是 mmap,传统意义的读写文件,read,write 都需要由系统调用,来回地在用户态跟内核态进行拷贝切换,

    -
    read(file, tmp_buf, len);
    -write(socket, tmp_buf, len);
    - - - -

    vms95Z

    -

    如上面的图显示的,要在用户态跟内核态进行切换,数据还需要在内核缓冲跟用户缓冲之间拷贝多次,

    -
    -
      -
    1. 第一步是调用 read,需要在用户态切换成内核态,DMA模块从磁盘中读取文件,并存储在内核缓冲区,相当于是第一次复制
    2. -
    3. 数据从内核缓冲区被拷贝到用户缓冲区,read 调用返回,伴随着内核态又切换成用户态,完成了第二次复制
    4. -
    5. 然后是write 写入,这里也会伴随着用户态跟内核态的切换,数据从用户缓冲区被复制到内核空间缓冲区,完成了第三次复制,这次有点不一样的是数据不是在内核缓冲区了,会复制到 socket buffer 中。
    6. -
    7. write 系统调用返回,又切换回了用户态,然后数据由 DMA 拷贝到协议引擎。
    8. -
    -
    -

    如此就能看出其实默认的读写操作代价是非常大的,而在 rocketmq 等高性能中间件中都有使用的零拷贝技术,其中 rocketmq 使用的是 mmap

    -

    mmap

    mmap基于 OS 的 mmap 的内存映射技术,通过MMU 映射文件,将文件直接映射到用户态的内存地址,使得对文件的操作不再是 write/read,而转化为直接对内存地址的操作,使随机读写文件和读写内存相似的速度。

    -
    -

    mmap 把文件映射到用户空间里的虚拟内存,省去了从内核缓冲区复制到用户空间的过程,文件中的位置在虚拟内存中有了对应的地址,可以像操作内存一样操作这个文件,这样的文件读写文件方式少了数据从内核缓存到用户空间的拷贝,效率很高。

    -
    -
    tmp_buf = mmap(file, len);
    -write(socket, tmp_buf, len);
    - -

    I68mFx

    -
    -

    第一步:mmap系统调用使得文件内容被DMA引擎复制到内核缓冲区。然后该缓冲区与用户进程共享,在内核和用户内存空间之间不进行任何拷贝。

    -

    第二步:写系统调用使得内核将数据从原来的内核缓冲区复制到与套接字相关的内核缓冲区。

    -

    第三步:第三次拷贝发生在DMA引擎将数据从内核套接字缓冲区传递给协议引擎时。

    -

    通过使用mmap而不是read,我们将内核需要拷贝的数据量减少了一半。当大量的数据被传输时,这将有很好的效果。然而,这种改进并不是没有代价的;在使用mmap+write方法时,有一些隐藏的陷阱。例如当你对一个文件进行内存映射,然后在另一个进程截断同一文件时调用写。你的写系统调用将被总线错误信号SIGBUS打断,因为你执行了一个错误的内存访问。该信号的默认行为是杀死进程并dumpcore–这对网络服务器来说不是最理想的操作。

    -

    有两种方法可以解决这个问题。

    -

    第一种方法是为SIGBUS信号安装一个信号处理程序,然后在处理程序中简单地调用返回。通过这样做,写系统调用会返回它在被打断之前所写的字节数,并将errno设置为成功。让我指出,这将是一个糟糕的解决方案,一个治标不治本的解决方案。因为SIGBUS预示着进程出了严重的问题,所以不鼓励使用这种解决方案。

    -

    第二个解决方案涉及内核的文件租赁(在Windows中称为 “机会锁”)。这是解决这个问题的正确方法。通过在文件描述符上使用租赁,你与内核在一个特定的文件上达成租约。然后你可以向内核请求一个读/写租约。当另一个进程试图截断你正在传输的文件时,内核会向你发送一个实时信号,即RT_SIGNAL_LEASE信号。它告诉你内核即将终止你对该文件的写或读租约。在你的程序访问一个无效的地址和被SIGBUS信号杀死之前,你的写调用会被打断了。写入调用的返回值是中断前写入的字节数,errno将被设置为成功。下面是一些示例代码,显示了如何从内核中获得租约。

    -
    if(fcntl(fd, F_SETSIG, RT_SIGNAL_LEASE) == -1) {
    -    perror("kernel lease set signal");
    -    return -1;
    -}
    -/* l_type can be F_RDLCK F_WRLCK */
    -if(fcntl(fd, F_SETLEASE, l_type)){
    -    perror("kernel lease set type");
    -    return -1;
    -}
    -]]> - - MQ - RocketMQ - 消息队列 - - - MQ - 消息队列 - RocketMQ - -
    聊一下 RocketMQ 的消息存储三 /2021/10/03/%E8%81%8A%E4%B8%80%E4%B8%8B-RocketMQ-%E7%9A%84%E6%B6%88%E6%81%AF%E5%AD%98%E5%82%A8%E4%B8%89/ @@ -15484,32 +15401,60 @@ netsh interface portproxy add v4tov4 listenaddress=0系列了,比较无聊,就是帮着干点零活的记录,这次过去起的比较早,前几天是在翻新瓦片,到这次周六是收尾了,到了的时候先是继续筛了沙子,上周也筛了,就是只筛了一点点,筛沙子的那个像纱窗一样的还是用一扇中空的中间有一根竖档的门钉上铁丝网做的,就是沙子一直放在外面,原来是有袋子装好的,后来是风吹雨打在上面的都已经破掉,还夹杂了很多树叶什么的,需要过下筛,并且前面都是下雨天,沙子都是湿的,不太像我以前看村里有人造房子筛沙子那样,用铲子铲上去就自己都下去的,湿的就是会在一坨,所以需要铲得比较少,然后撒的比较开,这个需要一点经验,然后如果有人一起的话就可以用扫把按住扫一下,这样就会筛得比较有效,不至于都滑下去,沙子本来大部分是可以筛出来的,还有一点就是这种情况网筛需要放得坡度小一点,不然就更容易直接往下调,袋子没破的就不用过筛了,只是湿掉了的是真的重,筛完了那些破掉了的袋子里的沙子,就没有特别的事情要做了,看到大工在那打墙,有一些敲下来的好的砖头就留着,需要削一下上面的混凝土,据大工说现在砖头要七八毛一块了,后面能够重新利用还是挺值钱的,我跟 LD 就用泥刀和铁锹的在那慢慢削,砖头上的泥灰有的比较牢固有的就像直接是沙子,泥刀刮一下就下来了,有的就结合得比较牢固,不过据说以前的砖头工艺上还比较落后,这个房子差不多是三十年前了的,砖头表面都是有点不平,甚至变形,那时候可能砖头是手工烧制的,现在的砖头比较工艺可好多了,不过可能也贵了很多,后来老丈人也过来了,指导了我们拌泥灰,就是水泥和黄沙混合,以前小时候可喜欢玩这个了,可是就也搞不清楚这个是怎么搅拌的,只看见是水泥跟黄沙围城一圈,中间放水,然后一点点搬进去,首先需要先把干的水泥跟黄沙进行混合,具体的比例是老丈人说的,拌的方式有点像堆沙堆,把水泥黄沙铲起来堆起来,就一直要往这个混合堆的尖尖上堆,这样子它自己滑下来能更好地混合,来回两趟就基本混合均匀了,然后就是跟以前看过的,中间扒拉出一个空间放水,然后慢慢把周围的混合好的泥沙推进去,需要注意不要太着急,旁边的推进去太多太快就会漏水出来,一个是会把旁边的地给弄脏,另一个也铲不回水,然后就是推完所有的都混合水了,就铲起来倒一下,再将铲子翻过来捣几下,后面我们就去吃饭了,去了一家叫金记的,又贵又不太好吃的店,就是离得比较近,六七个人只有六七个菜,吃完要四百多,也是有点离谱了。
    下午是重头戏,其实本来倒没啥事,就说帮忙搞下靠背(就是踢脚线上面到窗台附近的用木头还有其他材料的装饰性的),都撬撬掉,但是真的是有点离谱了,首先是撬棒真的很重,20 斤的重量(网上查的,没有真的查过),抡起来还要用力地铲进去,因为就是破坏性的要把整个都撬掉,对于我这种又没技巧又没力气的非专业选手,抡起撬棍铲两下手就开始痛了,只是也比较犟,不想刚开始弄就说太重了要休息,后面都完全靠的一点倔强劲撑着,看着里面的工艺感觉也是不容易的,直着横着的木条有好多,竖的一整条,每隔三五十公分,横着的就是三五十公分,每根都要用钉子钉起来,然后外层好像是贴上去,在同一个面的开了头之后就能靠着蛮力往下撬,但是到了转角就又要重新开头,而且最上面一根横条跟紧邻的那一块,大概十几公分,是横着的三条钉在一起,真的是大力都出不了奇迹了,用撬棍的一头用力地敲打都很震手,要从下面往上铲进去撬开一点,然后再从上面往下敲打,这里比较重要的是要小心钉子,我这次运气比较好,踩下去已经扎到了,不过正好在脚趾缝里,没有扎到脚,还是要小心的,做完这个我的手真的是差不多废了,上臂的疼痛已经动一下就受不了了,后面有撬下了最下面当踢脚线的小瓷砖,这个房子估计中间修过一次,两批水泥糊的,新的那批粘的特别牢,敲敲打打了半天才下来一点点,锤子敲上去跟一整块石头一样,震手又没有进展,整个搞完,楼上又在敲墙了,下面的灰尘也是从没见过,我一直在那洒水都完全没有缓解,就上去跟 LD 一起拣砖头,手痛到只能抬两块砖头都会痛了。
    回到家里开始越来越痛,两个手就完全没法动了,应该也是肌肉拉伤了,我这样是没足够的力气也不会什么技巧,像大工说的,他们也累也难,只是为了赚钱,不过他们有了经验跟技巧,会注意怎么使力不容易受伤,怎么样比较省力,还有一点就是即使这么累,他们一般也下午五点半就下班了,真的很累了,至少还有不少时间可以回家休息,而我们的职业呢,就像 LD 说的回家就像住酒店,就只是来洗澡睡个觉,希望能改善吧

    + 聊一下 RocketMQ 的消息存储之 MMAP + /2021/09/04/%E8%81%8A%E4%B8%80%E4%B8%8B-RocketMQ-%E7%9A%84%E6%B6%88%E6%81%AF%E5%AD%98%E5%82%A8/ + 这是个很大的话题了,可能会分成两部分说,第一部分就是所谓的零拷贝 ( zero-copy ),这一块其实也不新鲜,我对零拷贝的概念主要来自这篇文章,个人感觉写得非常好,在 rocketmq 中,最大的一块存储就是消息存储,也就是 CommitLog ,当然还有 ConsumeQueue 和 IndexFile,以及其他一些文件,CommitLog 的存储是以一个 1G 大小的文件作为存储单位,写完了就再建一个,那么如何提高这 1G 文件的读写效率呢,就是 mmap,传统意义的读写文件,read,write 都需要由系统调用,来回地在用户态跟内核态进行拷贝切换,

    +
    read(file, tmp_buf, len);
    +write(socket, tmp_buf, len);
    + + + +

    vms95Z

    +

    如上面的图显示的,要在用户态跟内核态进行切换,数据还需要在内核缓冲跟用户缓冲之间拷贝多次,

    +
    +
      +
    1. 第一步是调用 read,需要在用户态切换成内核态,DMA模块从磁盘中读取文件,并存储在内核缓冲区,相当于是第一次复制
    2. +
    3. 数据从内核缓冲区被拷贝到用户缓冲区,read 调用返回,伴随着内核态又切换成用户态,完成了第二次复制
    4. +
    5. 然后是write 写入,这里也会伴随着用户态跟内核态的切换,数据从用户缓冲区被复制到内核空间缓冲区,完成了第三次复制,这次有点不一样的是数据不是在内核缓冲区了,会复制到 socket buffer 中。
    6. +
    7. write 系统调用返回,又切换回了用户态,然后数据由 DMA 拷贝到协议引擎。
    8. +
    +
    +

    如此就能看出其实默认的读写操作代价是非常大的,而在 rocketmq 等高性能中间件中都有使用的零拷贝技术,其中 rocketmq 使用的是 mmap

    +

    mmap

    mmap基于 OS 的 mmap 的内存映射技术,通过MMU 映射文件,将文件直接映射到用户态的内存地址,使得对文件的操作不再是 write/read,而转化为直接对内存地址的操作,使随机读写文件和读写内存相似的速度。

    +
    +

    mmap 把文件映射到用户空间里的虚拟内存,省去了从内核缓冲区复制到用户空间的过程,文件中的位置在虚拟内存中有了对应的地址,可以像操作内存一样操作这个文件,这样的文件读写文件方式少了数据从内核缓存到用户空间的拷贝,效率很高。

    +
    +
    tmp_buf = mmap(file, len);
    +write(socket, tmp_buf, len);
    + +

    I68mFx

    +
    +

    第一步:mmap系统调用使得文件内容被DMA引擎复制到内核缓冲区。然后该缓冲区与用户进程共享,在内核和用户内存空间之间不进行任何拷贝。

    +

    第二步:写系统调用使得内核将数据从原来的内核缓冲区复制到与套接字相关的内核缓冲区。

    +

    第三步:第三次拷贝发生在DMA引擎将数据从内核套接字缓冲区传递给协议引擎时。

    +

    通过使用mmap而不是read,我们将内核需要拷贝的数据量减少了一半。当大量的数据被传输时,这将有很好的效果。然而,这种改进并不是没有代价的;在使用mmap+write方法时,有一些隐藏的陷阱。例如当你对一个文件进行内存映射,然后在另一个进程截断同一文件时调用写。你的写系统调用将被总线错误信号SIGBUS打断,因为你执行了一个错误的内存访问。该信号的默认行为是杀死进程并dumpcore–这对网络服务器来说不是最理想的操作。

    +

    有两种方法可以解决这个问题。

    +

    第一种方法是为SIGBUS信号安装一个信号处理程序,然后在处理程序中简单地调用返回。通过这样做,写系统调用会返回它在被打断之前所写的字节数,并将errno设置为成功。让我指出,这将是一个糟糕的解决方案,一个治标不治本的解决方案。因为SIGBUS预示着进程出了严重的问题,所以不鼓励使用这种解决方案。

    +

    第二个解决方案涉及内核的文件租赁(在Windows中称为 “机会锁”)。这是解决这个问题的正确方法。通过在文件描述符上使用租赁,你与内核在一个特定的文件上达成租约。然后你可以向内核请求一个读/写租约。当另一个进程试图截断你正在传输的文件时,内核会向你发送一个实时信号,即RT_SIGNAL_LEASE信号。它告诉你内核即将终止你对该文件的写或读租约。在你的程序访问一个无效的地址和被SIGBUS信号杀死之前,你的写调用会被打断了。写入调用的返回值是中断前写入的字节数,errno将被设置为成功。下面是一些示例代码,显示了如何从内核中获得租约。

    +
    if(fcntl(fd, F_SETSIG, RT_SIGNAL_LEASE) == -1) {
    +    perror("kernel lease set signal");
    +    return -1;
    +}
    +/* l_type can be F_RDLCK F_WRLCK */
    +if(fcntl(fd, F_SETLEASE, l_type)){
    +    perror("kernel lease set type");
    +    return -1;
    +}
    ]]>
    - 生活 + MQ + RocketMQ + 消息队列 - 生活 - 小技巧 - 运动 - 减肥 - 跑步 - 干活 + MQ + 消息队列 + RocketMQ
    @@ -15881,161 +15826,6 @@ netsh interface portproxy add v4tov4 listenaddress=0class CommitLogDispatcherBuildIndex implements CommitLogDispatcher { - - @Override - public void dispatch(DispatchRequest request) { - if (DefaultMessageStore.this.messageStoreConfig.isMessageIndexEnable()) { - DefaultMessageStore.this.indexService.buildIndex(request); - } - } -} -public void buildIndex(DispatchRequest req) { - IndexFile indexFile = retryGetAndCreateIndexFile(); - if (indexFile != null) { - long endPhyOffset = indexFile.getEndPhyOffset(); - DispatchRequest msg = req; - String topic = msg.getTopic(); - String keys = msg.getKeys(); - if (msg.getCommitLogOffset() < endPhyOffset) { - return; - } - - final int tranType = MessageSysFlag.getTransactionValue(msg.getSysFlag()); - switch (tranType) { - case MessageSysFlag.TRANSACTION_NOT_TYPE: - case MessageSysFlag.TRANSACTION_PREPARED_TYPE: - case MessageSysFlag.TRANSACTION_COMMIT_TYPE: - break; - case MessageSysFlag.TRANSACTION_ROLLBACK_TYPE: - return; - } - - if (req.getUniqKey() != null) { - indexFile = putKey(indexFile, msg, buildKey(topic, req.getUniqKey())); - if (indexFile == null) { - log.error("putKey error commitlog {} uniqkey {}", req.getCommitLogOffset(), req.getUniqKey()); - return; - } - } - - if (keys != null && keys.length() > 0) { - String[] keyset = keys.split(MessageConst.KEY_SEPARATOR); - for (int i = 0; i < keyset.length; i++) { - String key = keyset[i]; - if (key.length() > 0) { - indexFile = putKey(indexFile, msg, buildKey(topic, key)); - if (indexFile == null) { - log.error("putKey error commitlog {} uniqkey {}", req.getCommitLogOffset(), req.getUniqKey()); - return; - } - } - } - } - } else { - log.error("build index error, stop building index"); - } - }
    - -

    配置的数量

    -
    private boolean messageIndexEnable = true;
    -private int maxHashSlotNum = 5000000;
    -private int maxIndexNum = 5000000 * 4;
    - -

    最核心的其实是 IndexFile 的结构和如何写入

    -
    public boolean putKey(final String key, final long phyOffset, final long storeTimestamp) {
    -        if (this.indexHeader.getIndexCount() < this.indexNum) {
    -          // 获取 key 的 hash
    -            int keyHash = indexKeyHashMethod(key);
    -          // 计算属于哪个 slot
    -            int slotPos = keyHash % this.hashSlotNum;
    -          // 计算 slot 位置 因为结构是有个 indexHead,主要是分为三段 header,slot 和 index
    -            int absSlotPos = IndexHeader.INDEX_HEADER_SIZE + slotPos * hashSlotSize;
    -
    -            FileLock fileLock = null;
    -
    -            try {
    -
    -                // fileLock = this.fileChannel.lock(absSlotPos, hashSlotSize,
    -                // false);
    -                int slotValue = this.mappedByteBuffer.getInt(absSlotPos);
    -                if (slotValue <= invalidIndex || slotValue > this.indexHeader.getIndexCount()) {
    -                    slotValue = invalidIndex;
    -                }
    -
    -                long timeDiff = storeTimestamp - this.indexHeader.getBeginTimestamp();
    -
    -                timeDiff = timeDiff / 1000;
    -
    -                if (this.indexHeader.getBeginTimestamp() <= 0) {
    -                    timeDiff = 0;
    -                } else if (timeDiff > Integer.MAX_VALUE) {
    -                    timeDiff = Integer.MAX_VALUE;
    -                } else if (timeDiff < 0) {
    -                    timeDiff = 0;
    -                }
    -
    -              // 计算索引存放位置,头部 + slot 数量 * slot 大小 + 已有的 index 数量 + index 大小
    -                int absIndexPos =
    -                    IndexHeader.INDEX_HEADER_SIZE + this.hashSlotNum * hashSlotSize
    -                        + this.indexHeader.getIndexCount() * indexSize;
    -							
    -                this.mappedByteBuffer.putInt(absIndexPos, keyHash);
    -                this.mappedByteBuffer.putLong(absIndexPos + 4, phyOffset);
    -                this.mappedByteBuffer.putInt(absIndexPos + 4 + 8, (int) timeDiff);
    -                this.mappedByteBuffer.putInt(absIndexPos + 4 + 8 + 4, slotValue);
    -
    -              // 存放的是数量位移,不是绝对位置
    -                this.mappedByteBuffer.putInt(absSlotPos, this.indexHeader.getIndexCount());
    -
    -                if (this.indexHeader.getIndexCount() <= 1) {
    -                    this.indexHeader.setBeginPhyOffset(phyOffset);
    -                    this.indexHeader.setBeginTimestamp(storeTimestamp);
    -                }
    -
    -                this.indexHeader.incHashSlotCount();
    -                this.indexHeader.incIndexCount();
    -                this.indexHeader.setEndPhyOffset(phyOffset);
    -                this.indexHeader.setEndTimestamp(storeTimestamp);
    -
    -                return true;
    -            } catch (Exception e) {
    -                log.error("putKey exception, Key: " + key + " KeyHashCode: " + key.hashCode(), e);
    -            } finally {
    -                if (fileLock != null) {
    -                    try {
    -                        fileLock.release();
    -                    } catch (IOException e) {
    -                        log.error("Failed to release the lock", e);
    -                    }
    -                }
    -            }
    -        } else {
    -            log.warn("Over index file capacity: index count = " + this.indexHeader.getIndexCount()
    -                + "; index max num = " + this.indexNum);
    -        }
    -
    -        return false;
    -    }
    - -

    具体可以看一下这个简略的示意图

    ]]> MQ @@ -16447,90 +16237,21 @@ netsh interface portproxy add v4tov4 listenaddress=0return bean; } - // Create proxy if we have advice. - Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null); - if (specificInterceptors != DO_NOT_PROXY) { - this.advisedBeans.put(cacheKey, Boolean.TRUE); - Object proxy = createProxy( - bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean)); - this.proxyTypes.put(cacheKey, proxy.getClass()); - return proxy; - } - - this.advisedBeans.put(cacheKey, Boolean.FALSE); - return bean; - }
    - -

    然后在 org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#createProxy 中创建了代理类

    -]]> - - Java - SpringBoot - - - Java - Spring - SpringBoot - cglib - 事务 - - - - 聊在东京奥运会闭幕式这天-二 - /2021/08/19/%E8%81%8A%E5%9C%A8%E4%B8%9C%E4%BA%AC%E5%A5%A5%E8%BF%90%E4%BC%9A%E9%97%AD%E5%B9%95%E5%BC%8F%E8%BF%99%E5%A4%A9-%E4%BA%8C/ - 前面主要还是说了乒乓球的,因为整体还是乒乓球的比赛赛程比较长,比较激烈,扣人心弦,记得那会在公司没法看视频直播,就偶尔看看奥运会官网的比分,还几场马龙樊振东,陈梦被赢了一局就吓尿了,已经被混双那场留下了阴影,其实后面去看看16 年的比赛什么的,中国队虽然拿了这么多冠军,但是自改成 11 分制以来,其实都没办法那么完全彻底地碾压,而且像张继科,樊振东,陈梦都多少有些慢热,现在看来是马龙比较全面,不过看过了马龙,刘国梁,许昕等的一些过往经历,都是起起伏伏,即使是张怡宁这样的大魔王,也经历过逢王楠不赢的阶段,心态无法调整好。

    -

    其实最开始是举重项目,侯志慧是女子 49 公斤级的冠军,这场比赛是全场都看,其实看中国队的举重比赛跟跳水有点像,每一轮都需要到最后才能等到中国队,跳水其实每轮都有,举重会按照自己报的试举重量进行排名,重量大的会在后面举,抓举和挺举各三次试举机会,有时候会看着比较焦虑,一直等不来,怕一上来就没试举成功,而且中国队一般试举重量就是很大的,容易一次试举不成功就马上下一次,连着举其实压力会非常大,说实话真的是外行看热闹,每次都是多懂一点点,这次由于实在是比较无聊,所以看的会比较专心点,对于对应的规则知识点也会多了解一点,同时对于举重,没想到我们国家的这些运动员有这么强,最后八块金牌拿了七块,有一块拿到银牌也是有点因为教练的策略问题,这里其实也稍微知道一点,因为报上去的试举重量是谁小谁先举,并且我们国家都是实力非常强的,所以都会报大一些,并且如果这个项目有实力相近的选手,会比竞对多报一公斤,这样子如果前面竞争对手没举成功,我们把握就很大了,最坏的情况即使对手试举成功了,我们还有机会搏一把,比如谌利军这样的,只是说说感想,举重运动员真的是个比较单纯的群体,而且训练是非常痛苦枯燥的,非常容易受伤,像挺举就有点会压迫呼吸通道,看到好几个都是脸憋得通红,甚至直接因为压迫气道而没法完成后面的挺举,像之前 16 年的举重比赛,有个运动员没成功夺冠就非常愧疚地哭着说对不起祖国,没有获得冠军,这是怎么样的一种歉疚,怎么样的一种纯粹的感情呢,相对应地来说,我又要举男足,男篮的例子了,很多人在那嘲笑我这样对男足男篮愤愤不平的人,说可能我这样的人都没交个税(从缴纳个税的数量比例来算有可能),只是这里有两个打脸的事情,我足额缴纳个税,接近 20%的薪资都缴了个税,并且我买的所有东西都缴了增值税,如果让我这样缴纳了个税,缴纳了增值税的有个人的投票权,我一定会投票不让男足男篮使用我缴纳我的税金,用我们的缴纳的税,打出这么烂的表现,想乒乓球混双,拿个亚军都会被喷,那可是世界第二了,而且是就输了那么一场,足球篮球呢,我觉得是一方面成绩差,因为比赛真的有状态跟心态的影响,偶尔有一场失误非常正常,NBA 被黑八的有这么多强队,但是如果像男足男篮,成绩是越来越差,用范志毅的话来说就是脸都不要了,还有就是精气神,要在比赛中打出胜负欲,保持这种争胜心,才有机会再进步,前火箭队主教练鲁迪·汤姆贾诺维奇的话,“永远不要低估冠军的决心”,即使我现在打不过你,我会在下一次,下下次打败你,竞技体育永远要有这种精神,可以接受一时的失败,但是要保持永远争胜的心。

    -

    第一块金牌是杨倩拿下的,中国队拿奥运会首金也是有政治任务的,而恰恰杨倩这个金牌也有点碰巧是对手最后一枪失误了,当然竞技体育,特别是射击,真的是容不得一点点失误,像前面几届的美国神通埃蒙斯,失之毫厘差之千里,但是这个具体评价就比较少,唯一一点让我比较出戏的就是杨倩真的非常像王刚的徒弟漆二娃,哈哈,微博上也有挺多人觉得像,射击还是个比较可以接受年纪稍大的运动员,需要经验和稳定性,相对来说爆发力体力稍好一点,像庞伟这样的,混合团体10米气手枪金牌,36 岁可能其他项目已经是年龄很大了,不过前面说的举重的吕小军军神也是年纪蛮大了,但是非常强,而且在油管上简直就是个神,相对来说射击是关注比较少,杨倩的也只是看了后面拿到冠军这个结果,有些因为时间或者电视上没放,但是成绩还是不错的,没多少喷点。

    -

    第二篇先到这,纯主观,轻喷。

    -]]>
    - - 生活 - 运动 - - - 生活 - 运动 - 东京奥运会 - 举重 - 射击 - -
    - - 聊一下 SpringBoot 设置非 web 应用的方法 - /2022/07/31/%E8%81%8A%E4%B8%80%E4%B8%8B-SpringBoot-%E8%AE%BE%E7%BD%AE%E9%9D%9E-web-%E5%BA%94%E7%94%A8%E7%9A%84%E6%96%B9%E6%B3%95/ - 寻找原因

    这次碰到一个比较奇怪的问题,应该统一发布脚本统一给应用启动参数传了个 -Dserver.port=xxxx,其实这个端口会作为 dubbo 的服务端口,并且应用也不提供 web 服务,但是在启动的时候会报embedded servlet container failed to start. port xxxx was already in use就觉得有点奇怪,仔细看了启动参数猜测可能是这个问题,有可能是依赖的二方三方包带了 spring-web 的包,然后基于 springboot 的 auto configuration 会把这个自己加载,就在本地复现了下这个问题,结果的确是这个问题。

    -

    解决方案

    老版本 设置 spring 不带 web 功能

    比较老的 springboot 版本,可以使用

    -
    SpringApplication app = new SpringApplication(XXXXXApplication.class);
    -app.setWebEnvironment(false);
    -app.run(args);
    -

    新版本

    新版本的 springboot (>= 2.0.0)可以在 properties 里配置

    -
    spring.main.web-application-type=none
    -

    或者

    -
    SpringApplication app = new SpringApplication(XXXXXApplication.class);
    -app.setWebApplicationType(WebApplicationType.NONE);
    -

    这个枚举里还有其他两种配置

    -
    public enum WebApplicationType {
    -
    -	/**
    -	 * The application should not run as a web application and should not start an
    -	 * embedded web server.
    -	 */
    -	NONE,
    -
    -	/**
    -	 * The application should run as a servlet-based web application and should start an
    -	 * embedded servlet web server.
    -	 */
    -	SERVLET,
    -
    -	/**
    -	 * The application should run as a reactive web application and should start an
    -	 * embedded reactive web server.
    -	 */
    -	REACTIVE
    +		// Create proxy if we have advice.
    +		Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
    +		if (specificInterceptors != DO_NOT_PROXY) {
    +			this.advisedBeans.put(cacheKey, Boolean.TRUE);
    +			Object proxy = createProxy(
    +					bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
    +			this.proxyTypes.put(cacheKey, proxy.getClass());
    +			return proxy;
    +		}
     
    -}
    -

    相当于是把none 的类型和包括 servlet 和 reactive 放进了枚举类进行控制。

    + this.advisedBeans.put(cacheKey, Boolean.FALSE); + return bean; + }
    + +

    然后在 org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#createProxy 中创建了代理类

    ]]> Java @@ -16540,8 +16261,8 @@ app.setWebAp Java Spring SpringBoot - 自动装配 - AutoConfiguration + cglib + 事务 @@ -16752,6 +16473,75 @@ app.setWebAp 数据源动态切换 + + 聊一下 SpringBoot 设置非 web 应用的方法 + /2022/07/31/%E8%81%8A%E4%B8%80%E4%B8%8B-SpringBoot-%E8%AE%BE%E7%BD%AE%E9%9D%9E-web-%E5%BA%94%E7%94%A8%E7%9A%84%E6%96%B9%E6%B3%95/ + 寻找原因

    这次碰到一个比较奇怪的问题,应该统一发布脚本统一给应用启动参数传了个 -Dserver.port=xxxx,其实这个端口会作为 dubbo 的服务端口,并且应用也不提供 web 服务,但是在启动的时候会报embedded servlet container failed to start. port xxxx was already in use就觉得有点奇怪,仔细看了启动参数猜测可能是这个问题,有可能是依赖的二方三方包带了 spring-web 的包,然后基于 springboot 的 auto configuration 会把这个自己加载,就在本地复现了下这个问题,结果的确是这个问题。

    +

    解决方案

    老版本 设置 spring 不带 web 功能

    比较老的 springboot 版本,可以使用

    +
    SpringApplication app = new SpringApplication(XXXXXApplication.class);
    +app.setWebEnvironment(false);
    +app.run(args);
    +

    新版本

    新版本的 springboot (>= 2.0.0)可以在 properties 里配置

    +
    spring.main.web-application-type=none
    +

    或者

    +
    SpringApplication app = new SpringApplication(XXXXXApplication.class);
    +app.setWebApplicationType(WebApplicationType.NONE);
    +

    这个枚举里还有其他两种配置

    +
    public enum WebApplicationType {
    +
    +	/**
    +	 * The application should not run as a web application and should not start an
    +	 * embedded web server.
    +	 */
    +	NONE,
    +
    +	/**
    +	 * The application should run as a servlet-based web application and should start an
    +	 * embedded servlet web server.
    +	 */
    +	SERVLET,
    +
    +	/**
    +	 * The application should run as a reactive web application and should start an
    +	 * embedded reactive web server.
    +	 */
    +	REACTIVE
    +
    +}
    +

    相当于是把none 的类型和包括 servlet 和 reactive 放进了枚举类进行控制。

    +]]>
    + + Java + SpringBoot + + + Java + Spring + SpringBoot + 自动装配 + AutoConfiguration + +
    + + 聊在东京奥运会闭幕式这天-二 + /2021/08/19/%E8%81%8A%E5%9C%A8%E4%B8%9C%E4%BA%AC%E5%A5%A5%E8%BF%90%E4%BC%9A%E9%97%AD%E5%B9%95%E5%BC%8F%E8%BF%99%E5%A4%A9-%E4%BA%8C/ + 前面主要还是说了乒乓球的,因为整体还是乒乓球的比赛赛程比较长,比较激烈,扣人心弦,记得那会在公司没法看视频直播,就偶尔看看奥运会官网的比分,还几场马龙樊振东,陈梦被赢了一局就吓尿了,已经被混双那场留下了阴影,其实后面去看看16 年的比赛什么的,中国队虽然拿了这么多冠军,但是自改成 11 分制以来,其实都没办法那么完全彻底地碾压,而且像张继科,樊振东,陈梦都多少有些慢热,现在看来是马龙比较全面,不过看过了马龙,刘国梁,许昕等的一些过往经历,都是起起伏伏,即使是张怡宁这样的大魔王,也经历过逢王楠不赢的阶段,心态无法调整好。

    +

    其实最开始是举重项目,侯志慧是女子 49 公斤级的冠军,这场比赛是全场都看,其实看中国队的举重比赛跟跳水有点像,每一轮都需要到最后才能等到中国队,跳水其实每轮都有,举重会按照自己报的试举重量进行排名,重量大的会在后面举,抓举和挺举各三次试举机会,有时候会看着比较焦虑,一直等不来,怕一上来就没试举成功,而且中国队一般试举重量就是很大的,容易一次试举不成功就马上下一次,连着举其实压力会非常大,说实话真的是外行看热闹,每次都是多懂一点点,这次由于实在是比较无聊,所以看的会比较专心点,对于对应的规则知识点也会多了解一点,同时对于举重,没想到我们国家的这些运动员有这么强,最后八块金牌拿了七块,有一块拿到银牌也是有点因为教练的策略问题,这里其实也稍微知道一点,因为报上去的试举重量是谁小谁先举,并且我们国家都是实力非常强的,所以都会报大一些,并且如果这个项目有实力相近的选手,会比竞对多报一公斤,这样子如果前面竞争对手没举成功,我们把握就很大了,最坏的情况即使对手试举成功了,我们还有机会搏一把,比如谌利军这样的,只是说说感想,举重运动员真的是个比较单纯的群体,而且训练是非常痛苦枯燥的,非常容易受伤,像挺举就有点会压迫呼吸通道,看到好几个都是脸憋得通红,甚至直接因为压迫气道而没法完成后面的挺举,像之前 16 年的举重比赛,有个运动员没成功夺冠就非常愧疚地哭着说对不起祖国,没有获得冠军,这是怎么样的一种歉疚,怎么样的一种纯粹的感情呢,相对应地来说,我又要举男足,男篮的例子了,很多人在那嘲笑我这样对男足男篮愤愤不平的人,说可能我这样的人都没交个税(从缴纳个税的数量比例来算有可能),只是这里有两个打脸的事情,我足额缴纳个税,接近 20%的薪资都缴了个税,并且我买的所有东西都缴了增值税,如果让我这样缴纳了个税,缴纳了增值税的有个人的投票权,我一定会投票不让男足男篮使用我缴纳我的税金,用我们的缴纳的税,打出这么烂的表现,想乒乓球混双,拿个亚军都会被喷,那可是世界第二了,而且是就输了那么一场,足球篮球呢,我觉得是一方面成绩差,因为比赛真的有状态跟心态的影响,偶尔有一场失误非常正常,NBA 被黑八的有这么多强队,但是如果像男足男篮,成绩是越来越差,用范志毅的话来说就是脸都不要了,还有就是精气神,要在比赛中打出胜负欲,保持这种争胜心,才有机会再进步,前火箭队主教练鲁迪·汤姆贾诺维奇的话,“永远不要低估冠军的决心”,即使我现在打不过你,我会在下一次,下下次打败你,竞技体育永远要有这种精神,可以接受一时的失败,但是要保持永远争胜的心。

    +

    第一块金牌是杨倩拿下的,中国队拿奥运会首金也是有政治任务的,而恰恰杨倩这个金牌也有点碰巧是对手最后一枪失误了,当然竞技体育,特别是射击,真的是容不得一点点失误,像前面几届的美国神通埃蒙斯,失之毫厘差之千里,但是这个具体评价就比较少,唯一一点让我比较出戏的就是杨倩真的非常像王刚的徒弟漆二娃,哈哈,微博上也有挺多人觉得像,射击还是个比较可以接受年纪稍大的运动员,需要经验和稳定性,相对来说爆发力体力稍好一点,像庞伟这样的,混合团体10米气手枪金牌,36 岁可能其他项目已经是年龄很大了,不过前面说的举重的吕小军军神也是年纪蛮大了,但是非常强,而且在油管上简直就是个神,相对来说射击是关注比较少,杨倩的也只是看了后面拿到冠军这个结果,有些因为时间或者电视上没放,但是成绩还是不错的,没多少喷点。

    +

    第二篇先到这,纯主观,轻喷。

    +]]>
    + + 生活 + 运动 + + + 生活 + 运动 + 东京奥运会 + 举重 + 射击 + +
    聊在东京奥运会闭幕式这天 /2021/08/08/%E8%81%8A%E5%9C%A8%E4%B8%9C%E4%BA%AC%E5%A5%A5%E8%BF%90%E4%BC%9A%E9%97%AD%E5%B9%95%E5%BC%8F%E8%BF%99%E5%A4%A9/ @@ -16773,138 +16563,158 @@ app.setWebAp - 聊聊 Dubbo 的容错机制 - /2020/11/22/%E8%81%8A%E8%81%8A-Dubbo-%E7%9A%84%E5%AE%B9%E9%94%99%E6%9C%BA%E5%88%B6/ - 之前看了 dubbo 的一些代码,在学习过程中,主要关注那些比较“高级”的内容,SPI,自适应扩展等,却忘了一些作为一个 rpc 框架最核心需要的部分,比如如何通信,序列化,网络,容错机制等等,因为其实这个最核心的就是远程调用,自适应扩展其实就是让代码可扩展性,可读性,更优雅等,写的搓一点其实也问题不大,但是一个合适的通信协议,序列化方法,如何容错等却是真正保证是一个 rpc 框架最重要的要素。
    首先来看这张图
    cluster
    在集群调用失败时,Dubbo 提供了多种容错方案,缺省为 failover 重试。
    各节点关系:

    -
      -
    • 这里的 InvokerProvider 的一个可调用 Service 的抽象,Invoker 封装了 Provider 地址及 Service 接口信息
    • -
    • Directory 代表多个 Invoker,可以把它看成 List<Invoker> ,但与 List 不同的是,它的值可能是动态变化的,比如注册中心推送变更
    • -
    • ClusterDirectory 中的多个 Invoker 伪装成一个 Invoker,对上层透明,伪装过程包含了容错逻辑,调用失败后,重试另一个
    • -
    • Router 负责从多个 Invoker 中按路由规则选出子集,比如读写分离,应用隔离等
    • -
    • LoadBalance 负责从多个 Invoker 中选出具体的一个用于本次调用,选的过程包含了负载均衡算法,调用失败后,需要重选
    • -
    -

    集群容错模式

    Failover Cluster

    失败自动切换,当出现失败,重试其它服务器 1。通常用于读操作,但重试会带来更长延迟。可通过 retries=”2” 来设置重试次数(不含第一次)。

    -

    重试次数配置如下:

    -

    <dubbo:service retries=”2” />
    这里重点看下 Failover Cluster集群模式的实现

    -
    public class FailoverCluster implements Cluster {
    -
    -    public final static String NAME = "failover";
    +    聊一下 RocketMQ 的消息存储四
    +    /2021/10/17/%E8%81%8A%E4%B8%80%E4%B8%8B-RocketMQ-%E7%9A%84%E6%B6%88%E6%81%AF%E5%AD%98%E5%82%A8%E5%9B%9B/
    +    IndexFile 结构 hash 结构能够通过 key 寻找到对应在 CommitLog 中的位置

    +

    IndexFile 的构建则是分发给这个进行处理

    +
    class CommitLogDispatcherBuildIndex implements CommitLogDispatcher {
     
    -    public <T> Invoker<T> join(Directory<T> directory) throws RpcException {
    -        return new FailoverClusterInvoker<T>(directory);
    +    @Override
    +    public void dispatch(DispatchRequest request) {
    +        if (DefaultMessageStore.this.messageStoreConfig.isMessageIndexEnable()) {
    +            DefaultMessageStore.this.indexService.buildIndex(request);
    +        }
         }
    +}
    +public void buildIndex(DispatchRequest req) {
    +        IndexFile indexFile = retryGetAndCreateIndexFile();
    +        if (indexFile != null) {
    +            long endPhyOffset = indexFile.getEndPhyOffset();
    +            DispatchRequest msg = req;
    +            String topic = msg.getTopic();
    +            String keys = msg.getKeys();
    +            if (msg.getCommitLogOffset() < endPhyOffset) {
    +                return;
    +            }
     
    -}
    -

    这个代码就非常简单,重点需要看FailoverClusterInvoker里的代码,FailoverClusterInvoker继承了AbstractClusterInvoker类,其中invoke 方法是在抽象类里实现的

    -
    @Override
    -public Result invoke(final Invocation invocation) throws RpcException {
    -    checkWhetherDestroyed();
    -    // binding attachments into invocation.
    -    // 绑定 attachments 到 invocation 中.
    -    Map<String, Object> contextAttachments = RpcContext.getContext().getObjectAttachments();
    -    if (contextAttachments != null && contextAttachments.size() != 0) {
    -        ((RpcInvocation) invocation).addObjectAttachments(contextAttachments);
    -    }
    -    // 列举 Invoker
    -    List<Invoker<T>> invokers = list(invocation);
    -    // 加载 LoadBalance 负载均衡器
    -    LoadBalance loadbalance = initLoadBalance(invokers, invocation);
    -    RpcUtils.attachInvocationIdIfAsync(getUrl(), invocation);
    -    // 调用 实际的 doInvoke 进行后续操作
    -    return doInvoke(invocation, invokers, loadbalance);
    -}
    -// 这是个抽象方法,实际是由子类实现的
    - protected abstract Result doInvoke(Invocation invocation, List<Invoker<T>> invokers,
    -                                       LoadBalance loadbalance) throws RpcException;
    -

    然后重点就是FailoverClusterInvoker中的doInvoke方法了,其实它里面也就这么一个方法

    -
    @Override
    -    @SuppressWarnings({"unchecked", "rawtypes"})
    -    public Result doInvoke(Invocation invocation, final List<Invoker<T>> invokers, LoadBalance loadbalance) throws RpcException {
    -        List<Invoker<T>> copyInvokers = invokers;
    -        checkInvokers(copyInvokers, invocation);
    -        String methodName = RpcUtils.getMethodName(invocation);
    -        // 获取重试次数,这里默认是 2 次,还有可以注意下后面的+1
    -        int len = getUrl().getMethodParameter(methodName, RETRIES_KEY, DEFAULT_RETRIES) + 1;
    -        if (len <= 0) {
    -            len = 1;
    -        }
    -        // retry loop.
    -        RpcException le = null; // last exception.
    -        List<Invoker<T>> invoked = new ArrayList<Invoker<T>>(copyInvokers.size()); // invoked invokers.
    -        Set<String> providers = new HashSet<String>(len);
    -        // 循环调用,失败重试
    -        for (int i = 0; i < len; i++) {
    -            //Reselect before retry to avoid a change of candidate `invokers`.
    -            //NOTE: if `invokers` changed, then `invoked` also lose accuracy.
    -            if (i > 0) {
    -                checkWhetherDestroyed();
    -                // 在进行重试前重新列举 Invoker,这样做的好处是,如果某个服务挂了,
    -                // 通过调用 list 可得到最新可用的 Invoker 列表
    -                copyInvokers = list(invocation);
    -                // check again
    -                // 对 copyinvokers 进行判空检查
    -                checkInvokers(copyInvokers, invocation);
    -            }
    -            // 通过负载均衡来选择 invoker
    -            Invoker<T> invoker = select(loadbalance, invocation, copyInvokers, invoked);
    -            // 将其添加到 invoker 到 invoked 列表中
    -            invoked.add(invoker);
    -            // 设置上下文
    -            RpcContext.getContext().setInvokers((List) invoked);
    -            try {
    -                // 正式调用
    -                Result result = invoker.invoke(invocation);
    -                if (le != null && logger.isWarnEnabled()) {
    -                    logger.warn("Although retry the method " + methodName
    -                            + " in the service " + getInterface().getName()
    -                            + " was successful by the provider " + invoker.getUrl().getAddress()
    -                            + ", but there have been failed providers " + providers
    -                            + " (" + providers.size() + "/" + copyInvokers.size()
    -                            + ") from the registry " + directory.getUrl().getAddress()
    -                            + " on the consumer " + NetUtils.getLocalHost()
    -                            + " using the dubbo version " + Version.getVersion() + ". Last error is: "
    -                            + le.getMessage(), le);
    -                }
    -                return result;
    -            } catch (RpcException e) {
    -                if (e.isBiz()) { // biz exception.
    -                    throw e;
    -                }
    -                le = e;
    -            } catch (Throwable e) {
    -                le = new RpcException(e.getMessage(), e);
    -            } finally {
    -                providers.add(invoker.getUrl().getAddress());
    -            }
    -        }
    -        throw new RpcException(le.getCode(), "Failed to invoke the method "
    -                + methodName + " in the service " + getInterface().getName()
    -                + ". Tried " + len + " times of the providers " + providers
    -                + " (" + providers.size() + "/" + copyInvokers.size()
    -                + ") from the registry " + directory.getUrl().getAddress()
    -                + " on the consumer " + NetUtils.getLocalHost() + " using the dubbo version "
    -                + Version.getVersion() + ". Last error is: "
    -                + le.getMessage(), le.getCause() != null ? le.getCause() : le);
    -    }
    + final int tranType = MessageSysFlag.getTransactionValue(msg.getSysFlag()); + switch (tranType) { + case MessageSysFlag.TRANSACTION_NOT_TYPE: + case MessageSysFlag.TRANSACTION_PREPARED_TYPE: + case MessageSysFlag.TRANSACTION_COMMIT_TYPE: + break; + case MessageSysFlag.TRANSACTION_ROLLBACK_TYPE: + return; + } + + if (req.getUniqKey() != null) { + indexFile = putKey(indexFile, msg, buildKey(topic, req.getUniqKey())); + if (indexFile == null) { + log.error("putKey error commitlog {} uniqkey {}", req.getCommitLogOffset(), req.getUniqKey()); + return; + } + } + + if (keys != null && keys.length() > 0) { + String[] keyset = keys.split(MessageConst.KEY_SEPARATOR); + for (int i = 0; i < keyset.length; i++) { + String key = keyset[i]; + if (key.length() > 0) { + indexFile = putKey(indexFile, msg, buildKey(topic, key)); + if (indexFile == null) { + log.error("putKey error commitlog {} uniqkey {}", req.getCommitLogOffset(), req.getUniqKey()); + return; + } + } + } + } + } else { + log.error("build index error, stop building index"); + } + }
    +

    配置的数量

    +
    private boolean messageIndexEnable = true;
    +private int maxHashSlotNum = 5000000;
    +private int maxIndexNum = 5000000 * 4;
    -

    Failfast Cluster

    快速失败,只发起一次调用,失败立即报错。通常用于非幂等性的写操作,比如新增记录。

    -

    Failsafe Cluster

    失败安全,出现异常时,直接忽略。通常用于写入审计日志等操作。

    -

    Failback Cluster

    失败自动恢复,后台记录失败请求,定时重发。通常用于消息通知操作。

    -

    Forking Cluster

    并行调用多个服务器,只要一个成功即返回。通常用于实时性要求较高的读操作,但需要浪费更多服务资源。可通过 forks=”2” 来设置最大并行数。

    -

    Broadcast Cluster

    广播调用所有提供者,逐个调用,任意一台报错则报错 2。通常用于通知所有提供者更新缓存或日志等本地资源信息。

    +

    最核心的其实是 IndexFile 的结构和如何写入

    +
    public boolean putKey(final String key, final long phyOffset, final long storeTimestamp) {
    +        if (this.indexHeader.getIndexCount() < this.indexNum) {
    +          // 获取 key 的 hash
    +            int keyHash = indexKeyHashMethod(key);
    +          // 计算属于哪个 slot
    +            int slotPos = keyHash % this.hashSlotNum;
    +          // 计算 slot 位置 因为结构是有个 indexHead,主要是分为三段 header,slot 和 index
    +            int absSlotPos = IndexHeader.INDEX_HEADER_SIZE + slotPos * hashSlotSize;
    +
    +            FileLock fileLock = null;
    +
    +            try {
    +
    +                // fileLock = this.fileChannel.lock(absSlotPos, hashSlotSize,
    +                // false);
    +                int slotValue = this.mappedByteBuffer.getInt(absSlotPos);
    +                if (slotValue <= invalidIndex || slotValue > this.indexHeader.getIndexCount()) {
    +                    slotValue = invalidIndex;
    +                }
    +
    +                long timeDiff = storeTimestamp - this.indexHeader.getBeginTimestamp();
    +
    +                timeDiff = timeDiff / 1000;
    +
    +                if (this.indexHeader.getBeginTimestamp() <= 0) {
    +                    timeDiff = 0;
    +                } else if (timeDiff > Integer.MAX_VALUE) {
    +                    timeDiff = Integer.MAX_VALUE;
    +                } else if (timeDiff < 0) {
    +                    timeDiff = 0;
    +                }
    +
    +              // 计算索引存放位置,头部 + slot 数量 * slot 大小 + 已有的 index 数量 + index 大小
    +                int absIndexPos =
    +                    IndexHeader.INDEX_HEADER_SIZE + this.hashSlotNum * hashSlotSize
    +                        + this.indexHeader.getIndexCount() * indexSize;
    +							
    +                this.mappedByteBuffer.putInt(absIndexPos, keyHash);
    +                this.mappedByteBuffer.putLong(absIndexPos + 4, phyOffset);
    +                this.mappedByteBuffer.putInt(absIndexPos + 4 + 8, (int) timeDiff);
    +                this.mappedByteBuffer.putInt(absIndexPos + 4 + 8 + 4, slotValue);
    +
    +              // 存放的是数量位移,不是绝对位置
    +                this.mappedByteBuffer.putInt(absSlotPos, this.indexHeader.getIndexCount());
    +
    +                if (this.indexHeader.getIndexCount() <= 1) {
    +                    this.indexHeader.setBeginPhyOffset(phyOffset);
    +                    this.indexHeader.setBeginTimestamp(storeTimestamp);
    +                }
    +
    +                this.indexHeader.incHashSlotCount();
    +                this.indexHeader.incIndexCount();
    +                this.indexHeader.setEndPhyOffset(phyOffset);
    +                this.indexHeader.setEndTimestamp(storeTimestamp);
    +
    +                return true;
    +            } catch (Exception e) {
    +                log.error("putKey exception, Key: " + key + " KeyHashCode: " + key.hashCode(), e);
    +            } finally {
    +                if (fileLock != null) {
    +                    try {
    +                        fileLock.release();
    +                    } catch (IOException e) {
    +                        log.error("Failed to release the lock", e);
    +                    }
    +                }
    +            }
    +        } else {
    +            log.warn("Over index file capacity: index count = " + this.indexHeader.getIndexCount()
    +                + "; index max num = " + this.indexNum);
    +        }
    +
    +        return false;
    +    }
    + +

    具体可以看一下这个简略的示意图

    ]]>
    - Java - Dubbo - RPC - Dubbo - 容错机制 + MQ + RocketMQ + 消息队列 - Java - Dubbo - RPC - 容错机制 + MQ + 消息队列 + RocketMQ
    @@ -17041,8 +16851,8 @@ public Result invoke(final Invocation invocation) throws RpcException { Java Dubbo RPC - Dubbo SPI + Dubbo SPI Adaptive
    @@ -17055,6 +16865,115 @@ public Result invoke(final Invocation invocation) throws RpcException { 自适应拓展 + + 聊一下关于怎么陪伴学习 + /2022/11/06/%E8%81%8A%E4%B8%80%E4%B8%8B%E5%85%B3%E4%BA%8E%E6%80%8E%E4%B9%88%E9%99%AA%E4%BC%B4%E5%AD%A6%E4%B9%A0/ + 这是一次开车过程中结合网上的一些微博想到的,开车是之前LD买了车后,陪领导练车,其实在一开始练车的时候,我们已经是找了相对很空的封闭路段,路上基本很少有车,偶尔有一辆车,但是LD还是很害怕,车速还只有十几的时候,还很远的对面来车的时候就觉得很慌了,这个时候如果以常理肯定会说这样子完全不用怕,如果克服恐惧真的这么容易的话,问题就不会那么纠结了,人生是很难完全感同身受的,唯有降低预设的基准让事情从头理清楚,害怕了我们就先休息,有车了我们就停下,先适应完全没车的情况,变得更慢一点,如果这时候着急一点,反而会起到反效果,比如只是说不要怕,接着开,甚至有点厌烦了,那基本这个练车也不太成得了了,而正好是有耐心的一起慢慢练习,还有就是第二件是切身体会,就是当道路本来是两条道,但是封了一条的时候,这时候开车如果是像我这样的新手,如果开车时左右边看着的话,车肯定开不好,因为那样会一直左右调整,反而更容易控制不好左右的距离,蹭到旁边的隔离栏,正确的方式应该是专注于正前方的路,这样才能保证左右边距离尽可能均匀,而不是顾左失右或者顾右失左,所以很多陪伴学习需要注意的是方式和耐心,能够识别到关键点那是最好的,但是有时候更需要的是耐心,纯靠耐心不一定能解决问题,但是可能会找到问题关键点。

    +]]>
    + + 生活 + + + 生活 + +
    + + 聊聊 Dubbo 的 SPI + /2020/05/31/%E8%81%8A%E8%81%8A-Dubbo-%E7%9A%84-SPI/ + SPI全称是Service Provider Interface,咋眼看跟api是不是有点相似,api是application interface,这两个其实在某些方面有类似的地方,也有蛮大的区别,比如我们基于 dubbo 的微服务,一般我们可以提供服务,然后非泛化调用的话,我们可以把 api 包提供给应用调用方,他们根据接口签名传对应参数并配置好对应的服务发现如 zk 等就可以调用我们的服务了,然后 spi 会有点类似但是是反过来的关系,相当于是一种规范,比如我约定完成这个功能需要两个有两个接口,一个是连接的,一个是断开的,其实就可以用 jdbc 的驱动举例,比较老套了,然后各个厂家去做具体的实现吧,到时候根据我接口的全限定名的文件来加载实际的实现类,然后运行的时候调用对应实现类的方法就完了

    +

    3sKdpg

    +

    看上面的图,java.sql.Driver就是 spi,对应在classpath 的 META-INF/services 目录下的这个文件,里边的内容就是具体的实现类

    +

    1590735097909

    +

    简单介绍了 Java的 SPI,再来说说 dubbo 的,dubbo 中为啥要用 SPI 呢,主要是为了框架的可扩展性和性能方面的考虑,比如协议层 dubbo 默认使用 dubbo 协议,同时也支持很多其他协议,也支持用户自己实现协议,那么跟 Java 的 SPI 会有什么区别呢,我们也来看个文件

    +

    bqxWMp

    +

    是不是看着很想,又有点不一样,在 Java 的 SPI 配置文件里每一行只有一个实现类的全限定名,在 Dubbo的 SPI配置文件中是 key=value 的形式,我们只需要对应的 key 就能加载对应的实现,

    +
    /**
    +     * 返回指定名字的扩展。如果指定名字的扩展不存在,则抛异常 {@link IllegalStateException}.
    +     *
    +     * @param name
    +     * @return
    +     */
    +	@SuppressWarnings("unchecked")
    +	public T getExtension(String name) {
    +		if (name == null || name.length() == 0)
    +		    throw new IllegalArgumentException("Extension name == null");
    +		if ("true".equals(name)) {
    +		    return getDefaultExtension();
    +		}
    +		Holder<Object> holder = cachedInstances.get(name);
    +		if (holder == null) {
    +		    cachedInstances.putIfAbsent(name, new Holder<Object>());
    +		    holder = cachedInstances.get(name);
    +		}
    +		Object instance = holder.get();
    +		if (instance == null) {
    +		    synchronized (holder) {
    +	            instance = holder.get();
    +	            if (instance == null) {
    +	                instance = createExtension(name);
    +	                holder.set(instance);
    +	            }
    +	        }
    +		}
    +		return (T) instance;
    +	}
    +

    这里其实就可以看出来第二个不同点了,就是这个cachedInstances,第一个是不用像 Java 原生的 SPI 那样去遍历加载对应的服务类,只需要通过 key 去寻找,并且寻找的时候会先从缓存的对象里去取,还有就是注意下这里的 DCL(double check lock)

    +
    @SuppressWarnings("unchecked")
    +    private T createExtension(String name) {
    +        Class<?> clazz = getExtensionClasses().get(name);
    +        if (clazz == null) {
    +            throw findException(name);
    +        }
    +        try {
    +            T instance = (T) EXTENSION_INSTANCES.get(clazz);
    +            if (instance == null) {
    +                EXTENSION_INSTANCES.putIfAbsent(clazz, (T) clazz.newInstance());
    +                instance = (T) EXTENSION_INSTANCES.get(clazz);
    +            }
    +            injectExtension(instance);
    +            Set<Class<?>> wrapperClasses = cachedWrapperClasses;
    +            if (wrapperClasses != null && wrapperClasses.size() > 0) {
    +                for (Class<?> wrapperClass : wrapperClasses) {
    +                    instance = injectExtension((T) wrapperClass.getConstructor(type).newInstance(instance));
    +                }
    +            }
    +            return instance;
    +        } catch (Throwable t) {
    +            throw new IllegalStateException("Extension instance(name: " + name + ", class: " +
    +                    type + ")  could not be instantiated: " + t.getMessage(), t);
    +        }
    +    }
    +

    然后就是创建扩展了,这里如果 wrapperClasses 就会遍历生成wrapper实例,并做 setter 依赖注入,但是这里cachedWrapperClasses的来源还是有点搞不清楚,得再看下 com.alibaba.dubbo.common.extension.ExtensionLoader#loadFile的具体逻辑
    又看了遍新的代码,这个函数被抽出来了

    +
    /**
    +    * test if clazz is a wrapper class
    +    * <p>
    +    * which has Constructor with given class type as its only argument
    +    */
    +   private boolean isWrapperClass(Class<?> clazz) {
    +       try {
    +           clazz.getConstructor(type);
    +           return true;
    +       } catch (NoSuchMethodException e) {
    +           return false;
    +       }
    +   }
    +

    是否是 wrapperClass 其实就看构造函数的。

    +]]>
    + + Java + Dubbo + RPC + SPI + Dubbo + SPI + + + Java + Dubbo + RPC + SPI + +
    聊聊 Java 中绕不开的 Synchronized 关键字-二 /2021/06/27/%E8%81%8A%E8%81%8A-Java-%E4%B8%AD%E7%BB%95%E4%B8%8D%E5%BC%80%E7%9A%84-Synchronized-%E5%85%B3%E9%94%AE%E5%AD%97-%E4%BA%8C/ @@ -17211,23 +17130,158 @@ public Result invoke(final Invocation invocation) throws RpcException { } } -class L { - private boolean myboolean = true; -}
    +class L { + private boolean myboolean = true; +}
    + +

    https://img.nicksxs.com/uPic/LMzMtR.png

    +

    可以看到变成了重量级锁。

    +]]> + + Java + + + Java + Synchronized + 偏向锁 + 轻量级锁 + 重量级锁 + 自旋 + + + + 聊聊 Dubbo 的容错机制 + /2020/11/22/%E8%81%8A%E8%81%8A-Dubbo-%E7%9A%84%E5%AE%B9%E9%94%99%E6%9C%BA%E5%88%B6/ + 之前看了 dubbo 的一些代码,在学习过程中,主要关注那些比较“高级”的内容,SPI,自适应扩展等,却忘了一些作为一个 rpc 框架最核心需要的部分,比如如何通信,序列化,网络,容错机制等等,因为其实这个最核心的就是远程调用,自适应扩展其实就是让代码可扩展性,可读性,更优雅等,写的搓一点其实也问题不大,但是一个合适的通信协议,序列化方法,如何容错等却是真正保证是一个 rpc 框架最重要的要素。
    首先来看这张图
    cluster
    在集群调用失败时,Dubbo 提供了多种容错方案,缺省为 failover 重试。
    各节点关系:

    +
      +
    • 这里的 InvokerProvider 的一个可调用 Service 的抽象,Invoker 封装了 Provider 地址及 Service 接口信息
    • +
    • Directory 代表多个 Invoker,可以把它看成 List<Invoker> ,但与 List 不同的是,它的值可能是动态变化的,比如注册中心推送变更
    • +
    • ClusterDirectory 中的多个 Invoker 伪装成一个 Invoker,对上层透明,伪装过程包含了容错逻辑,调用失败后,重试另一个
    • +
    • Router 负责从多个 Invoker 中按路由规则选出子集,比如读写分离,应用隔离等
    • +
    • LoadBalance 负责从多个 Invoker 中选出具体的一个用于本次调用,选的过程包含了负载均衡算法,调用失败后,需要重选
    • +
    +

    集群容错模式

    Failover Cluster

    失败自动切换,当出现失败,重试其它服务器 1。通常用于读操作,但重试会带来更长延迟。可通过 retries=”2” 来设置重试次数(不含第一次)。

    +

    重试次数配置如下:

    +

    <dubbo:service retries=”2” />
    这里重点看下 Failover Cluster集群模式的实现

    +
    public class FailoverCluster implements Cluster {
    +
    +    public final static String NAME = "failover";
    +
    +    public <T> Invoker<T> join(Directory<T> directory) throws RpcException {
    +        return new FailoverClusterInvoker<T>(directory);
    +    }
    +
    +}
    +

    这个代码就非常简单,重点需要看FailoverClusterInvoker里的代码,FailoverClusterInvoker继承了AbstractClusterInvoker类,其中invoke 方法是在抽象类里实现的

    +
    @Override
    +public Result invoke(final Invocation invocation) throws RpcException {
    +    checkWhetherDestroyed();
    +    // binding attachments into invocation.
    +    // 绑定 attachments 到 invocation 中.
    +    Map<String, Object> contextAttachments = RpcContext.getContext().getObjectAttachments();
    +    if (contextAttachments != null && contextAttachments.size() != 0) {
    +        ((RpcInvocation) invocation).addObjectAttachments(contextAttachments);
    +    }
    +    // 列举 Invoker
    +    List<Invoker<T>> invokers = list(invocation);
    +    // 加载 LoadBalance 负载均衡器
    +    LoadBalance loadbalance = initLoadBalance(invokers, invocation);
    +    RpcUtils.attachInvocationIdIfAsync(getUrl(), invocation);
    +    // 调用 实际的 doInvoke 进行后续操作
    +    return doInvoke(invocation, invokers, loadbalance);
    +}
    +// 这是个抽象方法,实际是由子类实现的
    + protected abstract Result doInvoke(Invocation invocation, List<Invoker<T>> invokers,
    +                                       LoadBalance loadbalance) throws RpcException;
    +

    然后重点就是FailoverClusterInvoker中的doInvoke方法了,其实它里面也就这么一个方法

    +
    @Override
    +    @SuppressWarnings({"unchecked", "rawtypes"})
    +    public Result doInvoke(Invocation invocation, final List<Invoker<T>> invokers, LoadBalance loadbalance) throws RpcException {
    +        List<Invoker<T>> copyInvokers = invokers;
    +        checkInvokers(copyInvokers, invocation);
    +        String methodName = RpcUtils.getMethodName(invocation);
    +        // 获取重试次数,这里默认是 2 次,还有可以注意下后面的+1
    +        int len = getUrl().getMethodParameter(methodName, RETRIES_KEY, DEFAULT_RETRIES) + 1;
    +        if (len <= 0) {
    +            len = 1;
    +        }
    +        // retry loop.
    +        RpcException le = null; // last exception.
    +        List<Invoker<T>> invoked = new ArrayList<Invoker<T>>(copyInvokers.size()); // invoked invokers.
    +        Set<String> providers = new HashSet<String>(len);
    +        // 循环调用,失败重试
    +        for (int i = 0; i < len; i++) {
    +            //Reselect before retry to avoid a change of candidate `invokers`.
    +            //NOTE: if `invokers` changed, then `invoked` also lose accuracy.
    +            if (i > 0) {
    +                checkWhetherDestroyed();
    +                // 在进行重试前重新列举 Invoker,这样做的好处是,如果某个服务挂了,
    +                // 通过调用 list 可得到最新可用的 Invoker 列表
    +                copyInvokers = list(invocation);
    +                // check again
    +                // 对 copyinvokers 进行判空检查
    +                checkInvokers(copyInvokers, invocation);
    +            }
    +            // 通过负载均衡来选择 invoker
    +            Invoker<T> invoker = select(loadbalance, invocation, copyInvokers, invoked);
    +            // 将其添加到 invoker 到 invoked 列表中
    +            invoked.add(invoker);
    +            // 设置上下文
    +            RpcContext.getContext().setInvokers((List) invoked);
    +            try {
    +                // 正式调用
    +                Result result = invoker.invoke(invocation);
    +                if (le != null && logger.isWarnEnabled()) {
    +                    logger.warn("Although retry the method " + methodName
    +                            + " in the service " + getInterface().getName()
    +                            + " was successful by the provider " + invoker.getUrl().getAddress()
    +                            + ", but there have been failed providers " + providers
    +                            + " (" + providers.size() + "/" + copyInvokers.size()
    +                            + ") from the registry " + directory.getUrl().getAddress()
    +                            + " on the consumer " + NetUtils.getLocalHost()
    +                            + " using the dubbo version " + Version.getVersion() + ". Last error is: "
    +                            + le.getMessage(), le);
    +                }
    +                return result;
    +            } catch (RpcException e) {
    +                if (e.isBiz()) { // biz exception.
    +                    throw e;
    +                }
    +                le = e;
    +            } catch (Throwable e) {
    +                le = new RpcException(e.getMessage(), e);
    +            } finally {
    +                providers.add(invoker.getUrl().getAddress());
    +            }
    +        }
    +        throw new RpcException(le.getCode(), "Failed to invoke the method "
    +                + methodName + " in the service " + getInterface().getName()
    +                + ". Tried " + len + " times of the providers " + providers
    +                + " (" + providers.size() + "/" + copyInvokers.size()
    +                + ") from the registry " + directory.getUrl().getAddress()
    +                + " on the consumer " + NetUtils.getLocalHost() + " using the dubbo version "
    +                + Version.getVersion() + ". Last error is: "
    +                + le.getMessage(), le.getCause() != null ? le.getCause() : le);
    +    }
    -

    https://img.nicksxs.com/uPic/LMzMtR.png

    -

    可以看到变成了重量级锁。

    + +

    Failfast Cluster

    快速失败,只发起一次调用,失败立即报错。通常用于非幂等性的写操作,比如新增记录。

    +

    Failsafe Cluster

    失败安全,出现异常时,直接忽略。通常用于写入审计日志等操作。

    +

    Failback Cluster

    失败自动恢复,后台记录失败请求,定时重发。通常用于消息通知操作。

    +

    Forking Cluster

    并行调用多个服务器,只要一个成功即返回。通常用于实时性要求较高的读操作,但需要浪费更多服务资源。可通过 forks=”2” 来设置最大并行数。

    +

    Broadcast Cluster

    广播调用所有提供者,逐个调用,任意一台报错则报错 2。通常用于通知所有提供者更新缓存或日志等本地资源信息。

    ]]>
    Java + Dubbo - RPC + Dubbo + 容错机制 Java - Synchronized - 偏向锁 - 轻量级锁 - 重量级锁 - 自旋 + Dubbo + RPC + 容错机制
    @@ -17414,163 +17468,28 @@ public Result invoke(final Invocation invocation) throws RpcException {
    • 验证

    -
      -
    1. 文件格式验证
    2. -
    3. 元数据验证
    4. -
    5. 字节码验证
    6. -
    7. 符号引用验证
    8. -
    -
      -
    • 准备

      准备阶段是正式为类中定义的变量(即静态变量,被static修饰的变量)分配内存并设置类变量初始值的阶段

      -
    • -
    • 解析

      解析阶段是 Java 虚拟机将常量池内的符号引用替换为直接引用的过程

      -
    • -
    -

    以上验证准备解析 三个阶段又合称为链接阶段,链接阶段要做的是将加载到JVM中的二进制字节流的类数据信息合并到JVM的运行时状态中。

    -
      -
    • 初始化

      类的初始化阶段是类加载过程的最后一个步骤,也是除了自定义类加载器之外将主动权交给了应用程序,其实就是执行类构造器()方法的过程,()并不是我们在 Java 代码中直接编写的方法,它是 Javac编译器的自动生成物,()方法是由编译器自动收集类中的所有类变量的复制动作和静态句块(static{}块)中的语句合并产生的,编译器收集的顺序是由语句在原文件中出现的顺序决定的,静态语句块中只能访问定义在静态语句块之前的变量,定义在它之后的变量,在前面的静态语句块可以复制,但是不能访问,同时还要保证父类的执行先于子类,然后保证多线程下的并发问题
    • -
    -

    最终,方法区会存储当前类类信息,包括类的静态变量、类初始化代码(定义静态变量时的赋值语句 和 静态初始化代码块)、实例变量定义、实例初始化代码(定义实例变量时的赋值语句实例代码块和构造方法)和实例方法,还有父类的类信息引用。

    -]]> - - Java - 类加载 - -
    - - 聊聊 Java 的 equals 和 hashCode 方法 - /2021/01/03/%E8%81%8A%E8%81%8A-Java-%E7%9A%84-equals-%E5%92%8C-hashCode-%E6%96%B9%E6%B3%95/ - Java 中的这个话题也是比较常遇到的,关于这块原先也是比较忽略的,但是仔细想想又有点遗忘了就在这里记一下
    简单看下代码
    java.lang.Object#equals

    -
    public boolean equals(Object obj) {
    -        return (this == obj);
    -    }
    -

    对于所有对象的父类,equals 方法其实对比的就是对象的地址,也就是是否是同一个对象,试想如果像 Integer 或者 String 这种,我们没有重写 equals,那其实就等于是在用==,可能就没法达到我们的目的,所以像 String 这种常用的 jdk 类都是默认重写了
    java.lang.String#equals

    -
    public boolean equals(Object anObject) {
    -        if (this == anObject) {
    -            return true;
    -        }
    -        if (anObject instanceof String) {
    -            String anotherString = (String)anObject;
    -            int n = value.length;
    -            if (n == anotherString.value.length) {
    -                char v1[] = value;
    -                char v2[] = anotherString.value;
    -                int i = 0;
    -                while (n-- != 0) {
    -                    if (v1[i] != v2[i])
    -                        return false;
    -                    i++;
    -                }
    -                return true;
    -            }
    -        }
    -        return false;
    -    }
    -

    然后呢就是为啥一些书或者 effective java 中写了 equalshashCode 要一起重写,这里涉及到当对象作为 HashMapkey 的时候
    首先 HashMap 会使用 hashCode 去判断是否在同一个槽里,然后在通过 equals 去判断是否是同一个 key,是的话就替换,不是的话就链表接下去,如果不重写 hashCode 的话,默认的 objecthashCodenative 方法,根据对象的地址生成的,这样其实对象的值相同的话,因为地址不同,HashMap 也会出现异常,所以需要重写,同时也需要重写 equals 方法,才能确认是同一个 key,而不是落在同一个槽的不同 key.

    -]]>
    - - java - - - java - -
    - - 聊聊 Dubbo 的 SPI - /2020/05/31/%E8%81%8A%E8%81%8A-Dubbo-%E7%9A%84-SPI/ - SPI全称是Service Provider Interface,咋眼看跟api是不是有点相似,api是application interface,这两个其实在某些方面有类似的地方,也有蛮大的区别,比如我们基于 dubbo 的微服务,一般我们可以提供服务,然后非泛化调用的话,我们可以把 api 包提供给应用调用方,他们根据接口签名传对应参数并配置好对应的服务发现如 zk 等就可以调用我们的服务了,然后 spi 会有点类似但是是反过来的关系,相当于是一种规范,比如我约定完成这个功能需要两个有两个接口,一个是连接的,一个是断开的,其实就可以用 jdbc 的驱动举例,比较老套了,然后各个厂家去做具体的实现吧,到时候根据我接口的全限定名的文件来加载实际的实现类,然后运行的时候调用对应实现类的方法就完了

    -

    3sKdpg

    -

    看上面的图,java.sql.Driver就是 spi,对应在classpath 的 META-INF/services 目录下的这个文件,里边的内容就是具体的实现类

    -

    1590735097909

    -

    简单介绍了 Java的 SPI,再来说说 dubbo 的,dubbo 中为啥要用 SPI 呢,主要是为了框架的可扩展性和性能方面的考虑,比如协议层 dubbo 默认使用 dubbo 协议,同时也支持很多其他协议,也支持用户自己实现协议,那么跟 Java 的 SPI 会有什么区别呢,我们也来看个文件

    -

    bqxWMp

    -

    是不是看着很想,又有点不一样,在 Java 的 SPI 配置文件里每一行只有一个实现类的全限定名,在 Dubbo的 SPI配置文件中是 key=value 的形式,我们只需要对应的 key 就能加载对应的实现,

    -
    /**
    -     * 返回指定名字的扩展。如果指定名字的扩展不存在,则抛异常 {@link IllegalStateException}.
    -     *
    -     * @param name
    -     * @return
    -     */
    -	@SuppressWarnings("unchecked")
    -	public T getExtension(String name) {
    -		if (name == null || name.length() == 0)
    -		    throw new IllegalArgumentException("Extension name == null");
    -		if ("true".equals(name)) {
    -		    return getDefaultExtension();
    -		}
    -		Holder<Object> holder = cachedInstances.get(name);
    -		if (holder == null) {
    -		    cachedInstances.putIfAbsent(name, new Holder<Object>());
    -		    holder = cachedInstances.get(name);
    -		}
    -		Object instance = holder.get();
    -		if (instance == null) {
    -		    synchronized (holder) {
    -	            instance = holder.get();
    -	            if (instance == null) {
    -	                instance = createExtension(name);
    -	                holder.set(instance);
    -	            }
    -	        }
    -		}
    -		return (T) instance;
    -	}
    -

    这里其实就可以看出来第二个不同点了,就是这个cachedInstances,第一个是不用像 Java 原生的 SPI 那样去遍历加载对应的服务类,只需要通过 key 去寻找,并且寻找的时候会先从缓存的对象里去取,还有就是注意下这里的 DCL(double check lock)

    -
    @SuppressWarnings("unchecked")
    -    private T createExtension(String name) {
    -        Class<?> clazz = getExtensionClasses().get(name);
    -        if (clazz == null) {
    -            throw findException(name);
    -        }
    -        try {
    -            T instance = (T) EXTENSION_INSTANCES.get(clazz);
    -            if (instance == null) {
    -                EXTENSION_INSTANCES.putIfAbsent(clazz, (T) clazz.newInstance());
    -                instance = (T) EXTENSION_INSTANCES.get(clazz);
    -            }
    -            injectExtension(instance);
    -            Set<Class<?>> wrapperClasses = cachedWrapperClasses;
    -            if (wrapperClasses != null && wrapperClasses.size() > 0) {
    -                for (Class<?> wrapperClass : wrapperClasses) {
    -                    instance = injectExtension((T) wrapperClass.getConstructor(type).newInstance(instance));
    -                }
    -            }
    -            return instance;
    -        } catch (Throwable t) {
    -            throw new IllegalStateException("Extension instance(name: " + name + ", class: " +
    -                    type + ")  could not be instantiated: " + t.getMessage(), t);
    -        }
    -    }
    -

    然后就是创建扩展了,这里如果 wrapperClasses 就会遍历生成wrapper实例,并做 setter 依赖注入,但是这里cachedWrapperClasses的来源还是有点搞不清楚,得再看下 com.alibaba.dubbo.common.extension.ExtensionLoader#loadFile的具体逻辑
    又看了遍新的代码,这个函数被抽出来了

    -
    /**
    -    * test if clazz is a wrapper class
    -    * <p>
    -    * which has Constructor with given class type as its only argument
    -    */
    -   private boolean isWrapperClass(Class<?> clazz) {
    -       try {
    -           clazz.getConstructor(type);
    -           return true;
    -       } catch (NoSuchMethodException e) {
    -           return false;
    -       }
    -   }
    -

    是否是 wrapperClass 其实就看构造函数的。

    +
      +
    1. 文件格式验证
    2. +
    3. 元数据验证
    4. +
    5. 字节码验证
    6. +
    7. 符号引用验证
    8. +
    +
      +
    • 准备

      准备阶段是正式为类中定义的变量(即静态变量,被static修饰的变量)分配内存并设置类变量初始值的阶段

      +
    • +
    • 解析

      解析阶段是 Java 虚拟机将常量池内的符号引用替换为直接引用的过程

      +
    • +
    +

    以上验证准备解析 三个阶段又合称为链接阶段,链接阶段要做的是将加载到JVM中的二进制字节流的类数据信息合并到JVM的运行时状态中。

    +
      +
    • 初始化

      类的初始化阶段是类加载过程的最后一个步骤,也是除了自定义类加载器之外将主动权交给了应用程序,其实就是执行类构造器()方法的过程,()并不是我们在 Java 代码中直接编写的方法,它是 Javac编译器的自动生成物,()方法是由编译器自动收集类中的所有类变量的复制动作和静态句块(static{}块)中的语句合并产生的,编译器收集的顺序是由语句在原文件中出现的顺序决定的,静态语句块中只能访问定义在静态语句块之前的变量,定义在它之后的变量,在前面的静态语句块可以复制,但是不能访问,同时还要保证父类的执行先于子类,然后保证多线程下的并发问题
    • +
    +

    最终,方法区会存储当前类类信息,包括类的静态变量、类初始化代码(定义静态变量时的赋值语句 和 静态初始化代码块)、实例变量定义、实例初始化代码(定义实例变量时的赋值语句实例代码块和构造方法)和实例方法,还有父类的类信息引用。

    ]]>
    Java - Dubbo - RPC - Dubbo - SPI - SPI + 类加载 - - Java - Dubbo - RPC - SPI -
    聊聊 Java 的类加载机制二 @@ -18407,18 +18326,6 @@ public Result invoke(final Invocation invocation) throws RpcException { JMap - - 聊一下关于怎么陪伴学习 - /2022/11/06/%E8%81%8A%E4%B8%80%E4%B8%8B%E5%85%B3%E4%BA%8E%E6%80%8E%E4%B9%88%E9%99%AA%E4%BC%B4%E5%AD%A6%E4%B9%A0/ - 这是一次开车过程中结合网上的一些微博想到的,开车是之前LD买了车后,陪领导练车,其实在一开始练车的时候,我们已经是找了相对很空的封闭路段,路上基本很少有车,偶尔有一辆车,但是LD还是很害怕,车速还只有十几的时候,还很远的对面来车的时候就觉得很慌了,这个时候如果以常理肯定会说这样子完全不用怕,如果克服恐惧真的这么容易的话,问题就不会那么纠结了,人生是很难完全感同身受的,唯有降低预设的基准让事情从头理清楚,害怕了我们就先休息,有车了我们就停下,先适应完全没车的情况,变得更慢一点,如果这时候着急一点,反而会起到反效果,比如只是说不要怕,接着开,甚至有点厌烦了,那基本这个练车也不太成得了了,而正好是有耐心的一起慢慢练习,还有就是第二件是切身体会,就是当道路本来是两条道,但是封了一条的时候,这时候开车如果是像我这样的新手,如果开车时左右边看着的话,车肯定开不好,因为那样会一直左右调整,反而更容易控制不好左右的距离,蹭到旁边的隔离栏,正确的方式应该是专注于正前方的路,这样才能保证左右边距离尽可能均匀,而不是顾左失右或者顾右失左,所以很多陪伴学习需要注意的是方式和耐心,能够识别到关键点那是最好的,但是有时候更需要的是耐心,纯靠耐心不一定能解决问题,但是可能会找到问题关键点。

    -]]>
    - - 生活 - - - 生活 - -
    聊聊 Linux 下的 top 命令 /2021/03/28/%E8%81%8A%E8%81%8A-Linux-%E4%B8%8B%E7%9A%84-top-%E5%91%BD%E4%BB%A4/ @@ -18467,6 +18374,96 @@ public Result invoke(final Invocation invocation) throws RpcException { top + + 聊聊 Sharding-Jdbc 分库分表下的分页方案 + /2022/01/09/%E8%81%8A%E8%81%8A-Sharding-Jdbc-%E5%88%86%E5%BA%93%E5%88%86%E8%A1%A8%E4%B8%8B%E7%9A%84%E5%88%86%E9%A1%B5%E6%96%B9%E6%A1%88/ + 前面在聊 Sharding-Jdbc 的时候看到了一篇文章,关于一个分页的查询,一直比较直接的想法就是分库分表下的分页是非常不合理的,一般我们的实操方案都是分表加上 ES 搜索做分页,或者通过合表读写分离的方案,因为对于 sharding-jdbc 如果没有带分表键,查询基本都是只能在所有分表都执行一遍,然后再加上分页,基本上是分页越大后续的查询越耗资源,但是仔细的去想这个细节还是这次,就简单说说
    首先就是我的分表结构

    +
    CREATE TABLE `student_time_0` (
    +  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
    +  `user_id` int(11) NOT NULL,
    +  `name` varchar(200) COLLATE utf8_bin DEFAULT NULL,
    +  `age` tinyint(3) unsigned DEFAULT NULL,
    +  `create_time` bigint(20) DEFAULT NULL,
    +  PRIMARY KEY (`id`)
    +) ENGINE=InnoDB AUTO_INCREMENT=674 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
    +

    有这样的三个表,student_time_0, student_time_1, student_time_2, 以 user_id 作为分表键,根据表数量取模作为分表依据
    这里先构造点数据,

    +
    insert into student_time (`name`, `user_id`, `age`, `create_time`) values (?, ?, ?, ?)
    +

    主要是为了保证 create_time 唯一比较好说明问题,

    +
    int i = 0;
    +try (
    +        Connection conn = dataSource.getConnection();
    +        PreparedStatement ps = conn.prepareStatement(insertSql)) {
    +    do {
    +        ps.setString(1, localName + new Random().nextInt(100));
    +        ps.setLong(2, 10086L + (new Random().nextInt(100)));
    +        ps.setInt(3, 18);
    +        ps.setLong(4, new Date().getTime());
    +
    +
    +        int result = ps.executeUpdate();
    +        LOGGER.info("current execute result: {}", result);
    +        Thread.sleep(new Random().nextInt(100));
    +        i++;
    +    } while (i <= 2000);
    +

    三个表的数据分别是 673,678,650,说明符合预期了,各个表数据不一样,接下来比如我们想要做一个这样的分页查询

    +
    select * from student_time ORDER BY create_time ASC limit 1000, 5;
    +

    student_time 对于我们使用的 sharding-jdbc 来说当然是逻辑表,首先从一无所知去想这个查询如果我们自己来处理应该是怎么做,
    首先是不是可以每个表都从 333 开始取 5 条数据,类似于下面的查询,然后进行 15 条的合并重排序获取前面的 5 条

    +
    select * from student_time_0 ORDER BY create_time ASC limit 333, 5;
    +select * from student_time_1 ORDER BY create_time ASC limit 333, 5;
    +select * from student_time_2 ORDER BY create_time ASC limit 333, 5;
    +

    忽略前面 limit 差的 1,这个结果除非三个表的分布是绝对的均匀,否则结果肯定会出现一定的偏差,以为每个表的 333 这个位置对于其他表来说都不一定是一样的,这样对于最后整体的结果,就会出现偏差
    因为一直在纠结怎么让这个更直观的表现出来,所以尝试画了个图

    黑色的框代表我从每个表里按排序从 334 到 338 的 5 条数据, 他们在每个表里都是代表了各自正确的排序值,但是对于我们想要的其实是合表后的 1001,1005 这五条,然后我们假设总的排序值位于前 1000 的分布是第 0 个表是 320 条,第 1 个表是 340 条,第 2 个表是 340 条,那么可以明显地看出来我这么查的结果简单合并肯定是不对的。
    那么 sharding-jdbc 是如何保证这个结果的呢,其实就是我在每个表里都查分页偏移量和分页大小那么多的数据,在我这个例子里就是对于 0,1,2 三个分表每个都查 1005 条数据,即使我的数据不平衡到最极端的情况,前 1005 条数据都出在某个分表中,也可以正确获得最后的结果,但是明显的问题就是大分页,数据较多,就会导致非常大的问题,即使如 sharding-jdbc 对于合并排序的优化做得比较好,也还是需要传输那么大量的数据,并且查询也耗时,那么有没有解决方案呢,应该说有两个,或者说主要是想讲后者
    第一个办法是像这种查询,如果业务上不需要进行跳页,而是只给下一页,那么我们就能把前一次的最大偏移量的 create_time 记录下来,下一页就可以拿着这个偏移量进行查询,这个比较简单易懂,就不多说了
    第二个办法是看的58 沈剑的一篇文章,尝试理解讲述一下,
    这个办法的第一步跟前面那个错误的方法或者说不准确的方法一样,先是将分页偏移量平均后在三个表里进行查询

    +
    t0
    +334 10158 nick95  18  1641548941767
    +335 10098 nick11  18  1641548941879
    +336 10167 nick51  18  1641548942089
    +337 10167 nick3 18  1641548942119
    +338 10170 nick57  18  1641548942169
    +
    +
    +t1
    +334 10105 nick98  18  1641548939071   最小
    +335 10174 nick94  18  1641548939377
    +336 10129 nick85  18  1641548939442
    +337 10141 nick84  18  1641548939480
    +338 10096 nick74  18  1641548939668
    +
    +t2
    +334 10184 nick11  18  1641548945075
    +335 10109 nick93  18  1641548945382
    +336 10181 nick41  18  1641548945583
    +337 10130 nick80  18  1641548945993
    +338 10184 nick19  18  1641548946294  最大
    +

    然后要做什么呢,其实目标比较明白,因为前面那种方法其实就是我知道了前一页的偏移量,所以可以直接当做条件来进行查询,那这里我也想着拿到这个条件,所以我将第一遍查出来的最小的 create_time 和最大的 create_time 找出来,然后再去三个表里查询,其实主要是最小值,因为我拿着最小值去查以后我就能知道这个最小值在每个表里处在什么位置,

    +
    t0
    +322 10161 nick81  18  1641548939284
    +323 10113 nick16  18  1641548939393
    +324 10110 nick56  18  1641548939577
    +325 10116 nick69  18  1641548939588
    +326 10173 nick51  18  1641548939646
    +
    +t1
    +334 10105 nick98  18  1641548939071
    +335 10174 nick94  18  1641548939377
    +336 10129 nick85  18  1641548939442
    +337 10141 nick84  18  1641548939480
    +338 10096 nick74  18  1641548939668
    +
    +t2
    +297 10136 nick28  18  1641548939161
    +298 10142 nick68  18  1641548939177
    +299 10124 nick41  18  1641548939237
    +300 10148 nick87  18  1641548939510
    +301 10169 nick23  18  1641548939715
    +

    我只贴了前五条数据,为了方便知道偏移量,每个分表都使用了自增主键,我们可以看到前一次查询的最小值分别在其他两个表里的位置分别是 322-1 和 297-1,那么对于总体来说这个时间应该是在 322 - 1 + 333 + 297 - 1 = 951,那这样子我只要对后面的数据最多每个表查 1000 - 951 + 5 = 54 条数据再进行合并排序就可以获得最终正确的结果。
    这个就是传说中的二次查询法。

    +]]>
    + + Java + + + Java + Sharding-Jdbc + +
    聊聊 RocketMQ 的 Broker 源码 /2020/07/19/%E8%81%8A%E8%81%8A-RocketMQ-%E7%9A%84-Broker-%E6%BA%90%E7%A0%81/ @@ -18964,151 +18961,32 @@ result = result 调用DefaultMessageStore.start方法启动DefaultMessageStore对象中的一些服务线程。

    -
      -
    1. 启动ReputMessageService服务线程
    2. -
    3. 启动FlushConsumeQueueService服务线程;
    4. -
    5. 调用CommitLog.start方法,启动CommitLog对象中的FlushCommitLogService线程服务,若是同步刷盘(SYNC_FLUSH)则是启动GroupCommitService线程服务;若是异步刷盘(ASYNC_FLUSH)则是启动FlushRealTimeService线程服务;
    6. -
    7. 启动StoreStatsService线程服务;
    8. -
    9. 启动定时清理任务
    10. -
    -

    然后是启动ClientHousekeepingService的 netty 服务端和客户端,然后是启动fileWatchService证书服务,接着启动BrokerOuterAPI中的NettyRemotingClient,即建立与NameServer的链接,用于自身Broker与其他模块的RPC功能调用;包括获取NameServer的地址、注册Broker、注销Broker、获取Topic配置、获取消息进度信息、获取订阅关系等RPC功能,然后是PullRequestHoldService服务线程,这个就是实现长轮询的,然后启动管家ClientHousekeepingService服务,负责扫描不活跃的生产者,消费者和 filter,启动FilterServerManager 过滤器服务管理,然后启动定时任务调用org.apache.rocketmq.broker.BrokerController#registerBrokerAll向所有 nameserver 注册 broker,最后是按需开启org.apache.rocketmq.store.stats.BrokerStatsManager和org.apache.rocketmq.broker.latency.BrokerFastFailure,基本上启动过程就完成了

    -]]> - - MQ - RocketMQ - 消息队列 - RocketMQ - 中间件 - RocketMQ - - - MQ - 消息队列 - RocketMQ - 削峰填谷 - 中间件 - 源码解析 - Broker - -
    - - 聊聊 Sharding-Jdbc 的简单原理初篇 - /2021/12/26/%E8%81%8A%E8%81%8A-Sharding-Jdbc-%E7%9A%84%E7%AE%80%E5%8D%95%E5%8E%9F%E7%90%86%E5%88%9D%E7%AF%87/ - 在上一篇 sharding-jdbc 的介绍中其实碰到过一个问题,这里也引出了一个比较有意思的话题
    就是我在执行 query 的时候犯过一个比较难发现的错误,

    -
    ResultSet resultSet = ps.executeQuery(sql);
    -

    实际上应该是

    -
    ResultSet resultSet = ps.executeQuery();
    -

    而这里的差别就是,是否传 sql 这个参数,首先我们要知道这个 ps 是什么,它也是个接口java.sql.PreparedStatement,而真正的实现类是org.apache.shardingsphere.driver.jdbc.core.statement.ShardingSpherePreparedStatement,我们来看下继承关系

    这里可以看到继承关系里有org.apache.shardingsphere.driver.jdbc.unsupported.AbstractUnsupportedOperationPreparedStatement
    那么在我上面的写错的代码里

    -
    @Override
    -public final ResultSet executeQuery(final String sql) throws SQLException {
    -    throw new SQLFeatureNotSupportedException("executeQuery with SQL for PreparedStatement");
    -}
    -

    这个报错一开始让我有点懵,后来点进去了发现是这么个异常,但是我其实一开始是用的更新语句,以为更新不支持,因为平时使用没有深究过,以为是不是需要使用 Mybatis 才可以执行更新,但是理论上也不应该,再往上看原来这些异常是由 sharding-jdbc 包装的,也就是在上面说的AbstractUnsupportedOperationPreparedStatement,这其实也是一种设计思想,本身 jdbc 提供了一系列接口,由各家去支持,包括 mysql,sql server,oracle 等,而正因为这个设计,所以 sharding-jdbc 也可以在此基础上进行设计,我们可以总体地看下 sharding-jdbc 的实现基础

    看了前面ShardingSpherePreparedStatement的继承关系,应该也能猜到这里的几个类都是实现了 jdbc 的基础接口,

    在前一篇的 demo 中的

    -
    Connection conn = dataSource.getConnection();
    -

    其实就获得了org.apache.shardingsphere.driver.jdbc.core.connection.ShardingSphereConnection#ShardingSphereConnection
    然后获得java.sql.PreparedStatement

    -
    PreparedStatement ps = conn.prepareStatement(sql)
    -

    就是获取了org.apache.shardingsphere.driver.jdbc.core.statement.ShardingSpherePreparedStatement
    然后就是执行

    -
    ResultSet resultSet = ps.executeQuery();
    -

    然后获得结果
    org.apache.shardingsphere.driver.jdbc.core.resultset.ShardingSphereResultSet

    -

    其实像 mybatis 也是基于这样去实现的

    -]]>
    - - Java - - - Java - Sharding-Jdbc - -
    - - 聊聊 Sharding-Jdbc 分库分表下的分页方案 - /2022/01/09/%E8%81%8A%E8%81%8A-Sharding-Jdbc-%E5%88%86%E5%BA%93%E5%88%86%E8%A1%A8%E4%B8%8B%E7%9A%84%E5%88%86%E9%A1%B5%E6%96%B9%E6%A1%88/ - 前面在聊 Sharding-Jdbc 的时候看到了一篇文章,关于一个分页的查询,一直比较直接的想法就是分库分表下的分页是非常不合理的,一般我们的实操方案都是分表加上 ES 搜索做分页,或者通过合表读写分离的方案,因为对于 sharding-jdbc 如果没有带分表键,查询基本都是只能在所有分表都执行一遍,然后再加上分页,基本上是分页越大后续的查询越耗资源,但是仔细的去想这个细节还是这次,就简单说说
    首先就是我的分表结构

    -
    CREATE TABLE `student_time_0` (
    -  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
    -  `user_id` int(11) NOT NULL,
    -  `name` varchar(200) COLLATE utf8_bin DEFAULT NULL,
    -  `age` tinyint(3) unsigned DEFAULT NULL,
    -  `create_time` bigint(20) DEFAULT NULL,
    -  PRIMARY KEY (`id`)
    -) ENGINE=InnoDB AUTO_INCREMENT=674 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
    -

    有这样的三个表,student_time_0, student_time_1, student_time_2, 以 user_id 作为分表键,根据表数量取模作为分表依据
    这里先构造点数据,

    -
    insert into student_time (`name`, `user_id`, `age`, `create_time`) values (?, ?, ?, ?)
    -

    主要是为了保证 create_time 唯一比较好说明问题,

    -
    int i = 0;
    -try (
    -        Connection conn = dataSource.getConnection();
    -        PreparedStatement ps = conn.prepareStatement(insertSql)) {
    -    do {
    -        ps.setString(1, localName + new Random().nextInt(100));
    -        ps.setLong(2, 10086L + (new Random().nextInt(100)));
    -        ps.setInt(3, 18);
    -        ps.setLong(4, new Date().getTime());
    -
    -
    -        int result = ps.executeUpdate();
    -        LOGGER.info("current execute result: {}", result);
    -        Thread.sleep(new Random().nextInt(100));
    -        i++;
    -    } while (i <= 2000);
    -

    三个表的数据分别是 673,678,650,说明符合预期了,各个表数据不一样,接下来比如我们想要做一个这样的分页查询

    -
    select * from student_time ORDER BY create_time ASC limit 1000, 5;
    -

    student_time 对于我们使用的 sharding-jdbc 来说当然是逻辑表,首先从一无所知去想这个查询如果我们自己来处理应该是怎么做,
    首先是不是可以每个表都从 333 开始取 5 条数据,类似于下面的查询,然后进行 15 条的合并重排序获取前面的 5 条

    -
    select * from student_time_0 ORDER BY create_time ASC limit 333, 5;
    -select * from student_time_1 ORDER BY create_time ASC limit 333, 5;
    -select * from student_time_2 ORDER BY create_time ASC limit 333, 5;
    -

    忽略前面 limit 差的 1,这个结果除非三个表的分布是绝对的均匀,否则结果肯定会出现一定的偏差,以为每个表的 333 这个位置对于其他表来说都不一定是一样的,这样对于最后整体的结果,就会出现偏差
    因为一直在纠结怎么让这个更直观的表现出来,所以尝试画了个图

    黑色的框代表我从每个表里按排序从 334 到 338 的 5 条数据, 他们在每个表里都是代表了各自正确的排序值,但是对于我们想要的其实是合表后的 1001,1005 这五条,然后我们假设总的排序值位于前 1000 的分布是第 0 个表是 320 条,第 1 个表是 340 条,第 2 个表是 340 条,那么可以明显地看出来我这么查的结果简单合并肯定是不对的。
    那么 sharding-jdbc 是如何保证这个结果的呢,其实就是我在每个表里都查分页偏移量和分页大小那么多的数据,在我这个例子里就是对于 0,1,2 三个分表每个都查 1005 条数据,即使我的数据不平衡到最极端的情况,前 1005 条数据都出在某个分表中,也可以正确获得最后的结果,但是明显的问题就是大分页,数据较多,就会导致非常大的问题,即使如 sharding-jdbc 对于合并排序的优化做得比较好,也还是需要传输那么大量的数据,并且查询也耗时,那么有没有解决方案呢,应该说有两个,或者说主要是想讲后者
    第一个办法是像这种查询,如果业务上不需要进行跳页,而是只给下一页,那么我们就能把前一次的最大偏移量的 create_time 记录下来,下一页就可以拿着这个偏移量进行查询,这个比较简单易懂,就不多说了
    第二个办法是看的58 沈剑的一篇文章,尝试理解讲述一下,
    这个办法的第一步跟前面那个错误的方法或者说不准确的方法一样,先是将分页偏移量平均后在三个表里进行查询

    -
    t0
    -334 10158 nick95  18  1641548941767
    -335 10098 nick11  18  1641548941879
    -336 10167 nick51  18  1641548942089
    -337 10167 nick3 18  1641548942119
    -338 10170 nick57  18  1641548942169
    -
    -
    -t1
    -334 10105 nick98  18  1641548939071   最小
    -335 10174 nick94  18  1641548939377
    -336 10129 nick85  18  1641548939442
    -337 10141 nick84  18  1641548939480
    -338 10096 nick74  18  1641548939668
    -
    -t2
    -334 10184 nick11  18  1641548945075
    -335 10109 nick93  18  1641548945382
    -336 10181 nick41  18  1641548945583
    -337 10130 nick80  18  1641548945993
    -338 10184 nick19  18  1641548946294  最大
    -

    然后要做什么呢,其实目标比较明白,因为前面那种方法其实就是我知道了前一页的偏移量,所以可以直接当做条件来进行查询,那这里我也想着拿到这个条件,所以我将第一遍查出来的最小的 create_time 和最大的 create_time 找出来,然后再去三个表里查询,其实主要是最小值,因为我拿着最小值去查以后我就能知道这个最小值在每个表里处在什么位置,

    -
    t0
    -322 10161 nick81  18  1641548939284
    -323 10113 nick16  18  1641548939393
    -324 10110 nick56  18  1641548939577
    -325 10116 nick69  18  1641548939588
    -326 10173 nick51  18  1641548939646
    -
    -t1
    -334 10105 nick98  18  1641548939071
    -335 10174 nick94  18  1641548939377
    -336 10129 nick85  18  1641548939442
    -337 10141 nick84  18  1641548939480
    -338 10096 nick74  18  1641548939668
    -
    -t2
    -297 10136 nick28  18  1641548939161
    -298 10142 nick68  18  1641548939177
    -299 10124 nick41  18  1641548939237
    -300 10148 nick87  18  1641548939510
    -301 10169 nick23  18  1641548939715
    -

    我只贴了前五条数据,为了方便知道偏移量,每个分表都使用了自增主键,我们可以看到前一次查询的最小值分别在其他两个表里的位置分别是 322-1 和 297-1,那么对于总体来说这个时间应该是在 322 - 1 + 333 + 297 - 1 = 951,那这样子我只要对后面的数据最多每个表查 1000 - 951 + 5 = 54 条数据再进行合并排序就可以获得最终正确的结果。
    这个就是传说中的二次查询法。

    +

    调用DefaultMessageStore.start方法启动DefaultMessageStore对象中的一些服务线程。

    +
      +
    1. 启动ReputMessageService服务线程
    2. +
    3. 启动FlushConsumeQueueService服务线程;
    4. +
    5. 调用CommitLog.start方法,启动CommitLog对象中的FlushCommitLogService线程服务,若是同步刷盘(SYNC_FLUSH)则是启动GroupCommitService线程服务;若是异步刷盘(ASYNC_FLUSH)则是启动FlushRealTimeService线程服务;
    6. +
    7. 启动StoreStatsService线程服务;
    8. +
    9. 启动定时清理任务
    10. +
    +

    然后是启动ClientHousekeepingService的 netty 服务端和客户端,然后是启动fileWatchService证书服务,接着启动BrokerOuterAPI中的NettyRemotingClient,即建立与NameServer的链接,用于自身Broker与其他模块的RPC功能调用;包括获取NameServer的地址、注册Broker、注销Broker、获取Topic配置、获取消息进度信息、获取订阅关系等RPC功能,然后是PullRequestHoldService服务线程,这个就是实现长轮询的,然后启动管家ClientHousekeepingService服务,负责扫描不活跃的生产者,消费者和 filter,启动FilterServerManager 过滤器服务管理,然后启动定时任务调用org.apache.rocketmq.broker.BrokerController#registerBrokerAll向所有 nameserver 注册 broker,最后是按需开启org.apache.rocketmq.store.stats.BrokerStatsManager和org.apache.rocketmq.broker.latency.BrokerFastFailure,基本上启动过程就完成了

    ]]>
    - Java + MQ + RocketMQ + 消息队列 + RocketMQ + 中间件 + RocketMQ - Java - Sharding-Jdbc + MQ + 消息队列 + RocketMQ + 削峰填谷 + 中间件 + 源码解析 + Broker
    @@ -19277,6 +19155,35 @@ t2 CachedThreadPool + + 聊聊 Sharding-Jdbc 的简单原理初篇 + /2021/12/26/%E8%81%8A%E8%81%8A-Sharding-Jdbc-%E7%9A%84%E7%AE%80%E5%8D%95%E5%8E%9F%E7%90%86%E5%88%9D%E7%AF%87/ + 在上一篇 sharding-jdbc 的介绍中其实碰到过一个问题,这里也引出了一个比较有意思的话题
    就是我在执行 query 的时候犯过一个比较难发现的错误,

    +
    ResultSet resultSet = ps.executeQuery(sql);
    +

    实际上应该是

    +
    ResultSet resultSet = ps.executeQuery();
    +

    而这里的差别就是,是否传 sql 这个参数,首先我们要知道这个 ps 是什么,它也是个接口java.sql.PreparedStatement,而真正的实现类是org.apache.shardingsphere.driver.jdbc.core.statement.ShardingSpherePreparedStatement,我们来看下继承关系

    这里可以看到继承关系里有org.apache.shardingsphere.driver.jdbc.unsupported.AbstractUnsupportedOperationPreparedStatement
    那么在我上面的写错的代码里

    +
    @Override
    +public final ResultSet executeQuery(final String sql) throws SQLException {
    +    throw new SQLFeatureNotSupportedException("executeQuery with SQL for PreparedStatement");
    +}
    +

    这个报错一开始让我有点懵,后来点进去了发现是这么个异常,但是我其实一开始是用的更新语句,以为更新不支持,因为平时使用没有深究过,以为是不是需要使用 Mybatis 才可以执行更新,但是理论上也不应该,再往上看原来这些异常是由 sharding-jdbc 包装的,也就是在上面说的AbstractUnsupportedOperationPreparedStatement,这其实也是一种设计思想,本身 jdbc 提供了一系列接口,由各家去支持,包括 mysql,sql server,oracle 等,而正因为这个设计,所以 sharding-jdbc 也可以在此基础上进行设计,我们可以总体地看下 sharding-jdbc 的实现基础

    看了前面ShardingSpherePreparedStatement的继承关系,应该也能猜到这里的几个类都是实现了 jdbc 的基础接口,

    在前一篇的 demo 中的

    +
    Connection conn = dataSource.getConnection();
    +

    其实就获得了org.apache.shardingsphere.driver.jdbc.core.connection.ShardingSphereConnection#ShardingSphereConnection
    然后获得java.sql.PreparedStatement

    +
    PreparedStatement ps = conn.prepareStatement(sql)
    +

    就是获取了org.apache.shardingsphere.driver.jdbc.core.statement.ShardingSpherePreparedStatement
    然后就是执行

    +
    ResultSet resultSet = ps.executeQuery();
    +

    然后获得结果
    org.apache.shardingsphere.driver.jdbc.core.resultset.ShardingSphereResultSet

    +

    其实像 mybatis 也是基于这样去实现的

    +]]>
    + + Java + + + Java + Sharding-Jdbc + +
    聊聊 mysql 的 MVCC 续篇 /2020/05/02/%E8%81%8A%E8%81%8A-mysql-%E7%9A%84-MVCC-%E7%BB%AD%E7%AF%87/ @@ -19292,195 +19199,12 @@ void ReadView::prepare(trx_id_t id) { m_creator_trx_id = id; m_low_limit_no = m_low_limit_id = m_up_limit_id = trx_sys->max_trx_id;
    -

    m_low_limit_id赋的值是trx_sys->max_trx_id,代表的是当前系统最小的未分配的事务 id,所以呢,举个例子,当前有三个活跃事务,事务 id 分别是 100,200,300,而 m_up_limit_id = 100, m_low_limit_id = 301,当事务 id 是 200 的提交之后,它的更新就是可以被 100 和 300 看到,而不是说 m_ids 里没了 200,并且 200 比 100 大就应该不可见了

    -

    幻读

    还有一个问题是幻读的问题,这貌似也是个高频面试题,啥意思呢,或者说跟它最常拿来比较的脏读,脏读是指读到了别的事务未提交的数据,因为未提交,严格意义上来讲,不一定是会被最后落到库里,可能会回滚,也就是在 read uncommitted 级别下会出现的问题,但是幻读不太一样,幻读是指两次查询的结果数量不一样,比如我查了第一次是 select * from table1 where id < 10 for update,查出来了一条结果 id 是 5,然后再查一下发现出来了一条 id 是 5,一条 id 是 7,那是不是有点尴尬了,其实呢这个点我觉得脏读跟幻读也比较是从原理层面来命名,如果第一次接触的同学发觉有点不理解也比较正常,因为从逻辑上讲总之都是数据不符合预期,但是基于源码层面其实是不同的情况,幻读是在原先的 read view 无法完全解决的,怎么解决呢,简单的来说就是锁咯,我们知道innodb 是基于 record lock 行锁的,但是貌似没有办法解决这种问题,那么 innodb 就引入了 gap lock 间隙锁,比如上面说的情况下,id 小于 10 的情况下,是都应该锁住的,gap lock 其实是基于索引结构来锁的,因为索引树除了树形结构之外,还有一个next record 的指针,gap lock 也是基于这个来锁的
    看一下 mysql 的文档

    -
    -

    SELECT … FOR UPDATE sets an exclusive next-key lock on every record the search encounters. However, only an index record lock is required for statements that lock rows using a unique index to search for a unique row.

    -
    -

    对于一个 for update 查询,在 RR 级别下,会设置一个 next-key lock在每一条被查询到的记录上,next-lock 又是啥呢,其实就是 gap 锁和 record 锁的结合体,比如我在数据库里有 id 是 1,3,5,7,10,对于上面那条查询,查出来的结果就是 1,3,5,7,那么按照文档里描述的,对于这几条记录都会加上next-key lock,也就是(-∞, 1], (1, 3], (3, 5], (5, 7], (7, 10) 这些区间和记录会被锁起来,不让插入,再唠叨一下呢,就是其实如果是只读的事务,光 read view 一致性读就够了,如果是有写操作的呢,就需要锁了。

    -]]> - - Mysql - C - 数据结构 - 源码 - Mysql - - - mysql - 数据结构 - 源码 - mvcc - read view - gap lock - next-key lock - 幻读 - - - - 聊聊 mysql 的 MVCC 续续篇之锁分析 - /2020/05/10/%E8%81%8A%E8%81%8A-mysql-%E7%9A%84-MVCC-%E7%BB%AD%E7%BB%AD%E7%AF%87%E4%B9%8B%E5%8A%A0%E9%94%81%E5%88%86%E6%9E%90/ - 看完前面两篇水文之后,感觉不得不来分析下 mysql 的锁了,其实前面说到幻读的时候是有个前提没提到的,比如一个select * from table1 where id = 1这种查询语句其实是不会加传说中的锁的,当然这里是指在 RR 或者 RC 隔离级别下,
    看一段 mysql官方文档

    -
    -

    SELECT ... FROM is a consistent read, reading a snapshot of the database and setting no locks unless the transaction isolation level is set to SERIALIZABLE. For SERIALIZABLE level, the search sets shared next-key locks on the index records it encounters. However, only an index record lock is required for statements that lock rows using a unique index to search for a unique row.

    -
    -

    纯粹的这种一致性读,实际读取的是快照,也就是基于 read view 的读取方式,除非当前隔离级别是SERIALIZABLE
    但是对于以下几类

    -
      -
    • select * from table where ? lock in share mode;
    • -
    • select * from table where ? for update;
    • -
    • insert into table values (...);
    • -
    • update table set ? where ?;
    • -
    • delete from table where ?;
    • -
    -

    除了第一条是 S 锁之外,其他都是 X 排他锁,这边在顺带下,S 锁表示共享锁, X 表示独占锁,同为 S 锁之间不冲突,S 与 X,X 与 S,X 与 X 之间都冲突,也就是加了前者,后者就加不上了
    我们知道对于 RC 级别会出现幻读现象,对于 RR 级别不会出现,主要的区别是 RR 级别下对于以上的加锁读取都根据情况加上了 gap 锁,那么是不是 RR 级别下以上所有的都是要加 gap 锁呢,当然不是
    举个例子,RR 事务隔离级别下,table1 有个主键id 字段
    select * from table1 where id = 10 for update
    这条语句要加 gap 锁吗?
    答案是不需要,这里其实算是我看了这么久的一点自己的理解,啥时候要加 gap 锁,判断的条件是根据我查询的数据是否会因为不加 gap 锁而出现数量的不一致,我上面这条查询语句,在什么情况下会出现查询结果数量不一致呢,只要在这条记录被更新或者删除的时候,有没有可能我第一次查出来一条,第二次变成两条了呢,不可能,因为是主键索引。
    再变更下这个题的条件,当 id 不是主键,但是是唯一索引,这样需要怎么加锁,注意问题是怎么加锁,不是需不需要加 gap 锁,这里呢就是稍微延伸一下,把聚簇索引(主键索引)和二级索引带一下,当 id 不是主键,说明是个二级索引,但是它是唯一索引,体会下,首先对于 id = 10这个二级索引肯定要加锁,要不要锁 gap 呢,不用,因为是唯一索引,id = 10 只可能有这一条记录,然后呢,这样是不是就好了,还不行,因为啥,因为它是二级索引,对应的主键索引的记录才是真正的数据,万一被更新掉了咋办,所以在 id = 10 对应的主键索引上也需要加上锁(默认都是 record lock行锁),那主键索引上要不要加 gap 呢,也不用,也是精确定位到这一条记录
    最后呢,当 id 不是主键,也不是唯一索引,只是个普通的索引,这里就需要大名鼎鼎的 gap 锁了,
    是时候画个图了

    其实核心的目的还是不让这个 id=10 的记录不会出现幻读,那么就需要在 id 这个索引上加上三个 gap 锁,主键索引上就不用了,在 id 索引上已经控制住了id = 10 不会出现幻读,主键索引上这两条对应的记录已经锁了,所以就这样 OK 了

    -]]>
    - - Mysql - C - 数据结构 - 源码 - Mysql - - - mysql - 数据结构 - 源码 - mvcc - read view - gap lock - next-key lock - 幻读 - -
    - - 聊聊 mysql 索引的一些细节 - /2020/12/27/%E8%81%8A%E8%81%8A-mysql-%E7%B4%A2%E5%BC%95%E7%9A%84%E4%B8%80%E4%BA%9B%E7%BB%86%E8%8A%82/ - 前几天同事问了我个 mysql 索引的问题,虽然大概知道,但是还是想来实践下,就是 is null,is not null 这类查询是否能用索引,可能之前有些网上的文章说都是不能用索引,但是其实不是,我们来看个小试验

    -
    CREATE TABLE `null_index_t` (
    -  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    -  `null_key` varchar(255) DEFAULT NULL,
    -  `null_key1` varchar(255) DEFAULT NULL,
    -  `null_key2` varchar(255) DEFAULT NULL,
    -  PRIMARY KEY (`id`),
    -  KEY `idx_1` (`null_key`) USING BTREE,
    -  KEY `idx_2` (`null_key1`) USING BTREE,
    -  KEY `idx_3` (`null_key2`) USING BTREE
    -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
    -

    用个存储过程来插入数据

    -
    
    -delimiter $	#以delimiter来标记用$表示存储过程结束
    -create procedure nullIndex1()
    -begin
    -declare i int;	
    -declare j int;	
    -set i=1;
    -set j=1;
    -while(i<=100) do	
    -	while(j<=100) do	
    -		IF (i % 3 = 0) THEN
    -	     INSERT INTO null_index_t ( `null_key`, `null_key1`, `null_key2` ) VALUES (null , LEFT(MD5(RAND()), 8), LEFT(MD5(RAND()), 8));
    -    ELSEIF (i % 3 = 1) THEN
    -			 INSERT INTO null_index_t ( `null_key`, `null_key1`, `null_key2` ) VALUES (LEFT(MD5(RAND()), 8), NULL, LEFT(MD5(RAND()), 8));
    -	  ELSE
    -			 INSERT INTO null_index_t ( `null_key`, `null_key1`, `null_key2` ) VALUES (LEFT(MD5(RAND()), 8), LEFT(MD5(RAND()), 8), NULL);
    -    END IF;
    -		set j=j+1;
    -	end while;
    -	set i=i+1;
    -	set j=1;	
    -end while;
    -end 
    -$
    -call nullIndex1();
    -

    然后看下我们的 is null 查询

    -
    EXPLAIN select * from null_index_t WHERE null_key is null;
    -


    再来看看另一个

    -
    EXPLAIN select * from null_index_t WHERE null_key is not null;
    -


    从这里能看出来啥呢,可以思考下

    -

    从上面可以发现,is null应该是用上了索引了,所以至少不是一刀切不能用,但是看着is not null好像不太行额
    我们在做一点小改动,把这个表里的数据改成 9100 条是 null,剩下 900 条是有值的,然后再执行下

    然后再来看看执行结果

    -
    EXPLAIN select * from null_index_t WHERE null_key is null;
    -

    -
    EXPLAIN select * from null_index_t WHERE null_key is not null;
    -


    是不是不一样了,这里再补充下我试验使用的 mysql 是 5.7 的,不保证在其他版本的一致性,
    其实可以看出随着数据量的变化,mysql 会不会使用索引是会变化的,不是说 is not null 一定会使用,也不是一定不会使用,而是优化器会根据查询成本做个预判,这个预判尽可能会减小查询成本,主要包括回表啥的,但是也不一定完全准确。

    -]]>
    - - Mysql - C - 索引 - Mysql - - - mysql - 索引 - is null - is not null - procedure - -
    - - 聊聊 mysql 的 MVCC - /2020/04/26/%E8%81%8A%E8%81%8A-mysql-%E7%9A%84-MVCC/ - 很久以前,有位面试官问到,你知道 mysql 的事务隔离级别吗,“额 O__O …,不太清楚”,完了之后我就去网上找相关的文章,找到了这篇MySQL 四种事务隔离级的说明, 文章写得特别好,看了这个就懂了各个事务隔离级别都是啥,不过看了这个之后多思考一下的话还是会发现问题,这么神奇的事务隔离级别是怎么实现的呢

    -

    其中 innodb 的事务隔离用到了标题里说到的 mvcc,Multiversion concurrency control, 直译过来就是多版本并发控制,先不讲这个究竟是个啥,考虑下如果纯猜测,这个事务隔离级别应该会是怎么样实现呢,愚钝的我想了下,可以在事务开始的时候拷贝一个表,这个可以支持 RR 级别,RC 级别就不支持了,而且要是个非常大的表,想想就不可行

    -

    腆着脸说虽然这个不可行,但是思路是对的,具体实行起来需要做一系列(肥肠多)的改动,首先根据我的理解,其实这个拷贝一个表是变成拷贝一条记录,但是如果有多个事务,那就得拷贝多次,这个问题其实可以借助版本管理系统来解释,在用版本管理系统,git 之类的之前,很原始的可能是开发完一个功能后,就打个压缩包用时间等信息命名,然后如果后面要找回这个就直接用这个压缩包的就行了,后来有了 svn,git 中心式和分布式的版本管理系统,它的一个特点是粒度可以控制到文件和代码行级别,对应的我们的 mysql 事务是不是也可以从一开始预想的表级别细化到行的级别,可能之前很多人都了解过,数据库的一行记录除了我们用户自定义的字段,还有一些额外的字段,去源码data0type.h里捞一下

    -
    /* Precise data types for system columns and the length of those columns;
    -NOTE: the values must run from 0 up in the order given! All codes must
    -be less than 256 */
    -#define DATA_ROW_ID 0     /* row id: a 48-bit integer */
    -#define DATA_ROW_ID_LEN 6 /* stored length for row id */
    -
    -/** Transaction id: 6 bytes */
    -constexpr size_t DATA_TRX_ID = 1;
    -
    -/** Transaction ID type size in bytes. */
    -constexpr size_t DATA_TRX_ID_LEN = 6;
    -
    -/** Rollback data pointer: 7 bytes */
    -constexpr size_t DATA_ROLL_PTR = 2;
    -
    -/** Rollback data pointer type size in bytes. */
    -constexpr size_t DATA_ROLL_PTR_LEN = 7;
    - -

    一个是 DATA_ROW_ID,这个是在数据没指定主键的时候会生成一个隐藏的,如果用户有指定主键就是主键了

    -

    一个是 DATA_TRX_ID,这个表示这条记录的事务 ID

    -

    还有一个是 DATA_ROLL_PTR 指向回滚段的指针

    -

    指向的回滚段其实就是我们常说的 undo log,这里面的具体结构就是个链表,在 mvcc 里会使用到这个,还有就是这个 DATA_TRX_ID,每条记录都记录了这个事务 ID,表示的是这条记录的当前值是被哪个事务修改的,下面就扯回事务了,我们知道 Read Uncommitted, 其实用不到隔离,直接读取当前值就好了,到了 Read Committed 级别,我们要让事务读取到提交过的值,mysql 使用了一个叫 read view 的玩意,它里面有这些值是我们需要注意的,

    -

    m_low_limit_id, 这个是 read view 创建时最大的活跃事务 id

    -

    m_up_limit_id, 这个是 read view 创建时最小的活跃事务 id

    -

    m_ids, 这个是 read view 创建时所有的活跃事务 id 数组

    -

    m_creator_trx_id 这个是当前记录的创建事务 id

    -

    判断事务的可见性主要的逻辑是这样,

    -
      -
    1. 当记录的事务 id 小于最小活跃事务 id,说明是可见的,
    2. -
    3. 如果记录的事务 id 等于当前事务 id,说明是自己的更改,可见
    4. -
    5. 如果记录的事务 id 大于最大的活跃事务 id, 不可见
    6. -
    7. 如果记录的事务 id 介于 m_low_limit_idm_up_limit_id 之间,则要判断它是否在 m_ids 中,如果在,不可见,如果不在,表示已提交,可见
      具体的代码捞一下看看
      /** Check whether the changes by id are visible.
      -  @param[in]	id	transaction id to check against the view
      -  @param[in]	name	table name
      -  @return whether the view sees the modifications of id. */
      -  bool changes_visible(trx_id_t id, const table_name_t &name) const
      -      MY_ATTRIBUTE((warn_unused_result)) {
      -    ut_ad(id > 0);
      -
      -    if (id < m_up_limit_id || id == m_creator_trx_id) {
      -      return (true);
      -    }
      -
      -    check_trx_id_sanity(id, name);
      -
      -    if (id >= m_low_limit_id) {
      -      return (false);
      -
      -    } else if (m_ids.empty()) {
      -      return (true);
      -    }
      -
      -    const ids_t::value_type *p = m_ids.data();
      -
      -    return (!std::binary_search(p, p + m_ids.size(), id));
      -  }
      -剩下来一点是啥呢,就是 Read CommittedRepeated Read 也不一样,那前面说的 read view 都能支持吗,又是怎么支持呢,假如这个 read view 是在事务一开始就创建,那好像能支持的只是 RR 事务隔离级别,其实呢,这是通过创建 read view的时机,对于 RR 级别,就是在事务的第一个 select 语句是创建,对于 RC 级别,是在每个 select 语句执行前都是创建一次,那样就可以保证能读到所有已提交的数据
    8. -
    +

    m_low_limit_id赋的值是trx_sys->max_trx_id,代表的是当前系统最小的未分配的事务 id,所以呢,举个例子,当前有三个活跃事务,事务 id 分别是 100,200,300,而 m_up_limit_id = 100, m_low_limit_id = 301,当事务 id 是 200 的提交之后,它的更新就是可以被 100 和 300 看到,而不是说 m_ids 里没了 200,并且 200 比 100 大就应该不可见了

    +

    幻读

    还有一个问题是幻读的问题,这貌似也是个高频面试题,啥意思呢,或者说跟它最常拿来比较的脏读,脏读是指读到了别的事务未提交的数据,因为未提交,严格意义上来讲,不一定是会被最后落到库里,可能会回滚,也就是在 read uncommitted 级别下会出现的问题,但是幻读不太一样,幻读是指两次查询的结果数量不一样,比如我查了第一次是 select * from table1 where id < 10 for update,查出来了一条结果 id 是 5,然后再查一下发现出来了一条 id 是 5,一条 id 是 7,那是不是有点尴尬了,其实呢这个点我觉得脏读跟幻读也比较是从原理层面来命名,如果第一次接触的同学发觉有点不理解也比较正常,因为从逻辑上讲总之都是数据不符合预期,但是基于源码层面其实是不同的情况,幻读是在原先的 read view 无法完全解决的,怎么解决呢,简单的来说就是锁咯,我们知道innodb 是基于 record lock 行锁的,但是貌似没有办法解决这种问题,那么 innodb 就引入了 gap lock 间隙锁,比如上面说的情况下,id 小于 10 的情况下,是都应该锁住的,gap lock 其实是基于索引结构来锁的,因为索引树除了树形结构之外,还有一个next record 的指针,gap lock 也是基于这个来锁的
    看一下 mysql 的文档

    +
    +

    SELECT … FOR UPDATE sets an exclusive next-key lock on every record the search encounters. However, only an index record lock is required for statements that lock rows using a unique index to search for a unique row.

    +
    +

    对于一个 for update 查询,在 RR 级别下,会设置一个 next-key lock在每一条被查询到的记录上,next-lock 又是啥呢,其实就是 gap 锁和 record 锁的结合体,比如我在数据库里有 id 是 1,3,5,7,10,对于上面那条查询,查出来的结果就是 1,3,5,7,那么按照文档里描述的,对于这几条记录都会加上next-key lock,也就是(-∞, 1], (1, 3], (3, 5], (5, 7], (7, 10) 这些区间和记录会被锁起来,不让插入,再唠叨一下呢,就是其实如果是只读的事务,光 read view 一致性读就够了,如果是有写操作的呢,就需要锁了。

    ]]>
    Mysql @@ -19495,462 +19219,295 @@ constexpr size_t DATA_ROLL_PTR_LEN 源码 mvcc read view + gap lock + next-key lock + 幻读
    - 聊聊Java中的单例模式 - /2019/12/21/%E8%81%8A%E8%81%8AJava%E4%B8%AD%E7%9A%84%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F/ - 这是个 Java 面试的高频问题,我也遇到过,以往都是觉得这类题没意思,网上一搜一大堆,也不愿意记,其实说回来,主要还是没静下心来好好去理解,今天无意中看到一个课程,基本帮我把一些疑惑的点讲清楚了,首先单例是啥意思,这个其实是有范围一说,比如我起了个Spring Boot应用,在这个应用范围内,我的常规 bean 是单例的,意味着 getBean 的时候其实永远只会拿到那一个对象,那要怎么来写一个单例呢,首先就是传说中的饿汉模式,也是最简单的

    -

    饿汉模式

    public class Singleton1 {
    -    // 首先,将构造方法变成私有的
    -    private Singleton1() {};
    -    // 创建私有静态实例,这样第一次使用的时候就会进行创建
    -    private static Singleton instance = new Singleton1();
    -
    -    // 使用这个对象都是通过这个 getInstance 来获取
    -    public static Singleton1 getInstance() {
    -        return instance;
    -    }
    -    // 瞎写一个静态方法。这里想说的是,如果我们只是要调用 Singleton.getDate(...),
    -    // 本来是不想要生成 Singleton 实例的,不过没办法,已经生成了
    -    public static Date getDate(String mode) {return new Date();}
    -}
    -

    上面借鉴了一些代码,其实这是最基本,也不会错的方法,但是正如其中getDate方法里说的问题,有时候并没有想那这个对象,但是因为我调用了这个类的静态方法,导致对象已经生成了,可能这也是饿汉模式名字的来由,不管三七二十一给你生成个单例就完事了,不管有没有用,但是这种个人觉得也没啥大问题,如果是面试的话最好说出来它的缺点

    -

    饱汉模式

    public class Singleton2 {
    -    // 首先,也是先堵死 new Singleton() 这条路,将构造方法变成私有
    -    private Singleton2() {}
    -    // 和饿汉模式相比,这边不需要先实例化出来,注意这里的 volatile,它是必须的
    -    private static volatile Singleton2 instance = null;
    -
    -    private int m = 9;
    -
    -    public static Singleton getInstance() {
    -        if (instance == null) {
    -            // 加锁
    -            synchronized (Singleton2.class) {
    -                // 这一次判断也是必须的,不然会有并发问题
    -                if (instance == null) {
    -                    instance = new Singleton2();
    -                }
    -            }
    -        }
    -        return instance;
    -    }
    -}
    -

    这里容易错的有三点,理解了其实就比较好记了

    -

    第一点,为啥不在 getInstance 上整个代码块加 synchronized,这个其实比较容易理解,就是锁的力度太大,性能太差了,这点其实也要去理解,可以举个夸张的例子,比如我一个电商的服务,如果为了避免一个人的订单出现问题,是不是可以从请求入口就把他锁住,到请求结束释放,那么里面做的事情都有保障,然而这显然不可能,因为我们想要这种竞态条件抢占资源的时间尽量减少,防止其他线程等待。
    第二点,为啥synchronized之已经检查了 instance == null,还要在里面再检查一次,这个有个术语,叫 double check lock,但是为啥要这么做呢,其实很简单,想象当有两个线程,都过了第一步为空判断,这个时候只有一个线程能拿到这个锁,另一个线程就等待了,如果不再判断一次,那么第一个线程新建完对象释放锁之后,第二个线程又能拿到锁,再去创建一个对象。
    第三点,为啥要volatile关键字,原先对它的理解是它修饰的变量在 JMM 中能及时将变量值写到主存中,但是它还有个很重要的作用,就是防止指令重排序,instance = new Singleton();这行代码其实在底层是分成三条指令执行的,第一条是在堆上申请了一块内存放这个对象,但是对象的字段啥的都还是默认值,第二条是设置对象的值,比如上面的 m 是 9,然后第三条是将这个对象和虚拟机栈上的指针建立引用关联,那么如果我不用volatile关键字,这三条指令就有可能出现重排,比如变成了 1-3-2 这种顺序,当执行完第二步时,有个线程来访问这个对象了,先判断是不是空,发现不是空的,就拿去直接用了,是不是就出现问题了,所以这个volatile也是不可缺少的

    -

    嵌套类

    public class Singleton3 {
    -
    -    private Singleton3() {}
    -    // 主要是使用了 嵌套类可以访问外部类的静态属性和静态方法 的特性
    -    private static class Holder {
    -        private static Singleton3 instance = new Singleton3();
    -    }
    -    public static Singleton3 getInstance() {
    -        return Holder.instance;
    -    }
    -}
    -

    这个我个人感觉是饿汉模式的升级版,可以在调用getInstance的时候去实例化对象,也是比较推荐的

    -

    枚举单例

    public enum Singleton {
    -    INSTANCE;
    -    
    -    public void doSomething(){
    -        //todo doSomething
    -    }
    -}
    -

    枚举很特殊,它在类加载的时候会初始化里面的所有的实例,而且 JVM 保证了它们不会再被实例化,所以它天生就是单例的。

    -]]>
    - - Java - Design Patterns - Singleton - - - 设计模式 - Design Patterns - 单例 - Singleton - -
    - - 聊聊 redis 缓存的应用问题 - /2021/01/31/%E8%81%8A%E8%81%8A-redis-%E7%BC%93%E5%AD%98%E7%9A%84%E5%BA%94%E7%94%A8%E9%97%AE%E9%A2%98/ - 前面写过一系列的 redis 源码分析的,但是实际上很多的问题还是需要结合实际的使用,然后其实就避不开缓存使用的三个著名问题,穿透,击穿和雪崩,这三个概念也是有着千丝万缕的关系,

    -

    缓存穿透

    缓存穿透是指当数据库中本身就不存在这个数据的时候,使用一般的缓存策略时访问不到缓存后就访问数据库,但是因为数据库也没数据,所以如果不做任何策略优化的话,这类数据就每次都会访问一次数据库,对数据库压力也会比较大。

    -

    缓存击穿

    缓存击穿跟穿透比较类似的,都是访问缓存不在,然后去访问数据库,与穿透不一样的是击穿是在数据库中存在数据,但是可能由于第一次访问,或者缓存过期了,需要访问到数据库,这对于访问量小的情况其实算是个正常情况,但是随着请求量变高就会引发一些性能隐患。

    -

    缓存雪崩

    缓存雪崩就是击穿的大规模集群效应,当大量的缓存过期失效的时候,这些请求都是直接访问到数据库了,会对数据库造成很大的压力。

    -

    对于以上三种场景也有一些比较常见的解决方案,但也不能说是万无一失的,需要随着业务去寻找合适的方案

    -

    解决缓存穿透

    对于数据库中就没这个数据的时候,一种是可以对这个 key 设置下空值,即以一个特定的表示是数据库不存在的,这种情况需要合理地调整过期时间,当这个 key 在数据库中有数据了的话,也需要有策略去更新这个值,并且如果这类 key 非常多,这个方法就会不太合适,就可以使用第二种方法,就是布隆过滤器,bloom filter,前置一个布隆过滤器,当这个 key 在数据库不存在的话,先用布隆过滤器挡一道,如果不在的话就直接返回了,当然布隆过滤器不是绝对的准确的

    -

    解决缓存击穿

    当一个 key 的缓存过期了,如果大量请求过来访问这个 key,请求都会落在数据库里,这个时候就可以使用一些类似于互斥锁的方式去让一个线程去访问数据库,更新缓存,但是这里其实也有个问题,就是如果是热点 key 其实这种方式也比较危险,万一更新失败,或者更新操作的时候耗时比较久,就会有一大堆请求卡在那,这种情况可能需要有一些异步提前刷新缓存,可以结合具体场景选择方式

    -

    解决缓存雪崩

    雪崩的情况是指大批量的 key 都一起过期了,击穿的放大版,大批量的请求都打到数据库上了,一方面有可能直接缓存不可用了,就需要用集群化高可用的缓存服务,然后对于实际使用中也可以使用本地缓存结合 redis 缓存,去提高可用性,再配合一些限流措施,然后就是缓存使用过程总的过期时间最好能加一些随机值,防止在同一时间过期而导致雪崩,结合互斥锁防止大量请求打到数据库。

    + 聊聊 mysql 的 MVCC 续续篇之锁分析 + /2020/05/10/%E8%81%8A%E8%81%8A-mysql-%E7%9A%84-MVCC-%E7%BB%AD%E7%BB%AD%E7%AF%87%E4%B9%8B%E5%8A%A0%E9%94%81%E5%88%86%E6%9E%90/ + 看完前面两篇水文之后,感觉不得不来分析下 mysql 的锁了,其实前面说到幻读的时候是有个前提没提到的,比如一个select * from table1 where id = 1这种查询语句其实是不会加传说中的锁的,当然这里是指在 RR 或者 RC 隔离级别下,
    看一段 mysql官方文档

    +
    +

    SELECT ... FROM is a consistent read, reading a snapshot of the database and setting no locks unless the transaction isolation level is set to SERIALIZABLE. For SERIALIZABLE level, the search sets shared next-key locks on the index records it encounters. However, only an index record lock is required for statements that lock rows using a unique index to search for a unique row.

    +
    +

    纯粹的这种一致性读,实际读取的是快照,也就是基于 read view 的读取方式,除非当前隔离级别是SERIALIZABLE
    但是对于以下几类

    +
      +
    • select * from table where ? lock in share mode;
    • +
    • select * from table where ? for update;
    • +
    • insert into table values (...);
    • +
    • update table set ? where ?;
    • +
    • delete from table where ?;
    • +
    +

    除了第一条是 S 锁之外,其他都是 X 排他锁,这边在顺带下,S 锁表示共享锁, X 表示独占锁,同为 S 锁之间不冲突,S 与 X,X 与 S,X 与 X 之间都冲突,也就是加了前者,后者就加不上了
    我们知道对于 RC 级别会出现幻读现象,对于 RR 级别不会出现,主要的区别是 RR 级别下对于以上的加锁读取都根据情况加上了 gap 锁,那么是不是 RR 级别下以上所有的都是要加 gap 锁呢,当然不是
    举个例子,RR 事务隔离级别下,table1 有个主键id 字段
    select * from table1 where id = 10 for update
    这条语句要加 gap 锁吗?
    答案是不需要,这里其实算是我看了这么久的一点自己的理解,啥时候要加 gap 锁,判断的条件是根据我查询的数据是否会因为不加 gap 锁而出现数量的不一致,我上面这条查询语句,在什么情况下会出现查询结果数量不一致呢,只要在这条记录被更新或者删除的时候,有没有可能我第一次查出来一条,第二次变成两条了呢,不可能,因为是主键索引。
    再变更下这个题的条件,当 id 不是主键,但是是唯一索引,这样需要怎么加锁,注意问题是怎么加锁,不是需不需要加 gap 锁,这里呢就是稍微延伸一下,把聚簇索引(主键索引)和二级索引带一下,当 id 不是主键,说明是个二级索引,但是它是唯一索引,体会下,首先对于 id = 10这个二级索引肯定要加锁,要不要锁 gap 呢,不用,因为是唯一索引,id = 10 只可能有这一条记录,然后呢,这样是不是就好了,还不行,因为啥,因为它是二级索引,对应的主键索引的记录才是真正的数据,万一被更新掉了咋办,所以在 id = 10 对应的主键索引上也需要加上锁(默认都是 record lock行锁),那主键索引上要不要加 gap 呢,也不用,也是精确定位到这一条记录
    最后呢,当 id 不是主键,也不是唯一索引,只是个普通的索引,这里就需要大名鼎鼎的 gap 锁了,
    是时候画个图了

    其实核心的目的还是不让这个 id=10 的记录不会出现幻读,那么就需要在 id 这个索引上加上三个 gap 锁,主键索引上就不用了,在 id 索引上已经控制住了id = 10 不会出现幻读,主键索引上这两条对应的记录已经锁了,所以就这样 OK 了

    ]]>
    - Redis - 应用 - 缓存 - 缓存 - 穿透 - 击穿 - 雪崩 + Mysql + C + 数据结构 + 源码 + Mysql - Redis - 缓存穿透 - 缓存击穿 - 缓存雪崩 - 布隆过滤器 - bloom filter - 互斥锁 + mysql + 数据结构 + 源码 + mvcc + read view + gap lock + next-key lock + 幻读
    - 聊聊 SpringBoot 自动装配 - /2021/07/11/%E8%81%8A%E8%81%8ASpringBoot-%E8%87%AA%E5%8A%A8%E8%A3%85%E9%85%8D/ - springboot 自动装配调用链

    -

    springboot 相比 spring能更方便开发人员上手,比较重要的一点就是自动装配,大致来看下这个逻辑

    -
    public static void main(String[] args) {
    -		SpringApplication.run(SpbDemoApplication.class, args);
    -	}
    -
    -	/**
    -	 * Static helper that can be used to run a {@link SpringApplication} from the
    -	 * specified source using default settings.
    -	 * @param primarySource the primary source to load
    -	 * @param args the application arguments (usually passed from a Java main method)
    -	 * @return the running {@link ApplicationContext}
    -	 */
    -

    然后就是上面调用的 run 方法

    -
    public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
    -	return run(new Class<?>[] { primarySource }, args);
    -}
    -
    -/**
    - * Static helper that can be used to run a {@link SpringApplication} from the
    - * specified sources using default settings and user supplied arguments.
    - * @param primarySources the primary sources to load
    - * @param args the application arguments (usually passed from a Java main method)
    - * @return the running {@link ApplicationContext}
    - */
    -

    继续往下看

    -
    public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
    -	return new SpringApplication(primarySources).run(args);
    -}
    - -

    调用SpringApplication的构造方法

    -
    /**
    - * Create a new {@link SpringApplication} instance. The application context will load
    - * beans from the specified primary sources (see {@link SpringApplication class-level}
    - * documentation for details. The instance can be customized before calling
    - * {@link #run(String...)}.
    - * @param primarySources the primary bean sources
    - * @see #run(Class, String[])
    - * @see #SpringApplication(ResourceLoader, Class...)
    - * @see #setSources(Set)
    - */
    -
    -public SpringApplication(Class<?>... primarySources) {
    -	this(null, primarySources);
    -}
    -
    -/**
    - * Create a new {@link SpringApplication} instance. The application context will load
    - * beans from the specified primary sources (see {@link SpringApplication class-level}
    - * documentation for details. The instance can be customized before calling
    - * {@link #run(String...)}.
    - * @param resourceLoader the resource loader to use
    - * @param primarySources the primary bean sources
    - * @see #run(Class, String[])
    - * @see #setSources(Set)
    - */
    -@SuppressWarnings({ "unchecked", "rawtypes" })
    -public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
    -	this.resourceLoader = resourceLoader;
    -	Assert.notNull(primarySources, "PrimarySources must not be null");
    -	this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
    -	this.webApplicationType = WebApplicationType.deduceFromClasspath();
    -   // 注意看这里的,通过 SpringFactories 获取
    -	this.bootstrapRegistryInitializers = getBootstrapRegistryInitializersFromSpringFactories();
    -	setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
    -	setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
    -	this.mainApplicationClass = deduceMainApplicationClass();
    -}
    -

    这里就是重点了

    -
    private List<BootstrapRegistryInitializer> getBootstrapRegistryInitializersFromSpringFactories() {
    -	ArrayList<BootstrapRegistryInitializer> initializers = new ArrayList<>();
    -	getSpringFactoriesInstances(Bootstrapper.class).stream()
    -			.map((bootstrapper) -> ((BootstrapRegistryInitializer) bootstrapper::initialize))
    -			.forEach(initializers::add);
    -	initializers.addAll(getSpringFactoriesInstances(BootstrapRegistryInitializer.class));
    -	return initializers;
    -}
    -private <T> Collection<T> getSpringFactoriesInstances(Class<T> type) {
    -	return getSpringFactoriesInstances(type, new Class<?>[] {});
    -}
    -
    -private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) {
    -	ClassLoader classLoader = getClassLoader();
    -	// Use names and ensure unique to protect against duplicates
    -   // 去加载所有FACTORIES_RESOURCE_LOCATION路径下面,也就是 META-INF/spring.factories
    -	Set<String> names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
    -	List<T> instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
    -	AnnotationAwareOrderComparator.sort(instances);
    -	return instances;
    -}
    - -
    
    -/**
    - * Load the fully qualified class names of factory implementations of the
    - * given type from {@value #FACTORIES_RESOURCE_LOCATION}, using the given
    - * class loader.
    - * <p>As of Spring Framework 5.3, if a particular implementation class name
    - * is discovered more than once for the given factory type, duplicates will
    - * be ignored.
    - * @param factoryType the interface or abstract class representing the factory
    - * @param classLoader the ClassLoader to use for loading resources; can be
    - * {@code null} to use the default
    - * @throws IllegalArgumentException if an error occurs while loading factory names
    - * @see #loadFactories
    - */
    -public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {
    -	ClassLoader classLoaderToUse = classLoader;
    -	if (classLoaderToUse == null) {
    -		classLoaderToUse = SpringFactoriesLoader.class.getClassLoader();
    -	}
    -	String factoryTypeName = factoryType.getName();
    -	return loadSpringFactories(classLoaderToUse).getOrDefault(factoryTypeName, Collections.emptyList());
    -}
    -   private static Map<String, List<String>> loadSpringFactories(ClassLoader classLoader) {
    -	Map<String, List<String>> result = cache.get(classLoader);
    -	if (result != null) {
    -		return result;
    -	}
    +    聊聊 mysql 的 MVCC
    +    /2020/04/26/%E8%81%8A%E8%81%8A-mysql-%E7%9A%84-MVCC/
    +    很久以前,有位面试官问到,你知道 mysql 的事务隔离级别吗,“额 O__O …,不太清楚”,完了之后我就去网上找相关的文章,找到了这篇MySQL 四种事务隔离级的说明, 文章写得特别好,看了这个就懂了各个事务隔离级别都是啥,不过看了这个之后多思考一下的话还是会发现问题,这么神奇的事务隔离级别是怎么实现的呢

    +

    其中 innodb 的事务隔离用到了标题里说到的 mvcc,Multiversion concurrency control, 直译过来就是多版本并发控制,先不讲这个究竟是个啥,考虑下如果纯猜测,这个事务隔离级别应该会是怎么样实现呢,愚钝的我想了下,可以在事务开始的时候拷贝一个表,这个可以支持 RR 级别,RC 级别就不支持了,而且要是个非常大的表,想想就不可行

    +

    腆着脸说虽然这个不可行,但是思路是对的,具体实行起来需要做一系列(肥肠多)的改动,首先根据我的理解,其实这个拷贝一个表是变成拷贝一条记录,但是如果有多个事务,那就得拷贝多次,这个问题其实可以借助版本管理系统来解释,在用版本管理系统,git 之类的之前,很原始的可能是开发完一个功能后,就打个压缩包用时间等信息命名,然后如果后面要找回这个就直接用这个压缩包的就行了,后来有了 svn,git 中心式和分布式的版本管理系统,它的一个特点是粒度可以控制到文件和代码行级别,对应的我们的 mysql 事务是不是也可以从一开始预想的表级别细化到行的级别,可能之前很多人都了解过,数据库的一行记录除了我们用户自定义的字段,还有一些额外的字段,去源码data0type.h里捞一下

    +
    /* Precise data types for system columns and the length of those columns;
    +NOTE: the values must run from 0 up in the order given! All codes must
    +be less than 256 */
    +#define DATA_ROW_ID 0     /* row id: a 48-bit integer */
    +#define DATA_ROW_ID_LEN 6 /* stored length for row id */
     
    -	result = new HashMap<>();
    -	try {
    -           // 获取此 resources,作为 AutoConfiguration 的配置
    -		Enumeration<URL> urls = classLoader.getResources(FACTORIES_RESOURCE_LOCATION);
    -		while (urls.hasMoreElements()) {
    -			URL url = urls.nextElement();
    -			UrlResource resource = new UrlResource(url);
    -			Properties properties = PropertiesLoaderUtils.loadProperties(resource);
    -			for (Map.Entry<?, ?> entry : properties.entrySet()) {
    -				String factoryTypeName = ((String) entry.getKey()).trim();
    -				String[] factoryImplementationNames =
    -						StringUtils.commaDelimitedListToStringArray((String) entry.getValue());
    -				for (String factoryImplementationName : factoryImplementationNames) {
    -					result.computeIfAbsent(factoryTypeName, key -> new ArrayList<>())
    -							.add(factoryImplementationName.trim());
    -				}
    -			}
    -		}
    +/** Transaction id: 6 bytes */
    +constexpr size_t DATA_TRX_ID = 1;
     
    -		// Replace all lists with unmodifiable lists containing unique elements
    -		result.replaceAll((factoryType, implementations) -> implementations.stream().distinct()
    -				.collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)));
    -		cache.put(classLoader, result);
    -	}
    -	catch (IOException ex) {
    -		throw new IllegalArgumentException("Unable to load factories from location [" +
    -				FACTORIES_RESOURCE_LOCATION + "]", ex);
    -	}
    -	return result;
    -}
    +/** Transaction ID type size in bytes. */ +constexpr size_t DATA_TRX_ID_LEN = 6; -

    我们可以看下 spring-boot-autoconfigure 的 META-INF/spring.factories

    -
    # Initializers
    -org.springframework.context.ApplicationContextInitializer=\
    -org.springframework.boot.autoconfigure.SharedMetadataReaderFactoryContextInitializer,\
    -org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener
    +/** Rollback data pointer: 7 bytes */
    +constexpr size_t DATA_ROLL_PTR = 2;
     
    -# Application Listeners
    -org.springframework.context.ApplicationListener=\
    -org.springframework.boot.autoconfigure.BackgroundPreinitializer
    +/** Rollback data pointer type size in bytes. */
    +constexpr size_t DATA_ROLL_PTR_LEN = 7;
    -# Environment Post Processors -org.springframework.boot.env.EnvironmentPostProcessor=\ -org.springframework.boot.autoconfigure.integration.IntegrationPropertiesEnvironmentPostProcessor +

    一个是 DATA_ROW_ID,这个是在数据没指定主键的时候会生成一个隐藏的,如果用户有指定主键就是主键了

    +

    一个是 DATA_TRX_ID,这个表示这条记录的事务 ID

    +

    还有一个是 DATA_ROLL_PTR 指向回滚段的指针

    +

    指向的回滚段其实就是我们常说的 undo log,这里面的具体结构就是个链表,在 mvcc 里会使用到这个,还有就是这个 DATA_TRX_ID,每条记录都记录了这个事务 ID,表示的是这条记录的当前值是被哪个事务修改的,下面就扯回事务了,我们知道 Read Uncommitted, 其实用不到隔离,直接读取当前值就好了,到了 Read Committed 级别,我们要让事务读取到提交过的值,mysql 使用了一个叫 read view 的玩意,它里面有这些值是我们需要注意的,

    +

    m_low_limit_id, 这个是 read view 创建时最大的活跃事务 id

    +

    m_up_limit_id, 这个是 read view 创建时最小的活跃事务 id

    +

    m_ids, 这个是 read view 创建时所有的活跃事务 id 数组

    +

    m_creator_trx_id 这个是当前记录的创建事务 id

    +

    判断事务的可见性主要的逻辑是这样,

    +
      +
    1. 当记录的事务 id 小于最小活跃事务 id,说明是可见的,
    2. +
    3. 如果记录的事务 id 等于当前事务 id,说明是自己的更改,可见
    4. +
    5. 如果记录的事务 id 大于最大的活跃事务 id, 不可见
    6. +
    7. 如果记录的事务 id 介于 m_low_limit_idm_up_limit_id 之间,则要判断它是否在 m_ids 中,如果在,不可见,如果不在,表示已提交,可见
      具体的代码捞一下看看
      /** Check whether the changes by id are visible.
      +  @param[in]	id	transaction id to check against the view
      +  @param[in]	name	table name
      +  @return whether the view sees the modifications of id. */
      +  bool changes_visible(trx_id_t id, const table_name_t &name) const
      +      MY_ATTRIBUTE((warn_unused_result)) {
      +    ut_ad(id > 0);
       
      -# Auto Configuration Import Listeners
      -org.springframework.boot.autoconfigure.AutoConfigurationImportListener=\
      -org.springframework.boot.autoconfigure.condition.ConditionEvaluationReportAutoConfigurationImportListener
      +    if (id < m_up_limit_id || id == m_creator_trx_id) {
      +      return (true);
      +    }
       
      -# Auto Configuration Import Filters
      -org.springframework.boot.autoconfigure.AutoConfigurationImportFilter=\
      -org.springframework.boot.autoconfigure.condition.OnBeanCondition,\
      -org.springframework.boot.autoconfigure.condition.OnClassCondition,\
      -org.springframework.boot.autoconfigure.condition.OnWebApplicationCondition
      +    check_trx_id_sanity(id, name);
       
      -# 注意这里,其实就是类似于 dubbo spi 的通过 org.springframework.boot.autoconfigure.EnableAutoConfiguration作为 key
      -# 获取下面所有的 AutoConfiguration 配置类
      -# Auto Configure
      -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
      -org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
      -org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
      -org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
      -org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
      -org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
      -org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\
      -org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\
      -org.springframework.boot.autoconfigure.context.LifecycleAutoConfiguration,\
      -org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration,\
      -org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration,\
      -org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration,\
      -org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration,\
      -org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration,\
      -org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveDataAutoConfiguration,\
      -org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveRepositoriesAutoConfiguration,\
      -org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration,\
      -org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration,\
      -org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveDataAutoConfiguration,\
      -org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveRepositoriesAutoConfiguration,\
      -org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration,\
      -org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration,\
      -org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\
      -org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRepositoriesAutoConfiguration,\
      -org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRestClientAutoConfiguration,\
      -org.springframework.boot.autoconfigure.data.jdbc.JdbcRepositoriesAutoConfiguration,\
      -org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\
      -org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration,\
      -org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,\
      -org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration,\
      -org.springframework.boot.autoconfigure.data.mongo.MongoReactiveRepositoriesAutoConfiguration,\
      -org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration,\
      -org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration,\
      -org.springframework.boot.autoconfigure.data.neo4j.Neo4jReactiveDataAutoConfiguration,\
      -org.springframework.boot.autoconfigure.data.neo4j.Neo4jReactiveRepositoriesAutoConfiguration,\
      -org.springframework.boot.autoconfigure.data.neo4j.Neo4jRepositoriesAutoConfiguration,\
      -org.springframework.boot.autoconfigure.data.r2dbc.R2dbcDataAutoConfiguration,\
      -org.springframework.boot.autoconfigure.data.r2dbc.R2dbcRepositoriesAutoConfiguration,\
      -org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\
      -org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration,\
      -org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration,\
      -org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration,\
      -org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration,\
      -org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchRestClientAutoConfiguration,\
      -org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\
      -org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\
      -org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\
      -org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration,\
      -org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration,\
      -org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration,\
      -org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration,\
      -org.springframework.boot.autoconfigure.hazelcast.HazelcastJpaDependencyAutoConfiguration,\
      -org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration,\
      -org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration,\
      -org.springframework.boot.autoconfigure.influx.InfluxDbAutoConfiguration,\
      -org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration,\
      -org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration,\
      -org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration,\
      -org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
      -org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration,\
      -org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration,\
      -org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration,\
      -org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\
      -org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration,\
      -org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration,\
      -org.springframework.boot.autoconfigure.jms.JndiConnectionFactoryAutoConfiguration,\
      -org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration,\
      -org.springframework.boot.autoconfigure.jms.artemis.ArtemisAutoConfiguration,\
      -org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration,\
      -org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\
      -org.springframework.boot.autoconfigure.jsonb.JsonbAutoConfiguration,\
      -org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration,\
      -org.springframework.boot.autoconfigure.availability.ApplicationAvailabilityAutoConfiguration,\
      -org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration,\
      -org.springframework.boot.autoconfigure.ldap.LdapAutoConfiguration,\
      -org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration,\
      -org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration,\
      -org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration,\
      -org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration,\
      -org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,\
      -org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration,\
      -org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration,\
      -org.springframework.boot.autoconfigure.neo4j.Neo4jAutoConfiguration,\
      -org.springframework.boot.autoconfigure.netty.NettyAutoConfiguration,\
      -org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\
      -org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration,\
      -org.springframework.boot.autoconfigure.r2dbc.R2dbcAutoConfiguration,\
      -org.springframework.boot.autoconfigure.r2dbc.R2dbcTransactionManagerAutoConfiguration,\
      -org.springframework.boot.autoconfigure.rsocket.RSocketMessagingAutoConfiguration,\
      -org.springframework.boot.autoconfigure.rsocket.RSocketRequesterAutoConfiguration,\
      -org.springframework.boot.autoconfigure.rsocket.RSocketServerAutoConfiguration,\
      -org.springframework.boot.autoconfigure.rsocket.RSocketStrategiesAutoConfiguration,\
      -org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration,\
      -org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration,\
      -org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration,\
      -org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration,\
      -org.springframework.boot.autoconfigure.security.reactive.ReactiveUserDetailsServiceAutoConfiguration,\
      -org.springframework.boot.autoconfigure.security.rsocket.RSocketSecurityAutoConfiguration,\
      -org.springframework.boot.autoconfigure.security.saml2.Saml2RelyingPartyAutoConfiguration,\
      -org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,\
      -org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,\
      -org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientAutoConfiguration,\
      -org.springframework.boot.autoconfigure.security.oauth2.client.reactive.ReactiveOAuth2ClientAutoConfiguration,\
      -org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration,\
      -org.springframework.boot.autoconfigure.security.oauth2.resource.reactive.ReactiveOAuth2ResourceServerAutoConfiguration,\
      -org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,\
      -org.springframework.boot.autoconfigure.sql.init.SqlInitializationAutoConfiguration,\
      -org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration,\
      -org.springframework.boot.autoconfigure.task.TaskSchedulingAutoConfiguration,\
      -org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration,\
      -org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration,\
      -org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration,\
      -org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration,\
      -org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration,\
      -org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration,\
      -org.springframework.boot.autoconfigure.web.reactive.HttpHandlerAutoConfiguration,\
      -org.springframework.boot.autoconfigure.web.reactive.ReactiveWebServerFactoryAutoConfiguration,\
      -org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration,\
      -org.springframework.boot.autoconfigure.web.reactive.error.ErrorWebFluxAutoConfiguration,\
      -org.springframework.boot.autoconfigure.web.reactive.function.client.ClientHttpConnectorAutoConfiguration,\
      -org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration,\
      -org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,\
      -org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration,\
      -org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration,\
      -org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration,\
      -org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration,\
      -org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\
      -org.springframework.boot.autoconfigure.websocket.reactive.WebSocketReactiveAutoConfiguration,\
      -org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration,\
      -org.springframework.boot.autoconfigure.websocket.servlet.WebSocketMessagingAutoConfiguration,\
      -org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration,\
      -org.springframework.boot.autoconfigure.webservices.client.WebServiceTemplateAutoConfiguration
      +    if (id >= m_low_limit_id) {
      +      return (false);
      +
      +    } else if (m_ids.empty()) {
      +      return (true);
      +    }
      +
      +    const ids_t::value_type *p = m_ids.data();
      +
      +    return (!std::binary_search(p, p + m_ids.size(), id));
      +  }
      +剩下来一点是啥呢,就是 Read CommittedRepeated Read 也不一样,那前面说的 read view 都能支持吗,又是怎么支持呢,假如这个 read view 是在事务一开始就创建,那好像能支持的只是 RR 事务隔离级别,其实呢,这是通过创建 read view的时机,对于 RR 级别,就是在事务的第一个 select 语句是创建,对于 RC 级别,是在每个 select 语句执行前都是创建一次,那样就可以保证能读到所有已提交的数据
    8. +
    +]]>
    + + Mysql + C + 数据结构 + 源码 + Mysql + + + mysql + 数据结构 + 源码 + mvcc + read view + + + + 聊聊 mysql 索引的一些细节 + /2020/12/27/%E8%81%8A%E8%81%8A-mysql-%E7%B4%A2%E5%BC%95%E7%9A%84%E4%B8%80%E4%BA%9B%E7%BB%86%E8%8A%82/ + 前几天同事问了我个 mysql 索引的问题,虽然大概知道,但是还是想来实践下,就是 is null,is not null 这类查询是否能用索引,可能之前有些网上的文章说都是不能用索引,但是其实不是,我们来看个小试验

    +
    CREATE TABLE `null_index_t` (
    +  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    +  `null_key` varchar(255) DEFAULT NULL,
    +  `null_key1` varchar(255) DEFAULT NULL,
    +  `null_key2` varchar(255) DEFAULT NULL,
    +  PRIMARY KEY (`id`),
    +  KEY `idx_1` (`null_key`) USING BTREE,
    +  KEY `idx_2` (`null_key1`) USING BTREE,
    +  KEY `idx_3` (`null_key2`) USING BTREE
    +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
    +

    用个存储过程来插入数据

    +
    
    +delimiter $	#以delimiter来标记用$表示存储过程结束
    +create procedure nullIndex1()
    +begin
    +declare i int;	
    +declare j int;	
    +set i=1;
    +set j=1;
    +while(i<=100) do	
    +	while(j<=100) do	
    +		IF (i % 3 = 0) THEN
    +	     INSERT INTO null_index_t ( `null_key`, `null_key1`, `null_key2` ) VALUES (null , LEFT(MD5(RAND()), 8), LEFT(MD5(RAND()), 8));
    +    ELSEIF (i % 3 = 1) THEN
    +			 INSERT INTO null_index_t ( `null_key`, `null_key1`, `null_key2` ) VALUES (LEFT(MD5(RAND()), 8), NULL, LEFT(MD5(RAND()), 8));
    +	  ELSE
    +			 INSERT INTO null_index_t ( `null_key`, `null_key1`, `null_key2` ) VALUES (LEFT(MD5(RAND()), 8), LEFT(MD5(RAND()), 8), NULL);
    +    END IF;
    +		set j=j+1;
    +	end while;
    +	set i=i+1;
    +	set j=1;	
    +end while;
    +end 
    +$
    +call nullIndex1();
    +

    然后看下我们的 is null 查询

    +
    EXPLAIN select * from null_index_t WHERE null_key is null;
    +


    再来看看另一个

    +
    EXPLAIN select * from null_index_t WHERE null_key is not null;
    +


    从这里能看出来啥呢,可以思考下

    +

    从上面可以发现,is null应该是用上了索引了,所以至少不是一刀切不能用,但是看着is not null好像不太行额
    我们在做一点小改动,把这个表里的数据改成 9100 条是 null,剩下 900 条是有值的,然后再执行下

    然后再来看看执行结果

    +
    EXPLAIN select * from null_index_t WHERE null_key is null;
    +

    +
    EXPLAIN select * from null_index_t WHERE null_key is not null;
    +


    是不是不一样了,这里再补充下我试验使用的 mysql 是 5.7 的,不保证在其他版本的一致性,
    其实可以看出随着数据量的变化,mysql 会不会使用索引是会变化的,不是说 is not null 一定会使用,也不是一定不会使用,而是优化器会根据查询成本做个预判,这个预判尽可能会减小查询成本,主要包括回表啥的,但是也不一定完全准确。

    +]]>
    + + Mysql + C + 索引 + Mysql + + + mysql + 索引 + is null + is not null + procedure + +
    + + 聊聊 redis 缓存的应用问题 + /2021/01/31/%E8%81%8A%E8%81%8A-redis-%E7%BC%93%E5%AD%98%E7%9A%84%E5%BA%94%E7%94%A8%E9%97%AE%E9%A2%98/ + 前面写过一系列的 redis 源码分析的,但是实际上很多的问题还是需要结合实际的使用,然后其实就避不开缓存使用的三个著名问题,穿透,击穿和雪崩,这三个概念也是有着千丝万缕的关系,

    +

    缓存穿透

    缓存穿透是指当数据库中本身就不存在这个数据的时候,使用一般的缓存策略时访问不到缓存后就访问数据库,但是因为数据库也没数据,所以如果不做任何策略优化的话,这类数据就每次都会访问一次数据库,对数据库压力也会比较大。

    +

    缓存击穿

    缓存击穿跟穿透比较类似的,都是访问缓存不在,然后去访问数据库,与穿透不一样的是击穿是在数据库中存在数据,但是可能由于第一次访问,或者缓存过期了,需要访问到数据库,这对于访问量小的情况其实算是个正常情况,但是随着请求量变高就会引发一些性能隐患。

    +

    缓存雪崩

    缓存雪崩就是击穿的大规模集群效应,当大量的缓存过期失效的时候,这些请求都是直接访问到数据库了,会对数据库造成很大的压力。

    +

    对于以上三种场景也有一些比较常见的解决方案,但也不能说是万无一失的,需要随着业务去寻找合适的方案

    +

    解决缓存穿透

    对于数据库中就没这个数据的时候,一种是可以对这个 key 设置下空值,即以一个特定的表示是数据库不存在的,这种情况需要合理地调整过期时间,当这个 key 在数据库中有数据了的话,也需要有策略去更新这个值,并且如果这类 key 非常多,这个方法就会不太合适,就可以使用第二种方法,就是布隆过滤器,bloom filter,前置一个布隆过滤器,当这个 key 在数据库不存在的话,先用布隆过滤器挡一道,如果不在的话就直接返回了,当然布隆过滤器不是绝对的准确的

    +

    解决缓存击穿

    当一个 key 的缓存过期了,如果大量请求过来访问这个 key,请求都会落在数据库里,这个时候就可以使用一些类似于互斥锁的方式去让一个线程去访问数据库,更新缓存,但是这里其实也有个问题,就是如果是热点 key 其实这种方式也比较危险,万一更新失败,或者更新操作的时候耗时比较久,就会有一大堆请求卡在那,这种情况可能需要有一些异步提前刷新缓存,可以结合具体场景选择方式

    +

    解决缓存雪崩

    雪崩的情况是指大批量的 key 都一起过期了,击穿的放大版,大批量的请求都打到数据库上了,一方面有可能直接缓存不可用了,就需要用集群化高可用的缓存服务,然后对于实际使用中也可以使用本地缓存结合 redis 缓存,去提高可用性,再配合一些限流措施,然后就是缓存使用过程总的过期时间最好能加一些随机值,防止在同一时间过期而导致雪崩,结合互斥锁防止大量请求打到数据库。

    +]]>
    + + Redis + 应用 + 缓存 + 缓存 + 穿透 + 击穿 + 雪崩 + + + Redis + 缓存穿透 + 缓存击穿 + 缓存雪崩 + 布隆过滤器 + bloom filter + 互斥锁 + +
    + + 聊聊Java中的单例模式 + /2019/12/21/%E8%81%8A%E8%81%8AJava%E4%B8%AD%E7%9A%84%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F/ + 这是个 Java 面试的高频问题,我也遇到过,以往都是觉得这类题没意思,网上一搜一大堆,也不愿意记,其实说回来,主要还是没静下心来好好去理解,今天无意中看到一个课程,基本帮我把一些疑惑的点讲清楚了,首先单例是啥意思,这个其实是有范围一说,比如我起了个Spring Boot应用,在这个应用范围内,我的常规 bean 是单例的,意味着 getBean 的时候其实永远只会拿到那一个对象,那要怎么来写一个单例呢,首先就是传说中的饿汉模式,也是最简单的

    +

    饿汉模式

    public class Singleton1 {
    +    // 首先,将构造方法变成私有的
    +    private Singleton1() {};
    +    // 创建私有静态实例,这样第一次使用的时候就会进行创建
    +    private static Singleton instance = new Singleton1();
     
    -# Failure analyzers
    -org.springframework.boot.diagnostics.FailureAnalyzer=\
    -org.springframework.boot.autoconfigure.data.redis.RedisUrlSyntaxFailureAnalyzer,\
    -org.springframework.boot.autoconfigure.diagnostics.analyzer.NoSuchBeanDefinitionFailureAnalyzer,\
    -org.springframework.boot.autoconfigure.flyway.FlywayMigrationScriptMissingFailureAnalyzer,\
    -org.springframework.boot.autoconfigure.jdbc.DataSourceBeanCreationFailureAnalyzer,\
    -org.springframework.boot.autoconfigure.jdbc.HikariDriverConfigurationFailureAnalyzer,\
    -org.springframework.boot.autoconfigure.r2dbc.ConnectionFactoryBeanCreationFailureAnalyzer,\
    -org.springframework.boot.autoconfigure.session.NonUniqueSessionRepositoryFailureAnalyzer
    +    // 使用这个对象都是通过这个 getInstance 来获取
    +    public static Singleton1 getInstance() {
    +        return instance;
    +    }
    +    // 瞎写一个静态方法。这里想说的是,如果我们只是要调用 Singleton.getDate(...),
    +    // 本来是不想要生成 Singleton 实例的,不过没办法,已经生成了
    +    public static Date getDate(String mode) {return new Date();}
    +}
    +

    上面借鉴了一些代码,其实这是最基本,也不会错的方法,但是正如其中getDate方法里说的问题,有时候并没有想那这个对象,但是因为我调用了这个类的静态方法,导致对象已经生成了,可能这也是饿汉模式名字的来由,不管三七二十一给你生成个单例就完事了,不管有没有用,但是这种个人觉得也没啥大问题,如果是面试的话最好说出来它的缺点

    +

    饱汉模式

    public class Singleton2 {
    +    // 首先,也是先堵死 new Singleton() 这条路,将构造方法变成私有
    +    private Singleton2() {}
    +    // 和饿汉模式相比,这边不需要先实例化出来,注意这里的 volatile,它是必须的
    +    private static volatile Singleton2 instance = null;
     
    -# Template availability providers
    -org.springframework.boot.autoconfigure.template.TemplateAvailabilityProvider=\
    -org.springframework.boot.autoconfigure.freemarker.FreeMarkerTemplateAvailabilityProvider,\
    -org.springframework.boot.autoconfigure.mustache.MustacheTemplateAvailabilityProvider,\
    -org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAvailabilityProvider,\
    -org.springframework.boot.autoconfigure.thymeleaf.ThymeleafTemplateAvailabilityProvider,\
    -org.springframework.boot.autoconfigure.web.servlet.JspTemplateAvailabilityProvider
    +    private int m = 9;
     
    -# DataSource initializer detectors
    -org.springframework.boot.sql.init.dependency.DatabaseInitializerDetector=\
    -org.springframework.boot.autoconfigure.flyway.FlywayMigrationInitializerDatabaseInitializerDetector
    -
    + public static Singleton getInstance() { + if (instance == null) { + // 加锁 + synchronized (Singleton2.class) { + // 这一次判断也是必须的,不然会有并发问题 + if (instance == null) { + instance = new Singleton2(); + } + } + } + return instance; + } +}
    +

    这里容易错的有三点,理解了其实就比较好记了

    +

    第一点,为啥不在 getInstance 上整个代码块加 synchronized,这个其实比较容易理解,就是锁的力度太大,性能太差了,这点其实也要去理解,可以举个夸张的例子,比如我一个电商的服务,如果为了避免一个人的订单出现问题,是不是可以从请求入口就把他锁住,到请求结束释放,那么里面做的事情都有保障,然而这显然不可能,因为我们想要这种竞态条件抢占资源的时间尽量减少,防止其他线程等待。
    第二点,为啥synchronized之已经检查了 instance == null,还要在里面再检查一次,这个有个术语,叫 double check lock,但是为啥要这么做呢,其实很简单,想象当有两个线程,都过了第一步为空判断,这个时候只有一个线程能拿到这个锁,另一个线程就等待了,如果不再判断一次,那么第一个线程新建完对象释放锁之后,第二个线程又能拿到锁,再去创建一个对象。
    第三点,为啥要volatile关键字,原先对它的理解是它修饰的变量在 JMM 中能及时将变量值写到主存中,但是它还有个很重要的作用,就是防止指令重排序,instance = new Singleton();这行代码其实在底层是分成三条指令执行的,第一条是在堆上申请了一块内存放这个对象,但是对象的字段啥的都还是默认值,第二条是设置对象的值,比如上面的 m 是 9,然后第三条是将这个对象和虚拟机栈上的指针建立引用关联,那么如果我不用volatile关键字,这三条指令就有可能出现重排,比如变成了 1-3-2 这种顺序,当执行完第二步时,有个线程来访问这个对象了,先判断是不是空,发现不是空的,就拿去直接用了,是不是就出现问题了,所以这个volatile也是不可缺少的

    +

    嵌套类

    public class Singleton3 {
     
    -

    上面根据 org.springframework.boot.autoconfigure.EnableAutoConfiguration 获取的各个配置类,在通过反射加载就能得到一堆 JavaConfig配置类,然后再根据 ConditionalOnProperty等条件配置加载具体的 bean,大致就是这么个逻辑

    + private Singleton3() {} + // 主要是使用了 嵌套类可以访问外部类的静态属性和静态方法 的特性 + private static class Holder { + private static Singleton3 instance = new Singleton3(); + } + public static Singleton3 getInstance() { + return Holder.instance; + } +}
    +

    这个我个人感觉是饿汉模式的升级版,可以在调用getInstance的时候去实例化对象,也是比较推荐的

    +

    枚举单例

    public enum Singleton {
    +    INSTANCE;
    +    
    +    public void doSomething(){
    +        //todo doSomething
    +    }
    +}
    +

    枚举很特殊,它在类加载的时候会初始化里面的所有的实例,而且 JVM 保证了它们不会再被实例化,所以它天生就是单例的。

    ]]>
    Java - SpringBoot + Design Patterns + Singleton - Java - Spring - SpringBoot - 自动装配 - AutoConfiguration + 设计模式 + Design Patterns + 单例 + Singleton
    @@ -20029,124 +19586,47 @@ constexpr size_t DATA_ROLL_PTR_LEN 内存泄漏是什么鬼

    这里又要看下前面的 ThreadLocalMap 结构了,类似 HashMap,它有个 Entry 结构,在设置的时候会先包装成一个 Entry

    private void set(ThreadLocal<?> key, Object value) {
     
    -        // We don't use a fast path as with get() because it is at
    -        // least as common to use set() to create new entries as
    -        // it is to replace existing ones, in which case, a fast
    -        // path would fail more often than not.
    -
    -        Entry[] tab = table;
    -        int len = tab.length;
    -        int i = key.threadLocalHashCode & (len-1);
    -
    -        for (Entry e = tab[i];
    -             e != null;
    -             e = tab[i = nextIndex(i, len)]) {
    -            ThreadLocal<?> k = e.get();
    -
    -            if (k == key) {
    -                e.value = value;
    -                return;
    -            }
    -
    -            if (k == null) {
    -                replaceStaleEntry(key, value, i);
    -                return;
    -            }
    -        }
    -
    -        tab[i] = new Entry(key, value);
    -        int sz = ++size;
    -        if (!cleanSomeSlots(i, sz) && sz >= threshold)
    -            rehash();
    -}
    -

    这里其实比较重要的就是前面的 Entry 的构造方法,Entry 是个 WeakReference 的子类,然后在构造方法里可以看到 key 会被包装成一个弱引用,这里为什么使用弱引用,其实是方便这个 key 被回收,如果前面的 ThreadLocal tl实例被设置成 null 了,如果这里是直接的强引用的话,就只能等到线程整个回收了,但是其实是弱引用也会有问题,主要是因为这个 value,如果在 ThreadLocal tl 被设置成 null 了,那么其实这个 value 就会没法被访问到,所以最好的操作还是在使用完了就 remove 掉

    -]]> - - Java - - - Java - ThreadLocal - 弱引用 - 内存泄漏 - WeakReference - -
    - - 聊聊一次 brew update 引发的血案 - /2020/06/13/%E8%81%8A%E8%81%8A%E4%B8%80%E6%AC%A1-brew-update-%E5%BC%95%E5%8F%91%E7%9A%84%E8%A1%80%E6%A1%88/ - 熟悉我的人(谁熟悉你啊🙄)知道我以前写过 PHP,虽然现在在工作中没用到了,但是自己的一些小工具还是会用 PHP 来写,但是在 Mac 碰到了一个环境相关的问题,因为我也是个更新狂魔,用了 brew 之后因为 gfw 的原因,如果长时间不更新,有时候要装一个用它装一个软件的话,前置的更新耗时就会让人非常头大,所以我基本会隔天 update 一下,但是这样会带来一个很心烦的问题,就是像这样,因为我是要用一个固定版本的 PHP,如果一直升需要一直配扩展啥的也很麻烦,如果一直升级 PHP 到最新版可能会比较少碰到这个问题

    -
    dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.64.dylib
    -

    这是什么鬼啊,然后我去这个目录下看了下,已经都是libicui18n.67.dylib了,而且它没有把原来的版本保留下来,首先这个是个叫 icu4c是啥玩意,谷歌了一下

    -
    -

    ICU4C是ICU在C/C++平台下的版本, ICU(International Component for Unicode)是基于”IBM公共许可证”的,与开源组织合作研究的, 用于支持软件国际化的开源项目。ICU4C提供了C/C++平台强大的国际化开发能力,软件开发者几乎可以使用ICU4C解决任何国际化的问题,根据各地的风俗和语言习惯,实现对数字、货币、时间、日期、和消息的格式化、解析,对字符串进行大小写转换、整理、搜索和排序等功能,必须一提的是,ICU4C提供了强大的BIDI算法,对阿拉伯语等BIDI语言提供了完善的支持。

    -
    -

    然后首先想到的解决方案就是能不能我使用brew install icu4c@64来重装下原来的版本,发现不行,并木有,之前的做法就只能是去网上把 64 的下载下来,然后放到这个目录,比较麻烦不智能,虽然没抱着希望在谷歌着,不过这次竟然给我找到了一个我认为非常 nice 的解决方案,因为是在 Stack Overflow 找到的,本着写给像我这样的小小白看的,那就稍微翻译一下
    第一步,我们到 brew的目录下

    -
    cd $(brew --prefix)/Homebrew/Library/Taps/homebrew/homebrew-core/Formula
    -

    这个可以理解为是 maven 的 pom 文件,不过有很多不同之处,使用ruby 写的,然后一个文件对应一个组件或者软件,那我们看下有个叫icu4c.rb的文件,
    第二步看看它的提交历史

    -
    git log --follow icu4c.rb
    -

    在 git log 的海洋中寻找,寻找它的(64版本)的身影

    第三步注意这三个红框,Stack Overflow 给出来的答案这一步是找到这个 commit id 直接切出一个新分支

    -
    git checkout -b icu4c-63 e7f0f10dc63b1dc1061d475f1a61d01b70ef2cb7
    -

    其实注意 commit id 旁边的红框,这个是有tag 的,可以直接

    -
    git checkout icu4c-64
    -

    PS: 因为我的问题是出在 64 的问题,Stack Overflow 回答的是 63 的,反正是一样的解决方法
    第四部,切回去之后我们就可以用 brew 提供的基于文件的安装命令来重新装上 64 版本

    -
    brew reinstall ./icu4c.rb
    -

    然后就是第五步,切换版本

    -
    brew switch icu4c 64.2
    -

    最后把分支切回来

    -
    git checkout master
    -

    是不是感觉很厉害的解决方法,大佬还提供了一个更牛的,直接写个 zsh 方法

    -
    # zsh
    -function hiicu64() {
    -  local last_dir=$(pwd)
    -
    -  cd $(brew --prefix)/Homebrew/Library/Taps/homebrew/homebrew-core/Formula
    -  git checkout icu4c-4
    -  brew reinstall ./icu4c.rb
    -  brew switch icu4c 64.2
    -  git checkout master
    +        // We don't use a fast path as with get() because it is at
    +        // least as common to use set() to create new entries as
    +        // it is to replace existing ones, in which case, a fast
    +        // path would fail more often than not.
     
    -  cd $last_dir
    -}
    -

    对应自己的版本改改版本号就可以了,非常好用。

    -]]>
    - - Mac - PHP - Homebrew - PHP - icu4c - - - Mac - PHP - Homebrew - icu4c - zsh - -
    - - 聊聊我刚学会的应用诊断方法 - /2020/05/22/%E8%81%8A%E8%81%8A%E6%88%91%E5%88%9A%E5%AD%A6%E4%BC%9A%E7%9A%84%E5%BA%94%E7%94%A8%E8%AF%8A%E6%96%AD%E6%96%B9%E6%B3%95/ - 因为传说中的出身问题,我以前写的是PHP,在使用 swoole 之前,基本的应用调试手段就是简单粗暴的 var_dump,exit,对于单进程模型的 PHP 也是简单有效,技术栈换成 Java 之后,就变得没那么容易,一方面是需要编译,另一方面是一般都是基于 spring 的项目,如果问题定位比较模糊,那框架层的是很难靠简单的 System.out.println 或者打 log 解决,(PS:我觉得可能我写的东西比较适合从 PHP 这种弱类型语言转到 Java 的小白同学)这个时候一方面因为是 Java,有了非常好用的 idea IDE 的支持,可以各种花式调试,条件断点尤其牛叉,但是又因为有 Spring+Java 的双重原因,有些情况下单步调试可以把手按废掉,这也是我之前一直比较困惑苦逼的点,后来随着慢慢精(jiang)进(you)之后,比如对于一个 oom 的情况,我们可以通过启动参数加上-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=xx/xx 来配置溢出时的堆dump 日志,获取到这个文件后,我们可以通过像 Memory Analyzer (MAT)[https://www.eclipse.org/mat/] (The Eclipse Memory Analyzer is a fast and feature-rich Java heap analyzer that helps you find memory leaks and reduce memory consumption.)来查看诊断问题所在,之前用到的时候是因为有个死循环一直往链表里塞数据,属于比较简单的,后来一次是由于运维进行应用迁移时按默认的统一配置了堆内存大小,导致内存的确不够用,所以溢出了,
    今天想说的其实主要是我们的 thread dump,这也是我最近才真正用的一个方法,可能真的很小白了,用过 ide 的单步调试其实都知道会有一个一层层的玩意,比如函数从 A,调用了 B,再从 B 调用了 C,一直往下(因为是 Java,所以还有很多🤦‍♂️),这个其实也是大部分语言的调用模型,利用了栈这个数据结构,通过这个结构我们可以知道代码的调用链路,由于对于一个 spring 应用,在本身框架代码量非常庞大的情况下,外加如果应用代码也是非常多的时候,有时候通过单步调试真的很难短时间定位到问题,需要非常大的耐心和仔细观察,当然不是说完全不行,举个例子当我的应用经常启动需要非常长的时间,因为本身应用有非常多个 bean,比较难说究竟是 bean 的加载的确很慢还是有什么异常原因,这种时候就可以使用 thread dump 了,具体怎么操作呢

    如果在idea 中运行或者调试时,可以直接点击这个照相机一样的按钮,右边就会出现了左边会显示所有的线程,右边会显示线程栈,

    -
    "main@1" prio=5 tid=0x1 nid=NA runnable
    -  java.lang.Thread.State: RUNNABLE
    -	  at TreeDistance.treeDist(TreeDistance.java:64)
    -	  at TreeDistance.treeDist(TreeDistance.java:65)
    -	  at TreeDistance.treeDist(TreeDistance.java:65)
    -	  at TreeDistance.treeDist(TreeDistance.java:65)
    -	  at TreeDistance.main(TreeDistance.java:45)
    -

    这就是我们主线程的堆栈信息了,main 表示这个线程名,prio表示优先级,默认是 5,tid 表示线程 id,nid 表示对应的系统线程,后面的runnable 表示目前线程状态,因为是被我打了断点,所以是就许状态,然后下面就是对应的线程栈内容了,在TreeDistance类的 treeDist方法中,对应的文件行数是 64 行。
    这里使用 thread dump一般也不会是上面我截图代码里的这种代码量很少的,一般是大型项目,有时候跑着跑着没反应,又不知道跑到哪了,特别是一些刚接触的大项目或者需要定位一个大项目的一个疑难问题,一时没思路时,可以使用这个方法,个人觉得非常有帮助。

    + Entry[] tab = table; + int len = tab.length; + int i = key.threadLocalHashCode & (len-1); + + for (Entry e = tab[i]; + e != null; + e = tab[i = nextIndex(i, len)]) { + ThreadLocal<?> k = e.get(); + + if (k == key) { + e.value = value; + return; + } + + if (k == null) { + replaceStaleEntry(key, value, i); + return; + } + } + + tab[i] = new Entry(key, value); + int sz = ++size; + if (!cleanSomeSlots(i, sz) && sz >= threshold) + rehash(); +}
    +

    这里其实比较重要的就是前面的 Entry 的构造方法,Entry 是个 WeakReference 的子类,然后在构造方法里可以看到 key 会被包装成一个弱引用,这里为什么使用弱引用,其实是方便这个 key 被回收,如果前面的 ThreadLocal tl实例被设置成 null 了,如果这里是直接的强引用的话,就只能等到线程整个回收了,但是其实是弱引用也会有问题,主要是因为这个 value,如果在 ThreadLocal tl 被设置成 null 了,那么其实这个 value 就会没法被访问到,所以最好的操作还是在使用完了就 remove 掉

    ]]> Java - Thread dump - 问题排查 - 工具 Java - Thread dump + ThreadLocal + 弱引用 + 内存泄漏 + WeakReference @@ -20197,16 +19677,27 @@ constexpr size_t DATA_ROLL_PTR_LEN - 聊聊我的远程工作体验 - /2022/06/26/%E8%81%8A%E8%81%8A%E6%88%91%E7%9A%84%E8%BF%9C%E7%A8%8B%E5%B7%A5%E4%BD%9C%E4%BD%93%E9%AA%8C/ - 发生疫情之后,因为正好是春节假期,假期结束的时候还不具备回工作地点办公的条件,所以史无前例地开始了远程办公,以前对于远程办公的概念还停留在国外一些有“格局”的企业会允许员工远程办公,当然对于远程办公这个事情本身我个人也并不是全然支持的态度,其中涉及到很多方面,首先远程办公并不代表就是不用去办公地点上班,可以在家里摸鱼,相对能够得到较高报酬的能够远程办公的企业需要在远程办公期间能够有高效的产出,并且也需要像在公司办公地点一样,能随时被联系到,第二点是薪资福利之外的社保公积金,除非薪资相比非远程办公的企业高出比较多,不然没法 cover 企业额外缴纳的社保公积金,听说有部分企业也会远程办公点给员工上社保,但是毕竟能做到这点的很少,在允许远程办公的企业数量这个本来就不大的基数里,大概率是少之又少了。
    疫情这个特殊原因开始的远程办公体验也算是开了个之前不太容易开的头,也跟我前面说的第一点有关系,大部分的企业也会担心员工远程办公是否有与在公司办公地点办公一样或者比较接近的办公效率。同时我们在开始远程办公的时候也碰到了因为原先没做过相应准备而导致的许多问题,首先基础设施上就有几个问题,第一个是办公电脑的问题,因为整个公司各个部门的工作性质和内容不同,并不是每个部门都是配笔记本的,或者有些部门并不需要想研发一样带上电脑 on call,所以那么使用台式机或者没有将笔记本带回家的则需要自己准备电脑或者让公司邮寄。第二个是远程网络的问题,像我们公司有研发团队平时也已经准备好了 vpn,但是在这种时候我们没准备好的是 vpn 带宽,毕竟平时只会偶尔有需要连一下 vpn 到公司网络,像这样大量员工都需要连接 vpn 进行工作的话,我们的初步体验就是网络卡的不行,一些远程调试工作没法进行,并且还有一些问题是可能只有我们研发会碰到,比如我们的线上测试服务器网络在办公地点是有网络打通的,但是我们在家就没办法连接,还有就是沟通效率相关,因为这是个全国性的情况,线上会议工具原先都是为特定用户使用,并且视频音频实时传输所需要的带宽质量要求也是比较高的,大规模的远程会议沟通需求让这些做线上会议的服务也算是碰上了类似双十一的大考了,我们是先后使用了 zoom,腾讯会议跟钉钉视频会议,使用体验上来说是 zoom 做得相对比较成熟和稳定,不过后面腾讯会议跟钉钉视频会议也开始赶上来。
    前面说的这几个点都是得有远程办公经验的公司才会提前做好相应的准备,比如可以做动态网络扩容,能够在需要大量员工连接公司网络的情况下快速响应提升带宽,另一些则是偏软性的,比如如如何在远程办公的条件下控制我们项目进度,如果保证沟通信息是否能像当面沟通那样准确传达,这方面其实我的经验也是边实操边优化的,最开始我们可能为了高效同步消息,会频繁的使用视频会议沟通,这其实并不能解决沟通效率问题,反而打扰了正常的工作,后续我们在特别是做项目过程中就通过相对简单的每日早会和日报机制,将每天的进度与问题风险点进行同步确认,只与相关直接干系人进行视频电话沟通确认,并且要保持一个思维,即远程办公比较适宜的是相对比较成熟的团队,平常工作和合作都已经有默契或者说规则并且能够遵守,在这个前提下,将目光专注于做的事情而不是管到具体的人有没有全天都在高效工作。同样也希望国内的环境能够有更多的远程火种成长起来,让它成为更好的工作方式,WLB!

    + 聊聊我刚学会的应用诊断方法 + /2020/05/22/%E8%81%8A%E8%81%8A%E6%88%91%E5%88%9A%E5%AD%A6%E4%BC%9A%E7%9A%84%E5%BA%94%E7%94%A8%E8%AF%8A%E6%96%AD%E6%96%B9%E6%B3%95/ + 因为传说中的出身问题,我以前写的是PHP,在使用 swoole 之前,基本的应用调试手段就是简单粗暴的 var_dump,exit,对于单进程模型的 PHP 也是简单有效,技术栈换成 Java 之后,就变得没那么容易,一方面是需要编译,另一方面是一般都是基于 spring 的项目,如果问题定位比较模糊,那框架层的是很难靠简单的 System.out.println 或者打 log 解决,(PS:我觉得可能我写的东西比较适合从 PHP 这种弱类型语言转到 Java 的小白同学)这个时候一方面因为是 Java,有了非常好用的 idea IDE 的支持,可以各种花式调试,条件断点尤其牛叉,但是又因为有 Spring+Java 的双重原因,有些情况下单步调试可以把手按废掉,这也是我之前一直比较困惑苦逼的点,后来随着慢慢精(jiang)进(you)之后,比如对于一个 oom 的情况,我们可以通过启动参数加上-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=xx/xx 来配置溢出时的堆dump 日志,获取到这个文件后,我们可以通过像 Memory Analyzer (MAT)[https://www.eclipse.org/mat/] (The Eclipse Memory Analyzer is a fast and feature-rich Java heap analyzer that helps you find memory leaks and reduce memory consumption.)来查看诊断问题所在,之前用到的时候是因为有个死循环一直往链表里塞数据,属于比较简单的,后来一次是由于运维进行应用迁移时按默认的统一配置了堆内存大小,导致内存的确不够用,所以溢出了,
    今天想说的其实主要是我们的 thread dump,这也是我最近才真正用的一个方法,可能真的很小白了,用过 ide 的单步调试其实都知道会有一个一层层的玩意,比如函数从 A,调用了 B,再从 B 调用了 C,一直往下(因为是 Java,所以还有很多🤦‍♂️),这个其实也是大部分语言的调用模型,利用了栈这个数据结构,通过这个结构我们可以知道代码的调用链路,由于对于一个 spring 应用,在本身框架代码量非常庞大的情况下,外加如果应用代码也是非常多的时候,有时候通过单步调试真的很难短时间定位到问题,需要非常大的耐心和仔细观察,当然不是说完全不行,举个例子当我的应用经常启动需要非常长的时间,因为本身应用有非常多个 bean,比较难说究竟是 bean 的加载的确很慢还是有什么异常原因,这种时候就可以使用 thread dump 了,具体怎么操作呢

    如果在idea 中运行或者调试时,可以直接点击这个照相机一样的按钮,右边就会出现了左边会显示所有的线程,右边会显示线程栈,

    +
    "main@1" prio=5 tid=0x1 nid=NA runnable
    +  java.lang.Thread.State: RUNNABLE
    +	  at TreeDistance.treeDist(TreeDistance.java:64)
    +	  at TreeDistance.treeDist(TreeDistance.java:65)
    +	  at TreeDistance.treeDist(TreeDistance.java:65)
    +	  at TreeDistance.treeDist(TreeDistance.java:65)
    +	  at TreeDistance.main(TreeDistance.java:45)
    +

    这就是我们主线程的堆栈信息了,main 表示这个线程名,prio表示优先级,默认是 5,tid 表示线程 id,nid 表示对应的系统线程,后面的runnable 表示目前线程状态,因为是被我打了断点,所以是就许状态,然后下面就是对应的线程栈内容了,在TreeDistance类的 treeDist方法中,对应的文件行数是 64 行。
    这里使用 thread dump一般也不会是上面我截图代码里的这种代码量很少的,一般是大型项目,有时候跑着跑着没反应,又不知道跑到哪了,特别是一些刚接触的大项目或者需要定位一个大项目的一个疑难问题,一时没思路时,可以使用这个方法,个人觉得非常有帮助。

    ]]>
    - 生活 + Java + Thread dump + 问题排查 + 工具 - 生活 - 远程办公 + Java + Thread dump
    @@ -20253,6 +19744,19 @@ constexpr size_t DATA_ROLL_PTR_LEN 3PC + + 聊聊我的远程工作体验 + /2022/06/26/%E8%81%8A%E8%81%8A%E6%88%91%E7%9A%84%E8%BF%9C%E7%A8%8B%E5%B7%A5%E4%BD%9C%E4%BD%93%E9%AA%8C/ + 发生疫情之后,因为正好是春节假期,假期结束的时候还不具备回工作地点办公的条件,所以史无前例地开始了远程办公,以前对于远程办公的概念还停留在国外一些有“格局”的企业会允许员工远程办公,当然对于远程办公这个事情本身我个人也并不是全然支持的态度,其中涉及到很多方面,首先远程办公并不代表就是不用去办公地点上班,可以在家里摸鱼,相对能够得到较高报酬的能够远程办公的企业需要在远程办公期间能够有高效的产出,并且也需要像在公司办公地点一样,能随时被联系到,第二点是薪资福利之外的社保公积金,除非薪资相比非远程办公的企业高出比较多,不然没法 cover 企业额外缴纳的社保公积金,听说有部分企业也会远程办公点给员工上社保,但是毕竟能做到这点的很少,在允许远程办公的企业数量这个本来就不大的基数里,大概率是少之又少了。
    疫情这个特殊原因开始的远程办公体验也算是开了个之前不太容易开的头,也跟我前面说的第一点有关系,大部分的企业也会担心员工远程办公是否有与在公司办公地点办公一样或者比较接近的办公效率。同时我们在开始远程办公的时候也碰到了因为原先没做过相应准备而导致的许多问题,首先基础设施上就有几个问题,第一个是办公电脑的问题,因为整个公司各个部门的工作性质和内容不同,并不是每个部门都是配笔记本的,或者有些部门并不需要想研发一样带上电脑 on call,所以那么使用台式机或者没有将笔记本带回家的则需要自己准备电脑或者让公司邮寄。第二个是远程网络的问题,像我们公司有研发团队平时也已经准备好了 vpn,但是在这种时候我们没准备好的是 vpn 带宽,毕竟平时只会偶尔有需要连一下 vpn 到公司网络,像这样大量员工都需要连接 vpn 进行工作的话,我们的初步体验就是网络卡的不行,一些远程调试工作没法进行,并且还有一些问题是可能只有我们研发会碰到,比如我们的线上测试服务器网络在办公地点是有网络打通的,但是我们在家就没办法连接,还有就是沟通效率相关,因为这是个全国性的情况,线上会议工具原先都是为特定用户使用,并且视频音频实时传输所需要的带宽质量要求也是比较高的,大规模的远程会议沟通需求让这些做线上会议的服务也算是碰上了类似双十一的大考了,我们是先后使用了 zoom,腾讯会议跟钉钉视频会议,使用体验上来说是 zoom 做得相对比较成熟和稳定,不过后面腾讯会议跟钉钉视频会议也开始赶上来。
    前面说的这几个点都是得有远程办公经验的公司才会提前做好相应的准备,比如可以做动态网络扩容,能够在需要大量员工连接公司网络的情况下快速响应提升带宽,另一些则是偏软性的,比如如如何在远程办公的条件下控制我们项目进度,如果保证沟通信息是否能像当面沟通那样准确传达,这方面其实我的经验也是边实操边优化的,最开始我们可能为了高效同步消息,会频繁的使用视频会议沟通,这其实并不能解决沟通效率问题,反而打扰了正常的工作,后续我们在特别是做项目过程中就通过相对简单的每日早会和日报机制,将每天的进度与问题风险点进行同步确认,只与相关直接干系人进行视频电话沟通确认,并且要保持一个思维,即远程办公比较适宜的是相对比较成熟的团队,平常工作和合作都已经有默契或者说规则并且能够遵守,在这个前提下,将目光专注于做的事情而不是管到具体的人有没有全天都在高效工作。同样也希望国内的环境能够有更多的远程火种成长起来,让它成为更好的工作方式,WLB!

    +]]>
    + + 生活 + + + 生活 + 远程办公 + +
    聊聊最近平淡的生活之又聊通勤 /2021/11/07/%E8%81%8A%E8%81%8A%E6%9C%80%E8%BF%91%E5%B9%B3%E6%B7%A1%E7%9A%84%E7%94%9F%E6%B4%BB/ @@ -20265,28 +19769,510 @@ constexpr size_t DATA_ROLL_PTR_LEN 生活 - 生活 - 糟心事 - 规则 - 电瓶车 - 骑车 + 生活 + 糟心事 + 规则 + 电瓶车 + 骑车 + + + + 聊聊最近平淡的生活之看《神探狄仁杰》 + /2021/12/19/%E8%81%8A%E8%81%8A%E6%9C%80%E8%BF%91%E5%B9%B3%E6%B7%A1%E7%9A%84%E7%94%9F%E6%B4%BB%E4%B9%8B%E7%9C%8B%E3%80%8A%E7%A5%9E%E6%8E%A2%E7%8B%84%E4%BB%81%E6%9D%B0%E3%80%8B/ + 其实最近看的不止这一部,前面看了《继承者们》,《少年包青天》这些,就一起聊下,其中看《继承者们》算是个人比较喜欢,以前就有这种看剧的习惯,这个跟《一生一世》里任嘉伦说自己看《寻秦记》看了几十遍一样,我看喜欢的剧也基本上会看不止五遍,继承者们是有帅哥美女看,而且印象中剧情也挺甜的,一般情况下最好是已经有点遗忘剧情了,因为我个人觉得看剧分两种,无聊了又心情不太好,可以看些这类轻松又看过的剧,可以不完全专心地看剧,另外有心情专心看的时候,可以看一些需要思考,一些探案类的或者烧脑类。
    最近看了《神探狄仁杰》,因为跟前面看的《少年包青天》都是这类古装探案剧,正好有些感想,《少年包青天》算是儿时阴影,本来是不太会去看的,正好有一次有机会跟 LD 一起看了会就也觉得比较有意思就看了下去,不得不说,以前的这些剧还是很不错的,包括剧情和演员,第一部一共是 40 集,看的过程中也发现了大概是五个案子,平均八集一个案子,整体节奏还是比较慢的,但是基本每个案子其实都是构思得很巧妙,很久以前看过但是现在基本不太记得剧情了,每个案子在前面几集的时候基本都猜不到犯案逻辑,但是在看了狄仁杰之后,发现两部剧也有比较大的差别,少年包青天相对来说逻辑性会更强一些,个人主观觉得推理的严谨性更高,可能剧本打磨上更将就一下,而狄仁杰因为要提现他的个人强项,不比少年包青天中有公孙策一时瑜亮的情节,狄仁杰中分工明确,李元芳是个武力担当,曾泰是捧哏的,相对来说是狄仁杰在案子里从始至终地推进案情,有些甚至有些玄乎,会有一些跳脱跟不合理,有些像是狄仁杰的奇遇,不过这些想法是私人的观点,并不是想要评孰优孰劣;第二个感受是不知道是不是年代关系,特别是少年包青天,每个案件的大 boss 基本都不是个完全的坏人,甚至都是比较情有可原的可怜人,因为一些特殊原因,而好几个都是包拯身边的人,这一点其实跟狄仁杰里第一个使团惊魂案件比较类似,虎敬晖也是个人物形象比较丰满的角色,不是个标签化的淡薄形象,跟金木兰的感情和反叛行动在最后都说明的缘由,而且也有随着跟狄仁杰一起办案被其影响感化,最终为了救狄仁杰而被金木兰所杀,只是这样金木兰这个角色就会有些偏执和符号化,当然剧本肯定不是能面面俱到,这样的剧本已经比现在很多流量剧的好很多了。还想到了前阵子看的《指环王》中的白袍萨鲁曼在剧中也是个比较单薄的角色,这样的电影彪炳影史也没办法把个个人物都设计得完整有血有肉,或者说这本来也是应该有侧重点,当然其实我也不觉得指环王就是绝对的最好的,因为相对来说故事情节的复杂性等真的不如西游记,只是在 86 版之后的各种乱七八糟的翻牌和乱拍已经让这个真正的王者神话故事有点力不从心,这里边有部西游记后传是个人还比较喜欢的,虽然武打动作比较鬼畜,但是剧情基本是无敌的,在西游的架构上衍生出来这么完整丰富的故事,人物角色也都有各自的出彩点。
    说回狄仁杰,在这之前也看过徐克拍的几部狄仁杰的电影版,第一部刘德华拍得相对完成度更高,故事性也可圈可点,后面几部就是剧情拉胯,靠特效拉回来一点分,虽说这个也是所谓的狄仁杰宇宙的构思在里面但是现在来看基本是跟西游那些差不多,完全没有整体性可言,打一枪换一个地方,演员也没有延续性,剧情也是前后跳脱,没什么关联跟承上启下,导致质量层次不一,更不用谈什么狄仁杰宇宙了,不过这个事情也是难说,原因很多,现在资本都是更加趋利的,一些需要更长久时间才能有回报的投资是很难获得资本青睐,所以只能将重心投给选择一些流量明星,而本来应该将资源投给剧本打磨的基本就没了,再深入说也没意义了,社会现状就是这样。
    还有一点感想是,以前的剧里的拍摄环境还是比较惨的,看着一些房子,甚至皇宫都是比较破旧的,地面还是石板这种,想想以前的演员的环境再想想现在的,比如成龙说的,以前他拍剧就是啪摔了,问这条有没有过,过了就直接送医院,而不是现在可能手蹭破点皮就大叫,甚至还有饭圈这些破事。

    +]]>
    + + 生活 + + + 生活 + 看剧 + +
    + + 聊聊最近平淡的生活之看看老剧 + /2021/11/21/%E8%81%8A%E8%81%8A%E6%9C%80%E8%BF%91%E5%B9%B3%E6%B7%A1%E7%9A%84%E7%94%9F%E6%B4%BB%E4%B9%8B%E7%9C%8B%E7%9C%8B%E8%80%81%E5%89%A7/ + 最近因为也没什么好看的新剧和综艺所以就看看一些以前看过的老剧,我是个非常念旧的人吧,很多剧都会反反复复地看,一方面之前看过觉得好看的的确是一直记着,还有就是平时工作完了回来就想能放松下,剧情太纠结的,太烧脑的都不喜欢,也就是我常挂在口头的不喜欢看费脑子的剧,跟我不喜欢狼人杀的原因也类似。

    +

    前面其实是看的太阳的后裔,跟 LD 一起看的,之前其实算是看过一点,但是没有看的很完整,并且很多剧情也忘了,只是这个我我可能看得更少一点,因为最开始的时候觉得男主应该是男二,可能对长得这样的男主并且是这样的人设有点失望,感觉不是特别像个特种兵,但是由于本来也比较火,而且 LD 比较喜欢就从这个开始看了,有两个点是比较想说的

    +

    韩剧虽然被吐槽的很多,但是很多剧的质量,情节把控还是优于目前非常多国内剧的,相对来说剧情发展的前后承接不是那么硬凹出来的,而且人设都立得住,这个是非常重要的,很多国内剧怎么说呢,就是当爹的看起来就比儿子没大几岁,三四十岁的人去演一个十岁出头的小姑娘,除非容貌异常,比如刘晓庆这种,不然就会觉得导演在把我们观众当傻子。瞬间就没有想看下去的欲望了。

    +

    再一点就是情节是大众都能接受度比较高的,现在有很多普遍会找一些新奇的视角,比如卖腐,想某某令,两部都叫某某令,这其实是一个点,延伸出去就是跟前面说的一点有点类似,xx 老祖,人看着就二三十,叫 xx 老祖,(喜欢的人轻喷哈)然后名字有一堆,同一个人物一会叫这个名字,一会又叫另一个名字,然后一堆死表情。

    +

    因为今天有个特殊的事情发生,所以简短的写(shui)一篇了

    +]]>
    + + 生活 + + + 生活 + 看剧 + +
    + + 聊聊给亲戚朋友的老电脑重装系统那些事儿 + /2021/05/09/%E8%81%8A%E8%81%8A%E7%BB%99%E4%BA%B2%E6%88%9A%E6%9C%8B%E5%8F%8B%E7%9A%84%E8%80%81%E7%94%B5%E8%84%91%E9%87%8D%E8%A3%85%E7%B3%BB%E7%BB%9F%E9%82%A3%E4%BA%9B%E4%BA%8B%E5%84%BF/ + 前面这个五一回去之前,LD 姐姐跟我说电脑很卡了,想让我重装系统,问了下 LD 可能是那个 09 年买的笔记本,想想有点害怕[捂脸],前年有一次好像让我帮忙装了她同事的一个三星的笔记本,本着一些系统洁癖,所以就从开始找纯净版的 win7 家庭版,因为之前那些本基本都自带 win7 的家庭版,而且把激活码就贴在机器下面,然后从三星官网去找官方驱动,还好这个机型的驱动还在,先做了系统镜像,其实感觉这种情况需要两个 U 盘,一个 U 盘装系统作为安装启动盘,一个放驱动,毕竟不是专业装系统的,然后因为官方驱动需要一个个下载一个个安装,然后驱动文件下载的地方还没标明是 32 位还是 64 位的,结果还被 LD 姐姐催着,一直问好没好,略尴尬,索性还是找个一键安装的

    +

    这次甚至更夸张,上次还让带回去,我准备好了系统镜像啥的,第二天装,这次直接带了两个老旧笔记本过来说让当天就装好,感觉有点像被当修电脑的使,又说这些电脑其实都不用了的,都是为了她们当医生的要每年看会课,然后只能用电脑浏览器看,结果都在用 360 浏览器,真的是万恶的 360,其实以前对 360 没啥坏印象,毕竟以前也经常用,只是对于这些老电脑,360 全家桶真的就是装了就废了,2G 的内存,开机就开着 360 安全卫士,360 杀毒,有一个还装了腾讯电脑管家,然后腾讯视频跟爱奇艺也开机启动了,然后还打开 360 浏览器看课,就算再好的系统也吃不消这么用,重装了系统,还是这么装这些东西,也是分分钟变卡,可惜他们都没啥这类概念。

    +

    对于他们要看的课,更搞笑的是,明明在页面上注明了说要使用 IE 浏览器,结果他们都在用 360 浏览器看,但是这个也不能完全怪他们,因为实在是现在的 IE 啥的也有开始不兼容 flash 的配置,需要开启兼容配置,但是只要开启了之后就可以直接用 IE 看,比 360 靠谱很多, 资源占用也比较少,360 估计是基于 chromium 加了很多内置的插件,本身 chromium 也是内存大户,但是说这些其实他们也不懂,总觉得找我免费装下系统能撑一段时间,反正对我来说也应该很简单(他们觉得),实际上开始工作以后,我自己想装个双系统都是上淘宝买别人的服务装的,台式机更是几年没动过系统了,因为要重装一大堆软件,数据备份啥的,还有驱动什么的,分区格式,那些驱动精灵啥的也都是越来越坑,一装就给你带一堆垃圾软件。

    +

    感悟是,总觉得学计算机的就应该会装系统,会修电脑,之前亲戚还拿着一个完全开不起来的笔记本让我来修,这真的是,我说可以找官方维修的,结果我说我搞不定,她直接觉得是修不好了,直接电脑都懒得拿回去了,后面又一次反复解释了才明白,另外就是 360 全家桶,别说老电脑了,新机器都不太吃得消。

    +]]>
    + + 生活 + + + 生活 + 装电脑 + 老电脑 + 360 全家桶 + 修电脑的 + +
    + + 聊聊这次换车牌及其他 + /2022/02/20/%E8%81%8A%E8%81%8A%E8%BF%99%E6%AC%A1%E6%8D%A2%E8%BD%A6%E7%89%8C%E5%8F%8A%E5%85%B6%E4%BB%96/ + 去年 8 月份运气比较好,摇到了车牌,本来其实应该很早就开始摇的,前面第一次换工作没注意社保断缴了一个月,也是大意失荆州,后面到了 17 年社保满两年了,好像只摇了一次,还是就没摇过,有点忘了,好像是什么原因导致那次也没摇成功,但是后面暂住证就取消了,需要居住证,居住证又要一年及以上的租房合同,并且那会买车以后也不怎么开,住的地方车位还好,但是公司车位一个月要两三千,甚至还是打车上下班比较实惠,所以也没放在心上,后面摇到房以后,也觉得应该准备起来车子,就开始办了居住证,居住证其实还可以用劳动合同,而且办起来也挺快,大概是三四月份开始摇,到 8 月份的某一天收到短信说摇到了,一开始还挺开心,不过心里抱着也不怎么开,也没怎么大放在心上,不过这里有一点就是我把那个照片直接发出去,上面有着我的身份证号,被 LD 说了一顿,以后也应该小心点,但是后面不知道是哪里看了下,说杭州上牌已经需要国六标准的车了,瞬间感觉是空欢喜了,可是有同事说是可以的,我就又打了官方的电话,结果说可以的,要先转籍,然后再做上牌。

    +

    转籍其实是很方便的,在交警 12123 App 上申请就行了,在转籍以后,需要去实地验车,验车的话,在支付宝-杭州交警生活号里进行预约,找就近的车管所就好,需要准备一些东西,首先是行驶证,机动车登记证书,身份证,居住证,还有车上需要准备的东西是要有三脚架和反光背心,反光背心是最近几个月开始要的,问过之前去验车的只需要三脚架就好了,预约好了的话建议是赶上班时间越早越好,不然过去排队时间要很久,而且人多了以后会很乱,各种插队,而且有很多都是汽车销售,一个销售带着一堆车,我们附近那个进去的小路没一会就堵满车,进去需要先排队,然后扫码,接着交资料,这两个都排着队,如果去晚了就要排很久的队,交完资料才是排队等验车,验车就是打开引擎盖,有人会帮忙拓印发动机车架号,然后验车的会各种检查一下,车里面,还有后备箱,建议车内整理干净点,后备箱不要放杂物,检验完了之后,需要把三脚架跟反光背心放在后备箱盖子上,人在旁边拍个照,然后需要把车牌遮住后再拍个车子的照片,再之后就是去把车牌卸了,这个多吐槽下,那边应该是本来那边师傅帮忙卸车牌,结果他就说是教我们拆,虽然也不算难,但是不排除师傅有在偷懒,完了之后就是把旧车牌交回去,然后需要在手机上(警察叔叔 App)提交各种资料,包括身份证,行驶证,机动车登记证书,提交了之后就等寄车牌过来了。

    +

    这里面缺失的一个环节就是选号了,选号杭州有两个方式,一种就是根据交管局定期发布的选号号段,可以自定义拼 20 个号,在手机上的交警 12123 App 上可以三个一组的形式提交,如果有没被选走的,就可以预选到这个了,但是这种就是也需要有一定策略,最新出的号段能选中的概率大一点,然后数字全是 8,6 这种的肯定会一早就被选走,然后如果跟我一样可以提前选下尾号,因为尾号数字影响限号,我比较有可能周五回家,所以得避开 5,0 的,第二种就是 50 选一跟以前新车选号一样,就不介绍了。第一种选中了以后可以在前面交还旧车牌的时候填上等着寄过来了,因为我是第一种选中的,第二种也可以在手机上选,也在可以在交还车牌的时候现场选。

    +

    总体过程其实是 LD 在各种查资料跟帮我跑来跑去,要不是 LD,估计在交管局那边我就懵逼了,各种插队,而且车子开着车子,也不能随便跑,所以建议办这个的时候有个人一起比较好。

    +]]>
    + + 生活 + + + 生活 + 换车牌 + +
    + + 聊聊那些加塞狗 + /2021/01/17/%E8%81%8A%E8%81%8A%E9%82%A3%E4%BA%9B%E5%8A%A0%E5%A1%9E%E7%8B%97/ + 今天真的是被气得不轻,情况是碰到一个有 70 多秒的直行红灯,然后直行就排了很长的队,但是左转车道没车,就有好几辆车占着左转车道,准备往直行车道插队加塞,一般这种加塞的,会挑个不太计较的,如果前面一辆不让的话就再等等,我因为赶着回家,就不想让,结果那辆车几次车头直接往里冲,当时怒气值基本已经蓄满了,我真的是分毫都不想让,如果路上都是让着这种人的,那么这种情况只会越来越严重,我理解的这种心态,就赌你怕麻烦,多一事不如少一事,结果就是每次都能顺利插队加塞,其实延伸到我们社会中的种种实质性的排队或者等同于排队的情况,都已经有这种惯有思维,一方面这种不符合规则,可能在严重程度上容易被很多人所忽视,基本上已经被很多人当成是“合理”行为,另一方面,对于这些“微小”的违规行为,本身管理层面也基本没有想要管的意思,就更多的成为了纵容这些行为的导火索,并且大多数人都是想着如果不让,发生点小剐小蹭的要浪费很多时间精力来处理,甚至会觉得会被别人觉得自己太小气等等,诸多内外成本结合起来,会真的去硬刚的可能少之又少了,这样也就让更多的人觉得这种行为是被默许的,再举个非常小的例子,以我们公司疫情期间的盒饭发放为例,有两个比较“有意思”的事情,第一个就是因为疫情,本来是让排队要间隔一米,但是可能除了我比较怕死会跟前面的人保持点距离基本没别人会不挨着前面的人,甚至我跟我前面的人保持点距离,后面的同学会推着我让我上去;第二个是关于拿饭,这么多人排着队拿饭,然后有部分同学,一个人拿好几份,帮组里其他人的都拿了,有些甚至一个人拿十份,假如这个盒饭发放是说明了可以按部门直接全领了那就没啥问题,但是当时的状况是个人排队领自己的那一份,如果一个同学直接帮着组里十几个人都拿了,后面排队的人是什么感受呢,甚至有些是看到队伍排长了,就找队伍里自己认识的比较靠前的人说你帮我也拿一份,其实作为我这个比较按规矩办事的“愣头青”来说,我是比较不能接受这两件小事里的行为的,再往下说可能就有点偏激了,先说到这~

    +]]>
    + + 生活 + 开车 + + + 生活 + 开车 + 加塞 + 糟心事 + 规则 + +
    + + 聊聊部分公交车的设计bug + /2021/12/05/%E8%81%8A%E8%81%8A%E9%83%A8%E5%88%86%E5%85%AC%E4%BA%A4%E8%BD%A6%E7%9A%84%E8%AE%BE%E8%AE%A1bug/ + 今天惯例坐公交回住的地方,不小心撞了头,原因是我们想坐倒数第二排,然后LD 走在我后面,我就走到最后一排中间等着,但是最后一排是高一截的,等 LD 坐进去以后,我就往前走,结果撞到了车顶的扶手杆子的一端,差点撞昏了去,这里我觉得其实杆子长度应该短一点,不然从最后一排出来,还是有比较大概率因为没注意看而撞到头,特别是没注意看的情况,发力其实会比较大,一头撞上就会像我这样,眼前一黑,又痛得要死。
    还有一点就是座位设计了,先来看个图

    图里大致画了两条线,因为可能是轮胎还是什么原因,后排中间会有那么大的突起,但是看两条红线可以发现,靠近过道的座位边缘跟地面突起的边缘不是一样宽的,这样导致的结果就是坐着的时候有一个脚没地儿搁,要不就得侧着斜着坐,或者就是一个脚悬空,短程的可能还好,路程远一点还是比较难受的,特别是像我现在这样,大腿外侧有点难受的情况,就会更难受。
    虽然说这两个点,基本是屁用没有,但是我也是在自己这个博客说说,也当是个树洞了。

    +]]>
    + + 生活 + + + 生活 + 公交 + 杭州 + +
    + + 聊聊一次 brew update 引发的血案 + /2020/06/13/%E8%81%8A%E8%81%8A%E4%B8%80%E6%AC%A1-brew-update-%E5%BC%95%E5%8F%91%E7%9A%84%E8%A1%80%E6%A1%88/ + 熟悉我的人(谁熟悉你啊🙄)知道我以前写过 PHP,虽然现在在工作中没用到了,但是自己的一些小工具还是会用 PHP 来写,但是在 Mac 碰到了一个环境相关的问题,因为我也是个更新狂魔,用了 brew 之后因为 gfw 的原因,如果长时间不更新,有时候要装一个用它装一个软件的话,前置的更新耗时就会让人非常头大,所以我基本会隔天 update 一下,但是这样会带来一个很心烦的问题,就是像这样,因为我是要用一个固定版本的 PHP,如果一直升需要一直配扩展啥的也很麻烦,如果一直升级 PHP 到最新版可能会比较少碰到这个问题

    +
    dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.64.dylib
    +

    这是什么鬼啊,然后我去这个目录下看了下,已经都是libicui18n.67.dylib了,而且它没有把原来的版本保留下来,首先这个是个叫 icu4c是啥玩意,谷歌了一下

    +
    +

    ICU4C是ICU在C/C++平台下的版本, ICU(International Component for Unicode)是基于”IBM公共许可证”的,与开源组织合作研究的, 用于支持软件国际化的开源项目。ICU4C提供了C/C++平台强大的国际化开发能力,软件开发者几乎可以使用ICU4C解决任何国际化的问题,根据各地的风俗和语言习惯,实现对数字、货币、时间、日期、和消息的格式化、解析,对字符串进行大小写转换、整理、搜索和排序等功能,必须一提的是,ICU4C提供了强大的BIDI算法,对阿拉伯语等BIDI语言提供了完善的支持。

    +
    +

    然后首先想到的解决方案就是能不能我使用brew install icu4c@64来重装下原来的版本,发现不行,并木有,之前的做法就只能是去网上把 64 的下载下来,然后放到这个目录,比较麻烦不智能,虽然没抱着希望在谷歌着,不过这次竟然给我找到了一个我认为非常 nice 的解决方案,因为是在 Stack Overflow 找到的,本着写给像我这样的小小白看的,那就稍微翻译一下
    第一步,我们到 brew的目录下

    +
    cd $(brew --prefix)/Homebrew/Library/Taps/homebrew/homebrew-core/Formula
    +

    这个可以理解为是 maven 的 pom 文件,不过有很多不同之处,使用ruby 写的,然后一个文件对应一个组件或者软件,那我们看下有个叫icu4c.rb的文件,
    第二步看看它的提交历史

    +
    git log --follow icu4c.rb
    +

    在 git log 的海洋中寻找,寻找它的(64版本)的身影

    第三步注意这三个红框,Stack Overflow 给出来的答案这一步是找到这个 commit id 直接切出一个新分支

    +
    git checkout -b icu4c-63 e7f0f10dc63b1dc1061d475f1a61d01b70ef2cb7
    +

    其实注意 commit id 旁边的红框,这个是有tag 的,可以直接

    +
    git checkout icu4c-64
    +

    PS: 因为我的问题是出在 64 的问题,Stack Overflow 回答的是 63 的,反正是一样的解决方法
    第四部,切回去之后我们就可以用 brew 提供的基于文件的安装命令来重新装上 64 版本

    +
    brew reinstall ./icu4c.rb
    +

    然后就是第五步,切换版本

    +
    brew switch icu4c 64.2
    +

    最后把分支切回来

    +
    git checkout master
    +

    是不是感觉很厉害的解决方法,大佬还提供了一个更牛的,直接写个 zsh 方法

    +
    # zsh
    +function hiicu64() {
    +  local last_dir=$(pwd)
    +
    +  cd $(brew --prefix)/Homebrew/Library/Taps/homebrew/homebrew-core/Formula
    +  git checkout icu4c-4
    +  brew reinstall ./icu4c.rb
    +  brew switch icu4c 64.2
    +  git checkout master
    +
    +  cd $last_dir
    +}
    +

    对应自己的版本改改版本号就可以了,非常好用。

    +]]>
    + + Mac + PHP + Homebrew + PHP + icu4c + + + Mac + PHP + Homebrew + icu4c + zsh
    - 聊聊最近平淡的生活之看看老剧 - /2021/11/21/%E8%81%8A%E8%81%8A%E6%9C%80%E8%BF%91%E5%B9%B3%E6%B7%A1%E7%9A%84%E7%94%9F%E6%B4%BB%E4%B9%8B%E7%9C%8B%E7%9C%8B%E8%80%81%E5%89%A7/ - 最近因为也没什么好看的新剧和综艺所以就看看一些以前看过的老剧,我是个非常念旧的人吧,很多剧都会反反复复地看,一方面之前看过觉得好看的的确是一直记着,还有就是平时工作完了回来就想能放松下,剧情太纠结的,太烧脑的都不喜欢,也就是我常挂在口头的不喜欢看费脑子的剧,跟我不喜欢狼人杀的原因也类似。

    -

    前面其实是看的太阳的后裔,跟 LD 一起看的,之前其实算是看过一点,但是没有看的很完整,并且很多剧情也忘了,只是这个我我可能看得更少一点,因为最开始的时候觉得男主应该是男二,可能对长得这样的男主并且是这样的人设有点失望,感觉不是特别像个特种兵,但是由于本来也比较火,而且 LD 比较喜欢就从这个开始看了,有两个点是比较想说的

    -

    韩剧虽然被吐槽的很多,但是很多剧的质量,情节把控还是优于目前非常多国内剧的,相对来说剧情发展的前后承接不是那么硬凹出来的,而且人设都立得住,这个是非常重要的,很多国内剧怎么说呢,就是当爹的看起来就比儿子没大几岁,三四十岁的人去演一个十岁出头的小姑娘,除非容貌异常,比如刘晓庆这种,不然就会觉得导演在把我们观众当傻子。瞬间就没有想看下去的欲望了。

    -

    再一点就是情节是大众都能接受度比较高的,现在有很多普遍会找一些新奇的视角,比如卖腐,想某某令,两部都叫某某令,这其实是一个点,延伸出去就是跟前面说的一点有点类似,xx 老祖,人看着就二三十,叫 xx 老祖,(喜欢的人轻喷哈)然后名字有一堆,同一个人物一会叫这个名字,一会又叫另一个名字,然后一堆死表情。

    -

    因为今天有个特殊的事情发生,所以简短的写(shui)一篇了

    + 聊聊 SpringBoot 自动装配 + /2021/07/11/%E8%81%8A%E8%81%8ASpringBoot-%E8%87%AA%E5%8A%A8%E8%A3%85%E9%85%8D/ + springboot 自动装配调用链

    +

    springboot 相比 spring能更方便开发人员上手,比较重要的一点就是自动装配,大致来看下这个逻辑

    +
    public static void main(String[] args) {
    +		SpringApplication.run(SpbDemoApplication.class, args);
    +	}
    +
    +	/**
    +	 * Static helper that can be used to run a {@link SpringApplication} from the
    +	 * specified source using default settings.
    +	 * @param primarySource the primary source to load
    +	 * @param args the application arguments (usually passed from a Java main method)
    +	 * @return the running {@link ApplicationContext}
    +	 */
    +

    然后就是上面调用的 run 方法

    +
    public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
    +	return run(new Class<?>[] { primarySource }, args);
    +}
    +
    +/**
    + * Static helper that can be used to run a {@link SpringApplication} from the
    + * specified sources using default settings and user supplied arguments.
    + * @param primarySources the primary sources to load
    + * @param args the application arguments (usually passed from a Java main method)
    + * @return the running {@link ApplicationContext}
    + */
    +

    继续往下看

    +
    public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
    +	return new SpringApplication(primarySources).run(args);
    +}
    + +

    调用SpringApplication的构造方法

    +
    /**
    + * Create a new {@link SpringApplication} instance. The application context will load
    + * beans from the specified primary sources (see {@link SpringApplication class-level}
    + * documentation for details. The instance can be customized before calling
    + * {@link #run(String...)}.
    + * @param primarySources the primary bean sources
    + * @see #run(Class, String[])
    + * @see #SpringApplication(ResourceLoader, Class...)
    + * @see #setSources(Set)
    + */
    +
    +public SpringApplication(Class<?>... primarySources) {
    +	this(null, primarySources);
    +}
    +
    +/**
    + * Create a new {@link SpringApplication} instance. The application context will load
    + * beans from the specified primary sources (see {@link SpringApplication class-level}
    + * documentation for details. The instance can be customized before calling
    + * {@link #run(String...)}.
    + * @param resourceLoader the resource loader to use
    + * @param primarySources the primary bean sources
    + * @see #run(Class, String[])
    + * @see #setSources(Set)
    + */
    +@SuppressWarnings({ "unchecked", "rawtypes" })
    +public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
    +	this.resourceLoader = resourceLoader;
    +	Assert.notNull(primarySources, "PrimarySources must not be null");
    +	this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
    +	this.webApplicationType = WebApplicationType.deduceFromClasspath();
    +   // 注意看这里的,通过 SpringFactories 获取
    +	this.bootstrapRegistryInitializers = getBootstrapRegistryInitializersFromSpringFactories();
    +	setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
    +	setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
    +	this.mainApplicationClass = deduceMainApplicationClass();
    +}
    +

    这里就是重点了

    +
    private List<BootstrapRegistryInitializer> getBootstrapRegistryInitializersFromSpringFactories() {
    +	ArrayList<BootstrapRegistryInitializer> initializers = new ArrayList<>();
    +	getSpringFactoriesInstances(Bootstrapper.class).stream()
    +			.map((bootstrapper) -> ((BootstrapRegistryInitializer) bootstrapper::initialize))
    +			.forEach(initializers::add);
    +	initializers.addAll(getSpringFactoriesInstances(BootstrapRegistryInitializer.class));
    +	return initializers;
    +}
    +private <T> Collection<T> getSpringFactoriesInstances(Class<T> type) {
    +	return getSpringFactoriesInstances(type, new Class<?>[] {});
    +}
    +
    +private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) {
    +	ClassLoader classLoader = getClassLoader();
    +	// Use names and ensure unique to protect against duplicates
    +   // 去加载所有FACTORIES_RESOURCE_LOCATION路径下面,也就是 META-INF/spring.factories
    +	Set<String> names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
    +	List<T> instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
    +	AnnotationAwareOrderComparator.sort(instances);
    +	return instances;
    +}
    + +
    
    +/**
    + * Load the fully qualified class names of factory implementations of the
    + * given type from {@value #FACTORIES_RESOURCE_LOCATION}, using the given
    + * class loader.
    + * <p>As of Spring Framework 5.3, if a particular implementation class name
    + * is discovered more than once for the given factory type, duplicates will
    + * be ignored.
    + * @param factoryType the interface or abstract class representing the factory
    + * @param classLoader the ClassLoader to use for loading resources; can be
    + * {@code null} to use the default
    + * @throws IllegalArgumentException if an error occurs while loading factory names
    + * @see #loadFactories
    + */
    +public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {
    +	ClassLoader classLoaderToUse = classLoader;
    +	if (classLoaderToUse == null) {
    +		classLoaderToUse = SpringFactoriesLoader.class.getClassLoader();
    +	}
    +	String factoryTypeName = factoryType.getName();
    +	return loadSpringFactories(classLoaderToUse).getOrDefault(factoryTypeName, Collections.emptyList());
    +}
    +   private static Map<String, List<String>> loadSpringFactories(ClassLoader classLoader) {
    +	Map<String, List<String>> result = cache.get(classLoader);
    +	if (result != null) {
    +		return result;
    +	}
    +
    +	result = new HashMap<>();
    +	try {
    +           // 获取此 resources,作为 AutoConfiguration 的配置
    +		Enumeration<URL> urls = classLoader.getResources(FACTORIES_RESOURCE_LOCATION);
    +		while (urls.hasMoreElements()) {
    +			URL url = urls.nextElement();
    +			UrlResource resource = new UrlResource(url);
    +			Properties properties = PropertiesLoaderUtils.loadProperties(resource);
    +			for (Map.Entry<?, ?> entry : properties.entrySet()) {
    +				String factoryTypeName = ((String) entry.getKey()).trim();
    +				String[] factoryImplementationNames =
    +						StringUtils.commaDelimitedListToStringArray((String) entry.getValue());
    +				for (String factoryImplementationName : factoryImplementationNames) {
    +					result.computeIfAbsent(factoryTypeName, key -> new ArrayList<>())
    +							.add(factoryImplementationName.trim());
    +				}
    +			}
    +		}
    +
    +		// Replace all lists with unmodifiable lists containing unique elements
    +		result.replaceAll((factoryType, implementations) -> implementations.stream().distinct()
    +				.collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)));
    +		cache.put(classLoader, result);
    +	}
    +	catch (IOException ex) {
    +		throw new IllegalArgumentException("Unable to load factories from location [" +
    +				FACTORIES_RESOURCE_LOCATION + "]", ex);
    +	}
    +	return result;
    +}
    + +

    我们可以看下 spring-boot-autoconfigure 的 META-INF/spring.factories

    +
    # Initializers
    +org.springframework.context.ApplicationContextInitializer=\
    +org.springframework.boot.autoconfigure.SharedMetadataReaderFactoryContextInitializer,\
    +org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener
    +
    +# Application Listeners
    +org.springframework.context.ApplicationListener=\
    +org.springframework.boot.autoconfigure.BackgroundPreinitializer
    +
    +# Environment Post Processors
    +org.springframework.boot.env.EnvironmentPostProcessor=\
    +org.springframework.boot.autoconfigure.integration.IntegrationPropertiesEnvironmentPostProcessor
    +
    +# Auto Configuration Import Listeners
    +org.springframework.boot.autoconfigure.AutoConfigurationImportListener=\
    +org.springframework.boot.autoconfigure.condition.ConditionEvaluationReportAutoConfigurationImportListener
    +
    +# Auto Configuration Import Filters
    +org.springframework.boot.autoconfigure.AutoConfigurationImportFilter=\
    +org.springframework.boot.autoconfigure.condition.OnBeanCondition,\
    +org.springframework.boot.autoconfigure.condition.OnClassCondition,\
    +org.springframework.boot.autoconfigure.condition.OnWebApplicationCondition
    +
    +# 注意这里,其实就是类似于 dubbo spi 的通过 org.springframework.boot.autoconfigure.EnableAutoConfiguration作为 key
    +# 获取下面所有的 AutoConfiguration 配置类
    +# Auto Configure
    +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
    +org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
    +org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
    +org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
    +org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
    +org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
    +org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\
    +org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\
    +org.springframework.boot.autoconfigure.context.LifecycleAutoConfiguration,\
    +org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration,\
    +org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration,\
    +org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration,\
    +org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration,\
    +org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration,\
    +org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveDataAutoConfiguration,\
    +org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveRepositoriesAutoConfiguration,\
    +org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration,\
    +org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration,\
    +org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveDataAutoConfiguration,\
    +org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveRepositoriesAutoConfiguration,\
    +org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration,\
    +org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration,\
    +org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\
    +org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRepositoriesAutoConfiguration,\
    +org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRestClientAutoConfiguration,\
    +org.springframework.boot.autoconfigure.data.jdbc.JdbcRepositoriesAutoConfiguration,\
    +org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\
    +org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration,\
    +org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,\
    +org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration,\
    +org.springframework.boot.autoconfigure.data.mongo.MongoReactiveRepositoriesAutoConfiguration,\
    +org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration,\
    +org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration,\
    +org.springframework.boot.autoconfigure.data.neo4j.Neo4jReactiveDataAutoConfiguration,\
    +org.springframework.boot.autoconfigure.data.neo4j.Neo4jReactiveRepositoriesAutoConfiguration,\
    +org.springframework.boot.autoconfigure.data.neo4j.Neo4jRepositoriesAutoConfiguration,\
    +org.springframework.boot.autoconfigure.data.r2dbc.R2dbcDataAutoConfiguration,\
    +org.springframework.boot.autoconfigure.data.r2dbc.R2dbcRepositoriesAutoConfiguration,\
    +org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\
    +org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration,\
    +org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration,\
    +org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration,\
    +org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration,\
    +org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchRestClientAutoConfiguration,\
    +org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\
    +org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\
    +org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\
    +org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration,\
    +org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration,\
    +org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration,\
    +org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration,\
    +org.springframework.boot.autoconfigure.hazelcast.HazelcastJpaDependencyAutoConfiguration,\
    +org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration,\
    +org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration,\
    +org.springframework.boot.autoconfigure.influx.InfluxDbAutoConfiguration,\
    +org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration,\
    +org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration,\
    +org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration,\
    +org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
    +org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration,\
    +org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration,\
    +org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration,\
    +org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\
    +org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration,\
    +org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration,\
    +org.springframework.boot.autoconfigure.jms.JndiConnectionFactoryAutoConfiguration,\
    +org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration,\
    +org.springframework.boot.autoconfigure.jms.artemis.ArtemisAutoConfiguration,\
    +org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration,\
    +org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\
    +org.springframework.boot.autoconfigure.jsonb.JsonbAutoConfiguration,\
    +org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration,\
    +org.springframework.boot.autoconfigure.availability.ApplicationAvailabilityAutoConfiguration,\
    +org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration,\
    +org.springframework.boot.autoconfigure.ldap.LdapAutoConfiguration,\
    +org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration,\
    +org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration,\
    +org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration,\
    +org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration,\
    +org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,\
    +org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration,\
    +org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration,\
    +org.springframework.boot.autoconfigure.neo4j.Neo4jAutoConfiguration,\
    +org.springframework.boot.autoconfigure.netty.NettyAutoConfiguration,\
    +org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\
    +org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration,\
    +org.springframework.boot.autoconfigure.r2dbc.R2dbcAutoConfiguration,\
    +org.springframework.boot.autoconfigure.r2dbc.R2dbcTransactionManagerAutoConfiguration,\
    +org.springframework.boot.autoconfigure.rsocket.RSocketMessagingAutoConfiguration,\
    +org.springframework.boot.autoconfigure.rsocket.RSocketRequesterAutoConfiguration,\
    +org.springframework.boot.autoconfigure.rsocket.RSocketServerAutoConfiguration,\
    +org.springframework.boot.autoconfigure.rsocket.RSocketStrategiesAutoConfiguration,\
    +org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration,\
    +org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration,\
    +org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration,\
    +org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration,\
    +org.springframework.boot.autoconfigure.security.reactive.ReactiveUserDetailsServiceAutoConfiguration,\
    +org.springframework.boot.autoconfigure.security.rsocket.RSocketSecurityAutoConfiguration,\
    +org.springframework.boot.autoconfigure.security.saml2.Saml2RelyingPartyAutoConfiguration,\
    +org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,\
    +org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,\
    +org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientAutoConfiguration,\
    +org.springframework.boot.autoconfigure.security.oauth2.client.reactive.ReactiveOAuth2ClientAutoConfiguration,\
    +org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration,\
    +org.springframework.boot.autoconfigure.security.oauth2.resource.reactive.ReactiveOAuth2ResourceServerAutoConfiguration,\
    +org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,\
    +org.springframework.boot.autoconfigure.sql.init.SqlInitializationAutoConfiguration,\
    +org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration,\
    +org.springframework.boot.autoconfigure.task.TaskSchedulingAutoConfiguration,\
    +org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration,\
    +org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration,\
    +org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration,\
    +org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration,\
    +org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration,\
    +org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration,\
    +org.springframework.boot.autoconfigure.web.reactive.HttpHandlerAutoConfiguration,\
    +org.springframework.boot.autoconfigure.web.reactive.ReactiveWebServerFactoryAutoConfiguration,\
    +org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration,\
    +org.springframework.boot.autoconfigure.web.reactive.error.ErrorWebFluxAutoConfiguration,\
    +org.springframework.boot.autoconfigure.web.reactive.function.client.ClientHttpConnectorAutoConfiguration,\
    +org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration,\
    +org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,\
    +org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration,\
    +org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration,\
    +org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration,\
    +org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration,\
    +org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\
    +org.springframework.boot.autoconfigure.websocket.reactive.WebSocketReactiveAutoConfiguration,\
    +org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration,\
    +org.springframework.boot.autoconfigure.websocket.servlet.WebSocketMessagingAutoConfiguration,\
    +org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration,\
    +org.springframework.boot.autoconfigure.webservices.client.WebServiceTemplateAutoConfiguration
    +
    +# Failure analyzers
    +org.springframework.boot.diagnostics.FailureAnalyzer=\
    +org.springframework.boot.autoconfigure.data.redis.RedisUrlSyntaxFailureAnalyzer,\
    +org.springframework.boot.autoconfigure.diagnostics.analyzer.NoSuchBeanDefinitionFailureAnalyzer,\
    +org.springframework.boot.autoconfigure.flyway.FlywayMigrationScriptMissingFailureAnalyzer,\
    +org.springframework.boot.autoconfigure.jdbc.DataSourceBeanCreationFailureAnalyzer,\
    +org.springframework.boot.autoconfigure.jdbc.HikariDriverConfigurationFailureAnalyzer,\
    +org.springframework.boot.autoconfigure.r2dbc.ConnectionFactoryBeanCreationFailureAnalyzer,\
    +org.springframework.boot.autoconfigure.session.NonUniqueSessionRepositoryFailureAnalyzer
    +
    +# Template availability providers
    +org.springframework.boot.autoconfigure.template.TemplateAvailabilityProvider=\
    +org.springframework.boot.autoconfigure.freemarker.FreeMarkerTemplateAvailabilityProvider,\
    +org.springframework.boot.autoconfigure.mustache.MustacheTemplateAvailabilityProvider,\
    +org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAvailabilityProvider,\
    +org.springframework.boot.autoconfigure.thymeleaf.ThymeleafTemplateAvailabilityProvider,\
    +org.springframework.boot.autoconfigure.web.servlet.JspTemplateAvailabilityProvider
    +
    +# DataSource initializer detectors
    +org.springframework.boot.sql.init.dependency.DatabaseInitializerDetector=\
    +org.springframework.boot.autoconfigure.flyway.FlywayMigrationInitializerDatabaseInitializerDetector
    +
    + +

    上面根据 org.springframework.boot.autoconfigure.EnableAutoConfiguration 获取的各个配置类,在通过反射加载就能得到一堆 JavaConfig配置类,然后再根据 ConditionalOnProperty等条件配置加载具体的 bean,大致就是这么个逻辑

    ]]>
    - 生活 + Java + SpringBoot - 生活 - 看剧 + Java + Spring + SpringBoot + 自动装配 + AutoConfiguration
    @@ -20304,94 +20290,100 @@ constexpr size_t DATA_ROLL_PTR_LEN - 聊聊这次换车牌及其他 - /2022/02/20/%E8%81%8A%E8%81%8A%E8%BF%99%E6%AC%A1%E6%8D%A2%E8%BD%A6%E7%89%8C%E5%8F%8A%E5%85%B6%E4%BB%96/ - 去年 8 月份运气比较好,摇到了车牌,本来其实应该很早就开始摇的,前面第一次换工作没注意社保断缴了一个月,也是大意失荆州,后面到了 17 年社保满两年了,好像只摇了一次,还是就没摇过,有点忘了,好像是什么原因导致那次也没摇成功,但是后面暂住证就取消了,需要居住证,居住证又要一年及以上的租房合同,并且那会买车以后也不怎么开,住的地方车位还好,但是公司车位一个月要两三千,甚至还是打车上下班比较实惠,所以也没放在心上,后面摇到房以后,也觉得应该准备起来车子,就开始办了居住证,居住证其实还可以用劳动合同,而且办起来也挺快,大概是三四月份开始摇,到 8 月份的某一天收到短信说摇到了,一开始还挺开心,不过心里抱着也不怎么开,也没怎么大放在心上,不过这里有一点就是我把那个照片直接发出去,上面有着我的身份证号,被 LD 说了一顿,以后也应该小心点,但是后面不知道是哪里看了下,说杭州上牌已经需要国六标准的车了,瞬间感觉是空欢喜了,可是有同事说是可以的,我就又打了官方的电话,结果说可以的,要先转籍,然后再做上牌。

    -

    转籍其实是很方便的,在交警 12123 App 上申请就行了,在转籍以后,需要去实地验车,验车的话,在支付宝-杭州交警生活号里进行预约,找就近的车管所就好,需要准备一些东西,首先是行驶证,机动车登记证书,身份证,居住证,还有车上需要准备的东西是要有三脚架和反光背心,反光背心是最近几个月开始要的,问过之前去验车的只需要三脚架就好了,预约好了的话建议是赶上班时间越早越好,不然过去排队时间要很久,而且人多了以后会很乱,各种插队,而且有很多都是汽车销售,一个销售带着一堆车,我们附近那个进去的小路没一会就堵满车,进去需要先排队,然后扫码,接着交资料,这两个都排着队,如果去晚了就要排很久的队,交完资料才是排队等验车,验车就是打开引擎盖,有人会帮忙拓印发动机车架号,然后验车的会各种检查一下,车里面,还有后备箱,建议车内整理干净点,后备箱不要放杂物,检验完了之后,需要把三脚架跟反光背心放在后备箱盖子上,人在旁边拍个照,然后需要把车牌遮住后再拍个车子的照片,再之后就是去把车牌卸了,这个多吐槽下,那边应该是本来那边师傅帮忙卸车牌,结果他就说是教我们拆,虽然也不算难,但是不排除师傅有在偷懒,完了之后就是把旧车牌交回去,然后需要在手机上(警察叔叔 App)提交各种资料,包括身份证,行驶证,机动车登记证书,提交了之后就等寄车牌过来了。

    -

    这里面缺失的一个环节就是选号了,选号杭州有两个方式,一种就是根据交管局定期发布的选号号段,可以自定义拼 20 个号,在手机上的交警 12123 App 上可以三个一组的形式提交,如果有没被选走的,就可以预选到这个了,但是这种就是也需要有一定策略,最新出的号段能选中的概率大一点,然后数字全是 8,6 这种的肯定会一早就被选走,然后如果跟我一样可以提前选下尾号,因为尾号数字影响限号,我比较有可能周五回家,所以得避开 5,0 的,第二种就是 50 选一跟以前新车选号一样,就不介绍了。第一种选中了以后可以在前面交还旧车牌的时候填上等着寄过来了,因为我是第一种选中的,第二种也可以在手机上选,也在可以在交还车牌的时候现场选。

    -

    总体过程其实是 LD 在各种查资料跟帮我跑来跑去,要不是 LD,估计在交管局那边我就懵逼了,各种插队,而且车子开着车子,也不能随便跑,所以建议办这个的时候有个人一起比较好。

    -]]>
    - - 生活 - - - 生活 - 换车牌 - -
    - - 聊聊最近平淡的生活之看《神探狄仁杰》 - /2021/12/19/%E8%81%8A%E8%81%8A%E6%9C%80%E8%BF%91%E5%B9%B3%E6%B7%A1%E7%9A%84%E7%94%9F%E6%B4%BB%E4%B9%8B%E7%9C%8B%E3%80%8A%E7%A5%9E%E6%8E%A2%E7%8B%84%E4%BB%81%E6%9D%B0%E3%80%8B/ - 其实最近看的不止这一部,前面看了《继承者们》,《少年包青天》这些,就一起聊下,其中看《继承者们》算是个人比较喜欢,以前就有这种看剧的习惯,这个跟《一生一世》里任嘉伦说自己看《寻秦记》看了几十遍一样,我看喜欢的剧也基本上会看不止五遍,继承者们是有帅哥美女看,而且印象中剧情也挺甜的,一般情况下最好是已经有点遗忘剧情了,因为我个人觉得看剧分两种,无聊了又心情不太好,可以看些这类轻松又看过的剧,可以不完全专心地看剧,另外有心情专心看的时候,可以看一些需要思考,一些探案类的或者烧脑类。
    最近看了《神探狄仁杰》,因为跟前面看的《少年包青天》都是这类古装探案剧,正好有些感想,《少年包青天》算是儿时阴影,本来是不太会去看的,正好有一次有机会跟 LD 一起看了会就也觉得比较有意思就看了下去,不得不说,以前的这些剧还是很不错的,包括剧情和演员,第一部一共是 40 集,看的过程中也发现了大概是五个案子,平均八集一个案子,整体节奏还是比较慢的,但是基本每个案子其实都是构思得很巧妙,很久以前看过但是现在基本不太记得剧情了,每个案子在前面几集的时候基本都猜不到犯案逻辑,但是在看了狄仁杰之后,发现两部剧也有比较大的差别,少年包青天相对来说逻辑性会更强一些,个人主观觉得推理的严谨性更高,可能剧本打磨上更将就一下,而狄仁杰因为要提现他的个人强项,不比少年包青天中有公孙策一时瑜亮的情节,狄仁杰中分工明确,李元芳是个武力担当,曾泰是捧哏的,相对来说是狄仁杰在案子里从始至终地推进案情,有些甚至有些玄乎,会有一些跳脱跟不合理,有些像是狄仁杰的奇遇,不过这些想法是私人的观点,并不是想要评孰优孰劣;第二个感受是不知道是不是年代关系,特别是少年包青天,每个案件的大 boss 基本都不是个完全的坏人,甚至都是比较情有可原的可怜人,因为一些特殊原因,而好几个都是包拯身边的人,这一点其实跟狄仁杰里第一个使团惊魂案件比较类似,虎敬晖也是个人物形象比较丰满的角色,不是个标签化的淡薄形象,跟金木兰的感情和反叛行动在最后都说明的缘由,而且也有随着跟狄仁杰一起办案被其影响感化,最终为了救狄仁杰而被金木兰所杀,只是这样金木兰这个角色就会有些偏执和符号化,当然剧本肯定不是能面面俱到,这样的剧本已经比现在很多流量剧的好很多了。还想到了前阵子看的《指环王》中的白袍萨鲁曼在剧中也是个比较单薄的角色,这样的电影彪炳影史也没办法把个个人物都设计得完整有血有肉,或者说这本来也是应该有侧重点,当然其实我也不觉得指环王就是绝对的最好的,因为相对来说故事情节的复杂性等真的不如西游记,只是在 86 版之后的各种乱七八糟的翻牌和乱拍已经让这个真正的王者神话故事有点力不从心,这里边有部西游记后传是个人还比较喜欢的,虽然武打动作比较鬼畜,但是剧情基本是无敌的,在西游的架构上衍生出来这么完整丰富的故事,人物角色也都有各自的出彩点。
    说回狄仁杰,在这之前也看过徐克拍的几部狄仁杰的电影版,第一部刘德华拍得相对完成度更高,故事性也可圈可点,后面几部就是剧情拉胯,靠特效拉回来一点分,虽说这个也是所谓的狄仁杰宇宙的构思在里面但是现在来看基本是跟西游那些差不多,完全没有整体性可言,打一枪换一个地方,演员也没有延续性,剧情也是前后跳脱,没什么关联跟承上启下,导致质量层次不一,更不用谈什么狄仁杰宇宙了,不过这个事情也是难说,原因很多,现在资本都是更加趋利的,一些需要更长久时间才能有回报的投资是很难获得资本青睐,所以只能将重心投给选择一些流量明星,而本来应该将资源投给剧本打磨的基本就没了,再深入说也没意义了,社会现状就是这样。
    还有一点感想是,以前的剧里的拍摄环境还是比较惨的,看着一些房子,甚至皇宫都是比较破旧的,地面还是石板这种,想想以前的演员的环境再想想现在的,比如成龙说的,以前他拍剧就是啪摔了,问这条有没有过,过了就直接送医院,而不是现在可能手蹭破点皮就大叫,甚至还有饭圈这些破事。

    -]]>
    - - 生活 - - - 生活 - 看剧 - -
    - - 聊聊给亲戚朋友的老电脑重装系统那些事儿 - /2021/05/09/%E8%81%8A%E8%81%8A%E7%BB%99%E4%BA%B2%E6%88%9A%E6%9C%8B%E5%8F%8B%E7%9A%84%E8%80%81%E7%94%B5%E8%84%91%E9%87%8D%E8%A3%85%E7%B3%BB%E7%BB%9F%E9%82%A3%E4%BA%9B%E4%BA%8B%E5%84%BF/ - 前面这个五一回去之前,LD 姐姐跟我说电脑很卡了,想让我重装系统,问了下 LD 可能是那个 09 年买的笔记本,想想有点害怕[捂脸],前年有一次好像让我帮忙装了她同事的一个三星的笔记本,本着一些系统洁癖,所以就从开始找纯净版的 win7 家庭版,因为之前那些本基本都自带 win7 的家庭版,而且把激活码就贴在机器下面,然后从三星官网去找官方驱动,还好这个机型的驱动还在,先做了系统镜像,其实感觉这种情况需要两个 U 盘,一个 U 盘装系统作为安装启动盘,一个放驱动,毕竟不是专业装系统的,然后因为官方驱动需要一个个下载一个个安装,然后驱动文件下载的地方还没标明是 32 位还是 64 位的,结果还被 LD 姐姐催着,一直问好没好,略尴尬,索性还是找个一键安装的

    -

    这次甚至更夸张,上次还让带回去,我准备好了系统镜像啥的,第二天装,这次直接带了两个老旧笔记本过来说让当天就装好,感觉有点像被当修电脑的使,又说这些电脑其实都不用了的,都是为了她们当医生的要每年看会课,然后只能用电脑浏览器看,结果都在用 360 浏览器,真的是万恶的 360,其实以前对 360 没啥坏印象,毕竟以前也经常用,只是对于这些老电脑,360 全家桶真的就是装了就废了,2G 的内存,开机就开着 360 安全卫士,360 杀毒,有一个还装了腾讯电脑管家,然后腾讯视频跟爱奇艺也开机启动了,然后还打开 360 浏览器看课,就算再好的系统也吃不消这么用,重装了系统,还是这么装这些东西,也是分分钟变卡,可惜他们都没啥这类概念。

    -

    对于他们要看的课,更搞笑的是,明明在页面上注明了说要使用 IE 浏览器,结果他们都在用 360 浏览器看,但是这个也不能完全怪他们,因为实在是现在的 IE 啥的也有开始不兼容 flash 的配置,需要开启兼容配置,但是只要开启了之后就可以直接用 IE 看,比 360 靠谱很多, 资源占用也比较少,360 估计是基于 chromium 加了很多内置的插件,本身 chromium 也是内存大户,但是说这些其实他们也不懂,总觉得找我免费装下系统能撑一段时间,反正对我来说也应该很简单(他们觉得),实际上开始工作以后,我自己想装个双系统都是上淘宝买别人的服务装的,台式机更是几年没动过系统了,因为要重装一大堆软件,数据备份啥的,还有驱动什么的,分区格式,那些驱动精灵啥的也都是越来越坑,一装就给你带一堆垃圾软件。

    -

    感悟是,总觉得学计算机的就应该会装系统,会修电脑,之前亲戚还拿着一个完全开不起来的笔记本让我来修,这真的是,我说可以找官方维修的,结果我说我搞不定,她直接觉得是修不好了,直接电脑都懒得拿回去了,后面又一次反复解释了才明白,另外就是 360 全家桶,别说老电脑了,新机器都不太吃得消。

    -]]>
    - - 生活 - - - 生活 - 装电脑 - 老电脑 - 360 全家桶 - 修电脑的 - -
    - - 聊聊部分公交车的设计bug - /2021/12/05/%E8%81%8A%E8%81%8A%E9%83%A8%E5%88%86%E5%85%AC%E4%BA%A4%E8%BD%A6%E7%9A%84%E8%AE%BE%E8%AE%A1bug/ - 今天惯例坐公交回住的地方,不小心撞了头,原因是我们想坐倒数第二排,然后LD 走在我后面,我就走到最后一排中间等着,但是最后一排是高一截的,等 LD 坐进去以后,我就往前走,结果撞到了车顶的扶手杆子的一端,差点撞昏了去,这里我觉得其实杆子长度应该短一点,不然从最后一排出来,还是有比较大概率因为没注意看而撞到头,特别是没注意看的情况,发力其实会比较大,一头撞上就会像我这样,眼前一黑,又痛得要死。
    还有一点就是座位设计了,先来看个图

    图里大致画了两条线,因为可能是轮胎还是什么原因,后排中间会有那么大的突起,但是看两条红线可以发现,靠近过道的座位边缘跟地面突起的边缘不是一样宽的,这样导致的结果就是坐着的时候有一个脚没地儿搁,要不就得侧着斜着坐,或者就是一个脚悬空,短程的可能还好,路程远一点还是比较难受的,特别是像我现在这样,大腿外侧有点难受的情况,就会更难受。
    虽然说这两个点,基本是屁用没有,但是我也是在自己这个博客说说,也当是个树洞了。

    + 解决 网络文件夹目前是以其他用户名和密码进行映射的 问题 + /2023/04/09/%E8%A7%A3%E5%86%B3-%E7%BD%91%E7%BB%9C%E6%96%87%E4%BB%B6%E5%A4%B9%E7%9B%AE%E5%89%8D%E6%98%AF%E4%BB%A5%E5%85%B6%E4%BB%96%E7%94%A8%E6%88%B7%E5%90%8D%E5%92%8C%E5%AF%86%E7%A0%81%E8%BF%9B%E8%A1%8C%E6%98%A0%E5%B0%84%E7%9A%84/ + 之前在使用 smb 协议在 Windows 中共享磁盘使用映射网络驱动器的时候,如果前一次登录过账号密码后面有了改动,或者前一次改错了,
    就会出现这样的提示

    应该是 Windows 已经把之前的连接记录下来了,即使是链接不成功的
    可以通过在 cmd 或者 powershell 执行 net use 命令查看当前已经连接的

    这样就可以用命令来把这个删除
    net use [NETNAME] /delete
    比如这边就可以
    net use \\xxxxxxxx\f /delete
    然后再重新输入账号密码就好了
    关于net use的命令使用方式可以参考

    +
    net use [{<DeviceName> | *}] [\\<ComputerName>\<ShareName>[\<volume>]] [{<Password> | *}]] [/user:[<DomainName>\]<UserName] >[/user:[<DottedDomainName>\]<UserName>] [/user: [<UserName@DottedDomainName>] [/savecred] [/smartcard] [{/delete | /persistent:{yes | no}}]
    +net use [<DeviceName> [/home[{<Password> | *}] [/delete:{yes | no}]]
    +net use [/persistent:{yes | no}]
    +

    官方链接

    ]]>
    - 生活 + 技巧 - 生活 - 公交 - 杭州 + windows
    - 聊聊那些加塞狗 - /2021/01/17/%E8%81%8A%E8%81%8A%E9%82%A3%E4%BA%9B%E5%8A%A0%E5%A1%9E%E7%8B%97/ - 今天真的是被气得不轻,情况是碰到一个有 70 多秒的直行红灯,然后直行就排了很长的队,但是左转车道没车,就有好几辆车占着左转车道,准备往直行车道插队加塞,一般这种加塞的,会挑个不太计较的,如果前面一辆不让的话就再等等,我因为赶着回家,就不想让,结果那辆车几次车头直接往里冲,当时怒气值基本已经蓄满了,我真的是分毫都不想让,如果路上都是让着这种人的,那么这种情况只会越来越严重,我理解的这种心态,就赌你怕麻烦,多一事不如少一事,结果就是每次都能顺利插队加塞,其实延伸到我们社会中的种种实质性的排队或者等同于排队的情况,都已经有这种惯有思维,一方面这种不符合规则,可能在严重程度上容易被很多人所忽视,基本上已经被很多人当成是“合理”行为,另一方面,对于这些“微小”的违规行为,本身管理层面也基本没有想要管的意思,就更多的成为了纵容这些行为的导火索,并且大多数人都是想着如果不让,发生点小剐小蹭的要浪费很多时间精力来处理,甚至会觉得会被别人觉得自己太小气等等,诸多内外成本结合起来,会真的去硬刚的可能少之又少了,这样也就让更多的人觉得这种行为是被默许的,再举个非常小的例子,以我们公司疫情期间的盒饭发放为例,有两个比较“有意思”的事情,第一个就是因为疫情,本来是让排队要间隔一米,但是可能除了我比较怕死会跟前面的人保持点距离基本没别人会不挨着前面的人,甚至我跟我前面的人保持点距离,后面的同学会推着我让我上去;第二个是关于拿饭,这么多人排着队拿饭,然后有部分同学,一个人拿好几份,帮组里其他人的都拿了,有些甚至一个人拿十份,假如这个盒饭发放是说明了可以按部门直接全领了那就没啥问题,但是当时的状况是个人排队领自己的那一份,如果一个同学直接帮着组里十几个人都拿了,后面排队的人是什么感受呢,甚至有些是看到队伍排长了,就找队伍里自己认识的比较靠前的人说你帮我也拿一份,其实作为我这个比较按规矩办事的“愣头青”来说,我是比较不能接受这两件小事里的行为的,再往下说可能就有点偏激了,先说到这~

    + 记录一次折腾自组 nas 的失败经历-续篇 + /2023/05/14/%E8%AE%B0%E5%BD%95%E4%B8%80%E6%AC%A1%E6%8A%98%E8%85%BE%E8%87%AA%E7%BB%84-nas-%E7%9A%84%E5%A4%B1%E8%B4%A5%E7%BB%8F%E5%8E%86-%E7%BB%AD%E7%AF%87/ + 上次记录了前面的一些失败经验,最重要的点还没提到,先发一下配置单
    cpu i7-8700k
    主板 技嘉 z370m-ds3h
    内存 光威 ddr4-3200Mhz
    硬盘 京东京造 512g
    散热 利民 PA120
    电源 先马平头哥额定 550w
    机箱 爱国者半岛铁盒 F10
    cpu 跟主板是板 U 套装某鱼买的二手的,说实话如果不是后面的网卡问题,这个板 U 套装还是比较良心的,一次点亮(以前没组装过,还不知道有点不亮的情况,后面就体验到了),但是这里就出现了一个很大的坑,因为我这次是想要在裸机上装 exsi,然后看到了群里苏大的一篇 exsi 最新版本 8 的镜像构建文章,硬件也不是很旧,就想着用最新的系统,镜像写进 ventoy 后启动发现报错找不到网卡,这会我还没发现问题的严重性,想着按一些教程打个驱动进去就好了,而且我还以为驱动只要跟镜像 iso 放一块就行了,后面随着深入了解就知道要把驱动打进 iso 镜像里,但是找了一通发现我的网卡是瑞昱的 RTL8168,这个型号的板载网卡,走的是 PCIE 通道,有驱动的最后支持的系统是 exsi6.7,再往后就没有完整打包好的社区版驱动可以使用了,所以这是踩的第一个大坑,照理这个事情也没这么大问题,退回来 6.7 不就行了,问题恰恰是我那时候还不懂,又想用更新的系统,所以就在网上搜了半天,发现华硕的 z370 tuf gaming 系列是用的 intel 的网卡,社区的网卡驱动对 intel 的网卡支持比较好,所以想着还是换个主板算了,其实还有不少选择,买个 pcie 的 intel 网卡或者 usb 的其他千兆网卡,有个说出来可能比较难理解的,usb 的社区版驱动反而比 pcie 的支持得广,pcie 的还是只支持 intel 的。
    在某多多上买了个二手的 z370 tuf gaming 主板,结果踩到了第二个坑,可能比较小白的经验是,前面因为买的板 U 套装,他 cpu 是直接装在主板上邮给我的,所以我没装过 cpu,这回买来这块二手的华硕主板对我来说是第一次装 cpu,不过好像难度不大,一下就装好了,但结果就很惨,就是点不亮,散热器风扇会转,但是键盘灯不亮,而且散热风扇还转得很快,我还试着把内存换个槽,结果四个槽都不行,这个时候就很害怕了,看上去这家店也不像是太坑的,毕竟大量地在卖,所以我就很担心是不是前面 cpu 装的不对,把针脚什么的搞坏了,这个时候已经搞到晚上很迟了,但还是忍不住又装回原来的技嘉主板试了下,幸好能正常点亮,算了,还是就用技嘉这块主板吧,接口配置稍微差了点,网卡也不支持最新版的 exsi,所以我就用 vmware workstation 了,在 win10 的 lstc 上装一个,有点性能损耗就损耗吧,反正我也不暴力使用,能跑跑其他 Ubuntu 虚拟机啥的就可以了,或者回到前面的结果,可以装 6.7 的,网上带了瑞昱网卡驱动的 exsi6.7 的镜像挺多的,可以自己打一个或者用别人打包好的。折腾不止踩坑不止呐。

    ]]>
    - 生活 - 开车 + nas - 生活 - 开车 - 加塞 - 糟心事 - 规则 + nas
    - 记录一次折腾自组 nas 的失败经历-续续篇 - /2023/05/28/%E8%AE%B0%E5%BD%95%E4%B8%80%E6%AC%A1%E6%8A%98%E8%85%BE%E8%87%AA%E7%BB%84-nas-%E7%9A%84%E5%A4%B1%E8%B4%A5%E7%BB%8F%E5%8E%86-%E7%BB%AD%E7%BB%AD%E7%AF%87/ - 之前这个机器已经算是跑起来了,虽然不是很完善也不是最佳实践,不过这篇可能也不算是失败经历了,因为最后成功跑起来了,在没法装最新版的 exsi 的情况下,并且我后面买的华硕 z370 主板点不亮,所以我也有点死心就直接用Windows 下装 vmware workstation 装虚拟机,然后直通硬盘来做 nas,这样可能对于其他人来说是很垃圾的方案,不过因为我很多常用软件的都是在 Windows 环境下的,并且纯黑裙的环境会比较浪费,相比一些同学在群晖里安装 Windows 虚拟机,我觉得还是反过来比较好,毕竟 vmware 做虚拟机应该是比群晖专业点,不过这个方案也有一些问题
    第一种方式是直接找网上同学分享的处理好引导的 vmx,这种我碰到了一个问题就是在打开虚拟机安装群晖系统.pat的时候会提示“无法安装此文件,文件可能已损坏”,这其实不是真的文件已损坏,应该是群晖在做校验的时候存在什么条件没有通过,尝试了断网等方式都不成功,所以后来就用了比较釜底抽薪的方案,直接使用大佬开源的 arpl 引导制作工具
    第二种方式一开始是躺在我 B 站收藏夹里,有个 up 制作的,做得很细致,也把很多细节也解释了,过程其实不难,就是按步骤一步步执行,但是一开始选择了 918+的系统在我的方案里安装不了,会提示无法安装,经过视频下的评论的知道,尝试使用 920+的系统就顺利安装成功了,这里唯一的区别就是在添加硬盘的时候要选择物理磁盘,然后 vmware 给出的硬盘选项是Physical0, Physical1,记得别选错了,然后在启动后我租了 raid5,4 块 4T 的盘,可以组成一个 10T 多一点的存储空间,打算用来作为比较长读写的区域,更大的盘可能就会作为只读区域,减小写入量。后面还有一些问题待解决,一个是电源,考虑换个稍好一点,因为目前看下来电源风扇的噪音比较大,还有就是主板,最近看中了微星的 z390,不过价格比较贵,打算慢慢蹲蹲看。

    + 记录下 Java Stream 的一些高效操作 + /2022/05/15/%E8%AE%B0%E5%BD%95%E4%B8%8B-Java-Lambda-%E7%9A%84%E4%B8%80%E4%BA%9B%E9%AB%98%E6%95%88%E6%93%8D%E4%BD%9C/ + 我们日常在代码里处理一些集合逻辑的时候用到 Stream 其实还挺多的,普通的取值过滤集合一般都是结合 ide 的提示就能搞定了,但是有些不太常用的就在这记录下,争取后面都更新记录下来。

    +

    自定义 distinctByKey 对结果进行去重

    stream 中自带的 distinct 只能对元素进行去重
    比如下面代码

    +
    public static void main(String[] args) {
    +        List<Integer> list = new ArrayList<>();
    +        list.add(1);
    +        list.add(1);
    +        list.add(2);
    +        list = list.stream().distinct().collect(Collectors.toList());
    +        System.out.println(list);
    +    }
    +

    结果就是去了重的

    +
    [1, 2]
    +

    但是当我的元素是个复杂对象,我想根据对象里的某个元素进行过滤的时候,就需要用到自定义的 distinctByKey 了,比如下面的想对 userId 进行去重

    +
    public static void main(String[] args) {
    +        List<StudentRecord> list = new ArrayList<>();
    +        StudentRecord s1 = new StudentRecord();
    +        s1.setUserId(11L);
    +        s1.setCourseId(100L);
    +        s1.setScore(100);
    +        list.add(s1);
    +        StudentRecord s2 = new StudentRecord();
    +        s2.setUserId(11L);
    +        s2.setCourseId(101L);
    +        s2.setScore(100);
    +        list.add(s2);
    +        StudentRecord s3 = new StudentRecord();
    +        s3.setUserId(12L);
    +        s3.setCourseId(100L);
    +        s3.setScore(100);
    +        list.add(s3);
    +        System.out.println(list.stream().distinct().collect(Collectors.toList()));
    +    }
    +    @Data
    +    static class StudentRecord {
    +        Long id;
    +        Long userId;
    +        Long courseId;
    +        Integer score;
    +    }
    +

    结果就是

    +
    [StudentRecord(id=null, userId=11, courseId=100, score=100), StudentRecord(id=null, userId=11, courseId=101, score=100), StudentRecord(id=null, userId=12, courseId=100, score=100)]
    +

    因为对象都不一样,所以就没法去重了,这里就需要用

    +
    public static <T> Predicate<T> distinctByKey(
    +            Function<? super T, ?> keyExtractor) {
    +
    +        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
    +        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    +    }
    +

    然后就可以用它来去重了

    +
    System.out.println(list.stream().filter(distinctByKey(StudentRecord::getUserId)).collect(Collectors.toList()));
    +

    看下结果

    +
    [StudentRecord(id=null, userId=11, courseId=100, score=100), StudentRecord(id=null, userId=12, courseId=100, score=100)]
    +

    但是说实在的这个功能感觉应该是 stream 默认给实现的

    +

    使用 java.util.stream.Collectors#groupingBy 对 list 进行分组

    这个使用场景还是蛮多的,上面的场景里比如我要对 userId 进行分组,就一行代码就解决了

    +
    System.out.println(list.stream().collect(Collectors.groupingBy(StudentRecord::getUserId)));
    +

    结果

    {11=[StudentRecord(id=null, userId=11, courseId=100, score=100), StudentRecord(id=null, userId=11, courseId=101, score=100)], 12=[StudentRecord(id=null, userId=12, courseId=100, score=100)]}
    +

    很方便的变成了以 userId 作为 key,以相同 userIdStudentRecordList 作为 valuemap 结构

    ]]>
    - nas + java - nas + java + stream
    @@ -20529,142 +20521,83 @@ constexpr size_t DATA_ROLL_PTR_LEN - 记录下 Java Stream 的一些高效操作 - /2022/05/15/%E8%AE%B0%E5%BD%95%E4%B8%8B-Java-Lambda-%E7%9A%84%E4%B8%80%E4%BA%9B%E9%AB%98%E6%95%88%E6%93%8D%E4%BD%9C/ - 我们日常在代码里处理一些集合逻辑的时候用到 Stream 其实还挺多的,普通的取值过滤集合一般都是结合 ide 的提示就能搞定了,但是有些不太常用的就在这记录下,争取后面都更新记录下来。

    -

    自定义 distinctByKey 对结果进行去重

    stream 中自带的 distinct 只能对元素进行去重
    比如下面代码

    -
    public static void main(String[] args) {
    -        List<Integer> list = new ArrayList<>();
    -        list.add(1);
    -        list.add(1);
    -        list.add(2);
    -        list = list.stream().distinct().collect(Collectors.toList());
    -        System.out.println(list);
    -    }
    -

    结果就是去了重的

    -
    [1, 2]
    -

    但是当我的元素是个复杂对象,我想根据对象里的某个元素进行过滤的时候,就需要用到自定义的 distinctByKey 了,比如下面的想对 userId 进行去重

    -
    public static void main(String[] args) {
    -        List<StudentRecord> list = new ArrayList<>();
    -        StudentRecord s1 = new StudentRecord();
    -        s1.setUserId(11L);
    -        s1.setCourseId(100L);
    -        s1.setScore(100);
    -        list.add(s1);
    -        StudentRecord s2 = new StudentRecord();
    -        s2.setUserId(11L);
    -        s2.setCourseId(101L);
    -        s2.setScore(100);
    -        list.add(s2);
    -        StudentRecord s3 = new StudentRecord();
    -        s3.setUserId(12L);
    -        s3.setCourseId(100L);
    -        s3.setScore(100);
    -        list.add(s3);
    -        System.out.println(list.stream().distinct().collect(Collectors.toList()));
    -    }
    -    @Data
    -    static class StudentRecord {
    -        Long id;
    -        Long userId;
    -        Long courseId;
    -        Integer score;
    -    }
    -

    结果就是

    -
    [StudentRecord(id=null, userId=11, courseId=100, score=100), StudentRecord(id=null, userId=11, courseId=101, score=100), StudentRecord(id=null, userId=12, courseId=100, score=100)]
    -

    因为对象都不一样,所以就没法去重了,这里就需要用

    -
    public static <T> Predicate<T> distinctByKey(
    -            Function<? super T, ?> keyExtractor) {
    +    记录下 phpunit 的入门使用方法
    +    /2022/10/16/%E8%AE%B0%E5%BD%95%E4%B8%8B-phpunit-%E7%9A%84%E5%85%A5%E9%97%A8%E4%BD%BF%E7%94%A8%E6%96%B9%E6%B3%95/
    +    这周开始打算写个比较简单的php工具包,然后顺带学习使用下php的单元测试,通过phpunit还是比较方便的,首先就composer require phpunit/phpunit
    安装下 phpunit, 前面包就是通过 composer init 创建,装完依赖后就可以把自动加载代码生成下 composer dump-autoload
    目录结构差不多这样

    +
    .
    +├── composer.json
    +├── composer.lock
    +├── oldfile.txt
    +├── phpunit.xml
    +├── src
    +│   └── Rename.php
    +└── tests
    +    └── RenameTest.php
     
    -        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
    -        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    -    }
    -

    然后就可以用它来去重了

    -
    System.out.println(list.stream().filter(distinctByKey(StudentRecord::getUserId)).collect(Collectors.toList()));
    -

    看下结果

    -
    [StudentRecord(id=null, userId=11, courseId=100, score=100), StudentRecord(id=null, userId=12, courseId=100, score=100)]
    -

    但是说实在的这个功能感觉应该是 stream 默认给实现的

    -

    使用 java.util.stream.Collectors#groupingBy 对 list 进行分组

    这个使用场景还是蛮多的,上面的场景里比如我要对 userId 进行分组,就一行代码就解决了

    -
    System.out.println(list.stream().collect(Collectors.groupingBy(StudentRecord::getUserId)));
    -

    结果

    {11=[StudentRecord(id=null, userId=11, courseId=100, score=100), StudentRecord(id=null, userId=11, courseId=101, score=100)], 12=[StudentRecord(id=null, userId=12, courseId=100, score=100)]}
    -

    很方便的变成了以 userId 作为 key,以相同 userIdStudentRecordList 作为 valuemap 结构

    -]]>
    - - java - - - java - stream - - - - 记录一次折腾自组 nas 的失败经历-续续续篇 - /2023/06/18/%E8%AE%B0%E5%BD%95%E4%B8%80%E6%AC%A1%E6%8A%98%E8%85%BE%E8%87%AA%E7%BB%84-nas-%E7%9A%84%E5%A4%B1%E8%B4%A5%E7%BB%8F%E5%8E%86-%E7%BB%AD%E7%BB%AD%E7%BB%AD%E7%AF%87/ - 最近在搞 nas 的时候又翻了个很大的错误,因为前面说了正在用的技嘉的 z370m, 这个主板是跟 cpu 一起买的,如果是只是用在 Windows 环境,没什么扩展要求,或者只用 6 个sata盘位,用一个 ssd 做系统盘,是挺不错的,但是如果是像我这样的要搞盘位比较多的nas,发现有一系列的不足点,
    1、 前面有讲过,网卡问题,用的是 RTL 瑞昱的网卡,目前知道的最高能支持的 exsi 的版本是 6.7,再高的版本就不支持了,不过其实真的想用的话,6.7 版本也是可以用的,只是我当时是打包的 8.0 的系统,个人也不太喜欢用比较低版本的,所以算是一个不足点
    2、 第二点是m.2插槽,只有一个m.2也是很难理解的,一个做系统盘,另一个可以作为简单的数组存储,或者作为群晖的下载缓存,如果只有一个的话特别是现在这个 ssd 的价格这么低了,加一个还是很香的,这个问题跟后面也是有点关系的
    3、 PCIE 的插槽,这个主板只支持两个 PCIE 3.0 x1 的,它能支持 1Gbps 的传输速度,后面我买了个 PCIE 3.0 x1 转 m.2 的转接卡,这样其实真的是把速度拖慢了很多,还有一个 PCIE 3.0 X16 的,这是用来装显卡的,只用来扩展做个m.2或者 sata 又感觉很浪费,而且说不定未来会装个显卡
    4、 风扇口的问题,风扇接口其实原来一直没概念,我在这次装 nas 之前其实自己没有完整装个台式机过,之前买的目前在使用的主力机两个风扇在换了的时候才知道是用的大 4pin 接口串接的,其中一个有 pwm 的接口也没用,这样就没办法用主板自带调速软件来进行自动或者手动调速,有时候比如晚上不关机,放在房间里风扇声很大还是挺吵的,这个主板只有两个风扇接口,一个是 cpu 的,一个是系统风扇,其实就只有一个可以用了
    主要是以上几个点,所以我一直在关注二手主板,之前买了个华硕的 z370 tuf gaming,没想到点不亮,也不知道什么原因,还害我吓得以为 cpu 被我弄坏了,后面慢慢在网上看着发现有一块微星的 z390 TOMAHAWK战斧导弹,各方面接口都很不错,而且还有个千兆网口,在闲鱼蹲了很久终于在前不久蹲到了,买回来赶紧看看能不能点亮,结果一把点亮,还是用的螺丝刀开机的,就心里暗爽感觉捡到了宝,但是装进我的半岛铁盒 F10 机箱就发现跪了,出现的这个问题原来在网上哪里看到过,一直没注意,就是 sata 接口的方向,因为一个是 matx 的板,装进去即使 sata 接口的方向是跟主板平行的也留着足够的空间,但是 atx 板装上之后,大概只有 2 厘米左右的空间并且是两个叠着的端口,一个可能要能硬拗一下,但是两个我试了下,只能识别出一个,这个真让我翻了个大车,而且其实我换这个主板其实还有个大问题,就是我是在 Windows 下的vmware workstation 虚拟机里通过sata 直通,但是这个是认硬盘接口的,也就是顺序是有影响的,换了主板发现也不能支持,后面可能真的想用的话还得重新搞黑裙,要把数据备份出来,幸好换回原来的主板还能用,所以硬件也不能只看性能和接口丰富度,要看适配的其他硬件的合适度以及原先已经有的软件系统

    -]]>
    - - nas - - - nas - -
    - - 记录一次折腾自组 nas 的失败经历-续篇 - /2023/05/14/%E8%AE%B0%E5%BD%95%E4%B8%80%E6%AC%A1%E6%8A%98%E8%85%BE%E8%87%AA%E7%BB%84-nas-%E7%9A%84%E5%A4%B1%E8%B4%A5%E7%BB%8F%E5%8E%86-%E7%BB%AD%E7%AF%87/ - 上次记录了前面的一些失败经验,最重要的点还没提到,先发一下配置单
    cpu i7-8700k
    主板 技嘉 z370m-ds3h
    内存 光威 ddr4-3200Mhz
    硬盘 京东京造 512g
    散热 利民 PA120
    电源 先马平头哥额定 550w
    机箱 爱国者半岛铁盒 F10
    cpu 跟主板是板 U 套装某鱼买的二手的,说实话如果不是后面的网卡问题,这个板 U 套装还是比较良心的,一次点亮(以前没组装过,还不知道有点不亮的情况,后面就体验到了),但是这里就出现了一个很大的坑,因为我这次是想要在裸机上装 exsi,然后看到了群里苏大的一篇 exsi 最新版本 8 的镜像构建文章,硬件也不是很旧,就想着用最新的系统,镜像写进 ventoy 后启动发现报错找不到网卡,这会我还没发现问题的严重性,想着按一些教程打个驱动进去就好了,而且我还以为驱动只要跟镜像 iso 放一块就行了,后面随着深入了解就知道要把驱动打进 iso 镜像里,但是找了一通发现我的网卡是瑞昱的 RTL8168,这个型号的板载网卡,走的是 PCIE 通道,有驱动的最后支持的系统是 exsi6.7,再往后就没有完整打包好的社区版驱动可以使用了,所以这是踩的第一个大坑,照理这个事情也没这么大问题,退回来 6.7 不就行了,问题恰恰是我那时候还不懂,又想用更新的系统,所以就在网上搜了半天,发现华硕的 z370 tuf gaming 系列是用的 intel 的网卡,社区的网卡驱动对 intel 的网卡支持比较好,所以想着还是换个主板算了,其实还有不少选择,买个 pcie 的 intel 网卡或者 usb 的其他千兆网卡,有个说出来可能比较难理解的,usb 的社区版驱动反而比 pcie 的支持得广,pcie 的还是只支持 intel 的。
    在某多多上买了个二手的 z370 tuf gaming 主板,结果踩到了第二个坑,可能比较小白的经验是,前面因为买的板 U 套装,他 cpu 是直接装在主板上邮给我的,所以我没装过 cpu,这回买来这块二手的华硕主板对我来说是第一次装 cpu,不过好像难度不大,一下就装好了,但结果就很惨,就是点不亮,散热器风扇会转,但是键盘灯不亮,而且散热风扇还转得很快,我还试着把内存换个槽,结果四个槽都不行,这个时候就很害怕了,看上去这家店也不像是太坑的,毕竟大量地在卖,所以我就很担心是不是前面 cpu 装的不对,把针脚什么的搞坏了,这个时候已经搞到晚上很迟了,但还是忍不住又装回原来的技嘉主板试了下,幸好能正常点亮,算了,还是就用技嘉这块主板吧,接口配置稍微差了点,网卡也不支持最新版的 exsi,所以我就用 vmware workstation 了,在 win10 的 lstc 上装一个,有点性能损耗就损耗吧,反正我也不暴力使用,能跑跑其他 Ubuntu 虚拟机啥的就可以了,或者回到前面的结果,可以装 6.7 的,网上带了瑞昱网卡驱动的 exsi6.7 的镜像挺多的,可以自己打一个或者用别人打包好的。折腾不止踩坑不止呐。

    -]]>
    - - nas - - - nas - -
    - - 记录下 phpunit 的入门使用方法之setUp和tearDown - /2022/10/23/%E8%AE%B0%E5%BD%95%E4%B8%8B-phpunit-%E7%9A%84%E5%85%A5%E9%97%A8%E4%BD%BF%E7%94%A8%E6%96%B9%E6%B3%95%E4%B9%8BsetUp%E5%92%8CtearDown/ - 可能是太久没写单测了,写个单测发现不符合预期,后来验证下才反应过来
    我们来看下demo

    -
    class RenameTest extends TestCase
    +2 directories, 6 files
    +

    src/是源码,tests/是放的单测,比较重要的是phpunit.xml

    +
    <?xml version="1.0" encoding="UTF-8"?>
    +<phpunit colors="true" bootstrap="vendor/autoload.php">
    +    <testsuites>
    +        <testsuite name="php-rename">
    +            <directory>./tests/</directory>
    +        </testsuite>
    +    </testsuites>
    +</phpunit>
    +

    其中bootstrap就是需要把依赖包的自动加载入口配上,因为这个作为一个package,也会指出命名空间
    然后就是testsuite的路径,源码中

    +
    <?php
    +namespace Nicksxs\PhpRename;
    +
    +class Rename
     {
    -    public function setUp(): void
    +    public static function renameSingleFile($file, $newFileName): bool
         {
    -        var_dump("setUp");
    +        if(!is_file($file)) {
    +            echo "it's not a file";
    +            return false;
    +        }
    +        $fileInfo = pathinfo($file);
    +        return rename($file, $fileInfo["dirname"] . DIRECTORY_SEPARATOR . $newFileName . "." . $fileInfo["extension"]);
         }
    +}
    +

    就是一个简单的重命名
    然后test代码是这样,

    +
    <?php
     
    -    public function test1()
    +// require_once 'vendor/autoload.php';
    +
    +use PHPUnit\Framework\TestCase;
    +use Nicksxs\PhpRename\Rename;
    +use function PHPUnit\Framework\assertEquals;
    +
    +class RenameTest extends TestCase 
    +{
    +    public function setUp() :void
         {
    -        var_dump("test1");
    -        assertEquals(1, 1);
    +        $myfile = fopen(__DIR__ . DIRECTORY_SEPARATOR . "oldfile.txt", "w") or die("Unable to open file!");
    +        $txt = "file test1\n";
    +        fwrite($myfile, $txt);
    +        fclose($myfile);
         }
    -
    -    public function test2()
    +    public function testRename()
         {
    -        var_dump("test2");
    -        assertEquals(1, 1);
    +        Rename::renameSingleFile(__DIR__ . DIRECTORY_SEPARATOR . "oldfile.txt", "newfile");
    +        assertEquals(is_file(__DIR__ . DIRECTORY_SEPARATOR . "newfile.txt"), true);
         }
     
         protected function tearDown(): void
         {
    -        var_dump("tearDown");
    +        unlink(__DIR__ . DIRECTORY_SEPARATOR . "newfile.txt");
         }
    -}
    -

    因为我是想写个重命名的小工具,希望通过setUptearDown做一些文件初始化和清理工作,但是我把两个case的初始化跟清理工作写到了单个setUptearDown中,这样就出现了异常的错误
    通过上面的示例代码,可以看到执行结果

    +}
    +

    setUptearDown 就是初始化跟结束清理的,但是注意如果不指明 __DIR__ ,待会的目录就会在执行 vendor/bin/phpunit 下面,
    或者也可以指定在一个 tmp/ 目录下
    最后就可以通过vendor/bin/phpunit 来执行测试
    执行结果

    ❯ vendor/bin/phpunit
     PHPUnit 9.5.25 by Sebastian Bergmann and contributors.
     
    -.string(5) "setUp"
    -string(5) "test1"
    -string(8) "tearDown"
    -.                                                                  2 / 2 (100%)string(5) "setUp"
    -string(5) "test2"
    -string(8) "tearDown"
    -
    +.                                                                   1 / 1 (100%)
     
     Time: 00:00.005, Memory: 6.00 MB
     
    -OK (2 tests, 2 assertions)
    -

    其实就是很简单的会在每个test方法前后都执行setUptearDown

    +OK (1 test, 1 assertion)
    ]]> php @@ -20674,9 +20607,9 @@ OK (2 t - 记录一次折腾自组 nas 的失败经历 - /2023/05/07/%E8%AE%B0%E5%BD%95%E4%B8%80%E6%AC%A1%E6%8A%98%E8%85%BE%E8%87%AA%E7%BB%84-nas-%E7%9A%84%E5%A4%B1%E8%B4%A5%E7%BB%8F%E5%8E%86/ - 鉴于现在市面上的成品 nas 对于我来说要不就是太贵了,要不就是便宜的盘位少,性能比较差,很多 nas 主打还有用 docker 什么的,但是性能对于我个人比较特殊的使用方式来说还是不太够用的,比如现在比较性能好的 nas 像绿联新出的 DX4600,用的是N5105,passmark 分数还不如我 15 年买的 pc 上的 i5 4590,当然很多人是考虑功耗,这也是萝卜青菜各有所爱,可能我算下来还是觉得没多大必要
    然后就是考虑用什么硬件配置了,这个流派也有很多种,
    用蜗牛星际的原版硬件其实对于需求不大的也是挺好的,整套的都解决了,cpu 用 j1900 如果就做 nas 应该也够了,我没选的原因一方面是性能不符合我的要求,另一方面是现在市面上的机器大部分都是战损成色,而且也不太便宜,如果成色比较好的能够 400 以内拿下整机的话感觉还算可以,cpu 换成 j4125 或者 j3455 再加个 100 也能接受,但基本比较少有这种价格,之前看到一个换了 j3455 的只要 360,犹豫了下没下手,其他很多的都是 j1900 的都要 600 左右
    然后是各类 E3,E5 和商用服务器类型的,这种的特点是功耗大,其实 cpu 很便宜,E5 2630V3 跟 2630V4 都只要十几块钱,性能过得去,没有选的主要是机箱占地方也比较贵,还有是商用的怕很多系统需要自己找驱动什么的,配件比如 HBA 卡这种,买的不兼容什么的还是挺麻烦的,另外噪音也是个比较大的问题,租的房子比较小,即使放客厅也是靠着卧室的墙边,如果以后换大一点的房子倒是可以考虑
    最后就是我目前选的方案,就是普通的民用机器,找盘位多一点的机箱,我原来的 4590 的机器的机箱就不错,但是已经停产了,二手的太重了闲鱼都不出外地,cpu 跟主板其实考虑了很久,因为从 4590 开始核显就能硬解 H264 这种常规的视频了,考虑用intel 四代的 i3 或者 i5 应该纯 nas 来讲是足够用了,但是这样就跟我现在已经有的 4590 有点重叠了,而且也觉得最好是能性能好一些的,就开始看一些稍新一点的,很多用的多的有 i3-8100,跟 i3-10100 这种,但是这些已经被炒的价格比较高,寻寻觅觅了很久看中了 i5-8600,这个价格跟 8500 差不多,性能还好一些,主板就是我标题说的最“失败”的一个点了,主要是因为主板自带的网卡是 Realtek 的,至于更具体的后面会专门介绍,机箱是图便宜买的爱国者半岛铁盒的 F10,内存就买了一根光威的 32g 的,装系统的硬盘是用了以前囤的京东京造的麒麟系列,但是现在对这个系列挺不看好,之前有个盘就掉盘了,维修体验一开始也不好,半个多月维修,电源也是图便宜买的一个先马的平头哥系列,额定 550w 只要 140 左右,整体的机器就攒齐了,但是很多问题也随之出现了
    第一个问题是买的二手的板 U 套装,结果寄过来的时候没带挡板,导致一开始装上了又要拆下来;第二个问题是主机贪便宜,主机上固定主板螺丝的螺柱拧不进去,后来店家告诉我让我可以用电源固定的螺丝先拧一下才把螺柱拧进去;第三个问题是因为没什么装机经验导致的,散热装的太累了,因为要兼容各种主板,还有各种螺丝,装的时候也着急;第四个问题是电源的比较便宜,一方面比较不放心安全性,另一方面是我想多装几个硬盘,电源直出的只有四个 sata 口,需要买转接线,从 D 型的 4pin 口子转出来;第五个问题也是电源,主板电源线有点不太够,走背线就比较困难
    以上主要是装机的困难,下一篇介绍作为 nas 的各种问题吧

    + 记录一次折腾自组 nas 的失败经历-续续续篇 + /2023/06/18/%E8%AE%B0%E5%BD%95%E4%B8%80%E6%AC%A1%E6%8A%98%E8%85%BE%E8%87%AA%E7%BB%84-nas-%E7%9A%84%E5%A4%B1%E8%B4%A5%E7%BB%8F%E5%8E%86-%E7%BB%AD%E7%BB%AD%E7%BB%AD%E7%AF%87/ + 最近在搞 nas 的时候又翻了个很大的错误,因为前面说了正在用的技嘉的 z370m, 这个主板是跟 cpu 一起买的,如果是只是用在 Windows 环境,没什么扩展要求,或者只用 6 个sata盘位,用一个 ssd 做系统盘,是挺不错的,但是如果是像我这样的要搞盘位比较多的nas,发现有一系列的不足点,
    1、 前面有讲过,网卡问题,用的是 RTL 瑞昱的网卡,目前知道的最高能支持的 exsi 的版本是 6.7,再高的版本就不支持了,不过其实真的想用的话,6.7 版本也是可以用的,只是我当时是打包的 8.0 的系统,个人也不太喜欢用比较低版本的,所以算是一个不足点
    2、 第二点是m.2插槽,只有一个m.2也是很难理解的,一个做系统盘,另一个可以作为简单的数组存储,或者作为群晖的下载缓存,如果只有一个的话特别是现在这个 ssd 的价格这么低了,加一个还是很香的,这个问题跟后面也是有点关系的
    3、 PCIE 的插槽,这个主板只支持两个 PCIE 3.0 x1 的,它能支持 1Gbps 的传输速度,后面我买了个 PCIE 3.0 x1 转 m.2 的转接卡,这样其实真的是把速度拖慢了很多,还有一个 PCIE 3.0 X16 的,这是用来装显卡的,只用来扩展做个m.2或者 sata 又感觉很浪费,而且说不定未来会装个显卡
    4、 风扇口的问题,风扇接口其实原来一直没概念,我在这次装 nas 之前其实自己没有完整装个台式机过,之前买的目前在使用的主力机两个风扇在换了的时候才知道是用的大 4pin 接口串接的,其中一个有 pwm 的接口也没用,这样就没办法用主板自带调速软件来进行自动或者手动调速,有时候比如晚上不关机,放在房间里风扇声很大还是挺吵的,这个主板只有两个风扇接口,一个是 cpu 的,一个是系统风扇,其实就只有一个可以用了
    主要是以上几个点,所以我一直在关注二手主板,之前买了个华硕的 z370 tuf gaming,没想到点不亮,也不知道什么原因,还害我吓得以为 cpu 被我弄坏了,后面慢慢在网上看着发现有一块微星的 z390 TOMAHAWK战斧导弹,各方面接口都很不错,而且还有个千兆网口,在闲鱼蹲了很久终于在前不久蹲到了,买回来赶紧看看能不能点亮,结果一把点亮,还是用的螺丝刀开机的,就心里暗爽感觉捡到了宝,但是装进我的半岛铁盒 F10 机箱就发现跪了,出现的这个问题原来在网上哪里看到过,一直没注意,就是 sata 接口的方向,因为一个是 matx 的板,装进去即使 sata 接口的方向是跟主板平行的也留着足够的空间,但是 atx 板装上之后,大概只有 2 厘米左右的空间并且是两个叠着的端口,一个可能要能硬拗一下,但是两个我试了下,只能识别出一个,这个真让我翻了个大车,而且其实我换这个主板其实还有个大问题,就是我是在 Windows 下的vmware workstation 虚拟机里通过sata 直通,但是这个是认硬盘接口的,也就是顺序是有影响的,换了主板发现也不能支持,后面可能真的想用的话还得重新搞黑裙,要把数据备份出来,幸好换回原来的主板还能用,所以硬件也不能只看性能和接口丰富度,要看适配的其他硬件的合适度以及原先已经有的软件系统

    ]]>
    nas @@ -20734,19 +20667,129 @@ zk3 192.168.2.3
    - 解决 网络文件夹目前是以其他用户名和密码进行映射的 问题 - /2023/04/09/%E8%A7%A3%E5%86%B3-%E7%BD%91%E7%BB%9C%E6%96%87%E4%BB%B6%E5%A4%B9%E7%9B%AE%E5%89%8D%E6%98%AF%E4%BB%A5%E5%85%B6%E4%BB%96%E7%94%A8%E6%88%B7%E5%90%8D%E5%92%8C%E5%AF%86%E7%A0%81%E8%BF%9B%E8%A1%8C%E6%98%A0%E5%B0%84%E7%9A%84/ - 之前在使用 smb 协议在 Windows 中共享磁盘使用映射网络驱动器的时候,如果前一次登录过账号密码后面有了改动,或者前一次改错了,
    就会出现这样的提示

    应该是 Windows 已经把之前的连接记录下来了,即使是链接不成功的
    可以通过在 cmd 或者 powershell 执行 net use 命令查看当前已经连接的

    这样就可以用命令来把这个删除
    net use [NETNAME] /delete
    比如这边就可以
    net use \\xxxxxxxx\f /delete
    然后再重新输入账号密码就好了
    关于net use的命令使用方式可以参考

    -
    net use [{<DeviceName> | *}] [\\<ComputerName>\<ShareName>[\<volume>]] [{<Password> | *}]] [/user:[<DomainName>\]<UserName] >[/user:[<DottedDomainName>\]<UserName>] [/user: [<UserName@DottedDomainName>] [/savecred] [/smartcard] [{/delete | /persistent:{yes | no}}]
    -net use [<DeviceName> [/home[{<Password> | *}] [/delete:{yes | no}]]
    -net use [/persistent:{yes | no}]
    -

    官方链接

    + 记录下 phpunit 的入门使用方法之setUp和tearDown + /2022/10/23/%E8%AE%B0%E5%BD%95%E4%B8%8B-phpunit-%E7%9A%84%E5%85%A5%E9%97%A8%E4%BD%BF%E7%94%A8%E6%96%B9%E6%B3%95%E4%B9%8BsetUp%E5%92%8CtearDown/ + 可能是太久没写单测了,写个单测发现不符合预期,后来验证下才反应过来
    我们来看下demo

    +
    class RenameTest extends TestCase
    +{
    +    public function setUp(): void
    +    {
    +        var_dump("setUp");
    +    }
    +
    +    public function test1()
    +    {
    +        var_dump("test1");
    +        assertEquals(1, 1);
    +    }
    +
    +    public function test2()
    +    {
    +        var_dump("test2");
    +        assertEquals(1, 1);
    +    }
    +
    +    protected function tearDown(): void
    +    {
    +        var_dump("tearDown");
    +    }
    +}
    +

    因为我是想写个重命名的小工具,希望通过setUptearDown做一些文件初始化和清理工作,但是我把两个case的初始化跟清理工作写到了单个setUptearDown中,这样就出现了异常的错误
    通过上面的示例代码,可以看到执行结果

    +
    ❯ vendor/bin/phpunit
    +PHPUnit 9.5.25 by Sebastian Bergmann and contributors.
    +
    +.string(5) "setUp"
    +string(5) "test1"
    +string(8) "tearDown"
    +.                                                                  2 / 2 (100%)string(5) "setUp"
    +string(5) "test2"
    +string(8) "tearDown"
    +
    +
    +Time: 00:00.005, Memory: 6.00 MB
    +
    +OK (2 tests, 2 assertions)
    +

    其实就是很简单的会在每个test方法前后都执行setUptearDown

    +]]>
    + + php + + + php + +
    + + 这周末我又在老丈人家打了天小工 + /2020/08/30/%E8%BF%99%E5%91%A8%E6%9C%AB%E6%88%91%E5%8F%88%E5%9C%A8%E8%80%81%E4%B8%88%E4%BA%BA%E5%AE%B6%E6%89%93%E4%BA%86%E5%A4%A9%E5%B0%8F%E5%B7%A5/ + 因为活实在比较多,也不太好叫大工(活比较杂散),相比上一次我跟 LD 俩人晚起了一点,我真的是只要有事,早上就醒的很早,准备八点出发的,六点就醒了,然后想继续睡就一直做梦🤦‍♂️,差不多八点半多到的丈人家,他们应该已经干了有一会了,我们到了以后就分配给我撬地板的活,上次说的那个敲掉柜子的房间里,还铺着质地还不错的木地板,但是也不想要了,得撬掉重新铺。
    拿着撬棍和榔头就上楼去干了,浙江这几天的天气,最高温度一般 38、9,楼上那个房间也没风扇,有了也不能用,都是灰尘,撬了两下,我感觉我体内的水就像真气爆发一样变成汗炸了出来,眼睛全被汗糊住了,可能大部分人不太了解地板是怎么铺的,一般是在地面先铺一层混凝土,混凝土中间嵌进去规则的长条木条,然后真正的地板一块块的都是钉在那个木条上,用那种气枪钉和普通的钉子,并且块跟块之前还有一个木头的槽结构相互耦合,然后边缘的一圈在用较薄的木板将整个木地板封边(这些词都是我现造的),边缘的用的钉子会更多,所以那几下真的很用力,而且撬地板,得蹲下起来,如此反复,对于我这个体重快超过身高的中年人来说的确是非常大的挑战,接下来继续撬了几个,已经有种要虚脱晕倒的感觉了,及时去喝水擦了汗,又歇了一会,为啥一上来就这么拼呢,主要是因为那个房间丈人在干活的时候是直接看得到的🤦‍♂️,后来被 LD 一顿教育,本来就是去帮忙的,又不是专业做这个的,急啥。
    喝了水之后,又稍稍歇了一会,就开始继续撬了,本来觉得这个地板撬着好像还行,房间不大,没多久就撬完了,撬完之后喝了点饮料(补充点糖分,早餐吃得少,有点低血糖),然后看到 LD 在撬下面的木条了,这个动作开始了那天最大的经验值收集行动,前面说了这个木条一般是跟混凝土一块铺上去的,但是谁也没想到,这个混凝土铺上去的时候竟然处理的这么随意,根本没考虑跟下面的贴合,所以撬木条的时候直接把木条跟木条中间大块大块的混凝土一块撬起来了,想想那重量,于是我这靠蛮力干活的,就用力把木条带着混凝土一块撬了起来,还沾沾自喜,但是发现结果是撬起来一块之后,体力值瞬间归零,上一篇我也提到了,其实干这类活也是很有技巧性的,但是上次的是我没学会,可能需要花时间学的,但是这次是LD 用她的纤细胳膊教会我的,我在撬的时候,屏住一口气,双手用力,起,大概是吃好几口奶的力气都用出来了,但是 LD 在我休息的时候,慢慢悠悠的,先把撬棍挤到木条或者混凝土跟下层的缝里,然后往下垫一小块混凝土碎石,然后轻轻松松的扳两下,就撬开了,亏我高中的时候引以为傲的物理成绩,作为物理课代表,这么浅显易懂的杠杆原理都完全不会用到生活里,后面在用这个技巧撬的过程中,真的觉得自己蠢到家了,当然在明白了用点杠杆原理之后,撬地板的活就变得慢慢悠悠,悠哉悠哉的了(其实还是很热的,披着毛巾擦眼睛)。
    上午的活差不多完了,后面就是把撬出来的混凝土和地板条丢下去,地上铺着不用了的被子,然后就是午饭和午休环节了,午饭换了一家快餐,味道非常可以,下午的活就比较单调了,帮忙清理了上去扔下来的混凝土碎块跟木条,然后稍微打扫了下,老丈人就让我们回家了,接着上次说的,还是觉得比跑步啥的消耗大太多了,那汗流的,一口就能喝完一瓶 500 毫升左右的矿泉水。

    +]]>
    + + 生活 + 运动 + 跑步 + 干活 + + + 生活 + 运动 + 减肥 + 跑步 + 干活 + +
    + + dubbo 客户端配置的一个重要知识点 + /2022/06/11/dubbo-%E5%AE%A2%E6%88%B7%E7%AB%AF%E9%85%8D%E7%BD%AE%E7%9A%84%E4%B8%80%E4%B8%AA%E9%87%8D%E8%A6%81%E7%9F%A5%E8%AF%86%E7%82%B9/ + 在配置项目中其实会留着比较多的问题,由于不同的项目没有比较统一的规划和框架模板,一般都是只有创建者会比较了解(可能也不了解),譬如前阵子在配置一个 springboot + dubbo 的项目,发现了dubbo 连接注册中间客户端的问题,这里可以结合下代码来看
    比如有的应用是用的这个

    +
    <dependency>
    +    <groupId>org.apache.curator</groupId>
    +    <artifactId>curator-client</artifactId>
    +    <version>${curator.version}</version>            
    +</dependency>
    +<dependency>
    +    <groupId>org.apache.curator</groupId>
    +    <artifactId>curator-recipes</artifactId>
    +    <version>${curator.version}</version>
    +</dependency>
    +

    有个别应用用的是这个

    +
    <dependency>
    +    <groupId>com.101tec</groupId>
    +    <artifactId>zkclient</artifactId>
    +    <version>0.11</version>
    +</dependency>
    +

    还有的应用是找不到相关的依赖,并且这些的使用没有个比较好的说明,为啥用前者,为啥用后者,有啥注意点,
    首先在使用 2.6.5 的 alibaba 的 dubbo 的时候,只使用后者是会报错的,至于为啥会报错,其实就是这篇文章想说明的点
    报错的内容其实很简单, 就是缺少这个 org.apache.curator.framework.CuratorFrameworkFactory
    这个类看着像是依赖上面的配置,但是应该不需要两个配置一块用的,所以还是需要去看代码
    通过找上面类被依赖的和 dubbo 连接注册中心相关的代码,看到了这段指点迷津的代码

    +
    @SPI("curator")
    +public interface ZookeeperTransporter {
    +
    +    @Adaptive({Constants.CLIENT_KEY, Constants.TRANSPORTER_KEY})
    +    ZookeeperClient connect(URL url);
    +
    +}
    +

    众所周知,dubbo 创造了叫自适应扩展点加载的神奇技术,这里的 adaptive 注解中的Constants.CLIENT_KEYConstants.TRANSPORTER_KEY 可以在配置 dubbo 的注册信息的时候进行配置,如果是通过 xml 配置的话,可以在 <dubbo:registry/> 这个 tag 中的以上两个 key 进行配置,
    具体在 dubbo.xsd 中有描述

    +
    <xsd:element name="registry" type="registryType">
    +        <xsd:annotation>
    +            <xsd:documentation><![CDATA[ The registry config ]]></xsd:documentation>
    +        </xsd:annotation>
    +    </xsd:element>
    + +


    并且在 spi 的配置com.alibaba.dubbo.remoting.zookeeper.ZookeeperTransporter 中可以看到

    +
    zkclient=com.alibaba.dubbo.remoting.zookeeper.zkclient.ZkclientZookeeperTransporter
    +curator=com.alibaba.dubbo.remoting.zookeeper.curator.CuratorZookeeperTransporter
    +
    +zkclient=com.alibaba.dubbo.remoting.zookeeper.zkclient.ZkclientZookeeperTransporter
    +curator=com.alibaba.dubbo.remoting.zookeeper.curator.CuratorZookeeperTransporter
    +
    +zkclient=com.alibaba.dubbo.remoting.zookeeper.zkclient.ZkclientZookeeperTransporter
    +curator=com.alibaba.dubbo.remoting.zookeeper.curator.CuratorZookeeperTransporter
    +

    而在上面的代码里默认的SPI 值是 curator,所以如果不配置,那就会报上面找不到类的问题,所以如果需要使用 zkclient 的,就需要在<dubbo:registry/> 配置中添加 client="zkclient"这个配置,所以有些地方还是需要懂一些更深层次的原理,但也不至于每个东西都要抠到每一行代码原理,除非就是专门做这一块的。
    还有一点是发现有些应用是碰运气,刚好有个三方包把这个类带进来了,但是这个应用就没有单独配置这块,如果不了解或者后续忘了再来查问题就会很奇怪

    ]]>
    - 技巧 + Java + Dubbo - windows + Java + Dubbo
    @@ -20765,25 +20808,6 @@ net use [/看书 - - 这周末我又在老丈人家打了天小工 - /2020/08/30/%E8%BF%99%E5%91%A8%E6%9C%AB%E6%88%91%E5%8F%88%E5%9C%A8%E8%80%81%E4%B8%88%E4%BA%BA%E5%AE%B6%E6%89%93%E4%BA%86%E5%A4%A9%E5%B0%8F%E5%B7%A5/ - 因为活实在比较多,也不太好叫大工(活比较杂散),相比上一次我跟 LD 俩人晚起了一点,我真的是只要有事,早上就醒的很早,准备八点出发的,六点就醒了,然后想继续睡就一直做梦🤦‍♂️,差不多八点半多到的丈人家,他们应该已经干了有一会了,我们到了以后就分配给我撬地板的活,上次说的那个敲掉柜子的房间里,还铺着质地还不错的木地板,但是也不想要了,得撬掉重新铺。
    拿着撬棍和榔头就上楼去干了,浙江这几天的天气,最高温度一般 38、9,楼上那个房间也没风扇,有了也不能用,都是灰尘,撬了两下,我感觉我体内的水就像真气爆发一样变成汗炸了出来,眼睛全被汗糊住了,可能大部分人不太了解地板是怎么铺的,一般是在地面先铺一层混凝土,混凝土中间嵌进去规则的长条木条,然后真正的地板一块块的都是钉在那个木条上,用那种气枪钉和普通的钉子,并且块跟块之前还有一个木头的槽结构相互耦合,然后边缘的一圈在用较薄的木板将整个木地板封边(这些词都是我现造的),边缘的用的钉子会更多,所以那几下真的很用力,而且撬地板,得蹲下起来,如此反复,对于我这个体重快超过身高的中年人来说的确是非常大的挑战,接下来继续撬了几个,已经有种要虚脱晕倒的感觉了,及时去喝水擦了汗,又歇了一会,为啥一上来就这么拼呢,主要是因为那个房间丈人在干活的时候是直接看得到的🤦‍♂️,后来被 LD 一顿教育,本来就是去帮忙的,又不是专业做这个的,急啥。
    喝了水之后,又稍稍歇了一会,就开始继续撬了,本来觉得这个地板撬着好像还行,房间不大,没多久就撬完了,撬完之后喝了点饮料(补充点糖分,早餐吃得少,有点低血糖),然后看到 LD 在撬下面的木条了,这个动作开始了那天最大的经验值收集行动,前面说了这个木条一般是跟混凝土一块铺上去的,但是谁也没想到,这个混凝土铺上去的时候竟然处理的这么随意,根本没考虑跟下面的贴合,所以撬木条的时候直接把木条跟木条中间大块大块的混凝土一块撬起来了,想想那重量,于是我这靠蛮力干活的,就用力把木条带着混凝土一块撬了起来,还沾沾自喜,但是发现结果是撬起来一块之后,体力值瞬间归零,上一篇我也提到了,其实干这类活也是很有技巧性的,但是上次的是我没学会,可能需要花时间学的,但是这次是LD 用她的纤细胳膊教会我的,我在撬的时候,屏住一口气,双手用力,起,大概是吃好几口奶的力气都用出来了,但是 LD 在我休息的时候,慢慢悠悠的,先把撬棍挤到木条或者混凝土跟下层的缝里,然后往下垫一小块混凝土碎石,然后轻轻松松的扳两下,就撬开了,亏我高中的时候引以为傲的物理成绩,作为物理课代表,这么浅显易懂的杠杆原理都完全不会用到生活里,后面在用这个技巧撬的过程中,真的觉得自己蠢到家了,当然在明白了用点杠杆原理之后,撬地板的活就变得慢慢悠悠,悠哉悠哉的了(其实还是很热的,披着毛巾擦眼睛)。
    上午的活差不多完了,后面就是把撬出来的混凝土和地板条丢下去,地上铺着不用了的被子,然后就是午饭和午休环节了,午饭换了一家快餐,味道非常可以,下午的活就比较单调了,帮忙清理了上去扔下来的混凝土碎块跟木条,然后稍微打扫了下,老丈人就让我们回家了,接着上次说的,还是觉得比跑步啥的消耗大太多了,那汗流的,一口就能喝完一瓶 500 毫升左右的矿泉水。

    -]]>
    - - 生活 - 运动 - 跑步 - 干活 - - - 生活 - 运动 - 减肥 - 跑步 - 干活 - -
    闲聊下乘公交的用户体验 /2021/02/28/%E9%97%B2%E8%81%8A%E4%B8%8B%E4%B9%98%E5%85%AC%E4%BA%A4%E7%9A%84%E7%94%A8%E6%88%B7%E4%BD%93%E9%AA%8C/ @@ -20807,25 +20831,26 @@ net use [/ - 记录下 redis 的一些使用方法 - /2022/10/30/%E8%AE%B0%E5%BD%95%E4%B8%8B-redis-%E7%9A%84%E4%B8%80%E4%BA%9B%E4%BD%BF%E7%94%A8%E6%96%B9%E6%B3%95/ - 虽然说之前讲解过一些redis源码相关的,但是说实话,redis的各种使用其实有时候有点生疏,或者在一些特定的使用场景中,一些使用方法还是需要学习和记录的

    -

    获取所有数据

    获取list类型的所有元素,可以使用 lrange , 直接用lrange key 0 -1
    比如

    这里有一些方便的就是可以不用知道长度,直接全返回,或者如果想拿到特定区间的就可以直接指定起止范围,

    这样就不用一个个pop出来

    -

    裁剪list

    前面用了lrange取得了一个范围的数据,如果想将数据直接移除,那可以用 ltrim ,

    这两个命令就可以从list里取出批量数据,并且能从list里删除这部分数据

    + 闲话篇-也算碰到了为老不尊和坏人变老了的典型案例 + /2022/05/22/%E9%97%B2%E8%AF%9D%E7%AF%87-%E4%B9%9F%E7%AE%97%E7%A2%B0%E5%88%B0%E4%BA%86%E4%B8%BA%E8%80%81%E4%B8%8D%E5%B0%8A%E5%92%8C%E5%9D%8F%E4%BA%BA%E5%8F%98%E8%80%81%E4%BA%86%E7%9A%84%E5%85%B8%E5%9E%8B%E6%A1%88%E4%BE%8B/ + 在目前的房子也差不多租了四五年了,楼下邻居换了两拨了,我们这栋楼装修了不知道多少次,因为是学区的原因,房子交易的频率还是比较高的,不过比较神奇的我们对门的没换过,而且一直也没什么交集(除了后面说的水管爆裂),就进出的时候偶尔看到应该是住着一对老夫妻,感觉年纪也有个七八十了。

    +

    对对面这户人家的印象,就是对面的老头子经常是我出门上班去了他回来,看着他颤颤巍巍地走楼梯,我看到了都靠边走,而且有几次还听见好像是他儿子在说他,”年假这么大了,还是少出去吧”,说实话除了这次的事情,之前就有一次水管阀门爆裂了,算是有点交集,那次大概是去年冬天,天气已经很冷了,我们周日下午回来看到楼梯有点湿,但是没什么特别的异常就没怎么注意,到晚上洗完澡,楼下的邻居就来敲门,说我们门外的水表那一直在流水,出门一看真的是懵了,外面水表那在哗哗哗地流水,导致楼梯那就跟水帘洞一样,仔细看看是对面家的水表阀门那在漏水,我只能先用塑料袋包一下,然后大冬天(刚洗完澡)穿着凉拖跑下去找物业保安,走到一楼的时候发现水一直流到一楼了,楼梯上都是水流下来,五楼那是最惨的,感觉门框周边都浸透了,五楼的也是态度比较差的让我一定要把水弄好了,但是前面也说了谁是从对门那户的水表阀那出来的,理论上应该让对面的处理,结果我敲门敲了半天对面都没反应,想着我放着不管也不太好,就去找了物业保安,保安上来看了只能先把总阀关了,我也打电话给维修自来水管的,自来水公司的人过了会也是真的来修了,我那会是挺怕不来修,自来水公司的师傅到了以后拿开一看是对面那户的有个阀门估计是自己换上去的,跟我们这的完全不一样,看上去就比较劣质,师傅也挺气的,大晚上被叫过来,我又尝试着去敲门也还是没人应,也没办法,对面老人家我敲太响到时候出来说我吓到他们啥的,第二天去说也没现场了。

    +

    前面的这件事是个重要铺垫,前几天 LD 下班后把厨余垃圾套好袋子放在门口,打算等我下班了因为要去做核酸(hz 48 小时核酸)顺便带下去,结果到了七点多,说对面的老太太在那疯狂砸门了,LD 被吓到了不敢开门,老太太在外面一边砸门一边骂,“你们年轻人怎么素质这么差”(他们家也经常在门口放垃圾,我们刚来住的时候在楼梯转角他们就放这个废弃的洗衣机,每次走楼梯带点东西都要小心翼翼地走,不然都过不去,然后我赶紧赶回去,结果她听到我回家了,还特意开门继续骂,“你们年轻人怎么素质这么差,垃圾放在这里”,我说我们刚才放在这,打算待会做核酸的时候去扔掉,结果他们家老头,都已经没了牙齿,在那瞪大眼睛说,“你们早上就放在这了的,”我说是LD 刚才下班了放的,争论了一会,我说这个事情我们门口放了垃圾,这会我就去扔掉了,但是你们家老太太这么砸门总不太好,像之前门口水管爆掉了,我敲了门没人应,我也没要砸门一定把你们叫醒,结果老头老太说我们的水管从来没换过,不可能破的(其实到这,再往后说就没意思了,跟这么不要脸的人说多了也只是瞎扯),一会又回到这个垃圾的问题,那个老头说“你们昨天就放在这里了的”,睁着眼说瞎话可真是 666,感觉不是老太太拦着点他马上就要冲上来揍我了一样,事后我想想,这种情况我大概只能躺地上装死了,当这个事情发生之前我真的快把前面说的事情(水管阀坏了)给忘了,虽然这是理论上不该我来处理,除非是老头老太太请求我帮忙,这事后面我也从没说起过,本来完全没交集,对他们的是怎么样的人也没概念,总觉得年纪大了可能还比较心宽和蔼点,结果没想到就是一典型的坏人变老了,我说你们这么砸门,我老婆都被吓得不敢开门,结果对面老头老太太的儿子也出来了说,“我们就是敲下门,我母亲是机关单位退休的,所以肯定不会敲门很大声的,你老婆觉得吓到了是你们人生观价值观有问题”,听到这话我差点笑出来,连着两个可笑至极的脑残逻辑,无语他妈给无语开门,无语到家了。对门家我们之前有个印象就是因为我们都是顶楼,这边老小区以前都是把前后阳台包进来的,然后社区就来咨询大家的意见是不是统一把包进来的违建拆掉,还特地上来六楼跟他们说,结果对面的老头就说,“我要去住建局投诉你们”,本来这个事情是违法的,但是社区的意思也是征求各位业主的意见,结果感觉是社区上门强拆了一样,为老不尊,坏人变老了的典范了。

    ]]>
    - redis + 生活 - redis + 生活
    - 闲话篇-也算碰到了为老不尊和坏人变老了的典型案例 - /2022/05/22/%E9%97%B2%E8%AF%9D%E7%AF%87-%E4%B9%9F%E7%AE%97%E7%A2%B0%E5%88%B0%E4%BA%86%E4%B8%BA%E8%80%81%E4%B8%8D%E5%B0%8A%E5%92%8C%E5%9D%8F%E4%BA%BA%E5%8F%98%E8%80%81%E4%BA%86%E7%9A%84%E5%85%B8%E5%9E%8B%E6%A1%88%E4%BE%8B/ - 在目前的房子也差不多租了四五年了,楼下邻居换了两拨了,我们这栋楼装修了不知道多少次,因为是学区的原因,房子交易的频率还是比较高的,不过比较神奇的我们对门的没换过,而且一直也没什么交集(除了后面说的水管爆裂),就进出的时候偶尔看到应该是住着一对老夫妻,感觉年纪也有个七八十了。

    -

    对对面这户人家的印象,就是对面的老头子经常是我出门上班去了他回来,看着他颤颤巍巍地走楼梯,我看到了都靠边走,而且有几次还听见好像是他儿子在说他,”年假这么大了,还是少出去吧”,说实话除了这次的事情,之前就有一次水管阀门爆裂了,算是有点交集,那次大概是去年冬天,天气已经很冷了,我们周日下午回来看到楼梯有点湿,但是没什么特别的异常就没怎么注意,到晚上洗完澡,楼下的邻居就来敲门,说我们门外的水表那一直在流水,出门一看真的是懵了,外面水表那在哗哗哗地流水,导致楼梯那就跟水帘洞一样,仔细看看是对面家的水表阀门那在漏水,我只能先用塑料袋包一下,然后大冬天(刚洗完澡)穿着凉拖跑下去找物业保安,走到一楼的时候发现水一直流到一楼了,楼梯上都是水流下来,五楼那是最惨的,感觉门框周边都浸透了,五楼的也是态度比较差的让我一定要把水弄好了,但是前面也说了谁是从对门那户的水表阀那出来的,理论上应该让对面的处理,结果我敲门敲了半天对面都没反应,想着我放着不管也不太好,就去找了物业保安,保安上来看了只能先把总阀关了,我也打电话给维修自来水管的,自来水公司的人过了会也是真的来修了,我那会是挺怕不来修,自来水公司的师傅到了以后拿开一看是对面那户的有个阀门估计是自己换上去的,跟我们这的完全不一样,看上去就比较劣质,师傅也挺气的,大晚上被叫过来,我又尝试着去敲门也还是没人应,也没办法,对面老人家我敲太响到时候出来说我吓到他们啥的,第二天去说也没现场了。

    -

    前面的这件事是个重要铺垫,前几天 LD 下班后把厨余垃圾套好袋子放在门口,打算等我下班了因为要去做核酸(hz 48 小时核酸)顺便带下去,结果到了七点多,说对面的老太太在那疯狂砸门了,LD 被吓到了不敢开门,老太太在外面一边砸门一边骂,“你们年轻人怎么素质这么差”(他们家也经常在门口放垃圾,我们刚来住的时候在楼梯转角他们就放这个废弃的洗衣机,每次走楼梯带点东西都要小心翼翼地走,不然都过不去,然后我赶紧赶回去,结果她听到我回家了,还特意开门继续骂,“你们年轻人怎么素质这么差,垃圾放在这里”,我说我们刚才放在这,打算待会做核酸的时候去扔掉,结果他们家老头,都已经没了牙齿,在那瞪大眼睛说,“你们早上就放在这了的,”我说是LD 刚才下班了放的,争论了一会,我说这个事情我们门口放了垃圾,这会我就去扔掉了,但是你们家老太太这么砸门总不太好,像之前门口水管爆掉了,我敲了门没人应,我也没要砸门一定把你们叫醒,结果老头老太说我们的水管从来没换过,不可能破的(其实到这,再往后说就没意思了,跟这么不要脸的人说多了也只是瞎扯),一会又回到这个垃圾的问题,那个老头说“你们昨天就放在这里了的”,睁着眼说瞎话可真是 666,感觉不是老太太拦着点他马上就要冲上来揍我了一样,事后我想想,这种情况我大概只能躺地上装死了,当这个事情发生之前我真的快把前面说的事情(水管阀坏了)给忘了,虽然这是理论上不该我来处理,除非是老头老太太请求我帮忙,这事后面我也从没说起过,本来完全没交集,对他们的是怎么样的人也没概念,总觉得年纪大了可能还比较心宽和蔼点,结果没想到就是一典型的坏人变老了,我说你们这么砸门,我老婆都被吓得不敢开门,结果对面老头老太太的儿子也出来了说,“我们就是敲下门,我母亲是机关单位退休的,所以肯定不会敲门很大声的,你老婆觉得吓到了是你们人生观价值观有问题”,听到这话我差点笑出来,连着两个可笑至极的脑残逻辑,无语他妈给无语开门,无语到家了。对门家我们之前有个印象就是因为我们都是顶楼,这边老小区以前都是把前后阳台包进来的,然后社区就来咨询大家的意见是不是统一把包进来的违建拆掉,还特地上来六楼跟他们说,结果对面的老头就说,“我要去住建局投诉你们”,本来这个事情是违法的,但是社区的意思也是征求各位业主的意见,结果感觉是社区上门强拆了一样,为老不尊,坏人变老了的典范了。

    + 闲话篇-路遇神逻辑骑车带娃爹 + /2022/05/08/%E9%97%B2%E8%AF%9D%E7%AF%87-%E8%B7%AF%E9%81%87%E7%A5%9E%E9%80%BB%E8%BE%91%E9%AA%91%E8%BD%A6%E5%B8%A6%E5%A8%83%E7%88%B9/ + 周末吃完中饭去买菜,没想到碰到这个神(zhi)奇(zhang)大哥带着两个娃,在非机动车道虽然没有像上班高峰车那么多,但是有送外卖,各种叮咚买菜和普通像我这样骑电驴,骑自行车的人,我的情况可能还特殊点,前面说过电驴买了以后本来网上找到过怎么解除限速的,后面看了下,限速 25 虽然慢,但还是对安全很有好处的,我上下班也不赶这个时间,所以就没解除,其他路上的电瓶车包括这位带娃的大哥可能有不少都不符合国标的限速要求或者解除了限速,这些算是铺垫。

    +

    那位大哥,骑电瓶车一前一后带着两个娃,在非机动车道靠右边行驶,肉眼估计是在我右前方大概十几米的距离,不知道是小孩不舒服了还是啥,想下来还是就在跟他爹玩耍,我算是比较谨慎骑车的,看到这种情况已经准备好捏刹车了,但是也没想到这个娃这么神,差不多能并排四五辆电瓶车的非机动车道,直接从他爸的车下来跑到了非机动车道的最左边,前面我铺垫了电瓶车 25 码,换算一下大概 1 秒能前进 7 米,我是直接把刹车捏死了,才勉强避免撞上这个小孩,并且当时的情况本来我左后方有另一个大哥是想从我左边超过去,因为我刹车了他也赶紧刹车。

    +

    现在我们做个假设,假如我刹车不够及时,撞上了这个小孩,会是啥后果呢,小孩人没事还好,即使没事也免不了大吵一架,说我骑车不看前面,然后去医院做检查,负责医药费,如果是有点啥伤了,这事估计是没完了,我是心里一阵后怕。

    +

    说实话是张口快骂人了,“怎么带小孩的”,结果那大哥竟然还是那套话术,“你们骑车不会慢点的啊,说一下就好了啊,用得着这么说吗”,我是真的被这位的逻辑给打败了,还好是想超我车那大哥刹住车了,他要是刹不住呢,把我撞了我怪谁?这不是追尾事件,是 zhizhang 大哥的小孩鬼探头,下个电瓶车就下车,下来就往另一边跑,我们尽力刹车没撞到这小孩,说他没管好小孩这大哥还觉得自己委屈了?结果我倒是想骂脏话了,结果我左后方的的大哥就跟他说“你这么教小孩教得真好,你真厉害”,果然在中国还是不能好好说话,阴阳怪气才是王道,我前面也说了真的是后怕,为什么我从头到尾都没有说这个小孩不对,我是觉得这个年纪的小孩(估摸着也就五六岁或者再大个一两岁)这种安全意识应该是要父母和学校老师一起教育培养的,在路上不能这么随便乱跑,即使别人撞了他,别人有责任,那小孩的生理伤痛和心理伤害,父母也肯定要心疼的吧,另外对我们来说前面也说了,真的撞到了我们也是很难受的,这个社会里真的是自私自利的人太多了,平时让外卖小哥送爬下楼梯送上来外卖都觉得挺抱歉的,每次的接过来都说谢谢,人家也不容易,换在有些人身上大概会觉得自己花了钱就是大爷,给我送上来是必须的。

    ]]>
    生活 @@ -20835,89 +20860,54 @@ net use [/
    - 记录下 phpunit 的入门使用方法 - /2022/10/16/%E8%AE%B0%E5%BD%95%E4%B8%8B-phpunit-%E7%9A%84%E5%85%A5%E9%97%A8%E4%BD%BF%E7%94%A8%E6%96%B9%E6%B3%95/ - 这周开始打算写个比较简单的php工具包,然后顺带学习使用下php的单元测试,通过phpunit还是比较方便的,首先就composer require phpunit/phpunit
    安装下 phpunit, 前面包就是通过 composer init 创建,装完依赖后就可以把自动加载代码生成下 composer dump-autoload
    目录结构差不多这样

    -
    .
    -├── composer.json
    -├── composer.lock
    -├── oldfile.txt
    -├── phpunit.xml
    -├── src
    -│   └── Rename.php
    -└── tests
    -    └── RenameTest.php
    -
    -2 directories, 6 files
    -

    src/是源码,tests/是放的单测,比较重要的是phpunit.xml

    -
    <?xml version="1.0" encoding="UTF-8"?>
    -<phpunit colors="true" bootstrap="vendor/autoload.php">
    -    <testsuites>
    -        <testsuite name="php-rename">
    -            <directory>./tests/</directory>
    -        </testsuite>
    -    </testsuites>
    -</phpunit>
    -

    其中bootstrap就是需要把依赖包的自动加载入口配上,因为这个作为一个package,也会指出命名空间
    然后就是testsuite的路径,源码中

    -
    <?php
    -namespace Nicksxs\PhpRename;
    -
    -class Rename
    -{
    -    public static function renameSingleFile($file, $newFileName): bool
    -    {
    -        if(!is_file($file)) {
    -            echo "it's not a file";
    -            return false;
    +    聊聊 Java 的 equals 和 hashCode 方法
    +    /2021/01/03/%E8%81%8A%E8%81%8A-Java-%E7%9A%84-equals-%E5%92%8C-hashCode-%E6%96%B9%E6%B3%95/
    +    Java 中的这个话题也是比较常遇到的,关于这块原先也是比较忽略的,但是仔细想想又有点遗忘了就在这里记一下
    简单看下代码
    java.lang.Object#equals

    +
    public boolean equals(Object obj) {
    +        return (this == obj);
    +    }
    +

    对于所有对象的父类,equals 方法其实对比的就是对象的地址,也就是是否是同一个对象,试想如果像 Integer 或者 String 这种,我们没有重写 equals,那其实就等于是在用==,可能就没法达到我们的目的,所以像 String 这种常用的 jdk 类都是默认重写了
    java.lang.String#equals

    +
    public boolean equals(Object anObject) {
    +        if (this == anObject) {
    +            return true;
             }
    -        $fileInfo = pathinfo($file);
    -        return rename($file, $fileInfo["dirname"] . DIRECTORY_SEPARATOR . $newFileName . "." . $fileInfo["extension"]);
    -    }
    -}
    -

    就是一个简单的重命名
    然后test代码是这样,

    -
    <?php
    -
    -// require_once 'vendor/autoload.php';
    -
    -use PHPUnit\Framework\TestCase;
    -use Nicksxs\PhpRename\Rename;
    -use function PHPUnit\Framework\assertEquals;
    -
    -class RenameTest extends TestCase 
    -{
    -    public function setUp() :void
    -    {
    -        $myfile = fopen(__DIR__ . DIRECTORY_SEPARATOR . "oldfile.txt", "w") or die("Unable to open file!");
    -        $txt = "file test1\n";
    -        fwrite($myfile, $txt);
    -        fclose($myfile);
    -    }
    -    public function testRename()
    -    {
    -        Rename::renameSingleFile(__DIR__ . DIRECTORY_SEPARATOR . "oldfile.txt", "newfile");
    -        assertEquals(is_file(__DIR__ . DIRECTORY_SEPARATOR . "newfile.txt"), true);
    -    }
    -
    -    protected function tearDown(): void
    -    {
    -        unlink(__DIR__ . DIRECTORY_SEPARATOR . "newfile.txt");
    -    }
    -}
    -

    setUptearDown 就是初始化跟结束清理的,但是注意如果不指明 __DIR__ ,待会的目录就会在执行 vendor/bin/phpunit 下面,
    或者也可以指定在一个 tmp/ 目录下
    最后就可以通过vendor/bin/phpunit 来执行测试
    执行结果

    -
    ❯ vendor/bin/phpunit
    -PHPUnit 9.5.25 by Sebastian Bergmann and contributors.
    -
    -.                                                                   1 / 1 (100%)
    -
    -Time: 00:00.005, Memory: 6.00 MB
    -
    -OK (1 test, 1 assertion)
    + if (anObject instanceof String) { + String anotherString = (String)anObject; + int n = value.length; + if (n == anotherString.value.length) { + char v1[] = value; + char v2[] = anotherString.value; + int i = 0; + while (n-- != 0) { + if (v1[i] != v2[i]) + return false; + i++; + } + return true; + } + } + return false; + }
    +

    然后呢就是为啥一些书或者 effective java 中写了 equalshashCode 要一起重写,这里涉及到当对象作为 HashMapkey 的时候
    首先 HashMap 会使用 hashCode 去判断是否在同一个槽里,然后在通过 equals 去判断是否是同一个 key,是的话就替换,不是的话就链表接下去,如果不重写 hashCode 的话,默认的 objecthashCodenative 方法,根据对象的地址生成的,这样其实对象的值相同的话,因为地址不同,HashMap 也会出现异常,所以需要重写,同时也需要重写 equals 方法,才能确认是同一个 key,而不是落在同一个槽的不同 key.

    ]]>
    - php + java - php + java + +
    + + 难得的大扫除 + /2022/04/10/%E9%9A%BE%E5%BE%97%E7%9A%84%E5%A4%A7%E6%89%AB%E9%99%A4/ + 因为房东要来续签合同,记得之前她说要来看看,后来一直都没来成,一方面我们没打扫过也不想被看到,小房子东西从搬进来以后越来越多,虽然不是脏乱差,但也觉得有点不满意干净状态,这里不得不感叹房东家的有钱程度,买了房子自己都没进房子看过,买来只是为了个学籍,去年前房东把房子卖给新房东后,我们还是比较担心会要换房子了,这里其实是个我们在乎的优点略大于缺点的小房子,面积比较小,但是交通便利以及上下班通勤,周边配套也还不错,有个比较大的菜市场,虽然不常去,因为不太会挑不会还价,还是主要去附近一公里左右的超市,可以安静地挑菜,但是说实在的菜场的菜还是比超市新鲜一些。
    大扫除说实在的住在这边以后就没有一次真正意义上的大扫除,因为平时也有在正常打扫,只有偶尔的厨房煤气灶和厕所专门清理下,平时扫地拖地都有做,但是因为说实在的这房子也比较老了,地板什么的都有明显的老化,表面上的油漆都已经被磨损掉了,一些污渍很难拖干净,而且包括厨房和厕所的瓷砖都是纹路特别多,加上磨损,基本是污渍很多,特别是厨房的,又有油渍,我们搬进来的时候厨房的地就已经不太干净了,还有一点就是虽然不是在乡下的房子,但是旁边有两条主干道,一般只要开着窗没几天就灰尘积起来了,公司的电脑在家两天不到就一层灰,而且有些灰在地上时间久一点就会变成那种棉絮状的,看起来就会觉得更脏,并且地板我们平时就是扫一下,然后拖一下没明显的脏东西跟大灰尘就好了,有一些脏的就很难拖干净。
    这次的算是整体的大扫除,把柜子,桌子,茶几台,窗边的灰尘都要擦掉,有一些角落还是有蛮多灰尘,当然特别难受的就是电脑那些接口,线缆上的,都杂糅在一块,如果要全都解开了理顺了还是比较麻烦,并且得断电,所以还是尽力清理,但没有全弄开了(我承认我是在偷懒,这里得说下清理了键盘,键盘之前都是放着用,也没盖住,按键缝里就很容易积灰也很难清理,这次索性直接把键全拔了,但是里面的清理也还是挺麻烦,因为不是平板一块,而且还有小孔,有些缝隙也比较难擦进去,只能慢慢地用牙线棒裹着抹布还有棉签擦一下,然后把键帽用洗手液什么的都擦一下洗洗干净,最后晾干了装好感觉就是一把新键盘了,后面主要是拖地了,这次最神奇的就是这个拖地,本来我就跟 LD 吹牛说拖地我是专业的,从小拖到大,有些地板缝边上的污渍,我又是用力来回拖,再用脚踩着拖,还是能把一些原来以为拖不掉的污渍给拖干净了,但是后来的厨房就比较难,用洗洁精来回拖感觉一点都起不来,可能是污渍积了太久了,一开始都想要放弃了,就打算拖干就好了,后来突然看到旁边有个洗衣服的板刷,结果竟然能刷起来,这样就停不下来了,说累是真的非常累,感觉刷一块瓷砖就要休息一会,但是整体刷完之后就是焕然一新的赶脚,简直太有成就感了。

    +]]>
    + + 生活 + + + 生活 + 大扫除
    @@ -20933,31 +20923,41 @@ OK (1 t - 闲话篇-路遇神逻辑骑车带娃爹 - /2022/05/08/%E9%97%B2%E8%AF%9D%E7%AF%87-%E8%B7%AF%E9%81%87%E7%A5%9E%E9%80%BB%E8%BE%91%E9%AA%91%E8%BD%A6%E5%B8%A6%E5%A8%83%E7%88%B9/ - 周末吃完中饭去买菜,没想到碰到这个神(zhi)奇(zhang)大哥带着两个娃,在非机动车道虽然没有像上班高峰车那么多,但是有送外卖,各种叮咚买菜和普通像我这样骑电驴,骑自行车的人,我的情况可能还特殊点,前面说过电驴买了以后本来网上找到过怎么解除限速的,后面看了下,限速 25 虽然慢,但还是对安全很有好处的,我上下班也不赶这个时间,所以就没解除,其他路上的电瓶车包括这位带娃的大哥可能有不少都不符合国标的限速要求或者解除了限速,这些算是铺垫。

    -

    那位大哥,骑电瓶车一前一后带着两个娃,在非机动车道靠右边行驶,肉眼估计是在我右前方大概十几米的距离,不知道是小孩不舒服了还是啥,想下来还是就在跟他爹玩耍,我算是比较谨慎骑车的,看到这种情况已经准备好捏刹车了,但是也没想到这个娃这么神,差不多能并排四五辆电瓶车的非机动车道,直接从他爸的车下来跑到了非机动车道的最左边,前面我铺垫了电瓶车 25 码,换算一下大概 1 秒能前进 7 米,我是直接把刹车捏死了,才勉强避免撞上这个小孩,并且当时的情况本来我左后方有另一个大哥是想从我左边超过去,因为我刹车了他也赶紧刹车。

    -

    现在我们做个假设,假如我刹车不够及时,撞上了这个小孩,会是啥后果呢,小孩人没事还好,即使没事也免不了大吵一架,说我骑车不看前面,然后去医院做检查,负责医药费,如果是有点啥伤了,这事估计是没完了,我是心里一阵后怕。

    -

    说实话是张口快骂人了,“怎么带小孩的”,结果那大哥竟然还是那套话术,“你们骑车不会慢点的啊,说一下就好了啊,用得着这么说吗”,我是真的被这位的逻辑给打败了,还好是想超我车那大哥刹住车了,他要是刹不住呢,把我撞了我怪谁?这不是追尾事件,是 zhizhang 大哥的小孩鬼探头,下个电瓶车就下车,下来就往另一边跑,我们尽力刹车没撞到这小孩,说他没管好小孩这大哥还觉得自己委屈了?结果我倒是想骂脏话了,结果我左后方的的大哥就跟他说“你这么教小孩教得真好,你真厉害”,果然在中国还是不能好好说话,阴阳怪气才是王道,我前面也说了真的是后怕,为什么我从头到尾都没有说这个小孩不对,我是觉得这个年纪的小孩(估摸着也就五六岁或者再大个一两岁)这种安全意识应该是要父母和学校老师一起教育培养的,在路上不能这么随便乱跑,即使别人撞了他,别人有责任,那小孩的生理伤痛和心理伤害,父母也肯定要心疼的吧,另外对我们来说前面也说了,真的撞到了我们也是很难受的,这个社会里真的是自私自利的人太多了,平时让外卖小哥送爬下楼梯送上来外卖都觉得挺抱歉的,每次的接过来都说谢谢,人家也不容易,换在有些人身上大概会觉得自己花了钱就是大爷,给我送上来是必须的。

    + 记录下 redis 的一些使用方法 + /2022/10/30/%E8%AE%B0%E5%BD%95%E4%B8%8B-redis-%E7%9A%84%E4%B8%80%E4%BA%9B%E4%BD%BF%E7%94%A8%E6%96%B9%E6%B3%95/ + 虽然说之前讲解过一些redis源码相关的,但是说实话,redis的各种使用其实有时候有点生疏,或者在一些特定的使用场景中,一些使用方法还是需要学习和记录的

    +

    获取所有数据

    获取list类型的所有元素,可以使用 lrange , 直接用lrange key 0 -1
    比如

    这里有一些方便的就是可以不用知道长度,直接全返回,或者如果想拿到特定区间的就可以直接指定起止范围,

    这样就不用一个个pop出来

    +

    裁剪list

    前面用了lrange取得了一个范围的数据,如果想将数据直接移除,那可以用 ltrim ,

    这两个命令就可以从list里取出批量数据,并且能从list里删除这部分数据

    ]]>
    - 生活 + redis - 生活 + redis
    - 难得的大扫除 - /2022/04/10/%E9%9A%BE%E5%BE%97%E7%9A%84%E5%A4%A7%E6%89%AB%E9%99%A4/ - 因为房东要来续签合同,记得之前她说要来看看,后来一直都没来成,一方面我们没打扫过也不想被看到,小房子东西从搬进来以后越来越多,虽然不是脏乱差,但也觉得有点不满意干净状态,这里不得不感叹房东家的有钱程度,买了房子自己都没进房子看过,买来只是为了个学籍,去年前房东把房子卖给新房东后,我们还是比较担心会要换房子了,这里其实是个我们在乎的优点略大于缺点的小房子,面积比较小,但是交通便利以及上下班通勤,周边配套也还不错,有个比较大的菜市场,虽然不常去,因为不太会挑不会还价,还是主要去附近一公里左右的超市,可以安静地挑菜,但是说实在的菜场的菜还是比超市新鲜一些。
    大扫除说实在的住在这边以后就没有一次真正意义上的大扫除,因为平时也有在正常打扫,只有偶尔的厨房煤气灶和厕所专门清理下,平时扫地拖地都有做,但是因为说实在的这房子也比较老了,地板什么的都有明显的老化,表面上的油漆都已经被磨损掉了,一些污渍很难拖干净,而且包括厨房和厕所的瓷砖都是纹路特别多,加上磨损,基本是污渍很多,特别是厨房的,又有油渍,我们搬进来的时候厨房的地就已经不太干净了,还有一点就是虽然不是在乡下的房子,但是旁边有两条主干道,一般只要开着窗没几天就灰尘积起来了,公司的电脑在家两天不到就一层灰,而且有些灰在地上时间久一点就会变成那种棉絮状的,看起来就会觉得更脏,并且地板我们平时就是扫一下,然后拖一下没明显的脏东西跟大灰尘就好了,有一些脏的就很难拖干净。
    这次的算是整体的大扫除,把柜子,桌子,茶几台,窗边的灰尘都要擦掉,有一些角落还是有蛮多灰尘,当然特别难受的就是电脑那些接口,线缆上的,都杂糅在一块,如果要全都解开了理顺了还是比较麻烦,并且得断电,所以还是尽力清理,但没有全弄开了(我承认我是在偷懒,这里得说下清理了键盘,键盘之前都是放着用,也没盖住,按键缝里就很容易积灰也很难清理,这次索性直接把键全拔了,但是里面的清理也还是挺麻烦,因为不是平板一块,而且还有小孔,有些缝隙也比较难擦进去,只能慢慢地用牙线棒裹着抹布还有棉签擦一下,然后把键帽用洗手液什么的都擦一下洗洗干净,最后晾干了装好感觉就是一把新键盘了,后面主要是拖地了,这次最神奇的就是这个拖地,本来我就跟 LD 吹牛说拖地我是专业的,从小拖到大,有些地板缝边上的污渍,我又是用力来回拖,再用脚踩着拖,还是能把一些原来以为拖不掉的污渍给拖干净了,但是后来的厨房就比较难,用洗洁精来回拖感觉一点都起不来,可能是污渍积了太久了,一开始都想要放弃了,就打算拖干就好了,后来突然看到旁边有个洗衣服的板刷,结果竟然能刷起来,这样就停不下来了,说累是真的非常累,感觉刷一块瓷砖就要休息一会,但是整体刷完之后就是焕然一新的赶脚,简直太有成就感了。

    + 记录一次折腾自组 nas 的失败经历-续续篇 + /2023/05/28/%E8%AE%B0%E5%BD%95%E4%B8%80%E6%AC%A1%E6%8A%98%E8%85%BE%E8%87%AA%E7%BB%84-nas-%E7%9A%84%E5%A4%B1%E8%B4%A5%E7%BB%8F%E5%8E%86-%E7%BB%AD%E7%BB%AD%E7%AF%87/ + 之前这个机器已经算是跑起来了,虽然不是很完善也不是最佳实践,不过这篇可能也不算是失败经历了,因为最后成功跑起来了,在没法装最新版的 exsi 的情况下,并且我后面买的华硕 z370 主板点不亮,所以我也有点死心就直接用Windows 下装 vmware workstation 装虚拟机,然后直通硬盘来做 nas,这样可能对于其他人来说是很垃圾的方案,不过因为我很多常用软件的都是在 Windows 环境下的,并且纯黑裙的环境会比较浪费,相比一些同学在群晖里安装 Windows 虚拟机,我觉得还是反过来比较好,毕竟 vmware 做虚拟机应该是比群晖专业点,不过这个方案也有一些问题
    第一种方式是直接找网上同学分享的处理好引导的 vmx,这种我碰到了一个问题就是在打开虚拟机安装群晖系统.pat的时候会提示“无法安装此文件,文件可能已损坏”,这其实不是真的文件已损坏,应该是群晖在做校验的时候存在什么条件没有通过,尝试了断网等方式都不成功,所以后来就用了比较釜底抽薪的方案,直接使用大佬开源的 arpl 引导制作工具
    第二种方式一开始是躺在我 B 站收藏夹里,有个 up 制作的,做得很细致,也把很多细节也解释了,过程其实不难,就是按步骤一步步执行,但是一开始选择了 918+的系统在我的方案里安装不了,会提示无法安装,经过视频下的评论的知道,尝试使用 920+的系统就顺利安装成功了,这里唯一的区别就是在添加硬盘的时候要选择物理磁盘,然后 vmware 给出的硬盘选项是Physical0, Physical1,记得别选错了,然后在启动后我租了 raid5,4 块 4T 的盘,可以组成一个 10T 多一点的存储空间,打算用来作为比较长读写的区域,更大的盘可能就会作为只读区域,减小写入量。后面还有一些问题待解决,一个是电源,考虑换个稍好一点,因为目前看下来电源风扇的噪音比较大,还有就是主板,最近看中了微星的 z390,不过价格比较贵,打算慢慢蹲蹲看。

    ]]>
    - 生活 + nas - 生活 - 大扫除 + nas + +
    + + 记录一次折腾自组 nas 的失败经历 + /2023/05/07/%E8%AE%B0%E5%BD%95%E4%B8%80%E6%AC%A1%E6%8A%98%E8%85%BE%E8%87%AA%E7%BB%84-nas-%E7%9A%84%E5%A4%B1%E8%B4%A5%E7%BB%8F%E5%8E%86/ + 鉴于现在市面上的成品 nas 对于我来说要不就是太贵了,要不就是便宜的盘位少,性能比较差,很多 nas 主打还有用 docker 什么的,但是性能对于我个人比较特殊的使用方式来说还是不太够用的,比如现在比较性能好的 nas 像绿联新出的 DX4600,用的是N5105,passmark 分数还不如我 15 年买的 pc 上的 i5 4590,当然很多人是考虑功耗,这也是萝卜青菜各有所爱,可能我算下来还是觉得没多大必要
    然后就是考虑用什么硬件配置了,这个流派也有很多种,
    用蜗牛星际的原版硬件其实对于需求不大的也是挺好的,整套的都解决了,cpu 用 j1900 如果就做 nas 应该也够了,我没选的原因一方面是性能不符合我的要求,另一方面是现在市面上的机器大部分都是战损成色,而且也不太便宜,如果成色比较好的能够 400 以内拿下整机的话感觉还算可以,cpu 换成 j4125 或者 j3455 再加个 100 也能接受,但基本比较少有这种价格,之前看到一个换了 j3455 的只要 360,犹豫了下没下手,其他很多的都是 j1900 的都要 600 左右
    然后是各类 E3,E5 和商用服务器类型的,这种的特点是功耗大,其实 cpu 很便宜,E5 2630V3 跟 2630V4 都只要十几块钱,性能过得去,没有选的主要是机箱占地方也比较贵,还有是商用的怕很多系统需要自己找驱动什么的,配件比如 HBA 卡这种,买的不兼容什么的还是挺麻烦的,另外噪音也是个比较大的问题,租的房子比较小,即使放客厅也是靠着卧室的墙边,如果以后换大一点的房子倒是可以考虑
    最后就是我目前选的方案,就是普通的民用机器,找盘位多一点的机箱,我原来的 4590 的机器的机箱就不错,但是已经停产了,二手的太重了闲鱼都不出外地,cpu 跟主板其实考虑了很久,因为从 4590 开始核显就能硬解 H264 这种常规的视频了,考虑用intel 四代的 i3 或者 i5 应该纯 nas 来讲是足够用了,但是这样就跟我现在已经有的 4590 有点重叠了,而且也觉得最好是能性能好一些的,就开始看一些稍新一点的,很多用的多的有 i3-8100,跟 i3-10100 这种,但是这些已经被炒的价格比较高,寻寻觅觅了很久看中了 i5-8600,这个价格跟 8500 差不多,性能还好一些,主板就是我标题说的最“失败”的一个点了,主要是因为主板自带的网卡是 Realtek 的,至于更具体的后面会专门介绍,机箱是图便宜买的爱国者半岛铁盒的 F10,内存就买了一根光威的 32g 的,装系统的硬盘是用了以前囤的京东京造的麒麟系列,但是现在对这个系列挺不看好,之前有个盘就掉盘了,维修体验一开始也不好,半个多月维修,电源也是图便宜买的一个先马的平头哥系列,额定 550w 只要 140 左右,整体的机器就攒齐了,但是很多问题也随之出现了
    第一个问题是买的二手的板 U 套装,结果寄过来的时候没带挡板,导致一开始装上了又要拆下来;第二个问题是主机贪便宜,主机上固定主板螺丝的螺柱拧不进去,后来店家告诉我让我可以用电源固定的螺丝先拧一下才把螺柱拧进去;第三个问题是因为没什么装机经验导致的,散热装的太累了,因为要兼容各种主板,还有各种螺丝,装的时候也着急;第四个问题是电源的比较便宜,一方面比较不放心安全性,另一方面是我想多装几个硬盘,电源直出的只有四个 sata 口,需要买转接线,从 D 型的 4pin 口子转出来;第五个问题也是电源,主板电源线有点不太够,走背线就比较困难
    以上主要是装机的困难,下一篇介绍作为 nas 的各种问题吧

    +]]>
    + + nas + + + nas
    diff --git a/sitemap.xml b/sitemap.xml index 332cba7cc9..2cf8b9ae7b 100644 --- a/sitemap.xml +++ b/sitemap.xml @@ -4,7 +4,7 @@ https://nicksxs.me/2023/09/10/Tomcat-%E7%B3%BB%E5%88%97%E7%AF%87%E4%B8%80-%E4%BB%8B%E7%BB%8D%E4%B8%8B-connector/ - 2023-09-10 + 2023-09-11 monthly 0.6 @@ -641,7 +641,7 @@ - https://nicksxs.me/2021/02/21/AQS-%E4%B9%8B-Condition-%E6%B5%85%E6%9E%90%E7%AC%94%E8%AE%B0/ + https://nicksxs.me/2022/02/13/Disruptor-%E7%B3%BB%E5%88%97%E4%B8%80/ 2022-06-11 @@ -650,7 +650,7 @@ - https://nicksxs.me/2022/02/13/Disruptor-%E7%B3%BB%E5%88%97%E4%B8%80/ + https://nicksxs.me/2022/02/27/Disruptor-%E7%B3%BB%E5%88%97%E4%BA%8C/ 2022-06-11 @@ -668,7 +668,7 @@ - https://nicksxs.me/2022/02/27/Disruptor-%E7%B3%BB%E5%88%97%E4%BA%8C/ + https://nicksxs.me/2021/01/24/Leetcode-124-%E4%BA%8C%E5%8F%89%E6%A0%91%E4%B8%AD%E7%9A%84%E6%9C%80%E5%A4%A7%E8%B7%AF%E5%BE%84%E5%92%8C-Binary-Tree-Maximum-Path-Sum-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/ 2022-06-11 @@ -677,7 +677,7 @@ - https://nicksxs.me/2021/01/24/Leetcode-124-%E4%BA%8C%E5%8F%89%E6%A0%91%E4%B8%AD%E7%9A%84%E6%9C%80%E5%A4%A7%E8%B7%AF%E5%BE%84%E5%92%8C-Binary-Tree-Maximum-Path-Sum-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/ + https://nicksxs.me/2021/01/10/Leetcode-160-%E7%9B%B8%E4%BA%A4%E9%93%BE%E8%A1%A8-intersection-of-two-linked-lists-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/ 2022-06-11 @@ -686,7 +686,7 @@ - https://nicksxs.me/2021/01/10/Leetcode-160-%E7%9B%B8%E4%BA%A4%E9%93%BE%E8%A1%A8-intersection-of-two-linked-lists-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/ + https://nicksxs.me/2021/07/04/Leetcode-42-%E6%8E%A5%E9%9B%A8%E6%B0%B4-Trapping-Rain-Water-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/ 2022-06-11 @@ -704,7 +704,7 @@ - https://nicksxs.me/2021/07/04/Leetcode-42-%E6%8E%A5%E9%9B%A8%E6%B0%B4-Trapping-Rain-Water-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/ + https://nicksxs.me/2022/03/13/Leetcode-83-%E5%88%A0%E9%99%A4%E6%8E%92%E5%BA%8F%E9%93%BE%E8%A1%A8%E4%B8%AD%E7%9A%84%E9%87%8D%E5%A4%8D%E5%85%83%E7%B4%A0-Remove-Duplicates-from-Sorted-List-Easy-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/ 2022-06-11 @@ -713,7 +713,7 @@ - https://nicksxs.me/2022/03/13/Leetcode-83-%E5%88%A0%E9%99%A4%E6%8E%92%E5%BA%8F%E9%93%BE%E8%A1%A8%E4%B8%AD%E7%9A%84%E9%87%8D%E5%A4%8D%E5%85%83%E7%B4%A0-Remove-Duplicates-from-Sorted-List-Easy-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/ + https://nicksxs.me/2020/08/06/Linux-%E4%B8%8B-grep-%E5%91%BD%E4%BB%A4%E7%9A%84%E4%B8%80%E7%82%B9%E5%B0%8F%E6%8A%80%E5%B7%A7/ 2022-06-11 @@ -722,7 +722,7 @@ - https://nicksxs.me/2020/08/06/Linux-%E4%B8%8B-grep-%E5%91%BD%E4%BB%A4%E7%9A%84%E4%B8%80%E7%82%B9%E5%B0%8F%E6%8A%80%E5%B7%A7/ + https://nicksxs.me/2021/02/21/AQS-%E4%B9%8B-Condition-%E6%B5%85%E6%9E%90%E7%AC%94%E8%AE%B0/ 2022-06-11 @@ -740,7 +740,7 @@ - https://nicksxs.me/2021/04/18/rust%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0-%E6%89%80%E6%9C%89%E6%9D%83%E4%BA%8C/ + https://nicksxs.me/2021/04/18/rust%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/ 2022-06-11 @@ -758,7 +758,7 @@ - https://nicksxs.me/2021/04/18/rust%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/ + https://nicksxs.me/2021/04/18/rust%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0-%E6%89%80%E6%9C%89%E6%9D%83%E4%BA%8C/ 2022-06-11 @@ -767,7 +767,7 @@ - https://nicksxs.me/2021/03/07/%E3%80%8A%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6%E7%AE%97%E6%B3%95%E6%89%8B%E5%86%8C%E8%AF%BB%E4%B9%A6%E3%80%8B%E7%AC%94%E8%AE%B0%E4%B9%8B%E6%95%B4%E7%90%86%E7%AE%97%E6%B3%95/ + https://nicksxs.me/2021/12/05/wordpress-%E5%BF%98%E8%AE%B0%E5%AF%86%E7%A0%81%E7%9A%84%E4%B8%80%E7%A7%8D%E8%A7%A3%E5%86%B3%E6%96%B9%E6%B3%95/ 2022-06-11 @@ -776,7 +776,7 @@ - https://nicksxs.me/2021/12/05/wordpress-%E5%BF%98%E8%AE%B0%E5%AF%86%E7%A0%81%E7%9A%84%E4%B8%80%E7%A7%8D%E8%A7%A3%E5%86%B3%E6%96%B9%E6%B3%95/ + https://nicksxs.me/2021/03/07/%E3%80%8A%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6%E7%AE%97%E6%B3%95%E6%89%8B%E5%86%8C%E8%AF%BB%E4%B9%A6%E3%80%8B%E7%AC%94%E8%AE%B0%E4%B9%8B%E6%95%B4%E7%90%86%E7%AE%97%E6%B3%95/ 2022-06-11 @@ -812,7 +812,7 @@ - https://nicksxs.me/2021/09/04/%E8%81%8A%E4%B8%80%E4%B8%8B-RocketMQ-%E7%9A%84%E6%B6%88%E6%81%AF%E5%AD%98%E5%82%A8/ + https://nicksxs.me/2021/10/03/%E8%81%8A%E4%B8%80%E4%B8%8B-RocketMQ-%E7%9A%84%E6%B6%88%E6%81%AF%E5%AD%98%E5%82%A8%E4%B8%89/ 2022-06-11 @@ -821,7 +821,7 @@ - https://nicksxs.me/2021/10/03/%E8%81%8A%E4%B8%80%E4%B8%8B-RocketMQ-%E7%9A%84%E6%B6%88%E6%81%AF%E5%AD%98%E5%82%A8%E4%B8%89/ + https://nicksxs.me/2021/09/04/%E8%81%8A%E4%B8%80%E4%B8%8B-RocketMQ-%E7%9A%84%E6%B6%88%E6%81%AF%E5%AD%98%E5%82%A8/ 2022-06-11 @@ -839,7 +839,7 @@ - https://nicksxs.me/2021/10/17/%E8%81%8A%E4%B8%80%E4%B8%8B-RocketMQ-%E7%9A%84%E6%B6%88%E6%81%AF%E5%AD%98%E5%82%A8%E5%9B%9B/ + https://nicksxs.me/2021/09/19/%E8%81%8A%E4%B8%80%E4%B8%8B-SpringBoot-%E4%B8%AD%E4%BD%BF%E7%94%A8%E7%9A%84-cglib-%E4%BD%9C%E4%B8%BA%E5%8A%A8%E6%80%81%E4%BB%A3%E7%90%86%E4%B8%AD%E7%9A%84%E4%B8%80%E4%B8%AA%E6%B3%A8%E6%84%8F%E7%82%B9/ 2022-06-11 @@ -848,7 +848,7 @@ - https://nicksxs.me/2021/09/19/%E8%81%8A%E4%B8%80%E4%B8%8B-SpringBoot-%E4%B8%AD%E4%BD%BF%E7%94%A8%E7%9A%84-cglib-%E4%BD%9C%E4%B8%BA%E5%8A%A8%E6%80%81%E4%BB%A3%E7%90%86%E4%B8%AD%E7%9A%84%E4%B8%80%E4%B8%AA%E6%B3%A8%E6%84%8F%E7%82%B9/ + https://nicksxs.me/2021/09/26/%E8%81%8A%E4%B8%80%E4%B8%8B-SpringBoot-%E4%B8%AD%E5%8A%A8%E6%80%81%E5%88%87%E6%8D%A2%E6%95%B0%E6%8D%AE%E6%BA%90%E7%9A%84%E6%96%B9%E6%B3%95/ 2022-06-11 @@ -857,7 +857,7 @@ - https://nicksxs.me/2021/09/26/%E8%81%8A%E4%B8%80%E4%B8%8B-SpringBoot-%E4%B8%AD%E5%8A%A8%E6%80%81%E5%88%87%E6%8D%A2%E6%95%B0%E6%8D%AE%E6%BA%90%E7%9A%84%E6%96%B9%E6%B3%95/ + https://nicksxs.me/2021/10/17/%E8%81%8A%E4%B8%80%E4%B8%8B-RocketMQ-%E7%9A%84%E6%B6%88%E6%81%AF%E5%AD%98%E5%82%A8%E5%9B%9B/ 2022-06-11 @@ -866,7 +866,7 @@ - https://nicksxs.me/2020/11/22/%E8%81%8A%E8%81%8A-Dubbo-%E7%9A%84%E5%AE%B9%E9%94%99%E6%9C%BA%E5%88%B6/ + https://nicksxs.me/2021/06/27/%E8%81%8A%E8%81%8A-Java-%E4%B8%AD%E7%BB%95%E4%B8%8D%E5%BC%80%E7%9A%84-Synchronized-%E5%85%B3%E9%94%AE%E5%AD%97-%E4%BA%8C/ 2022-06-11 @@ -875,7 +875,7 @@ - https://nicksxs.me/2021/06/27/%E8%81%8A%E8%81%8A-Java-%E4%B8%AD%E7%BB%95%E4%B8%8D%E5%BC%80%E7%9A%84-Synchronized-%E5%85%B3%E9%94%AE%E5%AD%97-%E4%BA%8C/ + https://nicksxs.me/2020/11/22/%E8%81%8A%E8%81%8A-Dubbo-%E7%9A%84%E5%AE%B9%E9%94%99%E6%9C%BA%E5%88%B6/ 2022-06-11 @@ -911,7 +911,7 @@ - https://nicksxs.me/2021/12/26/%E8%81%8A%E8%81%8A-Sharding-Jdbc-%E7%9A%84%E7%AE%80%E5%8D%95%E5%8E%9F%E7%90%86%E5%88%9D%E7%AF%87/ + https://nicksxs.me/2022/01/09/%E8%81%8A%E8%81%8A-Sharding-Jdbc-%E5%88%86%E5%BA%93%E5%88%86%E8%A1%A8%E4%B8%8B%E7%9A%84%E5%88%86%E9%A1%B5%E6%96%B9%E6%A1%88/ 2022-06-11 @@ -920,7 +920,7 @@ - https://nicksxs.me/2022/01/09/%E8%81%8A%E8%81%8A-Sharding-Jdbc-%E5%88%86%E5%BA%93%E5%88%86%E8%A1%A8%E4%B8%8B%E7%9A%84%E5%88%86%E9%A1%B5%E6%96%B9%E6%A1%88/ + https://nicksxs.me/2021/12/12/%E8%81%8A%E8%81%8A-Sharding-Jdbc-%E7%9A%84%E7%AE%80%E5%8D%95%E4%BD%BF%E7%94%A8/ 2022-06-11 @@ -929,7 +929,7 @@ - https://nicksxs.me/2021/12/12/%E8%81%8A%E8%81%8A-Sharding-Jdbc-%E7%9A%84%E7%AE%80%E5%8D%95%E4%BD%BF%E7%94%A8/ + https://nicksxs.me/2021/04/04/%E8%81%8A%E8%81%8A-dubbo-%E7%9A%84%E7%BA%BF%E7%A8%8B%E6%B1%A0/ 2022-06-11 @@ -938,7 +938,7 @@ - https://nicksxs.me/2021/04/04/%E8%81%8A%E8%81%8A-dubbo-%E7%9A%84%E7%BA%BF%E7%A8%8B%E6%B1%A0/ + https://nicksxs.me/2021/12/26/%E8%81%8A%E8%81%8A-Sharding-Jdbc-%E7%9A%84%E7%AE%80%E5%8D%95%E5%8E%9F%E7%90%86%E5%88%9D%E7%AF%87/ 2022-06-11 @@ -1820,7 +1820,7 @@ - https://nicksxs.me/2016/08/14/34-Search-for-a-Range/ + https://nicksxs.me/2014/12/24/MFC%20%E6%A8%A1%E6%80%81%E5%AF%B9%E8%AF%9D%E6%A1%86/ 2020-01-12 @@ -1829,7 +1829,7 @@ - https://nicksxs.me/2014/12/24/MFC%20%E6%A8%A1%E6%80%81%E5%AF%B9%E8%AF%9D%E6%A1%86/ + https://nicksxs.me/2019/12/10/Redis-Part-1/ 2020-01-12 @@ -1838,7 +1838,7 @@ - https://nicksxs.me/2019/12/10/Redis-Part-1/ + https://nicksxs.me/2015/03/11/Reverse-Bits/ 2020-01-12 @@ -1847,7 +1847,7 @@ - https://nicksxs.me/2015/03/11/Reverse-Bits/ + https://nicksxs.me/2015/03/13/Reverse-Integer/ 2020-01-12 @@ -1856,7 +1856,7 @@ - https://nicksxs.me/2015/01/14/Two-Sum/ + https://nicksxs.me/2017/05/09/ambari-summary/ 2020-01-12 @@ -1865,7 +1865,7 @@ - https://nicksxs.me/2015/03/13/Reverse-Integer/ + https://nicksxs.me/2016/09/29/binary-watch/ 2020-01-12 @@ -1874,7 +1874,7 @@ - https://nicksxs.me/2016/09/29/binary-watch/ + https://nicksxs.me/2016/08/14/docker-mysql-cluster/ 2020-01-12 @@ -1883,7 +1883,7 @@ - https://nicksxs.me/2017/05/09/ambari-summary/ + https://nicksxs.me/2015/01/14/Two-Sum/ 2020-01-12 @@ -1892,7 +1892,7 @@ - https://nicksxs.me/2016/08/14/docker-mysql-cluster/ + https://nicksxs.me/2016/08/14/34-Search-for-a-Range/ 2020-01-12 @@ -2009,7 +2009,7 @@ - https://nicksxs.me/2015/01/04/Path-Sum/ + https://nicksxs.me/2015/03/11/Number-Of-1-Bits/ 2020-01-12 @@ -2018,7 +2018,7 @@ - https://nicksxs.me/2015/03/11/Number-Of-1-Bits/ + https://nicksxs.me/2015/01/04/Path-Sum/ 2020-01-12 @@ -2128,3195 +2128,3195 @@ https://nicksxs.me/ - 2023-09-10 + 2023-09-11 daily 1.0 + + https://nicksxs.me/tags/%E8%AF%BB%E5%90%8E%E6%84%9F/ + 2023-09-11 + weekly + 0.2 + + https://nicksxs.me/tags/%E7%94%9F%E6%B4%BB/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E5%B9%B4%E7%BB%88%E6%80%BB%E7%BB%93/ - 2023-09-10 + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/2020/ - 2023-09-10 + https://nicksxs.me/tags/2019/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/2021/ - 2023-09-10 + https://nicksxs.me/tags/2020/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E6%8B%96%E6%9B%B4/ - 2023-09-10 + https://nicksxs.me/tags/2021/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/Java/ - 2023-09-10 + https://nicksxs.me/tags/%E6%8B%96%E6%9B%B4/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/JVM/ - 2023-09-10 + https://nicksxs.me/tags/%E5%B9%B4%E4%B8%AD%E6%80%BB%E7%BB%93/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/C/ - 2023-09-10 + https://nicksxs.me/tags/%E6%8A%80%E6%9C%AF/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/leetcode/ - 2023-09-10 + https://nicksxs.me/tags/%E8%AF%BB%E4%B9%A6/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/java/ - 2023-09-10 + https://nicksxs.me/tags/2022/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/Binary-Tree/ - 2023-09-10 + https://nicksxs.me/tags/2023/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/DFS/ - 2023-09-10 + https://nicksxs.me/tags/java/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E4%BA%8C%E5%8F%89%E6%A0%91/ - 2023-09-10 + https://nicksxs.me/tags/%E5%B9%B6%E5%8F%91/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E9%A2%98%E8%A7%A3/ - 2023-09-10 + https://nicksxs.me/tags/j-u-c/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/Linked-List/ - 2023-09-10 + https://nicksxs.me/tags/aqs/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/nas/ - 2023-09-10 + https://nicksxs.me/tags/leetcode/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E8%AF%BB%E5%90%8E%E6%84%9F/ - 2023-09-10 + https://nicksxs.me/tags/c/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E6%8A%80%E6%9C%AF/ - 2023-09-10 + https://nicksxs.me/tags/Java/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E8%AF%BB%E4%B9%A6/ - 2023-09-10 + https://nicksxs.me/tags/Apollo/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E5%B9%B4%E4%B8%AD%E6%80%BB%E7%BB%93/ - 2023-09-10 + https://nicksxs.me/tags/environment/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/2019/ - 2023-09-10 + https://nicksxs.me/tags/value/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E5%B9%B6%E5%8F%91/ - 2023-09-10 + https://nicksxs.me/tags/%E6%B3%A8%E8%A7%A3/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/j-u-c/ - 2023-09-10 + https://nicksxs.me/tags/C/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/aqs/ - 2023-09-10 + https://nicksxs.me/tags/Stream/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/condition/ - 2023-09-10 + https://nicksxs.me/tags/Comparator/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/await/ - 2023-09-10 + https://nicksxs.me/tags/%E6%8E%92%E5%BA%8F/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/signal/ - 2023-09-10 + https://nicksxs.me/tags/sort/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/lock/ - 2023-09-10 + https://nicksxs.me/tags/nullsfirst/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/unlock/ - 2023-09-10 + https://nicksxs.me/tags/Disruptor/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/c/ - 2023-09-10 + https://nicksxs.me/tags/Dubbo/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/Apollo/ - 2023-09-10 + https://nicksxs.me/tags/RPC/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/environment/ - 2023-09-10 + https://nicksxs.me/tags/%E8%B4%9F%E8%BD%BD%E5%9D%87%E8%A1%A1/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/value/ - 2023-09-10 + https://nicksxs.me/tags/Filter/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E6%B3%A8%E8%A7%A3/ - 2023-09-10 + https://nicksxs.me/tags/Interceptor/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/Stream/ - 2023-09-10 + https://nicksxs.me/tags/AOP/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/Comparator/ - 2023-09-10 + https://nicksxs.me/tags/Spring/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E6%8E%92%E5%BA%8F/ - 2023-09-10 + https://nicksxs.me/tags/Tomcat/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/sort/ - 2023-09-10 + https://nicksxs.me/tags/Servlet/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/nullsfirst/ - 2023-09-10 + https://nicksxs.me/tags/Web/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/2022/ - 2023-09-10 + https://nicksxs.me/tags/JVM/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/2023/ - 2023-09-10 + https://nicksxs.me/tags/G1/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/Dubbo/ - 2023-09-10 + https://nicksxs.me/tags/GC/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/RPC/ - 2023-09-10 + https://nicksxs.me/tags/Garbage-First-Collector/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E8%B4%9F%E8%BD%BD%E5%9D%87%E8%A1%A1/ - 2023-09-10 + https://nicksxs.me/tags/headscale/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/Disruptor/ - 2023-09-10 + https://nicksxs.me/tags/%E9%A2%98%E8%A7%A3/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/Filter/ - 2023-09-10 + https://nicksxs.me/tags/Binary-Tree/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/Interceptor/ - 2023-09-10 + https://nicksxs.me/tags/DFS/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/AOP/ - 2023-09-10 + https://nicksxs.me/tags/%E4%BA%8C%E5%8F%89%E6%A0%91/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/Spring/ - 2023-09-10 + https://nicksxs.me/tags/%E9%80%92%E5%BD%92/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/Tomcat/ - 2023-09-10 + https://nicksxs.me/tags/Preorder-Traversal/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/Servlet/ - 2023-09-10 + https://nicksxs.me/tags/Inorder-Traversal/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/Web/ - 2023-09-10 + https://nicksxs.me/tags/%E5%89%8D%E5%BA%8F/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/G1/ - 2023-09-10 + https://nicksxs.me/tags/%E4%B8%AD%E5%BA%8F/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/GC/ - 2023-09-10 + https://nicksxs.me/tags/Print-FooBar-Alternately/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/Garbage-First-Collector/ - 2023-09-10 + https://nicksxs.me/tags/DP/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/Print-FooBar-Alternately/ - 2023-09-10 + https://nicksxs.me/tags/Shift-2D-Grid/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/DP/ - 2023-09-10 + https://nicksxs.me/tags/stack/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/Shift-2D-Grid/ - 2023-09-10 + https://nicksxs.me/tags/min-stack/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E9%80%92%E5%BD%92/ - 2023-09-10 + https://nicksxs.me/tags/%E6%9C%80%E5%B0%8F%E6%A0%88/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/Preorder-Traversal/ - 2023-09-10 + https://nicksxs.me/tags/leetcode-155/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/Inorder-Traversal/ - 2023-09-10 + https://nicksxs.me/tags/3Sum-Closest/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E5%89%8D%E5%BA%8F/ - 2023-09-10 + https://nicksxs.me/tags/Linked-List/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E4%B8%AD%E5%BA%8F/ - 2023-09-10 + https://nicksxs.me/tags/linked-list/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/stack/ - 2023-09-10 + https://nicksxs.me/tags/Lowest-Common-Ancestor-of-a-Binary-Tree/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/min-stack/ - 2023-09-10 + https://nicksxs.me/tags/First-Bad-Version/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E6%9C%80%E5%B0%8F%E6%A0%88/ - 2023-09-10 + https://nicksxs.me/tags/string/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/leetcode-155/ - 2023-09-10 + https://nicksxs.me/tags/Intersection-of-Two-Arrays/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/3Sum-Closest/ - 2023-09-10 + https://nicksxs.me/tags/Median-of-Two-Sorted-Arrays/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/linked-list/ - 2023-09-10 + https://nicksxs.me/tags/dp/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/Lowest-Common-Ancestor-of-a-Binary-Tree/ - 2023-09-10 + https://nicksxs.me/tags/%E4%BB%A3%E7%A0%81%E9%A2%98%E8%A7%A3/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/First-Bad-Version/ - 2023-09-10 + https://nicksxs.me/tags/Trapping-Rain-Water/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/string/ - 2023-09-10 + https://nicksxs.me/tags/%E6%8E%A5%E9%9B%A8%E6%B0%B4/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/headscale/ - 2023-09-10 + https://nicksxs.me/tags/Leetcode-42/ + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/Rotate-Image/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E7%9F%A9%E9%98%B5/ - 2023-09-10 + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/Median-of-Two-Sorted-Arrays/ - 2023-09-10 + https://nicksxs.me/tags/Remove-Duplicates-from-Sorted-List/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/dp/ - 2023-09-10 + https://nicksxs.me/tags/linux/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E4%BB%A3%E7%A0%81%E9%A2%98%E8%A7%A3/ - 2023-09-10 + https://nicksxs.me/tags/grep/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/Trapping-Rain-Water/ - 2023-09-10 + https://nicksxs.me/tags/%E8%BD%AC%E4%B9%89/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E6%8E%A5%E9%9B%A8%E6%B0%B4/ - 2023-09-10 + https://nicksxs.me/tags/mfc/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/Leetcode-42/ - 2023-09-10 + https://nicksxs.me/tags/Maven/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/Intersection-of-Two-Arrays/ - 2023-09-10 + https://nicksxs.me/tags/C/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/Remove-Duplicates-from-Sorted-List/ - 2023-09-10 + https://nicksxs.me/tags/Redis/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/linux/ - 2023-09-10 + https://nicksxs.me/tags/Distributed-Lock/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/grep/ - 2023-09-10 + https://nicksxs.me/tags/%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E8%BD%AC%E4%B9%89/ - 2023-09-10 + https://nicksxs.me/tags/SpringBoot/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/Maven/ - 2023-09-10 + https://nicksxs.me/tags/hadoop/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/mfc/ - 2023-09-10 + https://nicksxs.me/tags/cluster/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/C/ - 2023-09-10 + https://nicksxs.me/tags/condition/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/Redis/ - 2023-09-10 + https://nicksxs.me/tags/await/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/Distributed-Lock/ - 2023-09-10 + https://nicksxs.me/tags/signal/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81/ - 2023-09-10 + https://nicksxs.me/tags/lock/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/SpringBoot/ - 2023-09-10 + https://nicksxs.me/tags/unlock/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/hadoop/ - 2023-09-10 + https://nicksxs.me/tags/docker/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/cluster/ - 2023-09-10 + https://nicksxs.me/tags/mysql/ + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/Docker/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/namespace/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/cgroup/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/Dockerfile/ - 2023-09-10 + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/docker/ - 2023-09-10 + https://nicksxs.me/tags/echo/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/mysql/ - 2023-09-10 + https://nicksxs.me/tags/uname/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/echo/ - 2023-09-10 + https://nicksxs.me/tags/%E5%8F%91%E8%A1%8C%E7%89%88/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/uname/ - 2023-09-10 + https://nicksxs.me/tags/ssh/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E5%8F%91%E8%A1%8C%E7%89%88/ - 2023-09-10 + https://nicksxs.me/tags/%E7%AB%AF%E5%8F%A3%E8%BD%AC%E5%8F%91/ + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/Gogs/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/Webhook/ - 2023-09-10 + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E5%8D%9A%E5%AE%A2%EF%BC%8C%E6%96%87%E7%AB%A0/ - 2023-09-10 + https://nicksxs.me/tags/dnsmasq/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/dnsmasq/ - 2023-09-10 + https://nicksxs.me/tags/%E5%8D%9A%E5%AE%A2%EF%BC%8C%E6%96%87%E7%AB%A0/ + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/Mysql/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/Mybatis/ - 2023-09-10 - weekly - 0.2 - - - - https://nicksxs.me/tags/%E7%BC%93%E5%AD%98/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/hexo/ - 2023-09-10 + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/ssh/ - 2023-09-10 + https://nicksxs.me/tags/Sql%E6%B3%A8%E5%85%A5/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E7%AB%AF%E5%8F%A3%E8%BD%AC%E5%8F%91/ - 2023-09-10 + https://nicksxs.me/tags/%E7%BC%93%E5%AD%98/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/Sql%E6%B3%A8%E5%85%A5/ - 2023-09-10 + https://nicksxs.me/tags/nginx/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/nginx/ - 2023-09-10 + https://nicksxs.me/tags/%E6%97%A5%E5%BF%97/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E6%97%A5%E5%BF%97/ - 2023-09-10 + https://nicksxs.me/tags/openresty/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/openresty/ - 2023-09-10 + https://nicksxs.me/tags/php/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/php/ - 2023-09-10 + https://nicksxs.me/tags/powershell/ + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/mq/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/im/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/redis/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E6%BA%90%E7%A0%81/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E6%B7%98%E6%B1%B0%E7%AD%96%E7%95%A5/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E5%BA%94%E7%94%A8/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/Evict/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E8%BF%87%E6%9C%9F%E7%AD%96%E7%95%A5/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/Rust/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E6%89%80%E6%9C%89%E6%9D%83/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E5%86%85%E5%AD%98%E5%88%86%E5%B8%83/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E6%96%B0%E8%AF%AD%E8%A8%80/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E5%8F%AF%E5%8F%98%E5%BC%95%E7%94%A8/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E4%B8%8D%E5%8F%AF%E5%8F%98%E5%BC%95%E7%94%A8/ - 2023-09-10 - weekly - 0.2 - - - - https://nicksxs.me/tags/spark/ - 2023-09-10 + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/python/ - 2023-09-10 + https://nicksxs.me/tags/%E5%88%87%E7%89%87/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E5%88%87%E7%89%87/ - 2023-09-10 + https://nicksxs.me/tags/Spring-Event/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/Spring-Event/ - 2023-09-10 + https://nicksxs.me/tags/spark/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/powershell/ - 2023-09-10 + https://nicksxs.me/tags/python/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/gc/ - 2023-09-10 + https://nicksxs.me/tags/websocket/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E6%A0%87%E8%AE%B0%E6%95%B4%E7%90%86/ - 2023-09-10 + https://nicksxs.me/tags/swoole/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6/ - 2023-09-10 + https://nicksxs.me/tags/WordPress/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/jvm/ - 2023-09-10 + https://nicksxs.me/tags/%E5%B0%8F%E6%8A%80%E5%B7%A7/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/websocket/ - 2023-09-10 + https://nicksxs.me/tags/gc/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/swoole/ - 2023-09-10 + https://nicksxs.me/tags/%E6%A0%87%E8%AE%B0%E6%95%B4%E7%90%86/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/WordPress/ - 2023-09-10 + https://nicksxs.me/tags/%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E5%B0%8F%E6%8A%80%E5%B7%A7/ - 2023-09-10 + https://nicksxs.me/tags/jvm/ + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/MQ/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E6%B6%88%E6%81%AF%E9%98%9F%E5%88%97/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/RocketMQ/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E5%89%8A%E5%B3%B0%E5%A1%AB%E8%B0%B7/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E4%B8%AD%E9%97%B4%E4%BB%B6/ - 2023-09-10 + 2023-09-11 + weekly + 0.2 + + + + https://nicksxs.me/tags/nas/ + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E5%90%90%E6%A7%BD/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E7%96%AB%E6%83%85/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E7%BE%8E%E5%9B%BD/ - 2023-09-10 + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E6%89%93%E5%8D%A1/ - 2023-09-10 + https://nicksxs.me/tags/%E5%85%AC%E4%BA%A4%E8%BD%A6/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E5%B9%B8%E7%A6%8F%E4%BA%86%E5%90%97/ - 2023-09-10 + https://nicksxs.me/tags/%E5%8F%A3%E7%BD%A9/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E8%B6%B3%E7%90%83/ - 2023-09-10 + https://nicksxs.me/tags/%E6%9D%80%E4%BA%BA%E8%AF%9B%E5%BF%83/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E5%85%AC%E4%BA%A4%E8%BD%A6/ - 2023-09-10 + https://nicksxs.me/tags/%E5%BC%80%E8%BD%A6/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E5%8F%A3%E7%BD%A9/ - 2023-09-10 + https://nicksxs.me/tags/%E5%8A%A0%E5%A1%9E/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E6%9D%80%E4%BA%BA%E8%AF%9B%E5%BF%83/ - 2023-09-10 + https://nicksxs.me/tags/%E7%B3%9F%E5%BF%83%E4%BA%8B/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/Windows/ - 2023-09-10 + https://nicksxs.me/tags/%E8%A7%84%E5%88%99/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/git/ - 2023-09-10 + https://nicksxs.me/tags/%E5%85%AC%E4%BA%A4/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E5%BC%80%E8%BD%A6/ - 2023-09-10 + https://nicksxs.me/tags/%E8%B7%AF%E6%94%BF%E8%A7%84%E5%88%92/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E5%8A%A0%E5%A1%9E/ - 2023-09-10 + https://nicksxs.me/tags/%E5%9F%BA%E7%A1%80%E8%AE%BE%E6%96%BD/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E7%B3%9F%E5%BF%83%E4%BA%8B/ - 2023-09-10 + https://nicksxs.me/tags/%E6%9D%AD%E5%B7%9E/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E8%A7%84%E5%88%99/ - 2023-09-10 + https://nicksxs.me/tags/%E5%81%A5%E5%BA%B7%E7%A0%81/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E5%85%AC%E4%BA%A4/ - 2023-09-10 + https://nicksxs.me/tags/%E6%89%93%E5%8D%A1/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E8%B7%AF%E6%94%BF%E8%A7%84%E5%88%92/ - 2023-09-10 + https://nicksxs.me/tags/%E5%B9%B8%E7%A6%8F%E4%BA%86%E5%90%97/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E5%9F%BA%E7%A1%80%E8%AE%BE%E6%96%BD/ - 2023-09-10 + https://nicksxs.me/tags/%E8%B6%B3%E7%90%83/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E6%9D%AD%E5%B7%9E/ - 2023-09-10 + https://nicksxs.me/tags/Windows/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E5%81%A5%E5%BA%B7%E7%A0%81/ - 2023-09-10 + https://nicksxs.me/tags/git/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E8%BF%90%E5%8A%A8/ - 2023-09-10 + https://nicksxs.me/tags/scp/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E5%87%8F%E8%82%A5/ - 2023-09-10 + https://nicksxs.me/tags/%E8%BF%90%E5%8A%A8/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E8%B7%91%E6%AD%A5/ - 2023-09-10 + https://nicksxs.me/tags/%E5%87%8F%E8%82%A5/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E5%B9%B2%E6%B4%BB/ - 2023-09-10 + https://nicksxs.me/tags/%E8%B7%91%E6%AD%A5/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/scp/ - 2023-09-10 + https://nicksxs.me/tags/%E5%B9%B2%E6%B4%BB/ + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/wsl/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E5%BD%B1%E8%AF%84/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E5%AF%84%E7%94%9F%E8%99%AB/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E5%9B%A4%E7%89%A9%E8%B5%84/ - 2023-09-10 + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E5%AD%97%E7%AC%A6%E9%9B%86/ - 2023-09-10 + https://nicksxs.me/tags/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E7%BC%96%E7%A0%81/ - 2023-09-10 + https://nicksxs.me/tags/NameServer/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/utf8/ - 2023-09-10 + https://nicksxs.me/tags/%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/utf8mb4/ - 2023-09-10 + https://nicksxs.me/tags/%E5%AD%97%E7%AC%A6%E9%9B%86/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/utf8mb4-0900-ai-ci/ - 2023-09-10 + https://nicksxs.me/tags/%E7%BC%96%E7%A0%81/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/utf8mb4-unicode-ci/ - 2023-09-10 + https://nicksxs.me/tags/utf8/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/utf8mb4-general-ci/ - 2023-09-10 + https://nicksxs.me/tags/utf8mb4/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/NameServer/ - 2023-09-10 + https://nicksxs.me/tags/utf8mb4-0900-ai-ci/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90/ - 2023-09-10 + https://nicksxs.me/tags/utf8mb4-unicode-ci/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/DefaultMQPushConsumer/ - 2023-09-10 + https://nicksxs.me/tags/utf8mb4-general-ci/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0/ - 2023-09-10 + https://nicksxs.me/tags/DefaultMQPushConsumer/ + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/cglib/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E4%BA%8B%E5%8A%A1/ - 2023-09-10 + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E4%B8%9C%E4%BA%AC%E5%A5%A5%E8%BF%90%E4%BC%9A/ - 2023-09-10 - weekly - 0.2 - - - - https://nicksxs.me/tags/%E4%B8%BE%E9%87%8D/ - 2023-09-10 + https://nicksxs.me/tags/Druid/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E5%B0%84%E5%87%BB/ - 2023-09-10 + https://nicksxs.me/tags/%E6%95%B0%E6%8D%AE%E6%BA%90%E5%8A%A8%E6%80%81%E5%88%87%E6%8D%A2/ + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E8%87%AA%E5%8A%A8%E8%A3%85%E9%85%8D/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/AutoConfiguration/ - 2023-09-10 + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/Druid/ - 2023-09-10 + https://nicksxs.me/tags/%E4%B8%9C%E4%BA%AC%E5%A5%A5%E8%BF%90%E4%BC%9A/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E6%95%B0%E6%8D%AE%E6%BA%90%E5%8A%A8%E6%80%81%E5%88%87%E6%8D%A2/ - 2023-09-10 + https://nicksxs.me/tags/%E4%B8%BE%E9%87%8D/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E4%B9%92%E4%B9%93%E7%90%83/ - 2023-09-10 + https://nicksxs.me/tags/%E5%B0%84%E5%87%BB/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E8%B7%B3%E6%B0%B4/ - 2023-09-10 + https://nicksxs.me/tags/%E4%B9%92%E4%B9%93%E7%90%83/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E5%AE%B9%E9%94%99%E6%9C%BA%E5%88%B6/ - 2023-09-10 + https://nicksxs.me/tags/%E8%B7%B3%E6%B0%B4/ + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/SPI/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/Adaptive/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E8%87%AA%E9%80%82%E5%BA%94%E6%8B%93%E5%B1%95/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/Synchronized/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E5%81%8F%E5%90%91%E9%94%81/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E8%BD%BB%E9%87%8F%E7%BA%A7%E9%94%81/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E9%87%8D%E9%87%8F%E7%BA%A7%E9%94%81/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E8%87%AA%E6%97%8B/ - 2023-09-10 + 2023-09-11 + weekly + 0.2 + + + + https://nicksxs.me/tags/%E5%AE%B9%E9%94%99%E6%9C%BA%E5%88%B6/ + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E7%B1%BB%E5%8A%A0%E8%BD%BD/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E5%8A%A0%E8%BD%BD/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E9%AA%8C%E8%AF%81/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E5%87%86%E5%A4%87/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E8%A7%A3%E6%9E%90/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E5%88%9D%E5%A7%8B%E5%8C%96/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E9%93%BE%E6%8E%A5/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E5%8F%8C%E4%BA%B2%E5%A7%94%E6%B4%BE/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/JPS/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/JStack/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/JMap/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/top/ - 2023-09-10 + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/Broker/ - 2023-09-10 + https://nicksxs.me/tags/Sharding-Jdbc/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/Sharding-Jdbc/ - 2023-09-10 + https://nicksxs.me/tags/Broker/ + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/ThreadPool/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E7%BA%BF%E7%A8%8B%E6%B1%A0/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/FixedThreadPool/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/LimitedThreadPool/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/EagerThreadPool/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/CachedThreadPool/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/mvcc/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/read-view/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/gap-lock/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/next-key-lock/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E5%B9%BB%E8%AF%BB/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E7%B4%A2%E5%BC%95/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/is-null/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/is-not-null/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/procedure/ - 2023-09-10 - weekly - 0.2 - - - - https://nicksxs.me/tags/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/ - 2023-09-10 - weekly - 0.2 - - - - https://nicksxs.me/tags/Design-Patterns/ - 2023-09-10 - weekly - 0.2 - - - - https://nicksxs.me/tags/%E5%8D%95%E4%BE%8B/ - 2023-09-10 - weekly - 0.2 - - - - https://nicksxs.me/tags/Singleton/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E7%BC%93%E5%AD%98%E7%A9%BF%E9%80%8F/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E7%BC%93%E5%AD%98%E5%87%BB%E7%A9%BF/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E7%BC%93%E5%AD%98%E9%9B%AA%E5%B4%A9/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E5%B8%83%E9%9A%86%E8%BF%87%E6%BB%A4%E5%99%A8/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/bloom-filter/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E4%BA%92%E6%96%A5%E9%94%81/ - 2023-09-10 - weekly - 0.2 - - - - https://nicksxs.me/tags/ThreadLocal/ - 2023-09-10 - weekly - 0.2 - - - - https://nicksxs.me/tags/%E5%BC%B1%E5%BC%95%E7%94%A8/ - 2023-09-10 + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E5%86%85%E5%AD%98%E6%B3%84%E6%BC%8F/ - 2023-09-10 + https://nicksxs.me/tags/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/WeakReference/ - 2023-09-10 + https://nicksxs.me/tags/Design-Patterns/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/Mac/ - 2023-09-10 + https://nicksxs.me/tags/%E5%8D%95%E4%BE%8B/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/PHP/ - 2023-09-10 + https://nicksxs.me/tags/Singleton/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/Homebrew/ - 2023-09-10 + https://nicksxs.me/tags/ThreadLocal/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/icu4c/ - 2023-09-10 + https://nicksxs.me/tags/%E5%BC%B1%E5%BC%95%E7%94%A8/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/zsh/ - 2023-09-10 + https://nicksxs.me/tags/%E5%86%85%E5%AD%98%E6%B3%84%E6%BC%8F/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/Thread-dump/ - 2023-09-10 + https://nicksxs.me/tags/WeakReference/ + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E6%97%85%E6%B8%B8/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E5%8E%A6%E9%97%A8/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E4%B8%AD%E5%B1%B1%E8%B7%AF/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E5%B1%80%E5%8F%A3%E8%A1%97/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E9%BC%93%E6%B5%AA%E5%B1%BF/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E6%9B%BE%E5%8E%9D%E5%9E%B5/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E6%A4%8D%E7%89%A9%E5%9B%AD/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E9%A9%AC%E6%88%8F%E5%9B%A2/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E6%B2%99%E8%8C%B6%E9%9D%A2/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E6%B5%B7%E8%9B%8E%E7%85%8E/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E6%89%B6%E6%A2%AF/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E8%B8%A9%E8%B8%8F/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E5%AE%89%E5%85%A8/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E7%94%B5%E7%93%B6%E8%BD%A6/ - 2023-09-10 + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E8%BF%9C%E7%A8%8B%E5%8A%9E%E5%85%AC/ - 2023-09-10 + https://nicksxs.me/tags/Thread-dump/ + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E5%88%86%E5%B8%83%E5%BC%8F%E4%BA%8B%E5%8A%A1/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E4%B8%A4%E9%98%B6%E6%AE%B5%E6%8F%90%E4%BA%A4/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E4%B8%89%E9%98%B6%E6%AE%B5%E6%8F%90%E4%BA%A4/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/2PC/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/3PC/ - 2023-09-10 + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E9%AA%91%E8%BD%A6/ - 2023-09-10 + https://nicksxs.me/tags/%E8%BF%9C%E7%A8%8B%E5%8A%9E%E5%85%AC/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E7%9C%8B%E5%89%A7/ - 2023-09-10 + https://nicksxs.me/tags/%E9%AA%91%E8%BD%A6/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E6%8D%A2%E8%BD%A6%E7%89%8C/ - 2023-09-10 + https://nicksxs.me/tags/%E7%9C%8B%E5%89%A7/ + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E8%A3%85%E7%94%B5%E8%84%91/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E8%80%81%E7%94%B5%E8%84%91/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/360-%E5%85%A8%E5%AE%B6%E6%A1%B6/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/tags/%E4%BF%AE%E7%94%B5%E8%84%91%E7%9A%84/ - 2023-09-10 + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/dubbo/ - 2023-09-10 + https://nicksxs.me/tags/%E6%8D%A2%E8%BD%A6%E7%89%8C/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/stream/ - 2023-09-10 + https://nicksxs.me/tags/Mac/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/zookeeper/ - 2023-09-10 + https://nicksxs.me/tags/PHP/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/windows/ - 2023-09-10 + https://nicksxs.me/tags/Homebrew/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E7%9C%8B%E4%B9%A6/ - 2023-09-10 + https://nicksxs.me/tags/icu4c/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E9%AB%98%E9%80%9F/ - 2023-09-10 + https://nicksxs.me/tags/zsh/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E8%B7%AF%E7%94%B1%E5%99%A8/ - 2023-09-10 + https://nicksxs.me/tags/windows/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/tags/%E5%A4%A7%E6%89%AB%E9%99%A4/ - 2023-09-10 + https://nicksxs.me/tags/stream/ + 2023-09-11 weekly 0.2 - - - https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/ - 2023-09-10 + https://nicksxs.me/tags/dubbo/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Java/ - 2023-09-10 + https://nicksxs.me/tags/zookeeper/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E5%B9%B4%E7%BB%88%E6%80%BB%E7%BB%93/ - 2023-09-10 + https://nicksxs.me/tags/%E7%9C%8B%E4%B9%A6/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Java/leetcode/ - 2023-09-10 + https://nicksxs.me/tags/%E9%AB%98%E9%80%9F/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Java/JVM/ - 2023-09-10 + https://nicksxs.me/tags/%E5%A4%A7%E6%89%AB%E9%99%A4/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E5%B9%B4%E7%BB%88%E6%80%BB%E7%BB%93/2020/ - 2023-09-10 + https://nicksxs.me/tags/%E8%B7%AF%E7%94%B1%E5%99%A8/ + 2023-09-11 weekly 0.2 + + - https://nicksxs.me/categories/leetcode/ - 2023-09-10 + https://nicksxs.me/categories/%E8%AF%BB%E5%90%8E%E6%84%9F/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Java/GC/ - 2023-09-10 + https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/%E5%B9%B4%E7%BB%88%E6%80%BB%E7%BB%93/ - 2023-09-10 + https://nicksxs.me/categories/%E8%AF%BB%E5%90%8E%E6%84%9F/%E6%9D%91%E4%B8%8A%E6%98%A5%E6%A0%91/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Binary-Tree/ - 2023-09-10 + https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E5%B9%B4%E7%BB%88%E6%80%BB%E7%BB%93/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/nas/ - 2023-09-10 + https://nicksxs.me/categories/Java/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Linked-List/ - 2023-09-10 + https://nicksxs.me/categories/java/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/C/ - 2023-09-10 + https://nicksxs.me/categories/leetcode/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/%E5%B9%B4%E7%BB%88%E6%80%BB%E7%BB%93/2020/ - 2023-09-10 + https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E5%B9%B4%E4%B8%AD%E6%80%BB%E7%BB%93/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/%E8%AF%BB%E5%90%8E%E6%84%9F/ - 2023-09-10 + https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E5%B9%B4%E7%BB%88%E6%80%BB%E7%BB%93/2019/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/leetcode/java/ - 2023-09-10 + https://nicksxs.me/categories/headscale/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E5%B9%B4%E4%B8%AD%E6%80%BB%E7%BB%93/ - 2023-09-10 + https://nicksxs.me/categories/Java/JVM/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E5%B9%B4%E7%BB%88%E6%80%BB%E7%BB%93/2019/ - 2023-09-10 + https://nicksxs.me/categories/Java/%E5%B9%B6%E5%8F%91/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Java/%E5%B9%B6%E5%8F%91/ - 2023-09-10 + https://nicksxs.me/categories/Java/leetcode/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/java/ - 2023-09-10 + https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E5%B9%B4%E7%BB%88%E6%80%BB%E7%BB%93/2020/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/%E8%AF%BB%E5%90%8E%E6%84%9F/%E6%9D%91%E4%B8%8A%E6%98%A5%E6%A0%91/ - 2023-09-10 + https://nicksxs.me/categories/Binary-Tree/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/leetcode/java/Binary-Tree/ - 2023-09-10 + https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E5%B9%B4%E4%B8%AD%E6%80%BB%E7%BB%93/2020/ + 2023-09-11 + weekly + 0.2 + + + + https://nicksxs.me/categories/DP/ + 2023-09-11 + weekly + 0.2 + + + + https://nicksxs.me/categories/stack/ + 2023-09-11 + weekly + 0.2 + + + + https://nicksxs.me/categories/Linked-List/ + 2023-09-11 weekly 0.2 https://nicksxs.me/categories/Java/Apollo/ - 2023-09-10 + 2023-09-11 + weekly + 0.2 + + + + https://nicksxs.me/categories/linked-list/ + 2023-09-11 weekly 0.2 https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E5%B9%B4%E4%B8%AD%E6%80%BB%E7%BB%93/2021/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/categories/Java/%E9%9B%86%E5%90%88/ - 2023-09-10 + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/leetcode/java/Linked-List/ - 2023-09-10 + https://nicksxs.me/categories/%E5%AD%97%E7%AC%A6%E4%B8%B2-online/ + 2023-09-11 + weekly + 0.2 + + + + https://nicksxs.me/categories/Linux/ + 2023-09-11 weekly 0.2 https://nicksxs.me/categories/Java/Dubbo/ - 2023-09-10 + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Filter/ - 2023-09-10 + https://nicksxs.me/categories/C/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E5%B9%B4%E4%B8%AD%E6%80%BB%E7%BB%93/2020/ - 2023-09-10 + https://nicksxs.me/categories/Java/Maven/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/DP/ - 2023-09-10 + https://nicksxs.me/categories/Redis/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/leetcode/java/Binary-Tree/DFS/ - 2023-09-10 + https://nicksxs.me/categories/Filter/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Java/Apollo/value/ - 2023-09-10 + https://nicksxs.me/categories/Java/SpringBoot/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/stack/ - 2023-09-10 + https://nicksxs.me/categories/data-analysis/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/linked-list/ - 2023-09-10 + https://nicksxs.me/categories/docker/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Java/leetcode/Lowest-Common-Ancestor-of-a-Binary-Tree/ - 2023-09-10 + https://nicksxs.me/categories/Java/GC/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/headscale/ - 2023-09-10 + https://nicksxs.me/categories/Docker/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Java/leetcode/Rotate-Image/ - 2023-09-10 + https://nicksxs.me/categories/ssh/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/%E5%AD%97%E7%AC%A6%E4%B8%B2-online/ - 2023-09-10 + https://nicksxs.me/categories/%E6%8C%81%E7%BB%AD%E9%9B%86%E6%88%90/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Interceptor-AOP/ - 2023-09-10 + https://nicksxs.me/categories/%E5%B9%B4%E7%BB%88%E6%80%BB%E7%BB%93/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Linux/ - 2023-09-10 + https://nicksxs.me/categories/dns/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Java/Maven/ - 2023-09-10 + https://nicksxs.me/categories/Java/Mybatis/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/leetcode/java/DP/ - 2023-09-10 + https://nicksxs.me/categories/hexo/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Redis/ - 2023-09-10 + https://nicksxs.me/categories/leetcode/java/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Java/SpringBoot/ - 2023-09-10 + https://nicksxs.me/categories/nginx/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/leetcode/java/stack/ - 2023-09-10 + https://nicksxs.me/categories/php/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/data-analysis/ - 2023-09-10 + https://nicksxs.me/categories/%E8%AF%AD%E8%A8%80/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Docker/ - 2023-09-10 + https://nicksxs.me/categories/redis/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/docker/ - 2023-09-10 + https://nicksxs.me/categories/Java/Apollo/value/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/leetcode/java/linked-list/ - 2023-09-10 + https://nicksxs.me/categories/Java/leetcode/Lowest-Common-Ancestor-of-a-Binary-Tree/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/%E6%8C%81%E7%BB%AD%E9%9B%86%E6%88%90/ - 2023-09-10 + https://nicksxs.me/categories/Java/leetcode/Rotate-Image/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/leetcode/java/string/ - 2023-09-10 + https://nicksxs.me/categories/Linux/%E5%91%BD%E4%BB%A4/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/dns/ - 2023-09-10 + https://nicksxs.me/categories/Redis/Distributed-Lock/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Java/Mybatis/ - 2023-09-10 + https://nicksxs.me/categories/Interceptor-AOP/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Spring/ - 2023-09-10 + https://nicksxs.me/categories/Java/SpringBoot/Tomcat/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Linux/%E5%91%BD%E4%BB%A4/ - 2023-09-10 + https://nicksxs.me/categories/Docker/%E4%BB%8B%E7%BB%8D/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/hexo/ - 2023-09-10 + https://nicksxs.me/categories/ssh/%E6%8A%80%E5%B7%A7/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/ssh/ - 2023-09-10 + https://nicksxs.me/categories/%E5%B9%B4%E7%BB%88%E6%80%BB%E7%BB%93/2020/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/nginx/ - 2023-09-10 + https://nicksxs.me/categories/Java/Mybatis/Mysql/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Redis/Distributed-Lock/ - 2023-09-10 + https://nicksxs.me/categories/hexo/%E6%8A%80%E5%B7%A7/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Java/SpringBoot/Tomcat/ - 2023-09-10 + https://nicksxs.me/categories/leetcode/java/Binary-Tree/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/php/ - 2023-09-10 + https://nicksxs.me/categories/Mysql/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Docker/%E4%BB%8B%E7%BB%8D/ - 2023-09-10 + https://nicksxs.me/categories/Mybatis/ + 2023-09-11 + weekly + 0.2 + + + + https://nicksxs.me/categories/leetcode/java/DP/ + 2023-09-11 + weekly + 0.2 + + + + https://nicksxs.me/categories/leetcode/java/stack/ + 2023-09-11 weekly 0.2 https://nicksxs.me/categories/Redis/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/ - 2023-09-10 + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/redis/ - 2023-09-10 + https://nicksxs.me/categories/leetcode/java/Linked-List/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/%E8%AF%AD%E8%A8%80/ - 2023-09-10 + https://nicksxs.me/categories/leetcode/java/linked-list/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Java/Spring/ - 2023-09-10 + https://nicksxs.me/categories/leetcode/java/string/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Java/Mybatis/Mysql/ - 2023-09-10 + https://nicksxs.me/categories/Linux/%E5%91%BD%E4%BB%A4/grep/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Spring/Servlet/ - 2023-09-10 + https://nicksxs.me/categories/C/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Mybatis/ - 2023-09-10 + https://nicksxs.me/categories/Spring/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Java/gc/ - 2023-09-10 + https://nicksxs.me/categories/Linux/%E5%91%BD%E4%BB%A4/echo/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/%E8%AF%BB%E5%90%8E%E6%84%9F/%E7%94%9F%E6%B4%BB/ - 2023-09-10 + https://nicksxs.me/categories/leetcode/java/Binary-Tree/DFS/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Linux/%E5%91%BD%E4%BB%A4/grep/ - 2023-09-10 + https://nicksxs.me/categories/Mysql/Sql%E6%B3%A8%E5%85%A5/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E8%BF%90%E5%8A%A8/ - 2023-09-10 + https://nicksxs.me/categories/Mybatis/%E7%BC%93%E5%AD%98/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/hexo/%E6%8A%80%E5%B7%A7/ - 2023-09-10 + https://nicksxs.me/categories/Redis/%E6%BA%90%E7%A0%81/ + 2023-09-11 weekly 0.2 https://nicksxs.me/categories/%E5%B0%8F%E6%8A%80%E5%B7%A7/ - 2023-09-10 + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/ssh/%E6%8A%80%E5%B7%A7/ - 2023-09-10 + https://nicksxs.me/categories/C/Redis/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/MQ/ - 2023-09-10 + https://nicksxs.me/categories/Spring/Servlet/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E5%90%90%E6%A7%BD/ - 2023-09-10 + https://nicksxs.me/categories/Docker/%E5%8F%91%E8%A1%8C%E7%89%88%E6%9C%AC/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Mysql/ - 2023-09-10 + https://nicksxs.me/categories/Spring/Mybatis/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/%E8%AF%BB%E5%90%8E%E6%84%9F/%E7%99%BD%E5%B2%A9%E6%9D%BE/ - 2023-09-10 + https://nicksxs.me/categories/%E5%B0%8F%E6%8A%80%E5%B7%A7/grep/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Windows/ - 2023-09-10 + https://nicksxs.me/categories/Spring/Servlet/Interceptor/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/git/ - 2023-09-10 + https://nicksxs.me/categories/%E5%B0%8F%E6%8A%80%E5%B7%A7/grep/%E6%9F%A5%E6%97%A5%E5%BF%97/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E5%85%AC%E4%BA%A4/ - 2023-09-10 + https://nicksxs.me/categories/Spring/Servlet/Interceptor/AOP/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/shell/ - 2023-09-10 + https://nicksxs.me/categories/%E8%AF%AD%E8%A8%80/Rust/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/C/ - 2023-09-10 + https://nicksxs.me/categories/Rust/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/wsl/ - 2023-09-10 + https://nicksxs.me/categories/Java/Spring/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E5%BD%B1%E8%AF%84/ - 2023-09-10 + https://nicksxs.me/categories/Java/gc/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0/ - 2023-09-10 + https://nicksxs.me/categories/%E8%AF%BB%E5%90%8E%E6%84%9F/%E7%94%9F%E6%B4%BB/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Redis/%E6%BA%90%E7%A0%81/ - 2023-09-10 + https://nicksxs.me/categories/Java/gc/jvm/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Dubbo-RPC/ - 2023-09-10 + https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E8%BF%90%E5%8A%A8/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Java/Dubbo/RPC/ - 2023-09-10 + https://nicksxs.me/categories/MQ/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Java/%E7%B1%BB%E5%8A%A0%E8%BD%BD/ - 2023-09-10 + https://nicksxs.me/categories/nas/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Thread-dump/ - 2023-09-10 + https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E5%90%90%E6%A7%BD/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Linux/%E5%91%BD%E4%BB%A4/top/ - 2023-09-10 + https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E5%85%AC%E4%BA%A4/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Dubbo-%E7%BA%BF%E7%A8%8B%E6%B1%A0/ - 2023-09-10 + https://nicksxs.me/categories/%E8%AF%BB%E5%90%8E%E6%84%9F/%E7%99%BD%E5%B2%A9%E6%9D%BE/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Java/Design-Patterns/ - 2023-09-10 + https://nicksxs.me/categories/MQ/RocketMQ/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Redis/%E5%BA%94%E7%94%A8/ - 2023-09-10 + https://nicksxs.me/categories/Windows/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Linux/%E5%91%BD%E4%BB%A4/echo/ - 2023-09-10 + https://nicksxs.me/categories/git/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/SpringBoot/ - 2023-09-10 + https://nicksxs.me/categories/shell/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/%E8%AF%AD%E8%A8%80/Rust/ - 2023-09-10 + https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E5%90%90%E6%A7%BD/%E7%96%AB%E6%83%85/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Mac/ - 2023-09-10 + https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E8%BF%90%E5%8A%A8/%E8%B7%91%E6%AD%A5/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E6%97%85%E6%B8%B8/ - 2023-09-10 + https://nicksxs.me/categories/wsl/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/%E5%88%86%E5%B8%83%E5%BC%8F%E4%BA%8B%E5%8A%A1/ - 2023-09-10 + https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E5%BD%B1%E8%AF%84/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Rust/ - 2023-09-10 + https://nicksxs.me/categories/%E8%AF%BB%E5%90%8E%E6%84%9F/%E7%99%BD%E5%B2%A9%E6%9D%BE/%E5%B9%B8%E7%A6%8F%E4%BA%86%E5%90%97/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E5%BC%80%E8%BD%A6/ - 2023-09-10 + https://nicksxs.me/categories/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Spring/Servlet/Interceptor/ - 2023-09-10 + https://nicksxs.me/categories/%E6%B6%88%E6%81%AF%E9%98%9F%E5%88%97/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Mybatis/%E7%BC%93%E5%AD%98/ - 2023-09-10 + https://nicksxs.me/categories/Windows/%E5%B0%8F%E6%8A%80%E5%B7%A7/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Java/gc/jvm/ - 2023-09-10 + https://nicksxs.me/categories/MQ/RocketMQ/%E6%B6%88%E6%81%AF%E9%98%9F%E5%88%97/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/%E6%8A%80%E5%B7%A7/ - 2023-09-10 + https://nicksxs.me/categories/git/%E5%B0%8F%E6%8A%80%E5%B7%A7/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/MQ/RocketMQ/ - 2023-09-10 + https://nicksxs.me/categories/shell/%E5%B0%8F%E6%8A%80%E5%B7%A7/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E5%90%90%E6%A7%BD/%E7%96%AB%E6%83%85/ - 2023-09-10 + https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E5%90%90%E6%A7%BD/%E7%96%AB%E6%83%85/%E7%BE%8E%E5%9B%BD/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Mysql/Sql%E6%B3%A8%E5%85%A5/ - 2023-09-10 + https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E8%BF%90%E5%8A%A8/%E8%B7%91%E6%AD%A5/%E5%B9%B2%E6%B4%BB/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/%E8%AF%BB%E5%90%8E%E6%84%9F/%E7%99%BD%E5%B2%A9%E6%9D%BE/%E5%B9%B8%E7%A6%8F%E4%BA%86%E5%90%97/ - 2023-09-10 + https://nicksxs.me/categories/Java/Dubbo/RPC/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Windows/%E5%B0%8F%E6%8A%80%E5%B7%A7/ - 2023-09-10 + https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E5%90%90%E6%A7%BD/%E7%96%AB%E6%83%85/%E5%8F%A3%E7%BD%A9/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/git/%E5%B0%8F%E6%8A%80%E5%B7%A7/ - 2023-09-10 + https://nicksxs.me/categories/Dubbo-RPC/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E8%BF%90%E5%8A%A8/%E8%B7%91%E6%AD%A5/ - 2023-09-10 + https://nicksxs.me/categories/Java/%E7%B1%BB%E5%8A%A0%E8%BD%BD/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/shell/%E5%B0%8F%E6%8A%80%E5%B7%A7/ - 2023-09-10 + https://nicksxs.me/categories/Thread-dump/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/C/Redis/ - 2023-09-10 + https://nicksxs.me/categories/Linux/%E5%91%BD%E4%BB%A4/top/ + 2023-09-11 weekly 0.2 https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E5%BD%B1%E8%AF%84/2020/ - 2023-09-10 + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Dubbo/ - 2023-09-10 + https://nicksxs.me/categories/Dubbo-%E7%BA%BF%E7%A8%8B%E6%B1%A0/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Java/Dubbo/RPC/SPI/ - 2023-09-10 + https://nicksxs.me/categories/Mysql/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/%E9%97%AE%E9%A2%98%E6%8E%92%E6%9F%A5/ - 2023-09-10 + https://nicksxs.me/categories/Mysql/%E7%B4%A2%E5%BC%95/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/%E5%B0%8F%E6%8A%80%E5%B7%A7/top/ - 2023-09-10 + https://nicksxs.me/categories/Redis/%E5%BA%94%E7%94%A8/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Mysql/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/ - 2023-09-10 + https://nicksxs.me/categories/Java/Design-Patterns/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Mysql/%E7%B4%A2%E5%BC%95/ - 2023-09-10 + https://nicksxs.me/categories/%E6%B6%88%E6%81%AF%E9%98%9F%E5%88%97/RocketMQ/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Java/Singleton/ - 2023-09-10 + https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E6%97%85%E6%B8%B8/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Redis/%E7%BC%93%E5%AD%98/ - 2023-09-10 + https://nicksxs.me/categories/%E5%88%86%E5%B8%83%E5%BC%8F%E4%BA%8B%E5%8A%A1/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Docker/%E5%8F%91%E8%A1%8C%E7%89%88%E6%9C%AC/ - 2023-09-10 + https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E5%BC%80%E8%BD%A6/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Mac/PHP/ - 2023-09-10 + https://nicksxs.me/categories/Mac/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/%E5%88%86%E5%B8%83%E5%BC%8F%E4%BA%8B%E5%8A%A1/%E4%B8%A4%E9%98%B6%E6%AE%B5%E6%8F%90%E4%BA%A4/ - 2023-09-10 + https://nicksxs.me/categories/SpringBoot/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Spring/Servlet/Interceptor/AOP/ - 2023-09-10 + https://nicksxs.me/categories/%E6%8A%80%E5%B7%A7/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Spring/Mybatis/ - 2023-09-10 + https://nicksxs.me/categories/Java/Dubbo/RPC/SPI/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/%E5%B0%8F%E6%8A%80%E5%B7%A7/grep/ - 2023-09-10 + https://nicksxs.me/categories/Dubbo/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/%E6%B6%88%E6%81%AF%E9%98%9F%E5%88%97/ - 2023-09-10 + https://nicksxs.me/categories/%E9%97%AE%E9%A2%98%E6%8E%92%E6%9F%A5/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E5%90%90%E6%A7%BD/%E7%96%AB%E6%83%85/%E7%BE%8E%E5%9B%BD/ - 2023-09-10 + https://nicksxs.me/categories/%E5%B0%8F%E6%8A%80%E5%B7%A7/top/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E5%90%90%E6%A7%BD/%E7%96%AB%E6%83%85/%E5%8F%A3%E7%BD%A9/ - 2023-09-10 + https://nicksxs.me/categories/Mysql/%E6%BA%90%E7%A0%81/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E8%BF%90%E5%8A%A8/%E8%B7%91%E6%AD%A5/%E5%B9%B2%E6%B4%BB/ - 2023-09-10 + https://nicksxs.me/categories/C/Mysql/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/MQ/RocketMQ/%E6%B6%88%E6%81%AF%E9%98%9F%E5%88%97/ - 2023-09-10 + https://nicksxs.me/categories/Redis/%E7%BC%93%E5%AD%98/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Dubbo/%E5%AE%B9%E9%94%99%E6%9C%BA%E5%88%B6/ - 2023-09-10 + https://nicksxs.me/categories/Java/Singleton/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Dubbo/SPI/ - 2023-09-10 + https://nicksxs.me/categories/%E4%B8%AD%E9%97%B4%E4%BB%B6/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/%E5%B7%A5%E5%85%B7/ - 2023-09-10 + https://nicksxs.me/categories/%E5%88%86%E5%B8%83%E5%BC%8F%E4%BA%8B%E5%8A%A1/%E4%B8%A4%E9%98%B6%E6%AE%B5%E6%8F%90%E4%BA%A4/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/%E5%B0%8F%E6%8A%80%E5%B7%A7/top/%E6%8E%92%E5%BA%8F/ - 2023-09-10 + https://nicksxs.me/categories/Mac/PHP/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Mysql/%E6%BA%90%E7%A0%81/ - 2023-09-10 + https://nicksxs.me/categories/Dubbo/SPI/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Dubbo/%E7%BA%BF%E7%A8%8B%E6%B1%A0/ - 2023-09-10 + https://nicksxs.me/categories/Dubbo/%E5%AE%B9%E9%94%99%E6%9C%BA%E5%88%B6/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/C/Mysql/ - 2023-09-10 + https://nicksxs.me/categories/%E5%B7%A5%E5%85%B7/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/%E7%BC%93%E5%AD%98/ - 2023-09-10 + https://nicksxs.me/categories/%E5%B0%8F%E6%8A%80%E5%B7%A7/top/%E6%8E%92%E5%BA%8F/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Mac/Homebrew/ - 2023-09-10 + https://nicksxs.me/categories/Dubbo/%E7%BA%BF%E7%A8%8B%E6%B1%A0/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/%E5%88%86%E5%B8%83%E5%BC%8F%E4%BA%8B%E5%8A%A1/%E4%B8%89%E9%98%B6%E6%AE%B5%E6%8F%90%E4%BA%A4/ - 2023-09-10 + https://nicksxs.me/categories/%E7%BC%93%E5%AD%98/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/%E5%B0%8F%E6%8A%80%E5%B7%A7/grep/%E6%9F%A5%E6%97%A5%E5%BF%97/ - 2023-09-10 + https://nicksxs.me/categories/%E4%B8%AD%E9%97%B4%E4%BB%B6/RocketMQ/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/%E6%B6%88%E6%81%AF%E9%98%9F%E5%88%97/RocketMQ/ - 2023-09-10 + https://nicksxs.me/categories/%E5%88%86%E5%B8%83%E5%BC%8F%E4%BA%8B%E5%8A%A1/%E4%B8%89%E9%98%B6%E6%AE%B5%E6%8F%90%E4%BA%A4/ + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/Dubbo/SPI/Adaptive/ - 2023-09-10 + https://nicksxs.me/categories/Mac/Homebrew/ + 2023-09-11 weekly 0.2 https://nicksxs.me/categories/Dubbo/%E7%BA%BF%E7%A8%8B%E6%B1%A0/ThreadPool/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/categories/%E7%BC%93%E5%AD%98/%E7%A9%BF%E9%80%8F/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/categories/PHP/ - 2023-09-10 + 2023-09-11 weekly 0.2 - https://nicksxs.me/categories/%E4%B8%AD%E9%97%B4%E4%BB%B6/ - 2023-09-10 + https://nicksxs.me/categories/Dubbo/SPI/Adaptive/ + 2023-09-11 weekly 0.2 https://nicksxs.me/categories/%E7%BC%93%E5%AD%98/%E7%A9%BF%E9%80%8F/%E5%87%BB%E7%A9%BF/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/categories/PHP/icu4c/ - 2023-09-10 - weekly - 0.2 - - - - https://nicksxs.me/categories/%E4%B8%AD%E9%97%B4%E4%BB%B6/RocketMQ/ - 2023-09-10 + 2023-09-11 weekly 0.2 https://nicksxs.me/categories/%E7%BC%93%E5%AD%98/%E7%A9%BF%E9%80%8F/%E5%87%BB%E7%A9%BF/%E9%9B%AA%E5%B4%A9/ - 2023-09-10 + 2023-09-11 weekly 0.2 diff --git a/tags/c/index.html b/tags/c/index.html index 40aa271b8f..145bee1edd 100644 --- a/tags/c/index.html +++ b/tags/c/index.html @@ -1 +1 @@ -标签: c++ | Nicksxs's Blog

    Nicksxs's Blog

    What hurts more, the pain of hard work or the pain of regret?

    0%
    \ No newline at end of file +标签: C | Nicksxs's Blog

    Nicksxs's Blog

    What hurts more, the pain of hard work or the pain of regret?

    C 标签

    2019
    0%
    oudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.js> \ No newline at end of file diff --git a/tags/docker/index.html b/tags/docker/index.html index 643ae3cc01..cc838611be 100644 --- a/tags/docker/index.html +++ b/tags/docker/index.html @@ -1 +1 @@ -标签: docker | Nicksxs's Blog

    Nicksxs's Blog

    What hurts more, the pain of hard work or the pain of regret?

    docker 标签

    2016
    0%
    /script> \ No newline at end of file +标签: Docker | Nicksxs's Blog

    Nicksxs's Blog

    What hurts more, the pain of hard work or the pain of regret?

    0%
    \ No newline at end of file diff --git a/tags/java/index.html b/tags/java/index.html index 4c90e56a6a..acb8ed390a 100644 --- a/tags/java/index.html +++ b/tags/java/index.html @@ -1 +1 @@ -标签: java | Nicksxs's Blog

    Nicksxs's Blog

    What hurts more, the pain of hard work or the pain of regret?

    0%
    \ No newline at end of file +标签: Java | Nicksxs's Blog

    Nicksxs's Blog

    What hurts more, the pain of hard work or the pain of regret?

    0%
    ps://cdnjs.cloudflare.com/ajax/libs/quicklink/2.3.0/quicklink.umd.js> \ No newline at end of file diff --git a/tags/java/page/2/index.html b/tags/java/page/2/index.html index e2b940ba81..a78c1ea917 100644 --- a/tags/java/page/2/index.html +++ b/tags/java/page/2/index.html @@ -1 +1 @@ -标签: java | Nicksxs's Blog

    Nicksxs's Blog

    What hurts more, the pain of hard work or the pain of regret?

    0%
    \ No newline at end of file +标签: Java | Nicksxs's Blog

    Nicksxs's Blog

    What hurts more, the pain of hard work or the pain of regret?

    0%
    \ No newline at end of file diff --git a/tags/java/page/3/index.html b/tags/java/page/3/index.html index 59479a3706..03270ba571 100644 --- a/tags/java/page/3/index.html +++ b/tags/java/page/3/index.html @@ -1 +1 @@ -标签: java | Nicksxs's Blog

    Nicksxs's Blog

    What hurts more, the pain of hard work or the pain of regret?

    0%
    \ No newline at end of file +标签: Java | Nicksxs's Blog

    Nicksxs's Blog

    What hurts more, the pain of hard work or the pain of regret?

    0%
    \ No newline at end of file diff --git a/tags/java/page/4/index.html b/tags/java/page/4/index.html index fb0ba790bc..995827115d 100644 --- a/tags/java/page/4/index.html +++ b/tags/java/page/4/index.html @@ -1 +1 @@ -标签: java | Nicksxs's Blog

    Nicksxs's Blog

    What hurts more, the pain of hard work or the pain of regret?

    0%
    \ No newline at end of file +标签: Java | Nicksxs's Blog

    Nicksxs's Blog

    What hurts more, the pain of hard work or the pain of regret?

    0%
    \ No newline at end of file diff --git a/tags/java/page/5/index.html b/tags/java/page/5/index.html index da8ed53713..32483cfcb3 100644 --- a/tags/java/page/5/index.html +++ b/tags/java/page/5/index.html @@ -1 +1 @@ -标签: java | Nicksxs's Blog

    Nicksxs's Blog

    What hurts more, the pain of hard work or the pain of regret?

    0%
    \ No newline at end of file +标签: Java | Nicksxs's Blog

    Nicksxs's Blog

    What hurts more, the pain of hard work or the pain of regret?

    0%
    \ No newline at end of file diff --git a/tags/java/page/6/index.html b/tags/java/page/6/index.html index b133ccd5e8..dd9f3cc644 100644 --- a/tags/java/page/6/index.html +++ b/tags/java/page/6/index.html @@ -1 +1 @@ -标签: java | Nicksxs's Blog

    Nicksxs's Blog

    What hurts more, the pain of hard work or the pain of regret?

    0%
    \ No newline at end of file +标签: Java | Nicksxs's Blog

    Nicksxs's Blog

    What hurts more, the pain of hard work or the pain of regret?

    0%
    \ No newline at end of file diff --git a/tags/java/page/7/index.html b/tags/java/page/7/index.html index ea74d76799..ae6dc833a6 100644 --- a/tags/java/page/7/index.html +++ b/tags/java/page/7/index.html @@ -1 +1 @@ -标签: java | Nicksxs's Blog

    Nicksxs's Blog

    What hurts more, the pain of hard work or the pain of regret?

    0%
    \ No newline at end of file +标签: Java | Nicksxs's Blog

    Nicksxs's Blog

    What hurts more, the pain of hard work or the pain of regret?

    0%
    \ No newline at end of file diff --git a/tags/linked-list/index.html b/tags/linked-list/index.html index 071994a872..b1fccbc75a 100644 --- a/tags/linked-list/index.html +++ b/tags/linked-list/index.html @@ -1 +1 @@ -标签: linked list | Nicksxs's Blog

    Nicksxs's Blog

    What hurts more, the pain of hard work or the pain of regret?

    linked list 标签

    2020
    0%
    tistics/lean-analytics.js> \ No newline at end of file +标签: Linked List | Nicksxs's Blog

    Nicksxs's Blog

    What hurts more, the pain of hard work or the pain of regret?

    0%
    \ No newline at end of file