diff --git a/2014/12/30/Clone-Graph-Part-I/index.html b/2014/12/30/Clone-Graph-Part-I/index.html index b8bac47644..c5b428e90a 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?

0%

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?

0%

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.

\ No newline at end of file +}

anlysis

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

\ No newline at end of file diff --git a/2017/04/25/rabbitmq-tips/index.html b/2017/04/25/rabbitmq-tips/index.html index 37a8020328..dff8d8e5b7 100644 --- a/2017/04/25/rabbitmq-tips/index.html +++ b/2017/04/25/rabbitmq-tips/index.html @@ -1,4 +1,4 @@ -rabbitmq-tips | Nicksxs's Blog

Nicksxs's Blog

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

0%

rabbitmq-tips

rabbitmq 介绍

接触了一下rabbitmq,原来在选型的时候是在rabbitmq跟kafka之间做选择,网上搜了一下之后发现kafka的优势在于吞吐量,而rabbitmq相对注重可靠性,因为应用在im上,需要保证消息不能丢失所以就暂时选定rabbitmq,
Message Queue的需求由来已久,80年代最早在金融交易中,高盛等公司采用Teknekron公司的产品,当时的Message queuing软件叫做:the information bus(TIB)。 TIB被电信和通讯公司采用,路透社收购了Teknekron公司。之后,IBM开发了MQSeries,微软开发了Microsoft Message Queue(MSMQ)。这些商业MQ供应商的问题是厂商锁定,价格高昂。2001年,Java Message queuing试图解决锁定和交互性的问题,但对应用来说反而更加麻烦了。
RabbitMQ采用Erlang语言开发。Erlang语言由Ericson设计,专门为开发concurrent和distribution系统的一种语言,在电信领域使用广泛。OTP(Open Telecom Platform)作为Erlang语言的一部分,包含了很多基于Erlang开发的中间件/库/工具,如mnesia/SASL,极大方便了Erlang应用的开发。OTP就类似于Python语言中众多的module,用户借助这些module可以很方便的开发应用。
于是2004年,摩根大通和iMatrix开始着手Advanced Message Queuing Protocol (AMQP)开放标准的开发。2006年,AMQP规范发布。2007年,Rabbit技术公司基于AMQP标准开发的RabbitMQ 1.0 发布。所有主要的编程语言均有与代理接口通讯的客户端库。

简单的使用经验

通俗的理解

这里介绍下其中的一些概念,connection表示和队列服务器的连接,一般情况下是tcp连接, channel表示通道,可以在一个连接上建立多个通道,这里主要是节省了tcp连接握手的成本,exchange可以理解成一个路由器,将消息推送给对应的队列queue,其实是像一个订阅的模式。

集群经验

rabbitmqctl stop这个是关闭rabbitmq,在搭建集群时候先关闭服务,然后使用rabbitmq-server -detached静默启动,这时候使用rabbitmqctl cluster_status查看集群状态,因为还没将节点加入集群,所以只能看到类似

Cluster status of node rabbit@rabbit1 ...
+rabbitmq-tips | Nicksxs's Blog

Nicksxs's Blog

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

0%

rabbitmq-tips

rabbitmq 介绍

接触了一下rabbitmq,原来在选型的时候是在rabbitmq跟kafka之间做选择,网上搜了一下之后发现kafka的优势在于吞吐量,而rabbitmq相对注重可靠性,因为应用在im上,需要保证消息不能丢失所以就暂时选定rabbitmq,
Message Queue的需求由来已久,80年代最早在金融交易中,高盛等公司采用Teknekron公司的产品,当时的Message queuing软件叫做:the information bus(TIB)。 TIB被电信和通讯公司采用,路透社收购了Teknekron公司。之后,IBM开发了MQSeries,微软开发了Microsoft Message Queue(MSMQ)。这些商业MQ供应商的问题是厂商锁定,价格高昂。2001年,Java Message queuing试图解决锁定和交互性的问题,但对应用来说反而更加麻烦了。
RabbitMQ采用Erlang语言开发。Erlang语言由Ericson设计,专门为开发concurrent和distribution系统的一种语言,在电信领域使用广泛。OTP(Open Telecom Platform)作为Erlang语言的一部分,包含了很多基于Erlang开发的中间件/库/工具,如mnesia/SASL,极大方便了Erlang应用的开发。OTP就类似于Python语言中众多的module,用户借助这些module可以很方便的开发应用。
于是2004年,摩根大通和iMatrix开始着手Advanced Message Queuing Protocol (AMQP)开放标准的开发。2006年,AMQP规范发布。2007年,Rabbit技术公司基于AMQP标准开发的RabbitMQ 1.0 发布。所有主要的编程语言均有与代理接口通讯的客户端库。

简单的使用经验

通俗的理解

这里介绍下其中的一些概念,connection表示和队列服务器的连接,一般情况下是tcp连接, channel表示通道,可以在一个连接上建立多个通道,这里主要是节省了tcp连接握手的成本,exchange可以理解成一个路由器,将消息推送给对应的队列queue,其实是像一个订阅的模式。

集群经验

rabbitmqctl stop这个是关闭rabbitmq,在搭建集群时候先关闭服务,然后使用rabbitmq-server -detached静默启动,这时候使用rabbitmqctl cluster_status查看集群状态,因为还没将节点加入集群,所以只能看到类似

Cluster status of node rabbit@rabbit1 ...
 [{nodes,[{disc,[rabbit@rabbit1,rabbit@rabbit2,rabbit@rabbit3]}]},
  {running_nodes,[rabbit@rabbit2,rabbit@rabbit1]}]
 ...done.

然后就可以把当前节点加入集群,

rabbit2$ rabbitmqctl stop_app #这个stop_app与stop的区别是前者停的是rabbitmq应用,保留erlang节点,
@@ -7,4 +7,4 @@ Stopping node rabbit@rabbit2 #这里可以用--ram指定将当前节点作为内存节点加入集群
 Clustering node rabbit@rabbit2 with [rabbit@rabbit1] ...done.
 rabbit2$ rabbitmqctl start_app
-Starting node rabbit@rabbit2 ...done.

其他可以参考官方文档

一些坑

消息丢失

这里碰到过一个坑,对于使用exchange来做消息路由的,会有一个情况,就是在routing_key没被订阅的时候,会将该条找不到路由对应的queue的消息丢掉What happens if we break our contract and send a message with one or four words, like "orange" or "quick.orange.male.rabbit"? Well, these messages won't match any bindings and will be lost.对应链接,而当使用空的exchange时,会保留消息,当出现消费者的时候就可以将收到之前生产者所推送的消息对应链接,这里就是用了空的exchange。

集群搭建

集群搭建的时候有个erlang vm生成的random cookie,这个是用来做集群之间认证的,相同的cookie才能连接,但是如果通过vim打开复制后在其他几点新建文件写入会多一个换行,导致集群建立是报错,所以这里最好使用scp等传输命令直接传输cookie文件,同时要注意下cookie的文件权限。
另外在集群搭建的时候如果更改过hostname,那么要把rabbitmq的数据库删除,否则启动后会马上挂掉

\ No newline at end of file +Starting node rabbit@rabbit2 ...done.

其他可以参考官方文档

一些坑

消息丢失

这里碰到过一个坑,对于使用exchange来做消息路由的,会有一个情况,就是在routing_key没被订阅的时候,会将该条找不到路由对应的queue的消息丢掉What happens if we break our contract and send a message with one or four words, like "orange" or "quick.orange.male.rabbit"? Well, these messages won't match any bindings and will be lost.对应链接,而当使用空的exchange时,会保留消息,当出现消费者的时候就可以将收到之前生产者所推送的消息对应链接,这里就是用了空的exchange。

集群搭建

集群搭建的时候有个erlang vm生成的random cookie,这个是用来做集群之间认证的,相同的cookie才能连接,但是如果通过vim打开复制后在其他几点新建文件写入会多一个换行,导致集群建立是报错,所以这里最好使用scp等传输命令直接传输cookie文件,同时要注意下cookie的文件权限。
另外在集群搭建的时候如果更改过hostname,那么要把rabbitmq的数据库删除,否则启动后会马上挂掉

\ No newline at end of file diff --git a/2020/06/26/聊一下-RocketMQ-的-Consumer/index.html b/2020/06/26/聊一下-RocketMQ-的-Consumer/index.html index 1a4dc82618..34837fecac 100644 --- a/2020/06/26/聊一下-RocketMQ-的-Consumer/index.html +++ b/2020/06/26/聊一下-RocketMQ-的-Consumer/index.html @@ -1,4 +1,4 @@ -聊一下 RocketMQ 的 DefaultMQPushConsumer 源码 | Nicksxs's Blog

Nicksxs's Blog

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

0%

聊一下 RocketMQ 的 DefaultMQPushConsumer 源码

首先看下官方的小 demo

public static void main(String[] args) throws InterruptedException, MQClientException {
+聊一下 RocketMQ 的 DefaultMQPushConsumer 源码 | Nicksxs's Blog

Nicksxs's Blog

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

0%

聊一下 RocketMQ 的 DefaultMQPushConsumer 源码

首先看下官方的小 demo

public static void main(String[] args) throws InterruptedException, MQClientException {
 
         /*
          * Instantiate with specified consumer group name.
@@ -737,4 +737,4 @@
                 throw new RemotingTimeoutException(info);
             }
         }
-    }
\ No newline at end of file + }
\ No newline at end of file diff --git a/2020/07/05/聊一下-RocketMQ-的-NameServer-源码/index.html b/2020/07/05/聊一下-RocketMQ-的-NameServer-源码/index.html index f29b663824..ff7390496f 100644 --- a/2020/07/05/聊一下-RocketMQ-的-NameServer-源码/index.html +++ b/2020/07/05/聊一下-RocketMQ-的-NameServer-源码/index.html @@ -1,4 +1,4 @@ -聊一下 RocketMQ 的 NameServer 源码 | Nicksxs's Blog

Nicksxs's Blog

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

0%

聊一下 RocketMQ 的 NameServer 源码

前面介绍了,nameserver相当于dubbo的注册中心,用与管理broker,broker会在启动的时候注册到nameserver,并且会发送心跳给namaserver,nameserver负责保存活跃的broker,包括master和slave,同时保存topic和topic下的队列,以及filter列表,然后为producer和consumer的请求提供服务。

启动过程

public static void main(String[] args) {
+聊一下 RocketMQ 的 NameServer 源码 | Nicksxs's Blog

Nicksxs's Blog

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

0%

聊一下 RocketMQ 的 NameServer 源码

前面介绍了,nameserver相当于dubbo的注册中心,用与管理broker,broker会在启动的时候注册到nameserver,并且会发送心跳给namaserver,nameserver负责保存活跃的broker,包括master和slave,同时保存topic和topic下的队列,以及filter列表,然后为producer和consumer的请求提供服务。

启动过程

public static void main(String[] args) {
         main0(args);
     }
 
@@ -563,4 +563,4 @@
         response.setRemark("No topic route info in name server for the topic: " + requestHeader.getTopic()
             + FAQUrl.suggestTodo(FAQUrl.APPLY_TOPIC_URL));
         return response;
-    }

首先调用org.apache.rocketmq.namesrv.routeinfo.RouteInfoManager#pickupTopicRouteDataorg.apache.rocketmq.namesrv.routeinfo.RouteInfoManager#topicQueueTable获取到org.apache.rocketmq.common.protocol.route.QueueData这里面存了 brokerName,再通过org.apache.rocketmq.namesrv.routeinfo.RouteInfoManager#brokerAddrTable里获取到 broker 的地址信息等,然后再获取 orderMessage 的配置。

简要分析了下 RocketMQ 的 NameServer 的代码,比较粗粒度。

\ No newline at end of file + }

首先调用org.apache.rocketmq.namesrv.routeinfo.RouteInfoManager#pickupTopicRouteDataorg.apache.rocketmq.namesrv.routeinfo.RouteInfoManager#topicQueueTable获取到org.apache.rocketmq.common.protocol.route.QueueData这里面存了 brokerName,再通过org.apache.rocketmq.namesrv.routeinfo.RouteInfoManager#brokerAddrTable里获取到 broker 的地址信息等,然后再获取 orderMessage 的配置。

简要分析了下 RocketMQ 的 NameServer 的代码,比较粗粒度。

\ No newline at end of file diff --git a/baidusitemap.xml b/baidusitemap.xml index 6509f2c1e1..d19de71ccd 100644 --- a/baidusitemap.xml +++ b/baidusitemap.xml @@ -89,11 +89,11 @@ 2022-06-11 - https://nicksxs.me/2022/02/27/Disruptor-%E7%B3%BB%E5%88%97%E4%BA%8C/ + https://nicksxs.me/2022/02/13/Disruptor-%E7%B3%BB%E5%88%97%E4%B8%80/ 2022-06-11 - 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 @@ -109,11 +109,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 @@ -129,19 +129,19 @@ 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/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 - 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/2022/01/30/spring-event-%E4%BB%8B%E7%BB%8D/ 2022-06-11 - https://nicksxs.me/2022/01/30/spring-event-%E4%BB%8B%E7%BB%8D/ + 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 @@ -165,23 +165,23 @@ 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/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/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/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 - 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/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 - 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 - 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/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 @@ -189,7 +189,7 @@ 2022-06-11 - 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/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 @@ -197,27 +197,27 @@ 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/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 - 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/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/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 - 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/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 - 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/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/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/04/04/%E8%81%8A%E8%81%8A-dubbo-%E7%9A%84%E7%BA%BF%E7%A8%8B%E6%B1%A0/ 2022-06-11 @@ -609,31 +609,31 @@ 2020-01-12 - https://nicksxs.me/2019/12/10/Redis-Part-1/ + https://nicksxs.me/2015/03/13/Reverse-Integer/ 2020-01-12 - https://nicksxs.me/2017/05/09/ambari-summary/ + https://nicksxs.me/2015/03/11/Reverse-Bits/ 2020-01-12 - https://nicksxs.me/2015/03/13/Reverse-Integer/ + https://nicksxs.me/2015/01/14/Two-Sum/ 2020-01-12 - https://nicksxs.me/2015/01/14/Two-Sum/ + https://nicksxs.me/2016/09/29/binary-watch/ 2020-01-12 - https://nicksxs.me/2016/08/14/docker-mysql-cluster/ + https://nicksxs.me/2019/12/10/Redis-Part-1/ 2020-01-12 - https://nicksxs.me/2016/09/29/binary-watch/ + https://nicksxs.me/2017/05/09/ambari-summary/ 2020-01-12 - https://nicksxs.me/2015/03/11/Reverse-Bits/ + https://nicksxs.me/2016/08/14/docker-mysql-cluster/ 2020-01-12 @@ -645,7 +645,7 @@ 2020-01-12 - https://nicksxs.me/2019/12/26/redis%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%BB%8B%E7%BB%8D/ + https://nicksxs.me/2016/11/10/php-abstract-class-and-interface/ 2020-01-12 @@ -653,7 +653,7 @@ 2020-01-12 - https://nicksxs.me/2016/11/10/php-abstract-class-and-interface/ + https://nicksxs.me/2019/12/26/redis%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%BB%8B%E7%BB%8D/ 2020-01-12 @@ -661,11 +661,11 @@ 2020-01-12 - https://nicksxs.me/2014/12/30/Clone-Graph-Part-I/ + https://nicksxs.me/2019/09/23/AbstractQueuedSynchronizer/ 2020-01-12 - https://nicksxs.me/2019/09/23/AbstractQueuedSynchronizer/ + https://nicksxs.me/2014/12/30/Clone-Graph-Part-I/ 2020-01-12 @@ -673,11 +673,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 @@ -697,11 +697,11 @@ 2020-01-12 - https://nicksxs.me/2017/03/28/spark-little-tips/ + https://nicksxs.me/2016/07/13/swoole-websocket-test/ 2020-01-12 - https://nicksxs.me/2016/07/13/swoole-websocket-test/ + https://nicksxs.me/2017/03/28/spark-little-tips/ 2020-01-12 diff --git a/categories/Java/GC/index.html b/categories/Java/GC/index.html index 5e2584830a..ece85a6a44 100644 --- a/categories/Java/GC/index.html +++ b/categories/Java/GC/index.html @@ -1 +1 @@ -分类: gc | 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 +分类: gc | Nicksxs's Blog

Nicksxs's Blog

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

0%
,"url":"https://nicksxs.me/categories/Java/GC/"} \ No newline at end of file diff --git a/categories/Java/index.html b/categories/Java/index.html index 3737fc0bdb..3caa38ef95 100644 --- a/categories/Java/index.html +++ b/categories/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%
/json">{"enable":true,"home":false,"archive":false,"delay":true,"timeout":3000,"priority":true,"url":"https://nicksxs.me/categories/Java/"} \ No newline at end of file diff --git a/categories/linked-list/index.html b/categories/linked-list/index.html index 2dd0145c29..c9c9bb2260 100644 --- a/categories/linked-list/index.html +++ b/categories/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?

0%

linked list 分类

2020
\ 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%

linked list 分类

2020
ytics.js"> \ No newline at end of file diff --git a/css/main.css b/css/main.css index c8154157aa..9c016bf4e9 100644 --- a/css/main.css +++ b/css/main.css @@ -1 +1 @@ -:root{--body-bg-color:#f5f7f9;--content-bg-color:#fff;--card-bg-color:#f5f5f5;--text-color:#555;--blockquote-color:#666;--link-color:#555;--link-hover-color:#222;--brand-color:#fff;--brand-hover-color:#fff;--table-row-odd-bg-color:#f9f9f9;--table-row-hover-bg-color:#f5f5f5;--menu-item-bg-color:#f5f5f5;--theme-color:#222;--btn-default-bg:#fff;--btn-default-color:#555;--btn-default-border-color:#555;--btn-default-hover-bg:#222;--btn-default-hover-color:#fff;--btn-default-hover-border-color:#222;--highlight-background:#f3f3f3;--highlight-foreground:#444;--highlight-gutter-background:#e1e1e1;--highlight-gutter-foreground:#555;color-scheme:light}html{line-height:1.15;-webkit-text-size-adjust:100%}body{margin:0}main{display:block}h1{font-size:2em;margin:.67em 0}hr{box-sizing:content-box;height:0;overflow:visible}pre{font-family:monospace,monospace;font-size:1em}a{background:0 0}abbr[title]{border-bottom:none;text-decoration:underline;text-decoration:underline dotted}b,strong{font-weight:bolder}code,kbd,samp{font-family:monospace,monospace;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}img{border-style:none}button,input,optgroup,select,textarea{font-family:inherit;font-size:100%;line-height:1.15;margin:0}button,input{overflow:visible}button,select{text-transform:none}[type=button],[type=reset],[type=submit],button{-webkit-appearance:button}[type=button]::-moz-focus-inner,[type=reset]::-moz-focus-inner,[type=submit]::-moz-focus-inner,button::-moz-focus-inner{border-style:none;padding:0}[type=button]:-moz-focusring,[type=reset]:-moz-focusring,[type=submit]:-moz-focusring,button:-moz-focusring{outline:1px dotted ButtonText}fieldset{padding:.35em .75em .625em}legend{box-sizing:border-box;color:inherit;display:table;max-width:100%;padding:0;white-space:normal}progress{vertical-align:baseline}textarea{overflow:auto}[type=checkbox],[type=radio]{box-sizing:border-box;padding:0}[type=number]::-webkit-inner-spin-button,[type=number]::-webkit-outer-spin-button{height:auto}[type=search]{outline-offset:-2px;-webkit-appearance:textfield}[type=search]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{font:inherit;-webkit-appearance:button}details{display:block}summary{display:list-item}template{display:none}[hidden]{display:none}::selection{background:#262a30;color:#eee}body,html{height:100%}body{background:var(--body-bg-color);box-sizing:border-box;color:var(--text-color);font-family:Lato,'PingFang SC','Microsoft YaHei',sans-serif;font-size:1.2em;line-height:2;min-height:100%;position:relative;transition:padding .2s ease-in-out}h1,h2,h3,h4,h5,h6{font-family:Lato,'PingFang SC','Microsoft YaHei',sans-serif;font-weight:700;line-height:1.5;margin:30px 0 15px}h1{font-size:1.5em}h2{font-size:1.375em}h3{font-size:1.25em}h4{font-size:1.125em}h5{font-size:1em}h6{font-size:.875em}p{margin:0 0 20px}a{border-bottom:1px solid #999;color:var(--link-color);cursor:pointer;outline:0;text-decoration:none;overflow-wrap:break-word}a:hover{border-bottom-color:var(--link-hover-color);color:var(--link-hover-color)}embed,iframe,img,video{display:block;margin-left:auto;margin-right:auto;max-width:100%}hr{background-image:repeating-linear-gradient(-45deg,#ddd,#ddd 4px,transparent 4px,transparent 8px);border:0;height:3px;margin:40px 0}blockquote{border-left:4px solid #ddd;color:var(--blockquote-color);margin:0;padding:0 15px}blockquote cite::before{content:'-';padding:0 5px}dt{font-weight:700}dd{margin:0;padding:0}.table-container{overflow:auto}table{border-collapse:collapse;border-spacing:0;font-size:.875em;margin:0 0 20px;width:100%}tbody tr:nth-of-type(odd){background:var(--table-row-odd-bg-color)}tbody tr:hover{background:var(--table-row-hover-bg-color)}caption,td,th{padding:8px}td,th{border:1px solid #ddd;border-bottom:3px solid #ddd}th{font-weight:700;padding-bottom:10px}td{border-bottom-width:1px}.btn{background:var(--btn-default-bg);border:2px solid var(--btn-default-border-color);border-radius:2px;color:var(--btn-default-color);display:inline-block;font-size:.875em;line-height:2;padding:0 20px;transition:background-color .2s ease-in-out}.btn:hover{background:var(--btn-default-hover-bg);border-color:var(--btn-default-hover-border-color);color:var(--btn-default-hover-color)}.btn+.btn{margin:0 0 8px 8px}.btn .fa-fw{text-align:left;width:1.285714285714286em}.toggle{line-height:0}.toggle .toggle-line{background:#fff;display:block;height:2px;left:0;position:relative;top:0;transition:all .4s;width:100%}.toggle .toggle-line:not(:first-child){margin-top:3px}.toggle.toggle-arrow .toggle-line:first-child{left:50%;top:2px;transform:rotate(45deg);width:50%}.toggle.toggle-arrow .toggle-line:last-child{left:50%;top:-2px;transform:rotate(-45deg);width:50%}.toggle.toggle-close .toggle-line:nth-child(2){opacity:0}.toggle.toggle-close .toggle-line:first-child{top:5px;transform:rotate(45deg)}.toggle.toggle-close .toggle-line:last-child{top:-5px;transform:rotate(-45deg)}code[class*=language-],pre[class*=language-]{color:#000;background:0 0;text-shadow:0 1px #fff;font-family:Consolas,Monaco,'Andale Mono','Ubuntu Mono',monospace;font-size:1em;text-align:left;white-space:pre;word-spacing:normal;word-break:normal;word-wrap:normal;line-height:1.5;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-hyphens:none;-moz-hyphens:none;-ms-hyphens:none;hyphens:none}code[class*=language-] ::-moz-selection,code[class*=language-]::-moz-selection,pre[class*=language-] ::-moz-selection,pre[class*=language-]::-moz-selection{text-shadow:none;background:#b3d4fc}code[class*=language-] ::selection,code[class*=language-]::selection,pre[class*=language-] ::selection,pre[class*=language-]::selection{text-shadow:none;background:#b3d4fc}@media print{code[class*=language-],pre[class*=language-]{text-shadow:none}}pre[class*=language-]{padding:1em;margin:.5em 0;overflow:auto}:not(pre)>code[class*=language-],pre[class*=language-]{background:#f5f2f0}:not(pre)>code[class*=language-]{padding:.1em;border-radius:.3em;white-space:normal}.token.cdata,.token.comment,.token.doctype,.token.prolog{color:#708090}.token.punctuation{color:#999}.token.namespace{opacity:.7}.token.boolean,.token.constant,.token.deleted,.token.number,.token.property,.token.symbol,.token.tag{color:#905}.token.attr-name,.token.builtin,.token.char,.token.inserted,.token.selector,.token.string{color:#690}.language-css .token.string,.style .token.string,.token.entity,.token.operator,.token.url{color:#9a6e3a;background:hsla(0,0%,100%,.5)}.token.atrule,.token.attr-value,.token.keyword{color:#07a}.token.class-name,.token.function{color:#dd4a68}.token.important,.token.regex,.token.variable{color:#e90}.token.bold,.token.important{font-weight:700}.token.italic{font-style:italic}.token.entity{cursor:help}pre[class*=language-].line-numbers{position:relative;padding-left:3.8em;counter-reset:linenumber}pre[class*=language-].line-numbers>code{position:relative;white-space:inherit}.line-numbers .line-numbers-rows{position:absolute;pointer-events:none;top:0;font-size:100%;left:-3.8em;width:3em;letter-spacing:-1px;border-right:1px solid #999;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.line-numbers-rows>span{display:block;counter-increment:linenumber}.line-numbers-rows>span:before{content:counter(linenumber);color:#999;display:block;padding-right:.8em;text-align:right}.highlight:hover .copy-btn,pre:hover .copy-btn{opacity:1}figure.highlight .table-container{position:relative}.copy-btn{color:#333;cursor:pointer;line-height:1.6;opacity:0;padding:2px 6px;position:absolute;transition:opacity .2s ease-in-out;color:var(--highlight-foreground);font-size:14px;right:0;top:2px}figure.highlight{border-radius:5px;box-shadow:0 10px 30px 0 rgba(0,0,0,.4);padding-top:30px}figure.highlight .table-container{border-radius:0 0 5px 5px}figure.highlight::before{background:#fc625d;box-shadow:20px 0 #fdbc40,40px 0 #35cd4b;left:12px;margin-top:-20px;position:absolute;border-radius:50%;content:' ';height:12px;width:12px}code,figure.highlight,kbd,pre{background:var(--highlight-background);color:var(--highlight-foreground)}figure.highlight,pre{line-height:1.6;margin:0 auto 20px}figure.highlight figcaption,pre .caption,pre figcaption{background:var(--highlight-gutter-background);color:var(--highlight-foreground);display:flow-root;font-size:.875em;line-height:1.2;padding:.5em}figure.highlight figcaption a,pre .caption a,pre figcaption a{color:var(--highlight-foreground);float:right}figure.highlight figcaption a:hover,pre .caption a:hover,pre figcaption a:hover{border-bottom-color:var(--highlight-foreground)}code,pre{font-family:consolas,Menlo,monospace,'PingFang SC','Microsoft YaHei'}code{border-radius:3px;font-size:.875em;padding:2px 4px;overflow-wrap:break-word}kbd{border:2px solid #ccc;border-radius:.2em;box-shadow:.1em .1em .2em rgba(0,0,0,.1);font-family:inherit;padding:.1em .3em;white-space:nowrap}figure.highlight{position:relative}figure.highlight pre{border:0;margin:0;padding:10px 0}figure.highlight table{border:0;margin:0;width:auto}figure.highlight td{border:0;padding:0}figure.highlight .gutter{-moz-user-select:none;-ms-user-select:none;-webkit-user-select:none;user-select:none}figure.highlight .gutter pre{background:var(--highlight-gutter-background);color:var(--highlight-gutter-foreground);padding-left:10px;padding-right:10px;text-align:right}figure.highlight .code pre{padding-left:10px;width:100%}figure.highlight .marked{background:rgba(0,0,0,.3)}pre .caption,pre figcaption{margin-bottom:10px}.gist table{width:auto}.gist table td{border:0}pre{overflow:auto;padding:10px;position:relative}pre code{background:0 0;padding:0;text-shadow:none}.blockquote-center{border-left:0;margin:40px 0;padding:0;position:relative;text-align:center}.blockquote-center::after,.blockquote-center::before{left:0;line-height:1;opacity:.6;position:absolute;width:100%}.blockquote-center::before{border-top:1px solid #ccc;text-align:left;top:-20px;content:'\f10d';font-family:'Font Awesome 5 Free';font-weight:900}.blockquote-center::after{border-bottom:1px solid #ccc;bottom:-20px;text-align:right;content:'\f10e';font-family:'Font Awesome 5 Free';font-weight:900}.blockquote-center div,.blockquote-center p{text-align:center}.group-picture{margin-bottom:20px}.group-picture .group-picture-row{display:flex;gap:3px;margin-bottom:3px}.group-picture .group-picture-column{flex:1}.group-picture .group-picture-column img{height:100%;margin:0;object-fit:cover;width:100%}.post-body .label{color:#555;padding:0 2px}.post-body .label.default{background:#f0f0f0}.post-body .label.primary{background:#efe6f7}.post-body .label.info{background:#e5f2f8}.post-body .label.success{background:#e7f4e9}.post-body .label.warning{background:#fcf6e1}.post-body .label.danger{background:#fae8eb}.post-body .link-grid{display:grid;grid-gap:1.5rem;gap:1.5rem;grid-template-columns:1fr 1fr;margin-bottom:20px;padding:1rem}@media (max-width:767px){.post-body .link-grid{grid-template-columns:1fr}}.post-body .link-grid .link-grid-container{border:solid #ddd;box-shadow:1rem 1rem .5rem rgba(0,0,0,.5);min-height:5rem;min-width:0;padding:.5rem;position:relative;transition:background .3s}.post-body .link-grid .link-grid-container:hover{animation:next-shake .5s;background:var(--card-bg-color)}.post-body .link-grid .link-grid-container:active{box-shadow:.5rem .5rem .25rem rgba(0,0,0,.5);transform:translate(.2rem,.2rem)}.post-body .link-grid .link-grid-container .link-grid-image{border:1px solid #ddd;border-radius:50%;box-sizing:border-box;height:5rem;padding:3px;position:absolute;width:5rem}.post-body .link-grid .link-grid-container p{margin:0 1rem 0 6rem}.post-body .link-grid .link-grid-container p:first-of-type{font-size:1.2em}.post-body .link-grid .link-grid-container p:last-of-type{font-size:.8em;line-height:1.3rem;opacity:.7}.post-body .link-grid .link-grid-container a{border:0;height:100%;left:0;position:absolute;top:0;width:100%}@-moz-keyframes next-shake{0%{transform:translate(1pt,1pt) rotate(0)}10%{transform:translate(-1pt,-2pt) rotate(-1deg)}20%{transform:translate(-3pt,0) rotate(1deg)}30%{transform:translate(3pt,2pt) rotate(0)}40%{transform:translate(1pt,-1pt) rotate(1deg)}50%{transform:translate(-1pt,2pt) rotate(-1deg)}60%{transform:translate(-3pt,1pt) rotate(0)}70%{transform:translate(3pt,1pt) rotate(-1deg)}80%{transform:translate(-1pt,-1pt) rotate(1deg)}90%{transform:translate(1pt,2pt) rotate(0)}100%{transform:translate(1pt,-2pt) rotate(-1deg)}}@-webkit-keyframes next-shake{0%{transform:translate(1pt,1pt) rotate(0)}10%{transform:translate(-1pt,-2pt) rotate(-1deg)}20%{transform:translate(-3pt,0) rotate(1deg)}30%{transform:translate(3pt,2pt) rotate(0)}40%{transform:translate(1pt,-1pt) rotate(1deg)}50%{transform:translate(-1pt,2pt) rotate(-1deg)}60%{transform:translate(-3pt,1pt) rotate(0)}70%{transform:translate(3pt,1pt) rotate(-1deg)}80%{transform:translate(-1pt,-1pt) rotate(1deg)}90%{transform:translate(1pt,2pt) rotate(0)}100%{transform:translate(1pt,-2pt) rotate(-1deg)}}@-o-keyframes next-shake{0%{transform:translate(1pt,1pt) rotate(0)}10%{transform:translate(-1pt,-2pt) rotate(-1deg)}20%{transform:translate(-3pt,0) rotate(1deg)}30%{transform:translate(3pt,2pt) rotate(0)}40%{transform:translate(1pt,-1pt) rotate(1deg)}50%{transform:translate(-1pt,2pt) rotate(-1deg)}60%{transform:translate(-3pt,1pt) rotate(0)}70%{transform:translate(3pt,1pt) rotate(-1deg)}80%{transform:translate(-1pt,-1pt) rotate(1deg)}90%{transform:translate(1pt,2pt) rotate(0)}100%{transform:translate(1pt,-2pt) rotate(-1deg)}}@keyframes next-shake{0%{transform:translate(1pt,1pt) rotate(0)}10%{transform:translate(-1pt,-2pt) rotate(-1deg)}20%{transform:translate(-3pt,0) rotate(1deg)}30%{transform:translate(3pt,2pt) rotate(0)}40%{transform:translate(1pt,-1pt) rotate(1deg)}50%{transform:translate(-1pt,2pt) rotate(-1deg)}60%{transform:translate(-3pt,1pt) rotate(0)}70%{transform:translate(3pt,1pt) rotate(-1deg)}80%{transform:translate(-1pt,-1pt) rotate(1deg)}90%{transform:translate(1pt,2pt) rotate(0)}100%{transform:translate(1pt,-2pt) rotate(-1deg)}}.post-body .note{border-radius:3px;margin-bottom:20px;padding:1em;position:relative;border:1px solid #eee;border-left-width:5px}.post-body .note summary{cursor:pointer;outline:0}.post-body .note summary p{display:inline}.post-body .note h2,.post-body .note h3,.post-body .note h4,.post-body .note h5,.post-body .note h6{border-bottom:initial;margin:0;padding-top:0}.post-body .note blockquote:first-child,.post-body .note img:first-child,.post-body .note ol:first-child,.post-body .note p:first-child,.post-body .note pre:first-child,.post-body .note table:first-child,.post-body .note ul:first-child{margin-top:0}.post-body .note blockquote:last-child,.post-body .note img:last-child,.post-body .note ol:last-child,.post-body .note p:last-child,.post-body .note pre:last-child,.post-body .note table:last-child,.post-body .note ul:last-child{margin-bottom:0}.post-body .note.default{border-left-color:#777}.post-body .note.default h2,.post-body .note.default h3,.post-body .note.default h4,.post-body .note.default h5,.post-body .note.default h6{color:#777}.post-body .note.primary{border-left-color:#6f42c1}.post-body .note.primary h2,.post-body .note.primary h3,.post-body .note.primary h4,.post-body .note.primary h5,.post-body .note.primary h6{color:#6f42c1}.post-body .note.info{border-left-color:#428bca}.post-body .note.info h2,.post-body .note.info h3,.post-body .note.info h4,.post-body .note.info h5,.post-body .note.info h6{color:#428bca}.post-body .note.success{border-left-color:#5cb85c}.post-body .note.success h2,.post-body .note.success h3,.post-body .note.success h4,.post-body .note.success h5,.post-body .note.success h6{color:#5cb85c}.post-body .note.warning{border-left-color:#f0ad4e}.post-body .note.warning h2,.post-body .note.warning h3,.post-body .note.warning h4,.post-body .note.warning h5,.post-body .note.warning h6{color:#f0ad4e}.post-body .note.danger{border-left-color:#d9534f}.post-body .note.danger h2,.post-body .note.danger h3,.post-body .note.danger h4,.post-body .note.danger h5,.post-body .note.danger h6{color:#d9534f}.post-body .tabs{margin-bottom:20px}.post-body .tabs,.tabs-comment{padding-top:10px}.post-body .tabs ul.nav-tabs,.tabs-comment ul.nav-tabs{background:var(--content-bg-color);display:flex;display:flex;flex-wrap:wrap;justify-content:center;margin:0;padding:0;position:-webkit-sticky;position:sticky;top:0;z-index:5}@media (max-width:413px){.post-body .tabs ul.nav-tabs,.tabs-comment ul.nav-tabs{display:block;margin-bottom:5px}}.post-body .tabs ul.nav-tabs li.tab,.tabs-comment ul.nav-tabs li.tab{border-bottom:1px solid #ddd;border-left:1px solid transparent;border-right:1px solid transparent;border-radius:0 0 0 0;border-top:3px solid transparent;flex-grow:1;list-style-type:none}@media (max-width:413px){.post-body .tabs ul.nav-tabs li.tab,.tabs-comment ul.nav-tabs li.tab{border-bottom:1px solid transparent;border-left:3px solid transparent;border-right:1px solid transparent;border-top:1px solid transparent}}@media (max-width:413px){.post-body .tabs ul.nav-tabs li.tab,.tabs-comment ul.nav-tabs li.tab{border-radius:0}}.post-body .tabs ul.nav-tabs li.tab a,.tabs-comment ul.nav-tabs li.tab a{border-bottom:initial;display:block;line-height:1.8;padding:.25em .75em;text-align:center;transition:all .2s ease-out}.post-body .tabs ul.nav-tabs li.tab a i,.tabs-comment ul.nav-tabs li.tab a i{width:1.285714285714286em}.post-body .tabs ul.nav-tabs li.tab.active,.tabs-comment ul.nav-tabs li.tab.active{border-bottom-color:transparent;border-left-color:#ddd;border-right-color:#ddd;border-top-color:#fc6423}@media (max-width:413px){.post-body .tabs ul.nav-tabs li.tab.active,.tabs-comment ul.nav-tabs li.tab.active{border-bottom-color:#ddd;border-left-color:#fc6423;border-right-color:#ddd;border-top-color:#ddd}}.post-body .tabs ul.nav-tabs li.tab.active a,.tabs-comment ul.nav-tabs li.tab.active a{cursor:default}.post-body .tabs .tab-content,.tabs-comment .tab-content{border:1px solid #ddd;border-radius:0 0 0 0;border-top-color:transparent}@media (max-width:413px){.post-body .tabs .tab-content,.tabs-comment .tab-content{border-radius:0;border-top-color:#ddd}}.post-body .tabs .tab-content .tab-pane,.tabs-comment .tab-content .tab-pane{padding:20px 20px 0}.post-body .tabs .tab-content .tab-pane:not(.active),.tabs-comment .tab-content .tab-pane:not(.active){display:none}.pagination .next,.pagination .page-number,.pagination .prev,.pagination .space{display:inline-block;margin:-1px 10px 0;padding:0 10px}@media (max-width:767px){.pagination .next,.pagination .page-number,.pagination .prev,.pagination .space{margin:0 5px}}.pagination .page-number.current{background:#ccc;border-color:#ccc;color:var(--content-bg-color)}.pagination{border-top:1px solid #eee;margin:120px 0 0;text-align:center}.pagination .next,.pagination .page-number,.pagination .prev{border-bottom:0;border-top:1px solid #eee;transition:border-color .2s ease-in-out}.pagination .next:hover,.pagination .page-number:hover,.pagination .prev:hover{border-top-color:var(--link-hover-color)}@media (max-width:767px){.pagination{border-top:0}.pagination .next,.pagination .page-number,.pagination .prev{border-bottom:1px solid #eee;border-top:0}.pagination .next:hover,.pagination .page-number:hover,.pagination .prev:hover{border-bottom-color:var(--link-hover-color)}}.pagination .space{margin:0;padding:0}.comments{margin-top:60px;overflow:hidden}.comment-button-group{display:flex;display:flex;flex-wrap:wrap;justify-content:center;justify-content:center;margin:1em 0}.comment-button-group .comment-button{margin:.1em .2em}.comment-button-group .comment-button.active{background:var(--btn-default-hover-bg);border-color:var(--btn-default-hover-border-color);color:var(--btn-default-hover-color)}.comment-position{display:none}.comment-position.active{display:block}.tabs-comment{margin-top:4em;padding-top:0}.tabs-comment .comments{margin-top:0;padding-top:0}.headband{background:var(--theme-color);height:3px}@media (max-width:991px){.headband{display:none}}header.header{background:0 0}.header-inner{margin:0 auto;width:calc(100% - 20px)}@media (min-width:1200px){.header-inner{width:1160px}}@media (min-width:1600px){.header-inner{width:73%}}.site-brand-container{display:flex;flex-shrink:0;padding:0 10px}.use-motion .site-brand-container .toggle,.use-motion header.header{opacity:0}.site-meta{flex-grow:1;text-align:center}@media (max-width:767px){.site-meta{text-align:center}}.custom-logo-image{margin-top:20px}@media (max-width:991px){.custom-logo-image{display:none}}.brand{border-bottom:0;color:var(--brand-color);display:inline-block;padding:0 40px}.brand:hover{color:var(--brand-hover-color)}.site-title{font-family:Lato,'PingFang SC','Microsoft YaHei',sans-serif;font-size:1.375em;font-weight:400;line-height:1.5;margin:0}.site-subtitle{color:#ddd;font-size:.8125em;margin:10px 0}.use-motion .custom-logo-image,.use-motion .site-subtitle,.use-motion .site-title{opacity:0;position:relative;top:-10px}.site-nav-right,.site-nav-toggle{display:none}@media (max-width:767px){.site-nav-right,.site-nav-toggle{display:flex;flex-direction:column;justify-content:center}}.site-nav-right .toggle,.site-nav-toggle .toggle{color:var(--text-color);padding:10px;width:22px}.site-nav-right .toggle .toggle-line,.site-nav-toggle .toggle .toggle-line{background:var(--text-color);border-radius:1px}@media (max-width:767px){.site-nav{--scroll-height:0;height:0;overflow:hidden;transition:height .2s ease-in-out}body:not(.site-nav-on) .site-nav .animated{animation:none}body.site-nav-on .site-nav{height:var(--scroll-height)}}.menu{margin:0;padding:1em 0;text-align:center}.menu-item{display:inline-block;list-style:none;margin:0 10px}@media (max-width:767px){.menu-item{display:block;margin-top:10px}.menu-item.menu-item-search{display:none}}.menu-item a{border-bottom:0;display:block;font-size:.8125em;transition:border-color .2s ease-in-out}.menu-item a.menu-item-active,.menu-item a:hover{background:var(--menu-item-bg-color)}.menu-item .fa,.menu-item .fab,.menu-item .far,.menu-item .fas{margin-right:8px}.menu-item .badge{display:inline-block;font-weight:700;line-height:1;margin-left:.35em;margin-top:.35em;text-align:center;white-space:nowrap}@media (max-width:767px){.menu-item .badge{float:right;margin-left:0}}.use-motion .menu-item{visibility:hidden}.github-corner :hover .octo-arm{animation:octocat-wave 560ms ease-in-out}.github-corner svg{color:#fff;fill:var(--theme-color);position:absolute;right:0;top:0;z-index:5}@media (max-width:991px){.github-corner{display:none}.github-corner svg{color:var(--theme-color);fill:#fff}.github-corner .github-corner:hover .octo-arm{animation:none}.github-corner .github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}@-moz-keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@-webkit-keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@-o-keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}.sidebar-inner{color:#999;max-height:calc(100vh - 24px);padding:18px 10px;text-align:center;display:flex;flex-direction:column;justify-content:center}.site-overview-item:not(:first-child){margin-top:10px}.cc-license .cc-opacity{border-bottom:0;opacity:.7}.cc-license .cc-opacity:hover{opacity:.9}.cc-license img{display:inline-block}.site-author-image{border:1px solid #eee;max-width:120px;padding:2px}.site-author-name{color:var(--text-color);font-weight:600;margin:0}.site-description{color:#999;font-size:.8125em;margin-top:0}.links-of-author a{font-size:.8125em}.links-of-author .fa,.links-of-author .fab,.links-of-author .far,.links-of-author .fas{margin-right:2px}.sidebar .sidebar-button:not(:first-child){margin-top:15px}.sidebar .sidebar-button button{background:0 0;color:#fc6423;cursor:pointer;line-height:2;padding:0 15px;border:1px solid #fc6423;border-radius:4px}.sidebar .sidebar-button button:hover{background:#fc6423;color:#fff}.sidebar .sidebar-button button .fa,.sidebar .sidebar-button button .fab,.sidebar .sidebar-button button .far,.sidebar .sidebar-button button .fas{margin-right:5px}.links-of-blogroll{font-size:.8125em}.links-of-blogroll-title{font-size:.875em;font-weight:600;margin-top:0}.links-of-blogroll-list{list-style:none;margin:0;padding:0}.sidebar-dimmer{display:none}@media (max-width:991px){.sidebar-dimmer{background:#000;display:block;height:100%;left:0;opacity:0;position:fixed;top:0;transition:visibility .4s,opacity .4s;visibility:hidden;width:100%;z-index:10}.sidebar-active .sidebar-dimmer{opacity:.7;visibility:visible}}.sidebar-nav{display:none;margin:0;padding-bottom:20px;padding-left:0}.sidebar-nav-active .sidebar-nav{display:block}.sidebar-nav li{border-bottom:1px solid transparent;color:var(--text-color);cursor:pointer;display:inline-block;font-size:.875em}.sidebar-nav li.sidebar-nav-overview{margin-left:10px}.sidebar-nav li:hover{color:#fc6423}.sidebar-overview-active .sidebar-nav-overview,.sidebar-toc-active .sidebar-nav-toc{border-bottom-color:#fc6423;color:#fc6423}.sidebar-overview-active .sidebar-nav-overview:hover,.sidebar-toc-active .sidebar-nav-toc:hover{color:#fc6423}.sidebar-panel-container{flex:1;overflow-x:hidden;overflow-y:auto}.sidebar-panel{display:none}.sidebar-overview-active .site-overview-wrap{display:flex;flex-direction:column;justify-content:center}.sidebar-toc-active .post-toc-wrap{display:block}.sidebar-toggle{bottom:45px;height:12px;padding:6px 5px;width:14px;background:#222;cursor:pointer;opacity:.6;position:fixed;z-index:30;right:30px}@media (max-width:991px){.sidebar-toggle{right:20px}}.sidebar-toggle:hover{opacity:.8}@media (max-width:991px){.sidebar-toggle{opacity:.8}}.sidebar-toggle:hover .toggle-line{background:#fc6423}@media (any-hover:hover){body:not(.sidebar-active) .sidebar-toggle:hover .toggle-line:first-child{left:50%;top:2px;transform:rotate(45deg);width:50%}body:not(.sidebar-active) .sidebar-toggle:hover .toggle-line:last-child{left:50%;top:-2px;transform:rotate(-45deg);width:50%}}.sidebar-active .sidebar-toggle .toggle-line:nth-child(2){opacity:0}.sidebar-active .sidebar-toggle .toggle-line:first-child{top:5px;transform:rotate(45deg)}.sidebar-active .sidebar-toggle .toggle-line:last-child{top:-5px;transform:rotate(-45deg)}.post-toc{font-size:.875em}.post-toc ol{list-style:none;margin:0;padding:0 2px 5px 10px;text-align:left}.post-toc ol>ol{padding-left:0}.post-toc ol a{transition:all .2s ease-in-out}.post-toc .nav-item{line-height:1.8;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.post-toc .nav .nav-child{display:none}.post-toc .nav .active>.nav-child{display:block}.post-toc .nav .active-current>.nav-child{display:block}.post-toc .nav .active-current>.nav-child>.nav-item{display:block}.post-toc .nav .active>a{border-bottom-color:#fc6423;color:#fc6423}.post-toc .nav .active-current>a{color:#fc6423}.post-toc .nav .active-current>a:hover{color:#fc6423}.site-state{display:flex;flex-wrap:wrap;justify-content:center;line-height:1.4}.site-state-item{padding:0 15px}.site-state-item a{border-bottom:0;display:block}.site-state-item-count{display:block;font-size:1em;font-weight:600}.site-state-item-name{color:#999;font-size:.8125em}.footer{color:#999;font-size:.875em;padding:20px 0}.footer.footer-fixed{bottom:0;left:0;position:absolute;right:0}.footer-inner{box-sizing:border-box;text-align:center;display:flex;flex-direction:column;justify-content:center;margin:0 auto;width:calc(100% - 20px)}@media (min-width:1200px){.footer-inner{width:1160px}}@media (min-width:1600px){.footer-inner{width:73%}}.use-motion .footer{opacity:0}.languages{display:inline-block;font-size:1.125em;position:relative}.languages .lang-select-label span{margin:0 .5em}.languages .lang-select{height:100%;left:0;opacity:0;position:absolute;top:0;width:100%}.with-love{color:red;display:inline-block;margin:0 5px}.beian img{display:inline-block;margin:0 3px;vertical-align:middle}.busuanzi-count #busuanzi_container_site_uv{display:none}.busuanzi-count #busuanzi_container_site_pv{display:none}@-moz-keyframes icon-animate{0%,100%{transform:scale(1)}10%,30%{transform:scale(.9)}20%,40%,60%,80%{transform:scale(1.1)}50%,70%{transform:scale(1.1)}}@-webkit-keyframes icon-animate{0%,100%{transform:scale(1)}10%,30%{transform:scale(.9)}20%,40%,60%,80%{transform:scale(1.1)}50%,70%{transform:scale(1.1)}}@-o-keyframes icon-animate{0%,100%{transform:scale(1)}10%,30%{transform:scale(.9)}20%,40%,60%,80%{transform:scale(1.1)}50%,70%{transform:scale(1.1)}}@keyframes icon-animate{0%,100%{transform:scale(1)}10%,30%{transform:scale(.9)}20%,40%,60%,80%{transform:scale(1.1)}50%,70%{transform:scale(1.1)}}@media (max-width:567px){.main-inner{padding:initial!important}.posts-expand .post-header{margin-bottom:10px!important}.post-block{margin-top:initial!important;padding:8px 18px 8px!important}.post-body h1,.post-body h2,.post-body h3,.post-body h4,.post-body h5,.post-body h6{margin:20px 0 8px}.post-body .note h1,.post-body .note h2,.post-body .note h3,.post-body .note h4,.post-body .note h5,.post-body .note h6,.post-body .tabs .tab-content .tab-pane h1,.post-body .tabs .tab-content .tab-pane h2,.post-body .tabs .tab-content .tab-pane h3,.post-body .tabs .tab-content .tab-pane h4,.post-body .tabs .tab-content .tab-pane h5,.post-body .tabs .tab-content .tab-pane h6{margin:0 5px}.post-body>p{margin:0 0 10px}.post-body .note>p,.post-body .tabs .tab-content .tab-pane>p{padding:0 5px}.post-body img,.post-body video{margin-bottom:10px!important}.post-body .note{margin-bottom:10px!important;padding:10px!important}.post-body .tabs .tab-content .tab-pane{padding:10px 10px 0!important}.post-eof{margin:40px auto 20px!important}.pagination{margin-top:40px}}.noscript-warning{background-color:#f55;color:#fff;font-family:sans-serif;font-size:1rem;font-weight:700;left:0;position:fixed;text-align:center;top:0;width:100%;z-index:50}.back-to-top{font-size:12px;bottom:-100px;box-sizing:border-box;color:#fff;padding:0 6px;transition:bottom .2s ease-in-out;background:#222;cursor:pointer;opacity:.6;position:fixed;z-index:30;right:30px;width:24px}.back-to-top span{display:none}@media (max-width:991px){.back-to-top{right:20px}}.back-to-top:hover{opacity:.8}@media (max-width:991px){.back-to-top{opacity:.8}}.back-to-top:hover{color:#fc6423}.back-to-top.back-to-top-on{bottom:30px}.rtl.post-body a,.rtl.post-body h1,.rtl.post-body h2,.rtl.post-body h3,.rtl.post-body h4,.rtl.post-body h5,.rtl.post-body h6,.rtl.post-body li,.rtl.post-body ol,.rtl.post-body p,.rtl.post-body ul{direction:rtl;font-family:UKIJ Ekran}.rtl.post-title{font-family:UKIJ Ekran}.post-button{margin-top:40px;text-align:center}.use-motion .comments,.use-motion .pagination,.use-motion .post-block{visibility:hidden}.use-motion .post-header{visibility:hidden}.use-motion .post-body{visibility:hidden}.use-motion .collection-header{visibility:hidden}.posts-collapse .post-content{margin-bottom:35px;margin-left:35px;position:relative}@media (max-width:767px){.posts-collapse .post-content{margin-left:0;margin-right:0}}.posts-collapse .post-content .collection-title{font-size:1.125em;position:relative}.posts-collapse .post-content .collection-title::before{background:#999;border:1px solid #fff;margin-left:-6px;margin-top:-4px;position:absolute;top:50%;border-radius:50%;content:' ';height:10px;width:10px}.posts-collapse .post-content .collection-year{font-size:1.5em;font-weight:700;margin:60px 0;position:relative}.posts-collapse .post-content .collection-year::before{background:#bbb;margin-left:-4px;margin-top:-4px;position:absolute;top:50%;border-radius:50%;content:' ';height:8px;width:8px}.posts-collapse .post-content .collection-header{display:block;margin-left:20px}.posts-collapse .post-content .collection-header small{color:#bbb;margin-left:5px}.posts-collapse .post-content .post-header{border-bottom:1px dashed #ccc;margin:30px 2px 0;padding-left:15px;position:relative;transition:border .2s ease-in-out}.posts-collapse .post-content .post-header::before{background:#bbb;border:1px solid #fff;left:-6px;position:absolute;top:.75em;transition:background .2s ease-in-out;border-radius:50%;content:' ';height:6px;width:6px}.posts-collapse .post-content .post-header:hover{border-bottom-color:#666}.posts-collapse .post-content .post-header:hover::before{background:#222}.posts-collapse .post-content .post-meta-container{display:inline;font-size:.75em;margin-right:10px}.posts-collapse .post-content .post-title{display:inline}.posts-collapse .post-content .post-title a{border-bottom:0;color:var(--link-color)}.posts-collapse .post-content .post-title .fa-external-link-alt{font-size:.875em;margin-left:5px}.posts-collapse .post-content::before{background:#f5f5f5;content:' ';height:100%;margin-left:-2px;position:absolute;top:1.25em;width:4px}.post-body{font-family:Lato,'PingFang SC','Microsoft YaHei',sans-serif;overflow-wrap:break-word}@media (min-width:1200px){.post-body{font-size:1.125em}}@media (min-width:992px){.post-body{text-align:justify}}@media (max-width:991px){.post-body{text-align:justify}}.post-body h1 .header-anchor,.post-body h1 .headerlink,.post-body h2 .header-anchor,.post-body h2 .headerlink,.post-body h3 .header-anchor,.post-body h3 .headerlink,.post-body h4 .header-anchor,.post-body h4 .headerlink,.post-body h5 .header-anchor,.post-body h5 .headerlink,.post-body h6 .header-anchor,.post-body h6 .headerlink{border-bottom-style:none;color:inherit;float:right;font-size:.875em;margin-left:10px;opacity:0}.post-body h1 .header-anchor::before,.post-body h1 .headerlink::before,.post-body h2 .header-anchor::before,.post-body h2 .headerlink::before,.post-body h3 .header-anchor::before,.post-body h3 .headerlink::before,.post-body h4 .header-anchor::before,.post-body h4 .headerlink::before,.post-body h5 .header-anchor::before,.post-body h5 .headerlink::before,.post-body h6 .header-anchor::before,.post-body h6 .headerlink::before{content:'\f0c1';font-family:'Font Awesome 5 Free';font-weight:900}.post-body h1:hover .header-anchor,.post-body h1:hover .headerlink,.post-body h2:hover .header-anchor,.post-body h2:hover .headerlink,.post-body h3:hover .header-anchor,.post-body h3:hover .headerlink,.post-body h4:hover .header-anchor,.post-body h4:hover .headerlink,.post-body h5:hover .header-anchor,.post-body h5:hover .headerlink,.post-body h6:hover .header-anchor,.post-body h6:hover .headerlink{opacity:.5}.post-body h1:hover .header-anchor:hover,.post-body h1:hover .headerlink:hover,.post-body h2:hover .header-anchor:hover,.post-body h2:hover .headerlink:hover,.post-body h3:hover .header-anchor:hover,.post-body h3:hover .headerlink:hover,.post-body h4:hover .header-anchor:hover,.post-body h4:hover .headerlink:hover,.post-body h5:hover .header-anchor:hover,.post-body h5:hover .headerlink:hover,.post-body h6:hover .header-anchor:hover,.post-body h6:hover .headerlink:hover{opacity:1}.post-body .exturl .fa{font-size:.875em;margin-left:4px}.post-body .fancybox+figcaption,.post-body .image-caption,.post-body img+figcaption{color:#999;font-size:.875em;font-weight:700;line-height:1;margin:-15px auto 15px;text-align:center}.post-body embed,.post-body iframe,.post-body img,.post-body video{margin-bottom:20px}.post-body .video-container{height:0;margin-bottom:20px;overflow:hidden;padding-top:75%;position:relative;width:100%}.post-body .video-container embed,.post-body .video-container iframe,.post-body .video-container object{height:100%;left:0;margin:0;position:absolute;top:0;width:100%}.post-gallery{display:flex;min-height:200px}.post-gallery .post-gallery-image{flex:1}.post-gallery .post-gallery-image:not(:first-child){clip-path:polygon(40px 0,100% 0,100% 100%,0 100%);margin-left:-20px}.post-gallery .post-gallery-image:not(:last-child){margin-right:-20px}.post-gallery .post-gallery-image img{height:100%;object-fit:cover;opacity:1;width:100%}.posts-expand .post-gallery{margin-bottom:60px}.posts-collapse .post-gallery{margin:15px 0}.posts-expand .post-header{font-size:1.125em;margin-bottom:60px;text-align:center}.posts-expand .post-title{font-size:1.5em;font-weight:400;margin:initial;overflow-wrap:break-word}.posts-expand .post-title-link{border-bottom:0;color:var(--link-color);display:inline-block;position:relative}.posts-expand .post-title-link::before{background:var(--link-color);bottom:0;content:'';height:2px;left:0;position:absolute;transform:scaleX(0);transition:transform .2s ease-in-out;width:100%}.posts-expand .post-title-link:hover::before{transform:scaleX(1)}.posts-expand .post-title-link .fa-external-link-alt{font-size:.875em;margin-left:5px}.post-sticky-flag{display:inline-block;margin-right:8px;transform:rotate(30deg)}.posts-expand .post-meta-container{color:#999;font-family:Lato,'PingFang SC','Microsoft YaHei',sans-serif;font-size:.75em;margin-top:3px}.posts-expand .post-meta-container .post-description{font-size:.875em;margin-top:2px}.posts-expand .post-meta-container time{border-bottom:1px dashed #999}.post-meta{display:flex;flex-wrap:wrap;justify-content:center}:not(.post-meta-break)+.post-meta-item::before{content:'|';margin:0 .5em}.post-meta-item-icon{margin-right:3px}@media (max-width:991px){.post-meta-item-text{display:none}}.post-meta-break{flex-basis:100%;height:0}#busuanzi_container_page_pv{display:none}.post-nav{border-top:1px solid #eee;display:flex;gap:30px;justify-content:space-between;margin-top:1em;padding:10px 5px 0}.post-nav-item{flex:1}.post-nav-item a{border-bottom:0;display:block;font-size:.875em;line-height:1.6}.post-nav-item a:active{top:2px}.post-nav-item .fa{font-size:.75em}.post-nav-item:first-child .fa{margin-right:5px}.post-nav-item:last-child{text-align:right}.post-nav-item:last-child .fa{margin-left:5px}.post-footer{display:flex;flex-direction:column;justify-content:center}.post-eof{background:#ccc;height:1px;margin:80px auto 60px;width:8%}.post-block:last-of-type .post-eof{display:none}.post-copyright ul{list-style:none;padding:.5em 1em;background:var(--card-bg-color);border-left:3px solid #ff2a2a;margin:1em 0 0}.post-tags{margin-top:40px;text-align:center}.post-tags a{display:inline-block;font-size:.8125em}.post-tags a:not(:last-child){margin-right:10px}.post-widgets{border-top:1px solid #eee;margin-top:15px;text-align:center}.wpac-rating-container{height:20px;line-height:20px;margin-top:10px;padding-top:6px;text-align:center}.social-like{display:flex;font-size:.875em;justify-content:center;text-align:center}.reward-container{margin:1em 0 0;padding:1em 0;text-align:center}.reward-container button{background:0 0;color:#fc6423;cursor:pointer;line-height:2;padding:0 15px;border:2px solid #fc6423;border-radius:2px;outline:0;transition:all .2s ease-in-out;vertical-align:text-top}.reward-container button:hover{background:#fc6423;color:#fff}.post-reward{display:none;padding-top:20px}.post-reward.active{display:block}.post-reward div{display:inline-block}.post-reward div span{display:block}.post-reward img{display:inline-block;margin:.8em 2em 0;max-width:100%;width:180px}@-moz-keyframes next-roll{from{transform:rotateZ(30deg)}to{transform:rotateZ(-30deg)}}@-webkit-keyframes next-roll{from{transform:rotateZ(30deg)}to{transform:rotateZ(-30deg)}}@-o-keyframes next-roll{from{transform:rotateZ(30deg)}to{transform:rotateZ(-30deg)}}@keyframes next-roll{from{transform:rotateZ(30deg)}to{transform:rotateZ(-30deg)}}.category-all-page .category-all-title{text-align:center}.category-all-page .category-all{margin-top:20px}.category-all-page .category-list{list-style:none;margin:0;padding:0}.category-all-page .category-list-item{margin:5px 10px}.category-all-page .category-list-count{color:#bbb}.category-all-page .category-list-count::before{content:' ('}.category-all-page .category-list-count::after{content:') '}.category-all-page .category-list-child{padding-left:10px}.event-list hr{background:#222;margin:20px 0 45px}.event-list hr::after{background:#222;color:#fff;content:'NOW';display:inline-block;font-weight:700;padding:0 5px}.event-list .event{--event-background:#222;--event-foreground:#bbb;--event-title:#fff;background:var(--event-background);padding:15px}.event-list .event .event-summary{border-bottom:0;color:var(--event-title);margin:0;padding:0 0 0 35px;position:relative}.event-list .event .event-summary::before{animation:dot-flash 1s alternate infinite ease-in-out;background:var(--event-title);left:0;margin-top:-6px;position:absolute;top:50%;border-radius:50%;content:' ';height:12px;width:12px}.event-list .event:nth-of-type(odd) .event-summary::before{animation-delay:.5s}.event-list .event:not(:last-child){margin-bottom:20px}.event-list .event .event-relative-time{color:var(--event-foreground);display:inline-block;font-size:12px;font-weight:400;padding-left:12px}.event-list .event .event-details{color:var(--event-foreground);display:block;line-height:18px;padding:6px 0 6px 35px}.event-list .event .event-details::before{color:var(--event-foreground);display:inline-block;margin-right:9px;width:14px;font-family:'Font Awesome 5 Free';font-weight:900}.event-list .event .event-details.event-location::before{content:'\f041'}.event-list .event .event-details.event-duration::before{content:'\f017'}.event-list .event .event-details.event-description::before{content:'\f024'}.event-list .event-past{--event-background:#f5f5f5;--event-foreground:#999;--event-title:#222}@-moz-keyframes dot-flash{from{opacity:1;transform:scale(1)}to{opacity:0;transform:scale(.8)}}@-webkit-keyframes dot-flash{from{opacity:1;transform:scale(1)}to{opacity:0;transform:scale(.8)}}@-o-keyframes dot-flash{from{opacity:1;transform:scale(1)}to{opacity:0;transform:scale(.8)}}@keyframes dot-flash{from{opacity:1;transform:scale(1)}to{opacity:0;transform:scale(.8)}}ul.breadcrumb{font-size:.75em;list-style:none;margin:1em 0;padding:0 2em;text-align:center}ul.breadcrumb li{display:inline}ul.breadcrumb li:not(:first-child)::before{content:'/\00a0';font-weight:400;padding:.5em}ul.breadcrumb li:last-child{font-weight:700}.tag-cloud{text-align:center}.tag-cloud a{display:inline-block;margin:10px}.tag-cloud-0{border-bottom-color:#aaa;color:#aaa}.tag-cloud-1{border-bottom-color:#9a9a9a;color:#9a9a9a}.tag-cloud-2{border-bottom-color:#8b8b8b;color:#8b8b8b}.tag-cloud-3{border-bottom-color:#7c7c7c;color:#7c7c7c}.tag-cloud-4{border-bottom-color:#6c6c6c;color:#6c6c6c}.tag-cloud-5{border-bottom-color:#5d5d5d;color:#5d5d5d}.tag-cloud-6{border-bottom-color:#4e4e4e;color:#4e4e4e}.tag-cloud-7{border-bottom-color:#3e3e3e;color:#3e3e3e}.tag-cloud-8{border-bottom-color:#2f2f2f;color:#2f2f2f}.tag-cloud-9{border-bottom-color:#202020;color:#202020}.tag-cloud-10{border-bottom-color:#111;color:#111}.search-active{overflow:hidden}.search-pop-overlay{background:rgba(0,0,0,0);display:flex;height:100%;left:0;position:fixed;top:0;transition:visibility .4s,background .4s;visibility:hidden;width:100%;z-index:40}.search-active .search-pop-overlay{background:rgba(0,0,0,.3);visibility:visible}.search-popup{background:var(--card-bg-color);border-radius:5px;height:80%;margin:auto;transform:scale(0);transition:transform .4s;width:700px}.search-active .search-popup{transform:scale(1)}@media (max-width:767px){.search-popup{border-radius:0;height:100%;width:100%}}.search-popup .popup-btn-close,.search-popup .search-icon{color:#999;font-size:18px;padding:0 10px}.search-popup .popup-btn-close{cursor:pointer}.search-popup .popup-btn-close:hover .fa{color:#222}.search-popup .search-header{background:#eee;border-top-left-radius:5px;border-top-right-radius:5px;display:flex;padding:5px}.search-popup input.search-input{background:0 0;border:0;outline:0;width:100%}.search-popup input.search-input::-webkit-search-cancel-button{display:none}.search-popup .search-result-container{height:calc(100% - 55px);overflow:auto;padding:5px 25px}.search-popup .search-result-container hr{margin:5px 0 10px}.search-popup .search-result-container hr:first-child{display:none}.search-popup .search-result-list{margin:0 5px;padding:0}.search-popup a.search-result-title{font-weight:700}.search-popup p.search-result{border-bottom:1px dashed #ccc;padding:5px 0}.search-popup .search-input-container{flex-grow:1;padding:2px}.search-popup .no-result{display:flex}.search-popup .search-result-list{width:100%}.search-popup .search-result-icon{color:#ccc;margin:auto}mark.search-keyword{background:0 0;border-bottom:1px dashed #ff2a2a;color:#ff2a2a;font-weight:700}.popular-posts-header{border-bottom:1px solid #eee;font-size:1.125em;margin-bottom:10px;margin-top:60px}.popular-posts{padding:0}.popular-posts .popular-posts-item{margin-left:2em}.popular-posts .popular-posts-item .popular-posts-title{font-size:.875em;font-weight:400;line-height:2.4;margin:0}.use-motion .animated{animation-fill-mode:none;visibility:inherit}.use-motion .sidebar .animated{animation-fill-mode:both}.header-inner{background:var(--content-bg-color);border-radius:initial;box-shadow:initial;width:240px}@media (max-width:991px){.header-inner{border-radius:initial;width:auto}}.main{align-items:stretch;display:flex;justify-content:space-between;margin:0 auto;width:calc(100% - 20px)}@media (min-width:1200px){.main{width:1160px}}@media (min-width:1600px){.main{width:73%}}@media (max-width:991px){.main{display:block;width:auto}}.main-inner{border-radius:initial;box-sizing:border-box;width:calc(100% - 252px)}@media (max-width:991px){.main-inner{border-radius:initial;width:100%}}.footer-inner{padding-left:252px}@media (max-width:991px){.footer-inner{padding-left:0;padding-right:0;width:auto}}.site-brand-container{background:var(--theme-color)}@media (max-width:991px){.site-nav-on .site-brand-container{box-shadow:0 0 16px rgba(0,0,0,.5)}}.site-meta{padding:20px 0}.brand{padding:0}.site-subtitle{margin:10px 10px 0}@media (min-width:768px) and (max-width:991px){.site-nav-right,.site-nav-toggle{display:flex;flex-direction:column;justify-content:center}}.site-nav-right .toggle,.site-nav-toggle .toggle{color:#fff}.site-nav-right .toggle .toggle-line,.site-nav-toggle .toggle .toggle-line{background:#fff}@media (min-width:768px) and (max-width:991px){.site-nav{--scroll-height:0;height:0;overflow:hidden;transition:height .2s ease-in-out}body:not(.site-nav-on) .site-nav .animated{animation:none}body.site-nav-on .site-nav{height:var(--scroll-height)}}.menu .menu-item{display:block;margin:0}.menu .menu-item a{padding:5px 20px;position:relative;text-align:left;transition-property:background-color}@media (max-width:991px){.menu .menu-item.menu-item-search{display:none}}.menu .menu-item .badge{background:#ccc;border-radius:10px;color:var(--content-bg-color);float:right;padding:2px 5px;text-shadow:1px 1px 0 rgba(0,0,0,.1)}.main-menu .menu-item-active::after{background:#bbb;border-radius:50%;content:' ';height:6px;margin-top:-3px;position:absolute;right:15px;top:50%;width:6px}.sub-menu{margin:0;padding:6px 0}.sub-menu .menu-item{display:inline-block}.sub-menu .menu-item a{background:0 0;margin:5px 10px;padding:initial}.sub-menu .menu-item a:hover{background:0 0;color:#fc6423}.sub-menu .menu-item-active{border-bottom-color:#fc6423;color:#fc6423}.sub-menu .menu-item-active:hover{border-bottom-color:#fc6423}.sidebar{margin-top:12px;position:-webkit-sticky;position:sticky;top:12px;width:240px}@media (max-width:991px){.sidebar{display:none}}.sidebar-toggle{display:none}.sidebar-inner{background:var(--content-bg-color);border-radius:initial;box-shadow:initial;box-sizing:border-box;color:var(--text-color)}.site-state-item{padding:0 10px}.sidebar .sidebar-button{border-bottom:1px dotted #ccc;border-top:1px dotted #ccc}.sidebar .sidebar-button button{border:0;color:#fc6423;display:block;width:100%}.sidebar .sidebar-button button:hover{background:0 0;border:0;color:#e34603}.links-of-author{display:flex;flex-wrap:wrap;justify-content:center}.links-of-author-item{margin:5px 0 0;width:50%}.links-of-author-item a{box-sizing:border-box;display:inline-block;max-width:100%;overflow:hidden;padding:0 5px;text-overflow:ellipsis;white-space:nowrap}.links-of-author-item a{border-bottom:0;border-radius:4px;display:block}.links-of-author-item a:hover{background:var(--body-bg-color)}.main-inner{background:var(--content-bg-color);box-shadow:initial;padding:40px}@media (max-width:991px){.main-inner{padding:20px}}.sub-menu{border-bottom:1px solid #ddd}.post-block:first-of-type{padding-top:40px}@media (max-width:767px){.pagination{margin-bottom:10px}} \ No newline at end of file +:root{--body-bg-color:#f5f7f9;--content-bg-color:#fff;--card-bg-color:#f5f5f5;--text-color:#555;--blockquote-color:#666;--link-color:#555;--link-hover-color:#222;--brand-color:#fff;--brand-hover-color:#fff;--table-row-odd-bg-color:#f9f9f9;--table-row-hover-bg-color:#f5f5f5;--menu-item-bg-color:#f5f5f5;--theme-color:#222;--btn-default-bg:#fff;--btn-default-color:#555;--btn-default-border-color:#555;--btn-default-hover-bg:#222;--btn-default-hover-color:#fff;--btn-default-hover-border-color:#222;--highlight-background:#f3f3f3;--highlight-foreground:#444;--highlight-gutter-background:#e1e1e1;--highlight-gutter-foreground:#555;color-scheme:light}html{line-height:1.15;-webkit-text-size-adjust:100%}body{margin:0}main{display:block}h1{font-size:2em;margin:.67em 0}hr{box-sizing:content-box;height:0;overflow:visible}pre{font-family:monospace,monospace;font-size:1em}a{background:0 0}abbr[title]{border-bottom:none;text-decoration:underline;text-decoration:underline dotted}b,strong{font-weight:bolder}code,kbd,samp{font-family:monospace,monospace;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}img{border-style:none}button,input,optgroup,select,textarea{font-family:inherit;font-size:100%;line-height:1.15;margin:0}button,input{overflow:visible}button,select{text-transform:none}[type=button],[type=reset],[type=submit],button{-webkit-appearance:button}[type=button]::-moz-focus-inner,[type=reset]::-moz-focus-inner,[type=submit]::-moz-focus-inner,button::-moz-focus-inner{border-style:none;padding:0}[type=button]:-moz-focusring,[type=reset]:-moz-focusring,[type=submit]:-moz-focusring,button:-moz-focusring{outline:1px dotted ButtonText}fieldset{padding:.35em .75em .625em}legend{box-sizing:border-box;color:inherit;display:table;max-width:100%;padding:0;white-space:normal}progress{vertical-align:baseline}textarea{overflow:auto}[type=checkbox],[type=radio]{box-sizing:border-box;padding:0}[type=number]::-webkit-inner-spin-button,[type=number]::-webkit-outer-spin-button{height:auto}[type=search]{outline-offset:-2px;-webkit-appearance:textfield}[type=search]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{font:inherit;-webkit-appearance:button}details{display:block}summary{display:list-item}template{display:none}[hidden]{display:none}::selection{background:#262a30;color:#eee}body,html{height:100%}body{background:var(--body-bg-color);box-sizing:border-box;color:var(--text-color);font-family:Lato,'PingFang SC','Microsoft YaHei',sans-serif;font-size:1.2em;line-height:2;min-height:100%;position:relative;transition:padding .2s ease-in-out}h1,h2,h3,h4,h5,h6{font-family:Lato,'PingFang SC','Microsoft YaHei',sans-serif;font-weight:700;line-height:1.5;margin:30px 0 15px}h1{font-size:1.5em}h2{font-size:1.375em}h3{font-size:1.25em}h4{font-size:1.125em}h5{font-size:1em}h6{font-size:.875em}p{margin:0 0 20px}a{border-bottom:1px solid #999;color:var(--link-color);cursor:pointer;outline:0;text-decoration:none;overflow-wrap:break-word}a:hover{border-bottom-color:var(--link-hover-color);color:var(--link-hover-color)}embed,iframe,img,video{display:block;margin-left:auto;margin-right:auto;max-width:100%}hr{background-image:repeating-linear-gradient(-45deg,#ddd,#ddd 4px,transparent 4px,transparent 8px);border:0;height:3px;margin:40px 0}blockquote{border-left:4px solid #ddd;color:var(--blockquote-color);margin:0;padding:0 15px}blockquote cite::before{content:'-';padding:0 5px}dt{font-weight:700}dd{margin:0;padding:0}.table-container{overflow:auto}table{border-collapse:collapse;border-spacing:0;font-size:.875em;margin:0 0 20px;width:100%}tbody tr:nth-of-type(odd){background:var(--table-row-odd-bg-color)}tbody tr:hover{background:var(--table-row-hover-bg-color)}caption,td,th{padding:8px}td,th{border:1px solid #ddd;border-bottom:3px solid #ddd}th{font-weight:700;padding-bottom:10px}td{border-bottom-width:1px}.btn{background:var(--btn-default-bg);border:2px solid var(--btn-default-border-color);border-radius:2px;color:var(--btn-default-color);display:inline-block;font-size:.875em;line-height:2;padding:0 20px;transition:background-color .2s ease-in-out}.btn:hover{background:var(--btn-default-hover-bg);border-color:var(--btn-default-hover-border-color);color:var(--btn-default-hover-color)}.btn+.btn{margin:0 0 8px 8px}.btn .fa-fw{text-align:left;width:1.285714285714286em}.toggle{line-height:0}.toggle .toggle-line{background:#fff;display:block;height:2px;left:0;position:relative;top:0;transition:all .4s;width:100%}.toggle .toggle-line:not(:first-child){margin-top:3px}.toggle.toggle-arrow .toggle-line:first-child{left:50%;top:2px;transform:rotate(45deg);width:50%}.toggle.toggle-arrow .toggle-line:last-child{left:50%;top:-2px;transform:rotate(-45deg);width:50%}.toggle.toggle-close .toggle-line:nth-child(2){opacity:0}.toggle.toggle-close .toggle-line:first-child{top:5px;transform:rotate(45deg)}.toggle.toggle-close .toggle-line:last-child{top:-5px;transform:rotate(-45deg)}code[class*=language-],pre[class*=language-]{color:#000;background:0 0;text-shadow:0 1px #fff;font-family:Consolas,Monaco,'Andale Mono','Ubuntu Mono',monospace;font-size:1em;text-align:left;white-space:pre;word-spacing:normal;word-break:normal;word-wrap:normal;line-height:1.5;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-hyphens:none;-moz-hyphens:none;-ms-hyphens:none;hyphens:none}code[class*=language-] ::-moz-selection,code[class*=language-]::-moz-selection,pre[class*=language-] ::-moz-selection,pre[class*=language-]::-moz-selection{text-shadow:none;background:#b3d4fc}code[class*=language-] ::selection,code[class*=language-]::selection,pre[class*=language-] ::selection,pre[class*=language-]::selection{text-shadow:none;background:#b3d4fc}@media print{code[class*=language-],pre[class*=language-]{text-shadow:none}}pre[class*=language-]{padding:1em;margin:.5em 0;overflow:auto}:not(pre)>code[class*=language-],pre[class*=language-]{background:#f5f2f0}:not(pre)>code[class*=language-]{padding:.1em;border-radius:.3em;white-space:normal}.token.cdata,.token.comment,.token.doctype,.token.prolog{color:#708090}.token.punctuation{color:#999}.token.namespace{opacity:.7}.token.boolean,.token.constant,.token.deleted,.token.number,.token.property,.token.symbol,.token.tag{color:#905}.token.attr-name,.token.builtin,.token.char,.token.inserted,.token.selector,.token.string{color:#690}.language-css .token.string,.style .token.string,.token.entity,.token.operator,.token.url{color:#9a6e3a;background:hsla(0,0%,100%,.5)}.token.atrule,.token.attr-value,.token.keyword{color:#07a}.token.class-name,.token.function{color:#dd4a68}.token.important,.token.regex,.token.variable{color:#e90}.token.bold,.token.important{font-weight:700}.token.italic{font-style:italic}.token.entity{cursor:help}pre[class*=language-].line-numbers{position:relative;padding-left:3.8em;counter-reset:linenumber}pre[class*=language-].line-numbers>code{position:relative;white-space:inherit}.line-numbers .line-numbers-rows{position:absolute;pointer-events:none;top:0;font-size:100%;left:-3.8em;width:3em;letter-spacing:-1px;border-right:1px solid #999;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.line-numbers-rows>span{display:block;counter-increment:linenumber}.line-numbers-rows>span:before{content:counter(linenumber);color:#999;display:block;padding-right:.8em;text-align:right}.highlight:hover .copy-btn,pre:hover .copy-btn{opacity:1}figure.highlight .table-container{position:relative}.copy-btn{color:#333;cursor:pointer;line-height:1.6;opacity:0;padding:2px 6px;position:absolute;transition:opacity .2s ease-in-out;color:var(--highlight-foreground);font-size:14px;right:0;top:2px}figure.highlight{border-radius:5px;box-shadow:0 10px 30px 0 rgba(0,0,0,.4);padding-top:30px}figure.highlight .table-container{border-radius:0 0 5px 5px}figure.highlight::before{background:#fc625d;box-shadow:20px 0 #fdbc40,40px 0 #35cd4b;left:12px;margin-top:-20px;position:absolute;border-radius:50%;content:' ';height:12px;width:12px}code,figure.highlight,kbd,pre{background:var(--highlight-background);color:var(--highlight-foreground)}figure.highlight,pre{line-height:1.6;margin:0 auto 20px}figure.highlight figcaption,pre .caption,pre figcaption{background:var(--highlight-gutter-background);color:var(--highlight-foreground);display:flow-root;font-size:.875em;line-height:1.2;padding:.5em}figure.highlight figcaption a,pre .caption a,pre figcaption a{color:var(--highlight-foreground);float:right}figure.highlight figcaption a:hover,pre .caption a:hover,pre figcaption a:hover{border-bottom-color:var(--highlight-foreground)}code,pre{font-family:consolas,Menlo,monospace,'PingFang SC','Microsoft YaHei'}code{border-radius:3px;font-size:.875em;padding:2px 4px;overflow-wrap:break-word}kbd{border:2px solid #ccc;border-radius:.2em;box-shadow:.1em .1em .2em rgba(0,0,0,.1);font-family:inherit;padding:.1em .3em;white-space:nowrap}figure.highlight{position:relative}figure.highlight pre{border:0;margin:0;padding:10px 0}figure.highlight table{border:0;margin:0;width:auto}figure.highlight td{border:0;padding:0}figure.highlight .gutter{-moz-user-select:none;-ms-user-select:none;-webkit-user-select:none;user-select:none}figure.highlight .gutter pre{background:var(--highlight-gutter-background);color:var(--highlight-gutter-foreground);padding-left:10px;padding-right:10px;text-align:right}figure.highlight .code pre{padding-left:10px;width:100%}figure.highlight .marked{background:rgba(0,0,0,.3)}pre .caption,pre figcaption{margin-bottom:10px}.gist table{width:auto}.gist table td{border:0}pre{overflow:auto;padding:10px;position:relative}pre code{background:0 0;padding:0;text-shadow:none}.blockquote-center{border-left:0;margin:40px 0;padding:0;position:relative;text-align:center}.blockquote-center::after,.blockquote-center::before{left:0;line-height:1;opacity:.6;position:absolute;width:100%}.blockquote-center::before{border-top:1px solid #ccc;text-align:left;top:-20px;content:'\f10d';font-family:'Font Awesome 5 Free';font-weight:900}.blockquote-center::after{border-bottom:1px solid #ccc;bottom:-20px;text-align:right;content:'\f10e';font-family:'Font Awesome 5 Free';font-weight:900}.blockquote-center div,.blockquote-center p{text-align:center}.group-picture{margin-bottom:20px}.group-picture .group-picture-row{display:flex;gap:3px;margin-bottom:3px}.group-picture .group-picture-column{flex:1}.group-picture .group-picture-column img{height:100%;margin:0;object-fit:cover;width:100%}.post-body .label{color:#555;padding:0 2px}.post-body .label.default{background:#f0f0f0}.post-body .label.primary{background:#efe6f7}.post-body .label.info{background:#e5f2f8}.post-body .label.success{background:#e7f4e9}.post-body .label.warning{background:#fcf6e1}.post-body .label.danger{background:#fae8eb}.post-body .link-grid{display:grid;grid-gap:1.5rem;gap:1.5rem;grid-template-columns:1fr 1fr;margin-bottom:20px;padding:1rem}@media (max-width:767px){.post-body .link-grid{grid-template-columns:1fr}}.post-body .link-grid .link-grid-container{border:solid #ddd;box-shadow:1rem 1rem .5rem rgba(0,0,0,.5);min-height:5rem;min-width:0;padding:.5rem;position:relative;transition:background .3s}.post-body .link-grid .link-grid-container:hover{animation:next-shake .5s;background:var(--card-bg-color)}.post-body .link-grid .link-grid-container:active{box-shadow:.5rem .5rem .25rem rgba(0,0,0,.5);transform:translate(.2rem,.2rem)}.post-body .link-grid .link-grid-container .link-grid-image{border:1px solid #ddd;border-radius:50%;box-sizing:border-box;height:5rem;padding:3px;position:absolute;width:5rem}.post-body .link-grid .link-grid-container p{margin:0 1rem 0 6rem}.post-body .link-grid .link-grid-container p:first-of-type{font-size:1.2em}.post-body .link-grid .link-grid-container p:last-of-type{font-size:.8em;line-height:1.3rem;opacity:.7}.post-body .link-grid .link-grid-container a{border:0;height:100%;left:0;position:absolute;top:0;width:100%}@-moz-keyframes next-shake{0%{transform:translate(1pt,1pt) rotate(0)}10%{transform:translate(-1pt,-2pt) rotate(-1deg)}20%{transform:translate(-3pt,0) rotate(1deg)}30%{transform:translate(3pt,2pt) rotate(0)}40%{transform:translate(1pt,-1pt) rotate(1deg)}50%{transform:translate(-1pt,2pt) rotate(-1deg)}60%{transform:translate(-3pt,1pt) rotate(0)}70%{transform:translate(3pt,1pt) rotate(-1deg)}80%{transform:translate(-1pt,-1pt) rotate(1deg)}90%{transform:translate(1pt,2pt) rotate(0)}100%{transform:translate(1pt,-2pt) rotate(-1deg)}}@-webkit-keyframes next-shake{0%{transform:translate(1pt,1pt) rotate(0)}10%{transform:translate(-1pt,-2pt) rotate(-1deg)}20%{transform:translate(-3pt,0) rotate(1deg)}30%{transform:translate(3pt,2pt) rotate(0)}40%{transform:translate(1pt,-1pt) rotate(1deg)}50%{transform:translate(-1pt,2pt) rotate(-1deg)}60%{transform:translate(-3pt,1pt) rotate(0)}70%{transform:translate(3pt,1pt) rotate(-1deg)}80%{transform:translate(-1pt,-1pt) rotate(1deg)}90%{transform:translate(1pt,2pt) rotate(0)}100%{transform:translate(1pt,-2pt) rotate(-1deg)}}@-o-keyframes next-shake{0%{transform:translate(1pt,1pt) rotate(0)}10%{transform:translate(-1pt,-2pt) rotate(-1deg)}20%{transform:translate(-3pt,0) rotate(1deg)}30%{transform:translate(3pt,2pt) rotate(0)}40%{transform:translate(1pt,-1pt) rotate(1deg)}50%{transform:translate(-1pt,2pt) rotate(-1deg)}60%{transform:translate(-3pt,1pt) rotate(0)}70%{transform:translate(3pt,1pt) rotate(-1deg)}80%{transform:translate(-1pt,-1pt) rotate(1deg)}90%{transform:translate(1pt,2pt) rotate(0)}100%{transform:translate(1pt,-2pt) rotate(-1deg)}}@keyframes next-shake{0%{transform:translate(1pt,1pt) rotate(0)}10%{transform:translate(-1pt,-2pt) rotate(-1deg)}20%{transform:translate(-3pt,0) rotate(1deg)}30%{transform:translate(3pt,2pt) rotate(0)}40%{transform:translate(1pt,-1pt) rotate(1deg)}50%{transform:translate(-1pt,2pt) rotate(-1deg)}60%{transform:translate(-3pt,1pt) rotate(0)}70%{transform:translate(3pt,1pt) rotate(-1deg)}80%{transform:translate(-1pt,-1pt) rotate(1deg)}90%{transform:translate(1pt,2pt) rotate(0)}100%{transform:translate(1pt,-2pt) rotate(-1deg)}}.post-body .note{border-radius:3px;margin-bottom:20px;padding:1em;position:relative;border:1px solid #eee;border-left-width:5px}.post-body .note summary{cursor:pointer;outline:0}.post-body .note summary p{display:inline}.post-body .note h2,.post-body .note h3,.post-body .note h4,.post-body .note h5,.post-body .note h6{border-bottom:initial;margin:0;padding-top:0}.post-body .note blockquote:first-child,.post-body .note img:first-child,.post-body .note ol:first-child,.post-body .note p:first-child,.post-body .note pre:first-child,.post-body .note table:first-child,.post-body .note ul:first-child{margin-top:0}.post-body .note blockquote:last-child,.post-body .note img:last-child,.post-body .note ol:last-child,.post-body .note p:last-child,.post-body .note pre:last-child,.post-body .note table:last-child,.post-body .note ul:last-child{margin-bottom:0}.post-body .note.default{border-left-color:#777}.post-body .note.default h2,.post-body .note.default h3,.post-body .note.default h4,.post-body .note.default h5,.post-body .note.default h6{color:#777}.post-body .note.primary{border-left-color:#6f42c1}.post-body .note.primary h2,.post-body .note.primary h3,.post-body .note.primary h4,.post-body .note.primary h5,.post-body .note.primary h6{color:#6f42c1}.post-body .note.info{border-left-color:#428bca}.post-body .note.info h2,.post-body .note.info h3,.post-body .note.info h4,.post-body .note.info h5,.post-body .note.info h6{color:#428bca}.post-body .note.success{border-left-color:#5cb85c}.post-body .note.success h2,.post-body .note.success h3,.post-body .note.success h4,.post-body .note.success h5,.post-body .note.success h6{color:#5cb85c}.post-body .note.warning{border-left-color:#f0ad4e}.post-body .note.warning h2,.post-body .note.warning h3,.post-body .note.warning h4,.post-body .note.warning h5,.post-body .note.warning h6{color:#f0ad4e}.post-body .note.danger{border-left-color:#d9534f}.post-body .note.danger h2,.post-body .note.danger h3,.post-body .note.danger h4,.post-body .note.danger h5,.post-body .note.danger h6{color:#d9534f}.post-body .tabs{margin-bottom:20px}.post-body .tabs,.tabs-comment{padding-top:10px}.post-body .tabs ul.nav-tabs,.tabs-comment ul.nav-tabs{background:var(--content-bg-color);display:flex;display:flex;flex-wrap:wrap;justify-content:center;margin:0;padding:0;position:-webkit-sticky;position:sticky;top:0;z-index:5}@media (max-width:413px){.post-body .tabs ul.nav-tabs,.tabs-comment ul.nav-tabs{display:block;margin-bottom:5px}}.post-body .tabs ul.nav-tabs li.tab,.tabs-comment ul.nav-tabs li.tab{border-bottom:1px solid #ddd;border-left:1px solid transparent;border-right:1px solid transparent;border-radius:0 0 0 0;border-top:3px solid transparent;flex-grow:1;list-style-type:none}@media (max-width:413px){.post-body .tabs ul.nav-tabs li.tab,.tabs-comment ul.nav-tabs li.tab{border-bottom:1px solid transparent;border-left:3px solid transparent;border-right:1px solid transparent;border-top:1px solid transparent}}@media (max-width:413px){.post-body .tabs ul.nav-tabs li.tab,.tabs-comment ul.nav-tabs li.tab{border-radius:0}}.post-body .tabs ul.nav-tabs li.tab a,.tabs-comment ul.nav-tabs li.tab a{border-bottom:initial;display:block;line-height:1.8;padding:.25em .75em;text-align:center;transition:all .2s ease-out}.post-body .tabs ul.nav-tabs li.tab a i,.tabs-comment ul.nav-tabs li.tab a i{width:1.285714285714286em}.post-body .tabs ul.nav-tabs li.tab.active,.tabs-comment ul.nav-tabs li.tab.active{border-bottom-color:transparent;border-left-color:#ddd;border-right-color:#ddd;border-top-color:#fc6423}@media (max-width:413px){.post-body .tabs ul.nav-tabs li.tab.active,.tabs-comment ul.nav-tabs li.tab.active{border-bottom-color:#ddd;border-left-color:#fc6423;border-right-color:#ddd;border-top-color:#ddd}}.post-body .tabs ul.nav-tabs li.tab.active a,.tabs-comment ul.nav-tabs li.tab.active a{cursor:default}.post-body .tabs .tab-content,.tabs-comment .tab-content{border:1px solid #ddd;border-radius:0 0 0 0;border-top-color:transparent}@media (max-width:413px){.post-body .tabs .tab-content,.tabs-comment .tab-content{border-radius:0;border-top-color:#ddd}}.post-body .tabs .tab-content .tab-pane,.tabs-comment .tab-content .tab-pane{padding:20px 20px 0}.post-body .tabs .tab-content .tab-pane:not(.active),.tabs-comment .tab-content .tab-pane:not(.active){display:none}.pagination .next,.pagination .page-number,.pagination .prev,.pagination .space{display:inline-block;margin:-1px 10px 0;padding:0 10px}@media (max-width:767px){.pagination .next,.pagination .page-number,.pagination .prev,.pagination .space{margin:0 5px}}.pagination .page-number.current{background:#ccc;border-color:#ccc;color:var(--content-bg-color)}.pagination{border-top:1px solid #eee;margin:120px 0 0;text-align:center}.pagination .next,.pagination .page-number,.pagination .prev{border-bottom:0;border-top:1px solid #eee;transition:border-color .2s ease-in-out}.pagination .next:hover,.pagination .page-number:hover,.pagination .prev:hover{border-top-color:var(--link-hover-color)}@media (max-width:767px){.pagination{border-top:0}.pagination .next,.pagination .page-number,.pagination .prev{border-bottom:1px solid #eee;border-top:0}.pagination .next:hover,.pagination .page-number:hover,.pagination .prev:hover{border-bottom-color:var(--link-hover-color)}}.pagination .space{margin:0;padding:0}.comments{margin-top:60px;overflow:hidden}.comment-button-group{display:flex;display:flex;flex-wrap:wrap;justify-content:center;justify-content:center;margin:1em 0}.comment-button-group .comment-button{margin:.1em .2em}.comment-button-group .comment-button.active{background:var(--btn-default-hover-bg);border-color:var(--btn-default-hover-border-color);color:var(--btn-default-hover-color)}.comment-position{display:none}.comment-position.active{display:block}.tabs-comment{margin-top:4em;padding-top:0}.tabs-comment .comments{margin-top:0;padding-top:0}.headband{background:var(--theme-color);height:3px}@media (max-width:991px){.headband{display:none}}header.header{background:0 0}.header-inner{margin:0 auto;width:calc(100% - 20px)}@media (min-width:1200px){.header-inner{width:1360px}}@media (min-width:1600px){.header-inner{width:79%}}.site-brand-container{display:flex;flex-shrink:0;padding:0 10px}.use-motion .site-brand-container .toggle,.use-motion header.header{opacity:0}.site-meta{flex-grow:1;text-align:center}@media (max-width:767px){.site-meta{text-align:center}}.custom-logo-image{margin-top:20px}@media (max-width:991px){.custom-logo-image{display:none}}.brand{border-bottom:0;color:var(--brand-color);display:inline-block;padding:0 40px}.brand:hover{color:var(--brand-hover-color)}.site-title{font-family:Lato,'PingFang SC','Microsoft YaHei',sans-serif;font-size:1.375em;font-weight:400;line-height:1.5;margin:0}.site-subtitle{color:#ddd;font-size:.8125em;margin:10px 0}.use-motion .custom-logo-image,.use-motion .site-subtitle,.use-motion .site-title{opacity:0;position:relative;top:-10px}.site-nav-right,.site-nav-toggle{display:none}@media (max-width:767px){.site-nav-right,.site-nav-toggle{display:flex;flex-direction:column;justify-content:center}}.site-nav-right .toggle,.site-nav-toggle .toggle{color:var(--text-color);padding:10px;width:22px}.site-nav-right .toggle .toggle-line,.site-nav-toggle .toggle .toggle-line{background:var(--text-color);border-radius:1px}@media (max-width:767px){.site-nav{--scroll-height:0;height:0;overflow:hidden;transition:height .2s ease-in-out}body:not(.site-nav-on) .site-nav .animated{animation:none}body.site-nav-on .site-nav{height:var(--scroll-height)}}.menu{margin:0;padding:1em 0;text-align:center}.menu-item{display:inline-block;list-style:none;margin:0 10px}@media (max-width:767px){.menu-item{display:block;margin-top:10px}.menu-item.menu-item-search{display:none}}.menu-item a{border-bottom:0;display:block;font-size:.8125em;transition:border-color .2s ease-in-out}.menu-item a.menu-item-active,.menu-item a:hover{background:var(--menu-item-bg-color)}.menu-item .fa,.menu-item .fab,.menu-item .far,.menu-item .fas{margin-right:8px}.menu-item .badge{display:inline-block;font-weight:700;line-height:1;margin-left:.35em;margin-top:.35em;text-align:center;white-space:nowrap}@media (max-width:767px){.menu-item .badge{float:right;margin-left:0}}.use-motion .menu-item{visibility:hidden}.github-corner :hover .octo-arm{animation:octocat-wave 560ms ease-in-out}.github-corner svg{color:#fff;fill:var(--theme-color);position:absolute;right:0;top:0;z-index:5}@media (max-width:991px){.github-corner{display:none}.github-corner svg{color:var(--theme-color);fill:#fff}.github-corner .github-corner:hover .octo-arm{animation:none}.github-corner .github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}@-moz-keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@-webkit-keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@-o-keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}.sidebar-inner{color:#999;max-height:calc(100vh - 24px);padding:18px 10px;text-align:center;display:flex;flex-direction:column;justify-content:center}.site-overview-item:not(:first-child){margin-top:10px}.cc-license .cc-opacity{border-bottom:0;opacity:.7}.cc-license .cc-opacity:hover{opacity:.9}.cc-license img{display:inline-block}.site-author-image{border:1px solid #eee;max-width:120px;padding:2px}.site-author-name{color:var(--text-color);font-weight:600;margin:0}.site-description{color:#999;font-size:.8125em;margin-top:0}.links-of-author a{font-size:.8125em}.links-of-author .fa,.links-of-author .fab,.links-of-author .far,.links-of-author .fas{margin-right:2px}.sidebar .sidebar-button:not(:first-child){margin-top:15px}.sidebar .sidebar-button button{background:0 0;color:#fc6423;cursor:pointer;line-height:2;padding:0 15px;border:1px solid #fc6423;border-radius:4px}.sidebar .sidebar-button button:hover{background:#fc6423;color:#fff}.sidebar .sidebar-button button .fa,.sidebar .sidebar-button button .fab,.sidebar .sidebar-button button .far,.sidebar .sidebar-button button .fas{margin-right:5px}.links-of-blogroll{font-size:.8125em}.links-of-blogroll-title{font-size:.875em;font-weight:600;margin-top:0}.links-of-blogroll-list{list-style:none;margin:0;padding:0}.sidebar-dimmer{display:none}@media (max-width:991px){.sidebar-dimmer{background:#000;display:block;height:100%;left:0;opacity:0;position:fixed;top:0;transition:visibility .4s,opacity .4s;visibility:hidden;width:100%;z-index:10}.sidebar-active .sidebar-dimmer{opacity:.7;visibility:visible}}.sidebar-nav{display:none;margin:0;padding-bottom:20px;padding-left:0}.sidebar-nav-active .sidebar-nav{display:block}.sidebar-nav li{border-bottom:1px solid transparent;color:var(--text-color);cursor:pointer;display:inline-block;font-size:.875em}.sidebar-nav li.sidebar-nav-overview{margin-left:10px}.sidebar-nav li:hover{color:#fc6423}.sidebar-overview-active .sidebar-nav-overview,.sidebar-toc-active .sidebar-nav-toc{border-bottom-color:#fc6423;color:#fc6423}.sidebar-overview-active .sidebar-nav-overview:hover,.sidebar-toc-active .sidebar-nav-toc:hover{color:#fc6423}.sidebar-panel-container{flex:1;overflow-x:hidden;overflow-y:auto}.sidebar-panel{display:none}.sidebar-overview-active .site-overview-wrap{display:flex;flex-direction:column;justify-content:center}.sidebar-toc-active .post-toc-wrap{display:block}.sidebar-toggle{bottom:45px;height:12px;padding:6px 5px;width:14px;background:#222;cursor:pointer;opacity:.6;position:fixed;z-index:30;right:30px}@media (max-width:991px){.sidebar-toggle{right:20px}}.sidebar-toggle:hover{opacity:.8}@media (max-width:991px){.sidebar-toggle{opacity:.8}}.sidebar-toggle:hover .toggle-line{background:#fc6423}@media (any-hover:hover){body:not(.sidebar-active) .sidebar-toggle:hover .toggle-line:first-child{left:50%;top:2px;transform:rotate(45deg);width:50%}body:not(.sidebar-active) .sidebar-toggle:hover .toggle-line:last-child{left:50%;top:-2px;transform:rotate(-45deg);width:50%}}.sidebar-active .sidebar-toggle .toggle-line:nth-child(2){opacity:0}.sidebar-active .sidebar-toggle .toggle-line:first-child{top:5px;transform:rotate(45deg)}.sidebar-active .sidebar-toggle .toggle-line:last-child{top:-5px;transform:rotate(-45deg)}.post-toc{font-size:.875em}.post-toc ol{list-style:none;margin:0;padding:0 2px 5px 10px;text-align:left}.post-toc ol>ol{padding-left:0}.post-toc ol a{transition:all .2s ease-in-out}.post-toc .nav-item{line-height:1.8;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.post-toc .nav .nav-child{display:none}.post-toc .nav .active>.nav-child{display:block}.post-toc .nav .active-current>.nav-child{display:block}.post-toc .nav .active-current>.nav-child>.nav-item{display:block}.post-toc .nav .active>a{border-bottom-color:#fc6423;color:#fc6423}.post-toc .nav .active-current>a{color:#fc6423}.post-toc .nav .active-current>a:hover{color:#fc6423}.site-state{display:flex;flex-wrap:wrap;justify-content:center;line-height:1.4}.site-state-item{padding:0 15px}.site-state-item a{border-bottom:0;display:block}.site-state-item-count{display:block;font-size:1em;font-weight:600}.site-state-item-name{color:#999;font-size:.8125em}.footer{color:#999;font-size:.875em;padding:20px 0}.footer.footer-fixed{bottom:0;left:0;position:absolute;right:0}.footer-inner{box-sizing:border-box;text-align:center;display:flex;flex-direction:column;justify-content:center;margin:0 auto;width:calc(100% - 20px)}@media (min-width:1200px){.footer-inner{width:1360px}}@media (min-width:1600px){.footer-inner{width:79%}}.use-motion .footer{opacity:0}.languages{display:inline-block;font-size:1.125em;position:relative}.languages .lang-select-label span{margin:0 .5em}.languages .lang-select{height:100%;left:0;opacity:0;position:absolute;top:0;width:100%}.with-love{color:red;display:inline-block;margin:0 5px}.beian img{display:inline-block;margin:0 3px;vertical-align:middle}.busuanzi-count #busuanzi_container_site_uv{display:none}.busuanzi-count #busuanzi_container_site_pv{display:none}@-moz-keyframes icon-animate{0%,100%{transform:scale(1)}10%,30%{transform:scale(.9)}20%,40%,60%,80%{transform:scale(1.1)}50%,70%{transform:scale(1.1)}}@-webkit-keyframes icon-animate{0%,100%{transform:scale(1)}10%,30%{transform:scale(.9)}20%,40%,60%,80%{transform:scale(1.1)}50%,70%{transform:scale(1.1)}}@-o-keyframes icon-animate{0%,100%{transform:scale(1)}10%,30%{transform:scale(.9)}20%,40%,60%,80%{transform:scale(1.1)}50%,70%{transform:scale(1.1)}}@keyframes icon-animate{0%,100%{transform:scale(1)}10%,30%{transform:scale(.9)}20%,40%,60%,80%{transform:scale(1.1)}50%,70%{transform:scale(1.1)}}@media (max-width:567px){.main-inner{padding:initial!important}.posts-expand .post-header{margin-bottom:10px!important}.post-block{margin-top:initial!important;padding:8px 18px 8px!important}.post-body h1,.post-body h2,.post-body h3,.post-body h4,.post-body h5,.post-body h6{margin:20px 0 8px}.post-body .note h1,.post-body .note h2,.post-body .note h3,.post-body .note h4,.post-body .note h5,.post-body .note h6,.post-body .tabs .tab-content .tab-pane h1,.post-body .tabs .tab-content .tab-pane h2,.post-body .tabs .tab-content .tab-pane h3,.post-body .tabs .tab-content .tab-pane h4,.post-body .tabs .tab-content .tab-pane h5,.post-body .tabs .tab-content .tab-pane h6{margin:0 5px}.post-body>p{margin:0 0 10px}.post-body .note>p,.post-body .tabs .tab-content .tab-pane>p{padding:0 5px}.post-body img,.post-body video{margin-bottom:10px!important}.post-body .note{margin-bottom:10px!important;padding:10px!important}.post-body .tabs .tab-content .tab-pane{padding:10px 10px 0!important}.post-eof{margin:40px auto 20px!important}.pagination{margin-top:40px}}.noscript-warning{background-color:#f55;color:#fff;font-family:sans-serif;font-size:1rem;font-weight:700;left:0;position:fixed;text-align:center;top:0;width:100%;z-index:50}.back-to-top{font-size:12px;bottom:-100px;box-sizing:border-box;color:#fff;padding:0 6px;transition:bottom .2s ease-in-out;background:#222;cursor:pointer;opacity:.6;position:fixed;z-index:30;right:30px;width:24px}.back-to-top span{display:none}@media (max-width:991px){.back-to-top{right:20px}}.back-to-top:hover{opacity:.8}@media (max-width:991px){.back-to-top{opacity:.8}}.back-to-top:hover{color:#fc6423}.back-to-top.back-to-top-on{bottom:30px}.rtl.post-body a,.rtl.post-body h1,.rtl.post-body h2,.rtl.post-body h3,.rtl.post-body h4,.rtl.post-body h5,.rtl.post-body h6,.rtl.post-body li,.rtl.post-body ol,.rtl.post-body p,.rtl.post-body ul{direction:rtl;font-family:UKIJ Ekran}.rtl.post-title{font-family:UKIJ Ekran}.post-button{margin-top:40px;text-align:center}.use-motion .comments,.use-motion .pagination,.use-motion .post-block{visibility:hidden}.use-motion .post-header{visibility:hidden}.use-motion .post-body{visibility:hidden}.use-motion .collection-header{visibility:hidden}.posts-collapse .post-content{margin-bottom:35px;margin-left:35px;position:relative}@media (max-width:767px){.posts-collapse .post-content{margin-left:0;margin-right:0}}.posts-collapse .post-content .collection-title{font-size:1.125em;position:relative}.posts-collapse .post-content .collection-title::before{background:#999;border:1px solid #fff;margin-left:-6px;margin-top:-4px;position:absolute;top:50%;border-radius:50%;content:' ';height:10px;width:10px}.posts-collapse .post-content .collection-year{font-size:1.5em;font-weight:700;margin:60px 0;position:relative}.posts-collapse .post-content .collection-year::before{background:#bbb;margin-left:-4px;margin-top:-4px;position:absolute;top:50%;border-radius:50%;content:' ';height:8px;width:8px}.posts-collapse .post-content .collection-header{display:block;margin-left:20px}.posts-collapse .post-content .collection-header small{color:#bbb;margin-left:5px}.posts-collapse .post-content .post-header{border-bottom:1px dashed #ccc;margin:30px 2px 0;padding-left:15px;position:relative;transition:border .2s ease-in-out}.posts-collapse .post-content .post-header::before{background:#bbb;border:1px solid #fff;left:-6px;position:absolute;top:.75em;transition:background .2s ease-in-out;border-radius:50%;content:' ';height:6px;width:6px}.posts-collapse .post-content .post-header:hover{border-bottom-color:#666}.posts-collapse .post-content .post-header:hover::before{background:#222}.posts-collapse .post-content .post-meta-container{display:inline;font-size:.75em;margin-right:10px}.posts-collapse .post-content .post-title{display:inline}.posts-collapse .post-content .post-title a{border-bottom:0;color:var(--link-color)}.posts-collapse .post-content .post-title .fa-external-link-alt{font-size:.875em;margin-left:5px}.posts-collapse .post-content::before{background:#f5f5f5;content:' ';height:100%;margin-left:-2px;position:absolute;top:1.25em;width:4px}.post-body{font-family:Lato,'PingFang SC','Microsoft YaHei',sans-serif;overflow-wrap:break-word}@media (min-width:1200px){.post-body{font-size:1.125em}}@media (min-width:992px){.post-body{text-align:justify}}@media (max-width:991px){.post-body{text-align:justify}}.post-body h1 .header-anchor,.post-body h1 .headerlink,.post-body h2 .header-anchor,.post-body h2 .headerlink,.post-body h3 .header-anchor,.post-body h3 .headerlink,.post-body h4 .header-anchor,.post-body h4 .headerlink,.post-body h5 .header-anchor,.post-body h5 .headerlink,.post-body h6 .header-anchor,.post-body h6 .headerlink{border-bottom-style:none;color:inherit;float:right;font-size:.875em;margin-left:10px;opacity:0}.post-body h1 .header-anchor::before,.post-body h1 .headerlink::before,.post-body h2 .header-anchor::before,.post-body h2 .headerlink::before,.post-body h3 .header-anchor::before,.post-body h3 .headerlink::before,.post-body h4 .header-anchor::before,.post-body h4 .headerlink::before,.post-body h5 .header-anchor::before,.post-body h5 .headerlink::before,.post-body h6 .header-anchor::before,.post-body h6 .headerlink::before{content:'\f0c1';font-family:'Font Awesome 5 Free';font-weight:900}.post-body h1:hover .header-anchor,.post-body h1:hover .headerlink,.post-body h2:hover .header-anchor,.post-body h2:hover .headerlink,.post-body h3:hover .header-anchor,.post-body h3:hover .headerlink,.post-body h4:hover .header-anchor,.post-body h4:hover .headerlink,.post-body h5:hover .header-anchor,.post-body h5:hover .headerlink,.post-body h6:hover .header-anchor,.post-body h6:hover .headerlink{opacity:.5}.post-body h1:hover .header-anchor:hover,.post-body h1:hover .headerlink:hover,.post-body h2:hover .header-anchor:hover,.post-body h2:hover .headerlink:hover,.post-body h3:hover .header-anchor:hover,.post-body h3:hover .headerlink:hover,.post-body h4:hover .header-anchor:hover,.post-body h4:hover .headerlink:hover,.post-body h5:hover .header-anchor:hover,.post-body h5:hover .headerlink:hover,.post-body h6:hover .header-anchor:hover,.post-body h6:hover .headerlink:hover{opacity:1}.post-body .exturl .fa{font-size:.875em;margin-left:4px}.post-body .fancybox+figcaption,.post-body .image-caption,.post-body img+figcaption{color:#999;font-size:.875em;font-weight:700;line-height:1;margin:-15px auto 15px;text-align:center}.post-body embed,.post-body iframe,.post-body img,.post-body video{margin-bottom:20px}.post-body .video-container{height:0;margin-bottom:20px;overflow:hidden;padding-top:75%;position:relative;width:100%}.post-body .video-container embed,.post-body .video-container iframe,.post-body .video-container object{height:100%;left:0;margin:0;position:absolute;top:0;width:100%}.post-gallery{display:flex;min-height:200px}.post-gallery .post-gallery-image{flex:1}.post-gallery .post-gallery-image:not(:first-child){clip-path:polygon(40px 0,100% 0,100% 100%,0 100%);margin-left:-20px}.post-gallery .post-gallery-image:not(:last-child){margin-right:-20px}.post-gallery .post-gallery-image img{height:100%;object-fit:cover;opacity:1;width:100%}.posts-expand .post-gallery{margin-bottom:60px}.posts-collapse .post-gallery{margin:15px 0}.posts-expand .post-header{font-size:1.125em;margin-bottom:60px;text-align:center}.posts-expand .post-title{font-size:1.5em;font-weight:400;margin:initial;overflow-wrap:break-word}.posts-expand .post-title-link{border-bottom:0;color:var(--link-color);display:inline-block;position:relative}.posts-expand .post-title-link::before{background:var(--link-color);bottom:0;content:'';height:2px;left:0;position:absolute;transform:scaleX(0);transition:transform .2s ease-in-out;width:100%}.posts-expand .post-title-link:hover::before{transform:scaleX(1)}.posts-expand .post-title-link .fa-external-link-alt{font-size:.875em;margin-left:5px}.post-sticky-flag{display:inline-block;margin-right:8px;transform:rotate(30deg)}.posts-expand .post-meta-container{color:#999;font-family:Lato,'PingFang SC','Microsoft YaHei',sans-serif;font-size:.75em;margin-top:3px}.posts-expand .post-meta-container .post-description{font-size:.875em;margin-top:2px}.posts-expand .post-meta-container time{border-bottom:1px dashed #999}.post-meta{display:flex;flex-wrap:wrap;justify-content:center}:not(.post-meta-break)+.post-meta-item::before{content:'|';margin:0 .5em}.post-meta-item-icon{margin-right:3px}@media (max-width:991px){.post-meta-item-text{display:none}}.post-meta-break{flex-basis:100%;height:0}#busuanzi_container_page_pv{display:none}.post-nav{border-top:1px solid #eee;display:flex;gap:30px;justify-content:space-between;margin-top:1em;padding:10px 5px 0}.post-nav-item{flex:1}.post-nav-item a{border-bottom:0;display:block;font-size:.875em;line-height:1.6}.post-nav-item a:active{top:2px}.post-nav-item .fa{font-size:.75em}.post-nav-item:first-child .fa{margin-right:5px}.post-nav-item:last-child{text-align:right}.post-nav-item:last-child .fa{margin-left:5px}.post-footer{display:flex;flex-direction:column;justify-content:center}.post-eof{background:#ccc;height:1px;margin:80px auto 60px;width:8%}.post-block:last-of-type .post-eof{display:none}.post-copyright ul{list-style:none;padding:.5em 1em;background:var(--card-bg-color);border-left:3px solid #ff2a2a;margin:1em 0 0}.post-tags{margin-top:40px;text-align:center}.post-tags a{display:inline-block;font-size:.8125em}.post-tags a:not(:last-child){margin-right:10px}.post-widgets{border-top:1px solid #eee;margin-top:15px;text-align:center}.wpac-rating-container{height:20px;line-height:20px;margin-top:10px;padding-top:6px;text-align:center}.social-like{display:flex;font-size:.875em;justify-content:center;text-align:center}.reward-container{margin:1em 0 0;padding:1em 0;text-align:center}.reward-container button{background:0 0;color:#fc6423;cursor:pointer;line-height:2;padding:0 15px;border:2px solid #fc6423;border-radius:2px;outline:0;transition:all .2s ease-in-out;vertical-align:text-top}.reward-container button:hover{background:#fc6423;color:#fff}.post-reward{display:none;padding-top:20px}.post-reward.active{display:block}.post-reward div{display:inline-block}.post-reward div span{display:block}.post-reward img{display:inline-block;margin:.8em 2em 0;max-width:100%;width:180px}@-moz-keyframes next-roll{from{transform:rotateZ(30deg)}to{transform:rotateZ(-30deg)}}@-webkit-keyframes next-roll{from{transform:rotateZ(30deg)}to{transform:rotateZ(-30deg)}}@-o-keyframes next-roll{from{transform:rotateZ(30deg)}to{transform:rotateZ(-30deg)}}@keyframes next-roll{from{transform:rotateZ(30deg)}to{transform:rotateZ(-30deg)}}.category-all-page .category-all-title{text-align:center}.category-all-page .category-all{margin-top:20px}.category-all-page .category-list{list-style:none;margin:0;padding:0}.category-all-page .category-list-item{margin:5px 10px}.category-all-page .category-list-count{color:#bbb}.category-all-page .category-list-count::before{content:' ('}.category-all-page .category-list-count::after{content:') '}.category-all-page .category-list-child{padding-left:10px}.event-list hr{background:#222;margin:20px 0 45px}.event-list hr::after{background:#222;color:#fff;content:'NOW';display:inline-block;font-weight:700;padding:0 5px}.event-list .event{--event-background:#222;--event-foreground:#bbb;--event-title:#fff;background:var(--event-background);padding:15px}.event-list .event .event-summary{border-bottom:0;color:var(--event-title);margin:0;padding:0 0 0 35px;position:relative}.event-list .event .event-summary::before{animation:dot-flash 1s alternate infinite ease-in-out;background:var(--event-title);left:0;margin-top:-6px;position:absolute;top:50%;border-radius:50%;content:' ';height:12px;width:12px}.event-list .event:nth-of-type(odd) .event-summary::before{animation-delay:.5s}.event-list .event:not(:last-child){margin-bottom:20px}.event-list .event .event-relative-time{color:var(--event-foreground);display:inline-block;font-size:12px;font-weight:400;padding-left:12px}.event-list .event .event-details{color:var(--event-foreground);display:block;line-height:18px;padding:6px 0 6px 35px}.event-list .event .event-details::before{color:var(--event-foreground);display:inline-block;margin-right:9px;width:14px;font-family:'Font Awesome 5 Free';font-weight:900}.event-list .event .event-details.event-location::before{content:'\f041'}.event-list .event .event-details.event-duration::before{content:'\f017'}.event-list .event .event-details.event-description::before{content:'\f024'}.event-list .event-past{--event-background:#f5f5f5;--event-foreground:#999;--event-title:#222}@-moz-keyframes dot-flash{from{opacity:1;transform:scale(1)}to{opacity:0;transform:scale(.8)}}@-webkit-keyframes dot-flash{from{opacity:1;transform:scale(1)}to{opacity:0;transform:scale(.8)}}@-o-keyframes dot-flash{from{opacity:1;transform:scale(1)}to{opacity:0;transform:scale(.8)}}@keyframes dot-flash{from{opacity:1;transform:scale(1)}to{opacity:0;transform:scale(.8)}}ul.breadcrumb{font-size:.75em;list-style:none;margin:1em 0;padding:0 2em;text-align:center}ul.breadcrumb li{display:inline}ul.breadcrumb li:not(:first-child)::before{content:'/\00a0';font-weight:400;padding:.5em}ul.breadcrumb li:last-child{font-weight:700}.tag-cloud{text-align:center}.tag-cloud a{display:inline-block;margin:10px}.tag-cloud-0{border-bottom-color:#aaa;color:#aaa}.tag-cloud-1{border-bottom-color:#9a9a9a;color:#9a9a9a}.tag-cloud-2{border-bottom-color:#8b8b8b;color:#8b8b8b}.tag-cloud-3{border-bottom-color:#7c7c7c;color:#7c7c7c}.tag-cloud-4{border-bottom-color:#6c6c6c;color:#6c6c6c}.tag-cloud-5{border-bottom-color:#5d5d5d;color:#5d5d5d}.tag-cloud-6{border-bottom-color:#4e4e4e;color:#4e4e4e}.tag-cloud-7{border-bottom-color:#3e3e3e;color:#3e3e3e}.tag-cloud-8{border-bottom-color:#2f2f2f;color:#2f2f2f}.tag-cloud-9{border-bottom-color:#202020;color:#202020}.tag-cloud-10{border-bottom-color:#111;color:#111}.search-active{overflow:hidden}.search-pop-overlay{background:rgba(0,0,0,0);display:flex;height:100%;left:0;position:fixed;top:0;transition:visibility .4s,background .4s;visibility:hidden;width:100%;z-index:40}.search-active .search-pop-overlay{background:rgba(0,0,0,.3);visibility:visible}.search-popup{background:var(--card-bg-color);border-radius:5px;height:80%;margin:auto;transform:scale(0);transition:transform .4s;width:700px}.search-active .search-popup{transform:scale(1)}@media (max-width:767px){.search-popup{border-radius:0;height:100%;width:100%}}.search-popup .popup-btn-close,.search-popup .search-icon{color:#999;font-size:18px;padding:0 10px}.search-popup .popup-btn-close{cursor:pointer}.search-popup .popup-btn-close:hover .fa{color:#222}.search-popup .search-header{background:#eee;border-top-left-radius:5px;border-top-right-radius:5px;display:flex;padding:5px}.search-popup input.search-input{background:0 0;border:0;outline:0;width:100%}.search-popup input.search-input::-webkit-search-cancel-button{display:none}.search-popup .search-result-container{height:calc(100% - 55px);overflow:auto;padding:5px 25px}.search-popup .search-result-container hr{margin:5px 0 10px}.search-popup .search-result-container hr:first-child{display:none}.search-popup .search-result-list{margin:0 5px;padding:0}.search-popup a.search-result-title{font-weight:700}.search-popup p.search-result{border-bottom:1px dashed #ccc;padding:5px 0}.search-popup .search-input-container{flex-grow:1;padding:2px}.search-popup .no-result{display:flex}.search-popup .search-result-list{width:100%}.search-popup .search-result-icon{color:#ccc;margin:auto}mark.search-keyword{background:0 0;border-bottom:1px dashed #ff2a2a;color:#ff2a2a;font-weight:700}.popular-posts-header{border-bottom:1px solid #eee;font-size:1.125em;margin-bottom:10px;margin-top:60px}.popular-posts{padding:0}.popular-posts .popular-posts-item{margin-left:2em}.popular-posts .popular-posts-item .popular-posts-title{font-size:.875em;font-weight:400;line-height:2.4;margin:0}.use-motion .animated{animation-fill-mode:none;visibility:inherit}.use-motion .sidebar .animated{animation-fill-mode:both}.header-inner{background:var(--content-bg-color);border-radius:initial;box-shadow:initial;width:240px}@media (max-width:991px){.header-inner{border-radius:initial;width:auto}}.main{align-items:stretch;display:flex;justify-content:space-between;margin:0 auto;width:calc(100% - 20px)}@media (min-width:1200px){.main{width:1360px}}@media (min-width:1600px){.main{width:79%}}@media (max-width:991px){.main{display:block;width:auto}}.main-inner{border-radius:initial;box-sizing:border-box;width:calc(100% - 252px)}@media (max-width:991px){.main-inner{border-radius:initial;width:100%}}.footer-inner{padding-left:252px}@media (max-width:991px){.footer-inner{padding-left:0;padding-right:0;width:auto}}.site-brand-container{background:var(--theme-color)}@media (max-width:991px){.site-nav-on .site-brand-container{box-shadow:0 0 16px rgba(0,0,0,.5)}}.site-meta{padding:20px 0}.brand{padding:0}.site-subtitle{margin:10px 10px 0}@media (min-width:768px) and (max-width:991px){.site-nav-right,.site-nav-toggle{display:flex;flex-direction:column;justify-content:center}}.site-nav-right .toggle,.site-nav-toggle .toggle{color:#fff}.site-nav-right .toggle .toggle-line,.site-nav-toggle .toggle .toggle-line{background:#fff}@media (min-width:768px) and (max-width:991px){.site-nav{--scroll-height:0;height:0;overflow:hidden;transition:height .2s ease-in-out}body:not(.site-nav-on) .site-nav .animated{animation:none}body.site-nav-on .site-nav{height:var(--scroll-height)}}.menu .menu-item{display:block;margin:0}.menu .menu-item a{padding:5px 20px;position:relative;text-align:left;transition-property:background-color}@media (max-width:991px){.menu .menu-item.menu-item-search{display:none}}.menu .menu-item .badge{background:#ccc;border-radius:10px;color:var(--content-bg-color);float:right;padding:2px 5px;text-shadow:1px 1px 0 rgba(0,0,0,.1)}.main-menu .menu-item-active::after{background:#bbb;border-radius:50%;content:' ';height:6px;margin-top:-3px;position:absolute;right:15px;top:50%;width:6px}.sub-menu{margin:0;padding:6px 0}.sub-menu .menu-item{display:inline-block}.sub-menu .menu-item a{background:0 0;margin:5px 10px;padding:initial}.sub-menu .menu-item a:hover{background:0 0;color:#fc6423}.sub-menu .menu-item-active{border-bottom-color:#fc6423;color:#fc6423}.sub-menu .menu-item-active:hover{border-bottom-color:#fc6423}.sidebar{margin-top:12px;position:-webkit-sticky;position:sticky;top:12px;width:240px}@media (max-width:991px){.sidebar{display:none}}.sidebar-toggle{display:none}.sidebar-inner{background:var(--content-bg-color);border-radius:initial;box-shadow:initial;box-sizing:border-box;color:var(--text-color)}.site-state-item{padding:0 10px}.sidebar .sidebar-button{border-bottom:1px dotted #ccc;border-top:1px dotted #ccc}.sidebar .sidebar-button button{border:0;color:#fc6423;display:block;width:100%}.sidebar .sidebar-button button:hover{background:0 0;border:0;color:#e34603}.links-of-author{display:flex;flex-wrap:wrap;justify-content:center}.links-of-author-item{margin:5px 0 0;width:50%}.links-of-author-item a{box-sizing:border-box;display:inline-block;max-width:100%;overflow:hidden;padding:0 5px;text-overflow:ellipsis;white-space:nowrap}.links-of-author-item a{border-bottom:0;border-radius:4px;display:block}.links-of-author-item a:hover{background:var(--body-bg-color)}.main-inner{background:var(--content-bg-color);box-shadow:initial;padding:40px}@media (max-width:991px){.main-inner{padding:20px}}.sub-menu{border-bottom:1px solid #ddd}.post-block:first-of-type{padding-top:40px}@media (max-width:767px){.pagination{margin-bottom:10px}} \ No newline at end of file diff --git a/leancloud_counter_security_urls.json b/leancloud_counter_security_urls.json index 03c42d2ce8..0887235a8c 100644 --- a/leancloud_counter_security_urls.json +++ b/leancloud_counter_security_urls.json @@ -1 +1 @@ -[{"title":"村上春树《1Q84》读后感","url":"/2019/12/18/1Q84读后感/"},{"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":"AQS篇一","url":"/2021/02/14/AQS篇一/"},{"title":"34_Search_for_a_Range","url":"/2016/08/14/34-Search-for-a-Range/"},{"title":"2019年终总结","url":"/2020/02/01/2019年终总结/"},{"title":"AQS篇二 之 Condition 浅析笔记","url":"/2021/02/21/AQS-之-Condition-浅析笔记/"},{"title":"add-two-number","url":"/2015/04/14/Add-Two-Number/"},{"title":"Apollo 客户端启动过程分析","url":"/2022/09/18/Apollo-客户端启动过程分析/"},{"title":"Comparator使用小记","url":"/2020/04/05/Comparator使用小记/"},{"title":"Apollo 如何获取当前环境","url":"/2022/09/04/Apollo-如何获取当前环境/"},{"title":"Clone Graph Part I","url":"/2014/12/30/Clone-Graph-Part-I/"},{"title":"AbstractQueuedSynchronizer","url":"/2019/09/23/AbstractQueuedSynchronizer/"},{"title":"Apollo 的 value 注解是怎么自动更新的","url":"/2020/11/01/Apollo-的-value-注解是怎么自动更新的/"},{"title":"Disruptor 系列二","url":"/2022/02/27/Disruptor-系列二/"},{"title":"Disruptor 系列一","url":"/2022/02/13/Disruptor-系列一/"},{"title":"G1收集器概述","url":"/2020/02/09/G1收集器概述/"},{"title":"Filter, Interceptor, Aop, 啥, 啥, 啥? 这些都是啥?","url":"/2020/08/22/Filter-Intercepter-Aop-啥-啥-啥-这些都是啥/"},{"title":"Dubbo 使用的几个记忆点","url":"/2022/04/02/Dubbo-使用的几个记忆点/"},{"title":"Leetcode 021 合并两个有序链表 ( Merge Two Sorted Lists ) 题解分析","url":"/2021/10/07/Leetcode-021-合并两个有序链表-Merge-Two-Sorted-Lists-题解分析/"},{"title":"Leetcode 053 最大子序和 ( Maximum Subarray ) 题解分析","url":"/2021/11/28/Leetcode-053-最大子序和-Maximum-Subarray-题解分析/"},{"title":"JVM源码分析之G1垃圾收集器分析一","url":"/2019/12/07/JVM-G1-Part-1/"},{"title":"Leetcode 104 二叉树的最大深度(Maximum Depth of Binary Tree) 题解分析","url":"/2020/10/25/Leetcode-104-二叉树的最大深度-Maximum-Depth-of-Binary-Tree-题解分析/"},{"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 105 从前序与中序遍历序列构造二叉树(Construct Binary Tree from Preorder and Inorder Traversal) 题解分析","url":"/2020/12/13/Leetcode-105-从前序与中序遍历序列构造二叉树-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal-题解分析/"},{"title":"Disruptor 系列三","url":"/2022/09/25/Disruptor-系列三/"},{"title":"Leetcode 028 实现 strStr() ( Implement strStr() ) 题解分析","url":"/2021/10/31/Leetcode-028-实现-strStr-Implement-strStr-题解分析/"},{"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 1862 向下取整数对和 ( Sum of Floored Pairs *Hard* ) 题解分析","url":"/2022/09/11/Leetcode-1862-向下取整数对和-Sum-of-Floored-Pairs-Hard-题解分析/"},{"title":"Leetcode 2 Add Two Numbers 题解分析","url":"/2020/10/11/Leetcode-2-Add-Two-Numbers-题解分析/"},{"title":"Leetcode 1260 二维网格迁移 ( Shift 2D Grid *Easy* ) 题解分析","url":"/2022/07/22/Leetcode-1260-二维网格迁移-Shift-2D-Grid-Easy-题解分析/"},{"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 234 回文链表(Palindrome Linked List) 题解分析","url":"/2020/11/15/Leetcode-234-回文联表-Palindrome-Linked-List-题解分析/"},{"title":"Leetcode 278 第一个错误的版本 ( First Bad Version *Easy* ) 题解分析","url":"/2022/08/14/Leetcode-278-第一个错误的版本-First-Bad-Version-Easy-题解分析/"},{"title":"Leetcode 349 两个数组的交集 ( Intersection of Two Arrays *Easy* ) 题解分析","url":"/2022/03/07/Leetcode-349-两个数组的交集-Intersection-of-Two-Arrays-Easy-题解分析/"},{"title":"Leetcode 3 Longest Substring Without Repeating Characters 题解分析","url":"/2020/09/20/Leetcode-3-Longest-Substring-Without-Repeating-Characters-题解分析/"},{"title":"Leetcode 160 相交链表(intersection-of-two-linked-lists) 题解分析","url":"/2021/01/10/Leetcode-160-相交链表-intersection-of-two-linked-lists-题解分析/"},{"title":"Leetcode 4 寻找两个正序数组的中位数 ( Median of Two Sorted Arrays *Hard* ) 题解分析","url":"/2022/03/27/Leetcode-4-寻找两个正序数组的中位数-Median-of-Two-Sorted-Arrays-Hard-题解分析/"},{"title":"Leetcode 48 旋转图像(Rotate Image) 题解分析","url":"/2021/05/01/Leetcode-48-旋转图像-Rotate-Image-题解分析/"},{"title":"Leetcode 42 接雨水 (Trapping Rain Water) 题解分析","url":"/2021/07/04/Leetcode-42-接雨水-Trapping-Rain-Water-题解分析/"},{"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 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":"Leetcode 83 删除排序链表中的重复元素 ( Remove Duplicates from Sorted List *Easy* ) 题解分析","url":"/2022/03/13/Leetcode-83-删除排序链表中的重复元素-Remove-Duplicates-from-Sorted-List-Easy-题解分析/"},{"title":"MFC 模态对话框","url":"/2014/12/24/MFC 模态对话框/"},{"title":"Maven实用小技巧","url":"/2020/02/16/Maven实用小技巧/"},{"title":"Path Sum","url":"/2015/01/04/Path-Sum/"},{"title":"Linux 下 grep 命令的一点小技巧","url":"/2020/08/06/Linux-下-grep-命令的一点小技巧/"},{"title":"Number of 1 Bits","url":"/2015/03/11/Number-Of-1-Bits/"},{"title":"Redis_分布式锁","url":"/2019/12/10/Redis-Part-1/"},{"title":"ambari-summary","url":"/2017/05/09/ambari-summary/"},{"title":"Reverse Integer","url":"/2015/03/13/Reverse-Integer/"},{"title":"two sum","url":"/2015/01/14/Two-Sum/"},{"title":"docker-mysql-cluster","url":"/2016/08/14/docker-mysql-cluster/"},{"title":"binary-watch","url":"/2016/09/29/binary-watch/"},{"title":"Reverse Bits","url":"/2015/03/11/Reverse-Bits/"},{"title":"dubbo 客户端配置的一个重要知识点","url":"/2022/06/11/dubbo-客户端配置的一个重要知识点/"},{"title":"docker比一般多一点的初学者介绍二","url":"/2020/03/15/docker比一般多一点的初学者介绍二/"},{"title":"docker使用中发现的echo命令的一个小技巧及其他","url":"/2020/03/29/echo命令的一个小技巧/"},{"title":"gogs使用webhook部署react单页应用","url":"/2020/02/22/gogs使用webhook部署react单页应用/"},{"title":"minimum-size-subarray-sum-209","url":"/2016/10/11/minimum-size-subarray-sum-209/"},{"title":"docker比一般多一点的初学者介绍三","url":"/2020/03/21/docker比一般多一点的初学者介绍三/"},{"title":"invert-binary-tree","url":"/2015/06/22/invert-binary-tree/"},{"title":"mybatis 的 $ 和 # 是有啥区别","url":"/2020/09/06/mybatis-的-和-是有啥区别/"},{"title":"mybatis 的 foreach 使用的注意点","url":"/2022/07/09/mybatis-的-foreach-使用的注意点/"},{"title":"docker比一般多一点的初学者介绍","url":"/2020/03/08/docker比一般多一点的初学者介绍/"},{"title":"nginx 日志小记","url":"/2022/04/17/nginx-日志小记/"},{"title":"mybatis 的缓存是怎么回事","url":"/2020/10/03/mybatis-的缓存是怎么回事/"},{"title":"C++ 指针使用中的一个小问题","url":"/2014/12/23/my-new-post/"},{"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":"redis 的 rdb 和 COW 介绍","url":"/2021/08/15/redis-的-rdb-和-COW-介绍/"},{"title":"rabbitmq-tips","url":"/2017/04/25/rabbitmq-tips/"},{"title":"redis数据结构介绍-第一部分 SDS,链表,字典","url":"/2019/12/26/redis数据结构介绍/"},{"title":"redis数据结构介绍三-第三部分 整数集合","url":"/2020/01/10/redis数据结构介绍三/"},{"title":"php-abstract-class-and-interface","url":"/2016/11/10/php-abstract-class-and-interface/"},{"title":"redis数据结构介绍二-第二部分 跳表","url":"/2020/01/04/redis数据结构介绍二/"},{"title":"redis数据结构介绍五-第五部分 对象","url":"/2020/01/20/redis数据结构介绍五/"},{"title":"redis数据结构介绍四-第四部分 压缩表","url":"/2020/01/19/redis数据结构介绍四/"},{"title":"redis淘汰策略复习","url":"/2021/08/01/redis淘汰策略复习/"},{"title":"redis系列介绍七-过期策略","url":"/2020/04/12/redis系列介绍七/"},{"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":"redis数据结构介绍六 快表","url":"/2020/01/22/redis数据结构介绍六/"},{"title":"redis过期策略复习","url":"/2021/07/25/redis过期策略复习/"},{"title":"redis系列介绍八-淘汰策略","url":"/2020/04/18/redis系列介绍八/"},{"title":"rust学习笔记-所有权三之切片","url":"/2021/05/16/rust学习笔记-所有权三之切片/"},{"title":"spark-little-tips","url":"/2017/03/28/spark-little-tips/"},{"title":"rust学习笔记-所有权一","url":"/2021/04/18/rust学习笔记/"},{"title":"rust学习笔记-所有权二","url":"/2021/04/18/rust学习笔记-所有权二/"},{"title":"swoole-websocket-test","url":"/2016/07/13/swoole-websocket-test/"},{"title":"wordpress 忘记密码的一种解决方法","url":"/2021/12/05/wordpress-忘记密码的一种解决方法/"},{"title":"spring event 介绍","url":"/2022/01/30/spring-event-介绍/"},{"title":"summary-ranges-228","url":"/2016/10/12/summary-ranges-228/"},{"title":"《垃圾回收算法手册读书》笔记之整理算法","url":"/2021/03/07/《垃圾回收算法手册读书》笔记之整理算法/"},{"title":"《长安的荔枝》读后感","url":"/2022/07/17/《长安的荔枝》读后感/"},{"title":"上次的其他 外行聊国足","url":"/2022/03/06/上次的其他-外行聊国足/"},{"title":"一个 nginx 的简单记忆点","url":"/2022/08/21/一个-nginx-的简单记忆点/"},{"title":"介绍下最近比较实用的端口转发","url":"/2021/11/14/介绍下最近比较实用的端口转发/"},{"title":"从丁仲礼被美国制裁聊点啥","url":"/2020/12/20/从丁仲礼被美国制裁聊点啥/"},{"title":"从清华美院学姐聊聊我们身边的恶人","url":"/2020/11/29/从清华美院学姐聊聊我们身边的恶人/"},{"title":"介绍一下 RocketMQ","url":"/2020/06/21/介绍一下-RocketMQ/"},{"title":"关于公共交通再吐个槽","url":"/2021/03/21/关于公共交通再吐个槽/"},{"title":"分享记录一下一个 git 操作方法","url":"/2022/02/06/分享记录一下一个-git-操作方法/"},{"title":"分享记录一下一个 scp 操作方法","url":"/2022/02/06/分享记录一下一个-scp-操作方法/"},{"title":"周末我在老丈人家打了天小工","url":"/2020/08/16/周末我在老丈人家打了天小工/"},{"title":"关于读书打卡与分享","url":"/2021/02/07/关于读书打卡与分享/"},{"title":"在老丈人家的小工记三","url":"/2020/09/13/在老丈人家的小工记三/"},{"title":"在老丈人家的小工记五","url":"/2020/10/18/在老丈人家的小工记五/"},{"title":"在老丈人家的小工记四","url":"/2020/09/26/在老丈人家的小工记四/"},{"title":"屯菜惊魂记","url":"/2022/04/24/屯菜惊魂记/"},{"title":"寄生虫观后感","url":"/2020/03/01/寄生虫观后感/"},{"title":"我是如何走上跑步这条不归路的","url":"/2020/07/26/我是如何走上跑步这条不归路的/"},{"title":"搬运两个 StackOverflow 上的 Mysql 编码相关的问题解答","url":"/2022/01/16/搬运两个-StackOverflow-上的-Mysql-编码相关的问题解答/"},{"title":"看完了扫黑风暴,聊聊感想","url":"/2021/10/24/看完了扫黑风暴-聊聊感想/"},{"title":"是何原因竟让两人深夜奔袭十公里","url":"/2022/06/05/是何原因竟让两人深夜奔袭十公里/"},{"title":"给小电驴上牌","url":"/2022/03/20/给小电驴上牌/"},{"title":"聊一下 RocketMQ 的消息存储之 MMAP","url":"/2021/09/04/聊一下-RocketMQ-的消息存储/"},{"title":"聊一下 RocketMQ 的 NameServer 源码","url":"/2020/07/05/聊一下-RocketMQ-的-NameServer-源码/"},{"title":"聊一下 RocketMQ 的消息存储四","url":"/2021/10/17/聊一下-RocketMQ-的消息存储四/"},{"title":"聊一下 RocketMQ 的消息存储三","url":"/2021/10/03/聊一下-RocketMQ-的消息存储三/"},{"title":"聊一下 RocketMQ 的消息存储二","url":"/2021/09/12/聊一下-RocketMQ-的消息存储二/"},{"title":"聊一下 RocketMQ 的顺序消息","url":"/2021/08/29/聊一下-RocketMQ-的顺序消息/"},{"title":"聊一下 SpringBoot 设置非 web 应用的方法","url":"/2022/07/31/聊一下-SpringBoot-设置非-web-应用的方法/"},{"title":"聊一下 SpringBoot 中动态切换数据源的方法","url":"/2021/09/26/聊一下-SpringBoot-中动态切换数据源的方法/"},{"title":"聊在东京奥运会闭幕式这天-二","url":"/2021/08/19/聊在东京奥运会闭幕式这天-二/"},{"title":"聊在东京奥运会闭幕式这天","url":"/2021/08/08/聊在东京奥运会闭幕式这天/"},{"title":"聊一下 RocketMQ 的 DefaultMQPushConsumer 源码","url":"/2020/06/26/聊一下-RocketMQ-的-Consumer/"},{"title":"聊聊 Dubbo 的 SPI","url":"/2020/05/31/聊聊-Dubbo-的-SPI/"},{"title":"聊聊 Dubbo 的 SPI 续之自适应拓展","url":"/2020/06/06/聊聊-Dubbo-的-SPI-续之自适应拓展/"},{"title":"聊聊 Java 中绕不开的 Synchronized 关键字-二","url":"/2021/06/27/聊聊-Java-中绕不开的-Synchronized-关键字-二/"},{"title":"聊聊 Dubbo 的容错机制","url":"/2020/11/22/聊聊-Dubbo-的容错机制/"},{"title":"聊一下 SpringBoot 中使用的 cglib 作为动态代理中的一个注意点","url":"/2021/09/19/聊一下-SpringBoot-中使用的-cglib-作为动态代理中的一个注意点/"},{"title":"聊聊 Java 的 equals 和 hashCode 方法","url":"/2021/01/03/聊聊-Java-的-equals-和-hashCode-方法/"},{"title":"聊聊 Java 的类加载机制一","url":"/2020/11/08/聊聊-Java-的类加载机制/"},{"title":"聊聊 Java 的类加载机制二","url":"/2021/06/13/聊聊-Java-的类加载机制二/"},{"title":"聊聊 Java 中绕不开的 Synchronized 关键字","url":"/2021/06/20/聊聊-Java-中绕不开的-Synchronized-关键字/"},{"title":"聊聊 Java 自带的那些*逆天*工具","url":"/2020/08/02/聊聊-Java-自带的那些逆天工具/"},{"title":"聊聊 RocketMQ 的 Broker 源码","url":"/2020/07/19/聊聊-RocketMQ-的-Broker-源码/"},{"title":"聊聊 Linux 下的 top 命令","url":"/2021/03/28/聊聊-Linux-下的-top-命令/"},{"title":"聊聊 Sharding-Jdbc 的简单使用","url":"/2021/12/12/聊聊-Sharding-Jdbc-的简单使用/"},{"title":"聊聊 dubbo 的线程池","url":"/2021/04/04/聊聊-dubbo-的线程池/"},{"title":"聊聊 Sharding-Jdbc 分库分表下的分页方案","url":"/2022/01/09/聊聊-Sharding-Jdbc-分库分表下的分页方案/"},{"title":"聊聊 Sharding-Jdbc 的简单原理初篇","url":"/2021/12/26/聊聊-Sharding-Jdbc-的简单原理初篇/"},{"title":"聊聊 mysql 的 MVCC 续续篇之锁分析","url":"/2020/05/10/聊聊-mysql-的-MVCC-续续篇之加锁分析/"},{"title":"聊聊 mysql 的 MVCC 续篇","url":"/2020/05/02/聊聊-mysql-的-MVCC-续篇/"},{"title":"聊聊 mysql 的 MVCC","url":"/2020/04/26/聊聊-mysql-的-MVCC/"},{"title":"聊聊Java中的单例模式","url":"/2019/12/21/聊聊Java中的单例模式/"},{"title":"聊聊 redis 缓存的应用问题","url":"/2021/01/31/聊聊-redis-缓存的应用问题/"},{"title":"聊聊 mysql 索引的一些细节","url":"/2020/12/27/聊聊-mysql-索引的一些细节/"},{"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":"/2021/04/11/聊聊厦门旅游的好与不好/"},{"title":"聊聊我理解的分布式事务","url":"/2020/05/17/聊聊我理解的分布式事务/"},{"title":"聊聊我刚学会的应用诊断方法","url":"/2020/05/22/聊聊我刚学会的应用诊断方法/"},{"title":"聊聊如何识别和意识到日常生活中的各类危险","url":"/2021/06/06/聊聊如何识别和意识到日常生活中的各类危险/"},{"title":"聊聊我的远程工作体验","url":"/2022/06/26/聊聊我的远程工作体验/"},{"title":"聊聊最近平淡的生活之看《神探狄仁杰》","url":"/2021/12/19/聊聊最近平淡的生活之看《神探狄仁杰》/"},{"title":"聊聊最近平淡的生活之《花束般的恋爱》观后感","url":"/2021/12/31/聊聊最近平淡的生活之《花束般的恋爱》观后感/"},{"title":"聊聊最近平淡的生活之又聊通勤","url":"/2021/11/07/聊聊最近平淡的生活/"},{"title":"聊聊最近平淡的生活之看看老剧","url":"/2021/11/21/聊聊最近平淡的生活之看看老剧/"},{"title":"聊聊给亲戚朋友的老电脑重装系统那些事儿","url":"/2021/05/09/聊聊给亲戚朋友的老电脑重装系统那些事儿/"},{"title":"聊聊那些加塞狗","url":"/2021/01/17/聊聊那些加塞狗/"},{"title":"聊聊这次换车牌及其他","url":"/2022/02/20/聊聊这次换车牌及其他/"},{"title":"记一个容器中 dubbo 注册的小知识点","url":"/2022/10/09/记一个容器中-dubbo-注册的小知识点/"},{"title":"聊聊部分公交车的设计bug","url":"/2021/12/05/聊聊部分公交车的设计bug/"},{"title":"记录下 Java Stream 的一些高效操作","url":"/2022/05/15/记录下-Java-Lambda-的一些高效操作/"},{"title":"记录下 zookeeper 集群迁移和易错点","url":"/2022/05/29/记录下-zookeeper-集群迁移/"},{"title":"这周末我又在老丈人家打了天小工","url":"/2020/08/30/这周末我又在老丈人家打了天小工/"},{"title":"重看了下《蛮荒记》说说感受","url":"/2021/10/10/重看了下《蛮荒记》说说感受/"},{"title":"闲聊下乘公交的用户体验","url":"/2021/02/28/闲聊下乘公交的用户体验/"},{"title":"闲话篇-也算碰到了为老不尊和坏人变老了的典型案例","url":"/2022/05/22/闲话篇-也算碰到了为老不尊和坏人变老了的典型案例/"},{"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":"/2022/01/22/2021-年终总结/"},{"title":"2021 年中总结","url":"/2021/07/18/2021-年中总结/"},{"title":"34_Search_for_a_Range","url":"/2016/08/14/34-Search-for-a-Range/"},{"title":"AQS篇二 之 Condition 浅析笔记","url":"/2021/02/21/AQS-之-Condition-浅析笔记/"},{"title":"AbstractQueuedSynchronizer","url":"/2019/09/23/AbstractQueuedSynchronizer/"},{"title":"AQS篇一","url":"/2021/02/14/AQS篇一/"},{"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":"Clone Graph Part I","url":"/2014/12/30/Clone-Graph-Part-I/"},{"title":"Apollo 的 value 注解是怎么自动更新的","url":"/2020/11/01/Apollo-的-value-注解是怎么自动更新的/"},{"title":"Disruptor 系列一","url":"/2022/02/13/Disruptor-系列一/"},{"title":"Comparator使用小记","url":"/2020/04/05/Comparator使用小记/"},{"title":"Disruptor 系列二","url":"/2022/02/27/Disruptor-系列二/"},{"title":"Dubbo 使用的几个记忆点","url":"/2022/04/02/Dubbo-使用的几个记忆点/"},{"title":"G1收集器概述","url":"/2020/02/09/G1收集器概述/"},{"title":"Filter, Interceptor, Aop, 啥, 啥, 啥? 这些都是啥?","url":"/2020/08/22/Filter-Intercepter-Aop-啥-啥-啥-这些都是啥/"},{"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 1115 交替打印 FooBar ( Print FooBar Alternately *Medium* ) 题解分析","url":"/2022/05/01/Leetcode-1115-交替打印-FooBar-Print-FooBar-Alternately-Medium-题解分析/"},{"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 121 买卖股票的最佳时机(Best Time to Buy and Sell Stock) 题解分析","url":"/2021/03/14/Leetcode-121-买卖股票的最佳时机-Best-Time-to-Buy-and-Sell-Stock-题解分析/"},{"title":"Disruptor 系列三","url":"/2022/09/25/Disruptor-系列三/"},{"title":"Leetcode 16 最接近的三数之和 ( 3Sum Closest *Medium* ) 题解分析","url":"/2022/08/06/Leetcode-16-最接近的三数之和-3Sum-Closest-Medium-题解分析/"},{"title":"Leetcode 1260 二维网格迁移 ( Shift 2D Grid *Easy* ) 题解分析","url":"/2022/07/22/Leetcode-1260-二维网格迁移-Shift-2D-Grid-Easy-题解分析/"},{"title":"Leetcode 124 二叉树中的最大路径和(Binary Tree Maximum Path Sum) 题解分析","url":"/2021/01/24/Leetcode-124-二叉树中的最大路径和-Binary-Tree-Maximum-Path-Sum-题解分析/"},{"title":"Leetcode 155 最小栈(Min Stack) 题解分析","url":"/2020/12/06/Leetcode-155-最小栈-Min-Stack-题解分析/"},{"title":"Leetcode 160 相交链表(intersection-of-two-linked-lists) 题解分析","url":"/2021/01/10/Leetcode-160-相交链表-intersection-of-two-linked-lists-题解分析/"},{"title":"Leetcode 20 有效的括号 ( Valid Parentheses *Easy* ) 题解分析","url":"/2022/07/02/Leetcode-20-有效的括号-Valid-Parentheses-Easy-题解分析/"},{"title":"Leetcode 1862 向下取整数对和 ( Sum of Floored Pairs *Hard* ) 题解分析","url":"/2022/09/11/Leetcode-1862-向下取整数对和-Sum-of-Floored-Pairs-Hard-题解分析/"},{"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 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 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 42 接雨水 (Trapping Rain Water) 题解分析","url":"/2021/07/04/Leetcode-42-接雨水-Trapping-Rain-Water-题解分析/"},{"title":"Leetcode 4 寻找两个正序数组的中位数 ( Median of Two Sorted Arrays *Hard* ) 题解分析","url":"/2022/03/27/Leetcode-4-寻找两个正序数组的中位数-Median-of-Two-Sorted-Arrays-Hard-题解分析/"},{"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 83 删除排序链表中的重复元素 ( Remove Duplicates from Sorted List *Easy* ) 题解分析","url":"/2022/03/13/Leetcode-83-删除排序链表中的重复元素-Remove-Duplicates-from-Sorted-List-Easy-题解分析/"},{"title":"leetcode no.3","url":"/2015/04/15/Leetcode-No-3/"},{"title":"Linux 下 grep 命令的一点小技巧","url":"/2020/08/06/Linux-下-grep-命令的一点小技巧/"},{"title":"Leetcode 885 螺旋矩阵 III ( Spiral Matrix III *Medium* ) 题解分析","url":"/2022/08/23/Leetcode-885-螺旋矩阵-III-Spiral-Matrix-III-Medium-题解分析/"},{"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":"Reverse Integer","url":"/2015/03/13/Reverse-Integer/"},{"title":"Reverse Bits","url":"/2015/03/11/Reverse-Bits/"},{"title":"two sum","url":"/2015/01/14/Two-Sum/"},{"title":"binary-watch","url":"/2016/09/29/binary-watch/"},{"title":"Redis_分布式锁","url":"/2019/12/10/Redis-Part-1/"},{"title":"ambari-summary","url":"/2017/05/09/ambari-summary/"},{"title":"docker-mysql-cluster","url":"/2016/08/14/docker-mysql-cluster/"},{"title":"docker比一般多一点的初学者介绍三","url":"/2020/03/21/docker比一般多一点的初学者介绍三/"},{"title":"docker比一般多一点的初学者介绍","url":"/2020/03/08/docker比一般多一点的初学者介绍/"},{"title":"dubbo 客户端配置的一个重要知识点","url":"/2022/06/11/dubbo-客户端配置的一个重要知识点/"},{"title":"docker比一般多一点的初学者介绍二","url":"/2020/03/15/docker比一般多一点的初学者介绍二/"},{"title":"docker使用中发现的echo命令的一个小技巧及其他","url":"/2020/03/29/echo命令的一个小技巧/"},{"title":"invert-binary-tree","url":"/2015/06/22/invert-binary-tree/"},{"title":"minimum-size-subarray-sum-209","url":"/2016/10/11/minimum-size-subarray-sum-209/"},{"title":"gogs使用webhook部署react单页应用","url":"/2020/02/22/gogs使用webhook部署react单页应用/"},{"title":"C++ 指针使用中的一个小问题","url":"/2014/12/23/my-new-post/"},{"title":"mybatis 的 foreach 使用的注意点","url":"/2022/07/09/mybatis-的-foreach-使用的注意点/"},{"title":"mybatis 的 $ 和 # 是有啥区别","url":"/2020/09/06/mybatis-的-和-是有啥区别/"},{"title":"nginx 日志小记","url":"/2022/04/17/nginx-日志小记/"},{"title":"mybatis 的缓存是怎么回事","url":"/2020/10/03/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":"redis 的 rdb 和 COW 介绍","url":"/2021/08/15/redis-的-rdb-和-COW-介绍/"},{"title":"redis数据结构介绍三-第三部分 整数集合","url":"/2020/01/10/redis数据结构介绍三/"},{"title":"redis数据结构介绍-第一部分 SDS,链表,字典","url":"/2019/12/26/redis数据结构介绍/"},{"title":"redis数据结构介绍二-第二部分 跳表","url":"/2020/01/04/redis数据结构介绍二/"},{"title":"redis数据结构介绍五-第五部分 对象","url":"/2020/01/20/redis数据结构介绍五/"},{"title":"rabbitmq-tips","url":"/2017/04/25/rabbitmq-tips/"},{"title":"redis数据结构介绍六 快表","url":"/2020/01/22/redis数据结构介绍六/"},{"title":"redis数据结构介绍四-第四部分 压缩表","url":"/2020/01/19/redis数据结构介绍四/"},{"title":"redis淘汰策略复习","url":"/2021/08/01/redis淘汰策略复习/"},{"title":"redis过期策略复习","url":"/2021/07/25/redis过期策略复习/"},{"title":"redis系列介绍七-过期策略","url":"/2020/04/12/redis系列介绍七/"},{"title":"rust学习笔记-所有权三之切片","url":"/2021/05/16/rust学习笔记-所有权三之切片/"},{"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":"redis系列介绍八-淘汰策略","url":"/2020/04/18/redis系列介绍八/"},{"title":"rust学习笔记-所有权二","url":"/2021/04/18/rust学习笔记-所有权二/"},{"title":"rust学习笔记-所有权一","url":"/2021/04/18/rust学习笔记/"},{"title":"spring event 介绍","url":"/2022/01/30/spring-event-介绍/"},{"title":"swoole-websocket-test","url":"/2016/07/13/swoole-websocket-test/"},{"title":"一个 nginx 的简单记忆点","url":"/2022/08/21/一个-nginx-的简单记忆点/"},{"title":"spark-little-tips","url":"/2017/03/28/spark-little-tips/"},{"title":"summary-ranges-228","url":"/2016/10/12/summary-ranges-228/"},{"title":"《长安的荔枝》读后感","url":"/2022/07/17/《长安的荔枝》读后感/"},{"title":"wordpress 忘记密码的一种解决方法","url":"/2021/12/05/wordpress-忘记密码的一种解决方法/"},{"title":"《垃圾回收算法手册读书》笔记之整理算法","url":"/2021/03/07/《垃圾回收算法手册读书》笔记之整理算法/"},{"title":"介绍下最近比较实用的端口转发","url":"/2021/11/14/介绍下最近比较实用的端口转发/"},{"title":"从清华美院学姐聊聊我们身边的恶人","url":"/2020/11/29/从清华美院学姐聊聊我们身边的恶人/"},{"title":"上次的其他 外行聊国足","url":"/2022/03/06/上次的其他-外行聊国足/"},{"title":"介绍一下 RocketMQ","url":"/2020/06/21/介绍一下-RocketMQ/"},{"title":"从丁仲礼被美国制裁聊点啥","url":"/2020/12/20/从丁仲礼被美国制裁聊点啥/"},{"title":"关于读书打卡与分享","url":"/2021/02/07/关于读书打卡与分享/"},{"title":"分享记录一下一个 git 操作方法","url":"/2022/02/06/分享记录一下一个-git-操作方法/"},{"title":"分享记录一下一个 scp 操作方法","url":"/2022/02/06/分享记录一下一个-scp-操作方法/"},{"title":"关于公共交通再吐个槽","url":"/2021/03/21/关于公共交通再吐个槽/"},{"title":"周末我在老丈人家打了天小工","url":"/2020/08/16/周末我在老丈人家打了天小工/"},{"title":"在老丈人家的小工记五","url":"/2020/10/18/在老丈人家的小工记五/"},{"title":"在老丈人家的小工记三","url":"/2020/09/13/在老丈人家的小工记三/"},{"title":"在老丈人家的小工记四","url":"/2020/09/26/在老丈人家的小工记四/"},{"title":"屯菜惊魂记","url":"/2022/04/24/屯菜惊魂记/"},{"title":"我是如何走上跑步这条不归路的","url":"/2020/07/26/我是如何走上跑步这条不归路的/"},{"title":"寄生虫观后感","url":"/2020/03/01/寄生虫观后感/"},{"title":"搬运两个 StackOverflow 上的 Mysql 编码相关的问题解答","url":"/2022/01/16/搬运两个-StackOverflow-上的-Mysql-编码相关的问题解答/"},{"title":"看完了扫黑风暴,聊聊感想","url":"/2021/10/24/看完了扫黑风暴-聊聊感想/"},{"title":"给小电驴上牌","url":"/2022/03/20/给小电驴上牌/"},{"title":"聊一下 RocketMQ 的消息存储之 MMAP","url":"/2021/09/04/聊一下-RocketMQ-的消息存储/"},{"title":"是何原因竟让两人深夜奔袭十公里","url":"/2022/06/05/是何原因竟让两人深夜奔袭十公里/"},{"title":"聊一下 RocketMQ 的 DefaultMQPushConsumer 源码","url":"/2020/06/26/聊一下-RocketMQ-的-Consumer/"},{"title":"聊一下 RocketMQ 的 NameServer 源码","url":"/2020/07/05/聊一下-RocketMQ-的-NameServer-源码/"},{"title":"聊一下 RocketMQ 的消息存储三","url":"/2021/10/03/聊一下-RocketMQ-的消息存储三/"},{"title":"聊一下 RocketMQ 的消息存储二","url":"/2021/09/12/聊一下-RocketMQ-的消息存储二/"},{"title":"聊一下 SpringBoot 中使用的 cglib 作为动态代理中的一个注意点","url":"/2021/09/19/聊一下-SpringBoot-中使用的-cglib-作为动态代理中的一个注意点/"},{"title":"聊一下 RocketMQ 的消息存储四","url":"/2021/10/17/聊一下-RocketMQ-的消息存储四/"},{"title":"聊一下 RocketMQ 的顺序消息","url":"/2021/08/29/聊一下-RocketMQ-的顺序消息/"},{"title":"聊一下 SpringBoot 中动态切换数据源的方法","url":"/2021/09/26/聊一下-SpringBoot-中动态切换数据源的方法/"},{"title":"聊一下 SpringBoot 设置非 web 应用的方法","url":"/2022/07/31/聊一下-SpringBoot-设置非-web-应用的方法/"},{"title":"聊在东京奥运会闭幕式这天-二","url":"/2021/08/19/聊在东京奥运会闭幕式这天-二/"},{"title":"聊聊 Dubbo 的 SPI 续之自适应拓展","url":"/2020/06/06/聊聊-Dubbo-的-SPI-续之自适应拓展/"},{"title":"聊在东京奥运会闭幕式这天","url":"/2021/08/08/聊在东京奥运会闭幕式这天/"},{"title":"聊聊 Dubbo 的 SPI","url":"/2020/05/31/聊聊-Dubbo-的-SPI/"},{"title":"聊聊 Dubbo 的容错机制","url":"/2020/11/22/聊聊-Dubbo-的容错机制/"},{"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 的类加载机制二","url":"/2021/06/13/聊聊-Java-的类加载机制二/"},{"title":"聊聊 Java 的 equals 和 hashCode 方法","url":"/2021/01/03/聊聊-Java-的-equals-和-hashCode-方法/"},{"title":"聊聊 Linux 下的 top 命令","url":"/2021/03/28/聊聊-Linux-下的-top-命令/"},{"title":"聊聊 Java 自带的那些*逆天*工具","url":"/2020/08/02/聊聊-Java-自带的那些逆天工具/"},{"title":"聊聊 RocketMQ 的 Broker 源码","url":"/2020/07/19/聊聊-RocketMQ-的-Broker-源码/"},{"title":"聊聊 Sharding-Jdbc 分库分表下的分页方案","url":"/2022/01/09/聊聊-Sharding-Jdbc-分库分表下的分页方案/"},{"title":"聊聊 Sharding-Jdbc 的简单使用","url":"/2021/12/12/聊聊-Sharding-Jdbc-的简单使用/"},{"title":"聊聊 Sharding-Jdbc 的简单原理初篇","url":"/2021/12/26/聊聊-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 的 MVCC","url":"/2020/04/26/聊聊-mysql-的-MVCC/"},{"title":"聊聊 mysql 索引的一些细节","url":"/2020/12/27/聊聊-mysql-索引的一些细节/"},{"title":"聊聊 redis 缓存的应用问题","url":"/2021/01/31/聊聊-redis-缓存的应用问题/"},{"title":"聊聊传说中的 ThreadLocal","url":"/2021/05/30/聊聊传说中的-ThreadLocal/"},{"title":"聊聊Java中的单例模式","url":"/2019/12/21/聊聊Java中的单例模式/"},{"title":"聊聊一次 brew update 引发的血案","url":"/2020/06/13/聊聊一次-brew-update-引发的血案/"},{"title":"聊聊厦门旅游的好与不好","url":"/2021/04/11/聊聊厦门旅游的好与不好/"},{"title":"聊聊 SpringBoot 自动装配","url":"/2021/07/11/聊聊SpringBoot-自动装配/"},{"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/31/聊聊最近平淡的生活之《花束般的恋爱》观后感/"},{"title":"聊聊那些加塞狗","url":"/2021/01/17/聊聊那些加塞狗/"},{"title":"聊聊最近平淡的生活之看看老剧","url":"/2021/11/21/聊聊最近平淡的生活之看看老剧/"},{"title":"聊聊给亲戚朋友的老电脑重装系统那些事儿","url":"/2021/05/09/聊聊给亲戚朋友的老电脑重装系统那些事儿/"},{"title":"聊聊部分公交车的设计bug","url":"/2021/12/05/聊聊部分公交车的设计bug/"},{"title":"聊聊这次换车牌及其他","url":"/2022/02/20/聊聊这次换车牌及其他/"},{"title":"记录下 Java Stream 的一些高效操作","url":"/2022/05/15/记录下-Java-Lambda-的一些高效操作/"},{"title":"聊聊最近平淡的生活之看《神探狄仁杰》","url":"/2021/12/19/聊聊最近平淡的生活之看《神探狄仁杰》/"},{"title":"记录下 zookeeper 集群迁移和易错点","url":"/2022/05/29/记录下-zookeeper-集群迁移/"},{"title":"闲聊下乘公交的用户体验","url":"/2021/02/28/闲聊下乘公交的用户体验/"},{"title":"重看了下《蛮荒记》说说感受","url":"/2021/10/10/重看了下《蛮荒记》说说感受/"},{"title":"闲话篇-也算碰到了为老不尊和坏人变老了的典型案例","url":"/2022/05/22/闲话篇-也算碰到了为老不尊和坏人变老了的典型案例/"},{"title":"闲话篇-路遇神逻辑骑车带娃爹","url":"/2022/05/08/闲话篇-路遇神逻辑骑车带娃爹/"},{"title":"难得的大扫除","url":"/2022/04/10/难得的大扫除/"},{"title":"记一个容器中 dubbo 注册的小知识点","url":"/2022/10/09/记一个容器中-dubbo-注册的小知识点/"},{"title":"这周末我又在老丈人家打了天小工","url":"/2020/08/30/这周末我又在老丈人家打了天小工/"}] \ No newline at end of file diff --git a/search.xml b/search.xml index 89b54aef06..a2a4d58cb6 100644 --- a/search.xml +++ b/search.xml @@ -20,6 +20,35 @@ 读后感 + + 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公里的目标,体重也稍有下降,比较满意的结果。

+

期待

希望工作方面技术方面能有所长进,生活上能多点时间陪家人,继续跑步减肥,家人健健康康的,嗯

+]]>
+ + 生活 + 年终总结 + 2019 + + + 生活 + 年终总结 + 2019 + +
2020 年终总结 /2021/03/31/2020-%E5%B9%B4%E7%BB%88%E6%80%BB%E7%BB%93/ @@ -64,6 +93,23 @@ 年中总结 + + 2021 年终总结 + /2022/01/22/2021-%E5%B9%B4%E7%BB%88%E6%80%BB%E7%BB%93/ + 又是一年年终总结,本着极度讨厌实时需求的理念,我还是 T+N 发布这个年终总结

+

工作篇

工作没什么大变化,有了些微的提升,可能因为是来了之后做了些项目对比公司与来还算是比较重要的,但是技术难度上没有特别突出的点,可能最开始用 openresty+lua 做了个 ab 测的工具,还是让我比较满意的,后面一般都是业务型的需求,今年可能在业务相关的技术逻辑上有了一些深度的了解,而原来一直想做的业务架构升级和通用型技术中间件这样的优化还是停留在想象中,前面说的 ab 测应该算是个半成品,还是没能多走出这一步,得需要多做一些实在的事情,比如轻量级的业务框架,能够对原先不熟悉的业务逻辑,代码逻辑有比较深入的理解,而不是一直都是让特定的同学负责特定的逻辑,很多时候还是在偷懒,习惯以一些简单安全的方案去做事情,在技术上还是要有所追求,还有就是能够在新语言,主要是 rust,swift 这类的能有些小玩具可以做,rust 的话是因为今年看了一本相关的书,后面三分之一其实消化得不好,这本书整体来说是很不错的,只是 rust 本身在所有权这块,还有引用包装等方面是设计得比较难懂,也可能是我基础差,所以还是想在复习下,可以做一个简单的命令行工具这种,然后 swift 是想说可以做点 mac 的小软件,原生的毕竟性能好点,又小。基于 web 做的客户端大部分都是又丑又大,极少数能好看点,但也是很重,起码 7~80M 的大小,原生的估计能除以 10。
整体的职业规划貌似陷入了比较大的困惑期,在目前公司发展前景不是很大,但是出去貌似也没有比较适合我的机会,总的来说还是杭州比较卷,个人觉得有自己的时间是非常重要的,而且这个不光是用来自我提升的,还是让自己有足够的时间做缓冲,有足够的时间锻炼减肥,时间少的情况下,不光会在仅有的时间里暴饮暴食,还没空锻炼,身体是革命的本钱,现在其实能特别明显地感觉到身体状态下滑,容易疲劳,焦虑。所以是否也许有可能以后要往外企这类的方向去发展。
工作上其实还是有个不大不小的缺点,就是容易激动,容易焦虑,前一点可能有稍稍地改观,因为工作中的很多现状其实是我个人难以改变的,即使觉得不合理,但是结构在那里,还不如自己放宽心,尽量做好事情就行。第二点的话还是做得比较差,一直以来抗压能力都比较差,跟成长环境,家庭环境都有比较大的关系,而且说实在的特别是父母,基本也没有在这方面给我正向的帮助,比较擅长给我施压,从小就是通过压力让我好好读书,当个乖学生,考个好学校,并没有能真正地理解我的压力,教我或者帮助我解压,只会在那说着不着边际的空话,甚至经常反过来对我施压。还是希望能慢慢解开,这点可能对我身体也有影响,也许需要看一些心理疏导相关的书籍。工作篇暂时到这,后续还有其他篇,未完待续哈哈😀

+]]>
+ + 生活 + 年终总结 + + + 生活 + 年终总结 + 2021 + 拖更 + +
2021 年中总结 /2021/07/18/2021-%E5%B9%B4%E4%B8%AD%E6%80%BB%E7%BB%93/ @@ -88,384 +134,110 @@ - 2021 年终总结 - /2022/01/22/2021-%E5%B9%B4%E7%BB%88%E6%80%BB%E7%BB%93/ - 又是一年年终总结,本着极度讨厌实时需求的理念,我还是 T+N 发布这个年终总结

-

工作篇

工作没什么大变化,有了些微的提升,可能因为是来了之后做了些项目对比公司与来还算是比较重要的,但是技术难度上没有特别突出的点,可能最开始用 openresty+lua 做了个 ab 测的工具,还是让我比较满意的,后面一般都是业务型的需求,今年可能在业务相关的技术逻辑上有了一些深度的了解,而原来一直想做的业务架构升级和通用型技术中间件这样的优化还是停留在想象中,前面说的 ab 测应该算是个半成品,还是没能多走出这一步,得需要多做一些实在的事情,比如轻量级的业务框架,能够对原先不熟悉的业务逻辑,代码逻辑有比较深入的理解,而不是一直都是让特定的同学负责特定的逻辑,很多时候还是在偷懒,习惯以一些简单安全的方案去做事情,在技术上还是要有所追求,还有就是能够在新语言,主要是 rust,swift 这类的能有些小玩具可以做,rust 的话是因为今年看了一本相关的书,后面三分之一其实消化得不好,这本书整体来说是很不错的,只是 rust 本身在所有权这块,还有引用包装等方面是设计得比较难懂,也可能是我基础差,所以还是想在复习下,可以做一个简单的命令行工具这种,然后 swift 是想说可以做点 mac 的小软件,原生的毕竟性能好点,又小。基于 web 做的客户端大部分都是又丑又大,极少数能好看点,但也是很重,起码 7~80M 的大小,原生的估计能除以 10。
整体的职业规划貌似陷入了比较大的困惑期,在目前公司发展前景不是很大,但是出去貌似也没有比较适合我的机会,总的来说还是杭州比较卷,个人觉得有自己的时间是非常重要的,而且这个不光是用来自我提升的,还是让自己有足够的时间做缓冲,有足够的时间锻炼减肥,时间少的情况下,不光会在仅有的时间里暴饮暴食,还没空锻炼,身体是革命的本钱,现在其实能特别明显地感觉到身体状态下滑,容易疲劳,焦虑。所以是否也许有可能以后要往外企这类的方向去发展。
工作上其实还是有个不大不小的缺点,就是容易激动,容易焦虑,前一点可能有稍稍地改观,因为工作中的很多现状其实是我个人难以改变的,即使觉得不合理,但是结构在那里,还不如自己放宽心,尽量做好事情就行。第二点的话还是做得比较差,一直以来抗压能力都比较差,跟成长环境,家庭环境都有比较大的关系,而且说实在的特别是父母,基本也没有在这方面给我正向的帮助,比较擅长给我施压,从小就是通过压力让我好好读书,当个乖学生,考个好学校,并没有能真正地理解我的压力,教我或者帮助我解压,只会在那说着不着边际的空话,甚至经常反过来对我施压。还是希望能慢慢解开,这点可能对我身体也有影响,也许需要看一些心理疏导相关的书籍。工作篇暂时到这,后续还有其他篇,未完待续哈哈😀

-]]>
+ 34_Search_for_a_Range + /2016/08/14/34-Search-for-a-Range/ + question

34. Search for a Range

Original Page

+

Given a sorted array of integers, find the starting and ending position of a given target value.

+

Your algorithm’s runtime complexity must be in the order of O(log n).

+

If the target is not found in the array, return [-1, -1].

+

For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].

+

analysis

一开始就想到了二分查找,但是原来做二分查找的时候一般都是找到确定的那个数就完成了,
这里的情况比较特殊,需要找到整个区间,所以需要两遍查找,并且一个是找到小于target
的最大索引,一个是找到大于target的最大索引,代码参考leetcode discuss,这位仁
兄也做了详细的分析解释。

+

code

class Solution {
+public:
+    vector<int> searchRange(vector<int>& nums, int target) {
+        vector<int> ret(2, -1);
+        int i = 0, j = nums.size() - 1;
+        int mid;
+        while(i < j){
+            mid = (i + j) / 2;
+            if(nums[mid] < target) i = mid + 1;
+            else j = mid;
+        }
+        if(nums[i] != target) return ret;
+        else {
+            ret[0] = i;
+            if((i+1) < (nums.size() - 1) && nums[i+1] > target){
+                ret[1] = i;
+                return ret;
+            }
+        }   //一点小优化
+        j = nums.size() - 1;
+        while(i < j){
+            mid = (i + j) / 2 + 1;
+            if(nums[mid] > target) j = mid - 1;
+            else i = mid;
+        }
+        ret[1] = j;
+        return ret;
+    }
+};
]]>
- 生活 - 年终总结 + leetcode - 生活 - 年终总结 - 2021 - 拖更 + leetcode + 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;
-        }
-    }
+ 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;
 
-

第二个线程

当第二个线程进来的时候应该是怎么样,结合代码来看

-
/**
-     * 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();
-    }
+class BoundedBuffer { + final Lock lock = new ReentrantLock(); + // condition 依赖于 lock 来产生 + final Condition notFull = lock.newCondition(); + final Condition notEmpty = lock.newCondition(); -

然后来看下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;
-            }
+    // 对象池子,put 跟 take 的就是这里的
+    final Object[] items = new Object[100];
+    int putptr, takeptr, count;
+
+    // 生产
+    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();
         }
-        // 不然就会继续走到这里
-        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;
-                }
-            }
+    // 消费
+    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();
         }
-    }
+ } +}
-

所以从这里可以看出来,其实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 - -
- - 34_Search_for_a_Range - /2016/08/14/34-Search-for-a-Range/ - question

34. Search for a Range

Original Page

-

Given a sorted array of integers, find the starting and ending position of a given target value.

-

Your algorithm’s runtime complexity must be in the order of O(log n).

-

If the target is not found in the array, return [-1, -1].

-

For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].

-

analysis

一开始就想到了二分查找,但是原来做二分查找的时候一般都是找到确定的那个数就完成了,
这里的情况比较特殊,需要找到整个区间,所以需要两遍查找,并且一个是找到小于target
的最大索引,一个是找到大于target的最大索引,代码参考leetcode discuss,这位仁
兄也做了详细的分析解释。

-

code

class Solution {
-public:
-    vector<int> searchRange(vector<int>& nums, int target) {
-        vector<int> ret(2, -1);
-        int i = 0, j = nums.size() - 1;
-        int mid;
-        while(i < j){
-            mid = (i + j) / 2;
-            if(nums[mid] < target) i = mid + 1;
-            else j = mid;
-        }
-        if(nums[i] != target) return ret;
-        else {
-            ret[0] = i;
-            if((i+1) < (nums.size() - 1) && nums[i+1] > target){
-                ret[1] = i;
-                return ret;
-            }
-        }   //一点小优化
-        j = nums.size() - 1;
-        while(i < j){
-            mid = (i + j) / 2 + 1;
-            if(nums[mid] > target) j = mid - 1;
-            else i = mid;
-        }
-        ret[1] = j;
-        return ret;
-    }
-};
]]>
- - leetcode - - - leetcode - c++ - -
- - 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公里的目标,体重也稍有下降,比较满意的结果。

-

期待

希望工作方面技术方面能有所长进,生活上能多点时间陪家人,继续跑步减肥,家人健健康康的,嗯

-]]>
- - 生活 - 年终总结 - 2019 - - - 生活 - 年终总结 - 2019 - -
- - 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();
-
-    // 对象池子,put 跟 take 的就是这里的
-    final Object[] items = new Object[100];
-    int putptr, takeptr, count;
-
-    // 生产
-    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();
-        }
-    }
-
-    // 消费
-    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();
-        }
-    }
-}
- -

介绍下 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

+

介绍下 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>
@@ -905,552 +677,400 @@ public:
       
   
   
-    add-two-number
-    /2015/04/14/Add-Two-Number/
-    problem

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

-

Input:(2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

-

分析(不用英文装逼了)
这个代码是抄来的,链接原作是这位大大。

- -

一开始没看懂题,后来发现是要进位的,自己写的时候想把长短不同时长的串接到结果
串的后面,试了下因为进位会有些问题比较难搞定,这样的话就是在其中一个为空的
时候还是会循环操作,在链表太大的时候可能会有问题,就这样(逃
原来是有个小错误没发现,改进后的代码也AC了,棒棒哒!

-

正确代码

/**
- * Definition for singly-linked list.
- * struct ListNode {
- *     int val;
- *     ListNode *next;
- *     ListNode(int x) : val(x), next(NULL) {}
- * };
- */
-class Solution {
-public:
-    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
-        ListNode dummy(0);
-        ListNode* p = &dummy;
+    AbstractQueuedSynchronizer
+    /2019/09/23/AbstractQueuedSynchronizer/
+    最近看了大神的 AQS 的文章,之前总是断断续续地看一点,每次都知难而退,下次看又从头开始,昨天总算硬着头皮看完了第一部分
首先 AQS 只要有这些属性

+
// 头结点,你直接把它当做 当前持有锁的线程 可能是最好理解的
+private transient volatile Node head;
 
-        int cn = 0;
-        while(l1 || l2){
-            int val = cn + (l1 ? l1->val : 0) + (l2 ? l2->val : 0);
-            cn = val / 10;
-            val = val % 10;
-            p->next = new ListNode(val);
-            p = p->next;
-            if(l1){
-                l1 = l1->next;
-            }
-            if(l2){
-                l2 = l2->next;
-            }
-        }
-        if(cn != 0){
-            p->next = new ListNode(cn);
-            p = p->next;
-        }
-        return dummy.next;
-    }
-};
+// 阻塞的尾节点,每个新的节点进来,都插入到最后,也就形成了一个链表 +private transient volatile Node tail; -

失败的代码

/**
- * Definition for singly-linked list.
- * struct ListNode {
- *     int val;
- *     ListNode *next;
- *     ListNode(int x) : val(x), next(NULL) {}
- * };
- */
-class Solution {
-public:
-    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
-        ListNode dummy(0);
-        ListNode* p = &dummy;
+// 这个是最重要的,代表当前锁的状态,0代表没有被占用,大于 0 代表有线程持有当前锁
+// 这个值可以大于 1,是因为锁可以重入,每次重入都加上 1
+private volatile int state;
 
-        int cn = 0;
-        int flag = 0;
-        while(l1 || l2){
-            int val = cn + (l1 ? l1->val : 0) + (l2 ? l2->val : 0);
-            cn = val / 10;
-            val = val % 10;
-            p->next = new ListNode(val);
-            p = p->next;
-            if(!l1 && cn == 0){
-                flag = 1;
-                break;
-            }
-            if(!l2 && cn == 0){
-                flag = 1;
-                break;
-            }
-            if(l1){
-                l1 = l1->next;
-            }
-            if(l2){
-                l2 = l2->next;
-            }
-        }
-        if(!l1 && cn == 0 && flag == 1){
-            p->next = l2->next;
-        }
-        if(!l2 && cn == 0 && flag == 1){
-            p->next = l1->next;
-        }
-        if(cn != 0){
-            p->next = new ListNode(cn);
-            p = p->next;
-        }
-        return dummy.next;
-    }
-};
+// 代表当前持有独占锁的线程,举个最重要的使用例子,因为锁可以重入 +// reentrantLock.lock()可以嵌套调用多次,所以每次用这个来判断当前线程是否已经拥有了锁 +// if (currentThread == getExclusiveOwnerThread()) {state++} +private transient Thread exclusiveOwnerThread; //继承自AbstractOwnableSynchronizer
+

大概了解了 aqs 底层的双向等待队列,
结构是这样的

每个 node 里面主要是的代码结构也比较简单

+
static final class Node {
+    // 标识节点当前在共享模式下
+    static final Node SHARED = new Node();
+    // 标识节点当前在独占模式下
+    static final Node EXCLUSIVE = null;
+
+    // ======== 下面的几个int常量是给waitStatus用的 ===========
+    /** waitStatus value to indicate thread has cancelled */
+    // 代码此线程取消了争抢这个锁
+    static final int CANCELLED =  1;
+    /** waitStatus value to indicate successor's thread needs unparking */
+    // 官方的描述是,其表示当前node的后继节点对应的线程需要被唤醒
+    static final int SIGNAL    = -1;
+    /** waitStatus value to indicate thread is waiting on condition */
+    // 本文不分析condition,所以略过吧,下一篇文章会介绍这个
+    static final int CONDITION = -2;
+    /**
+     * waitStatus value to indicate the next acquireShared should
+     * unconditionally propagate
+     */
+    // 同样的不分析,略过吧
+    static final int PROPAGATE = -3;
+    // =====================================================
+
+
+    // 取值为上面的1、-1、-2、-3,或者0(以后会讲到)
+    // 这么理解,暂时只需要知道如果这个值 大于0 代表此线程取消了等待,
+    //    ps: 半天抢不到锁,不抢了,ReentrantLock是可以指定timeouot的。。。
+    volatile int waitStatus;
+    // 前驱节点的引用
+    volatile Node prev;
+    // 后继节点的引用
+    volatile Node next;
+    // 这个就是线程本尊
+    volatile Thread thread;
+
+}
+

其实可以主要关注这个 waitStatus 因为这个是后面的节点给前面的节点设置的,等于-1 的时候代表后面有节点等待,需要去唤醒,
这里使用了一个变种的 CLH 队列实现,CLH 队列相关内容可以查看这篇 自旋锁、排队自旋锁、MCS锁、CLH锁

]]>
- leetcode + java - leetcode - c++ + java + aqs
- Apollo 客户端启动过程分析 - /2022/09/18/Apollo-%E5%AE%A2%E6%88%B7%E7%AB%AF%E5%90%AF%E5%8A%A8%E8%BF%87%E7%A8%8B%E5%88%86%E6%9E%90/ - 入口是可以在 springboot 的启动类上打上EnableApolloConfig 注解

-
@Import(ApolloConfigRegistrar.class)
-public @interface EnableApolloConfig {
-

这个 import 实现了

-
public class ApolloConfigRegistrar implements ImportBeanDefinitionRegistrar {
-
-  private ApolloConfigRegistrarHelper helper = ServiceBootstrap.loadPrimary(ApolloConfigRegistrarHelper.class);
-
-  @Override
-  public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
-    helper.registerBeanDefinitions(importingClassMetadata, registry);
-  }
-}
- -

然后就调用了

-
com.ctrip.framework.apollo.spring.spi.DefaultApolloConfigRegistrarHelper#registerBeanDefinitions
-

接着是注册了这个 bean,com.ctrip.framework.apollo.spring.config.PropertySourcesProcessor

-
@Override
-public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
-  AnnotationAttributes attributes = AnnotationAttributes
-      .fromMap(importingClassMetadata.getAnnotationAttributes(EnableApolloConfig.class.getName()));
-  String[] namespaces = attributes.getStringArray("value");
-  int order = attributes.getNumber("order");
-  PropertySourcesProcessor.addNamespaces(Lists.newArrayList(namespaces), order);
-
-  Map<String, Object> propertySourcesPlaceholderPropertyValues = new HashMap<>();
-  // to make sure the default PropertySourcesPlaceholderConfigurer's priority is higher than PropertyPlaceholderConfigurer
-  propertySourcesPlaceholderPropertyValues.put("order", 0);
-
-  BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, PropertySourcesPlaceholderConfigurer.class.getName(),
-      PropertySourcesPlaceholderConfigurer.class, propertySourcesPlaceholderPropertyValues);
-  // 注册了这个 bean
-  BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, PropertySourcesProcessor.class.getName(),
-      PropertySourcesProcessor.class);
- -

而com.ctrip.framework.apollo.spring.config.PropertySourcesProcessor 实现了 org.springframework.beans.factory.config.BeanFactoryPostProcessor
它里面的 com.ctrip.framework.apollo.spring.config.PropertySourcesProcessor#postProcessBeanFactory 方法就会被 spring 调用,

-
private void initializePropertySources() {
-    if (environment.getPropertySources().contains(PropertySourcesConstants.APOLLO_PROPERTY_SOURCE_NAME)) {
-      //already initialized
-      return;
-    }
-    CompositePropertySource composite = new CompositePropertySource(PropertySourcesConstants.APOLLO_PROPERTY_SOURCE_NAME);
-
-    //sort by order asc
-    ImmutableSortedSet<Integer> orders = ImmutableSortedSet.copyOf(NAMESPACE_NAMES.keySet());
-    Iterator<Integer> iterator = orders.iterator();
-
-    while (iterator.hasNext()) {
-      int order = iterator.next();
-      for (String namespace : NAMESPACE_NAMES.get(order)) {
-      // 这里获取每个 namespace 的配置
-        Config config = ConfigService.getConfig(namespace);
+    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;
+        }
+    }
- composite.addPropertySource(configPropertySourceFactory.getConfigPropertySource(namespace, config)); - } +

第二个线程

当第二个线程进来的时候应该是怎么样,结合代码来看

+
/**
+     * 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();
     }
-

然后是 com.ctrip.framework.apollo.ConfigService#getConfig
接着就是它
com.ctrip.framework.apollo.internals.DefaultConfigManager#getConfig

-
@Override
-  public Config getConfig(String namespace) {
-    Config config = m_configs.get(namespace);
 
-    if (config == null) {
-      synchronized (this) {
-        config = m_configs.get(namespace);
-
-        if (config == null) {
-          ConfigFactory factory = m_factoryManager.getFactory(namespace);
+

然后来看下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;
+    }
-// 通过 factory 来创建配置获取 - config = factory.create(namespace); - m_configs.put(namespace, config); +

然后就是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;
+                }
+            }
         }
-      }
-    }
-

创建配置

-
com.ctrip.framework.apollo.spi.DefaultConfigFactory#create
-@Override
-  public Config create(String namespace) {
-    ConfigFileFormat format = determineFileFormat(namespace);
-    if (ConfigFileFormat.isPropertiesCompatible(format)) {
-      return new DefaultConfig(namespace, createPropertiesCompatibleFileConfigRepository(namespace, format));
+    }
+ +

所以从这里可以看出来,其实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);
     }
-    // 调用到这
-    return new DefaultConfig(namespace, createLocalConfigRepository(namespace));
-  }
-

然后

-
LocalFileConfigRepository createLocalConfigRepository(String namespace) {
-    if (m_configUtil.isInLocalMode()) {
-      logger.warn(
-          "==== Apollo is in local mode! Won't pull configs from remote server for namespace {} ! ====",
-          namespace);
-      return new LocalFileConfigRepository(namespace);
+/**
+     * 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;
     }
-    // 正常会走这个,因为要从配置中心获取
-    return new LocalFileConfigRepository(namespace, createRemoteConfigRepository(namespace));
-  }
+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; + } +// 这段代码和上面的一致,只是为了顺序性,又拷下来看下 -

然后是创建远程配置仓库

-
com.ctrip.framework.apollo.spi.DefaultConfigFactory#createRemoteConfigRepository
-  RemoteConfigRepository createRemoteConfigRepository(String namespace) {
-    return new RemoteConfigRepository(namespace);
-  }
-

继续对当前的 namespace 创建远程配置仓库

-
com.ctrip.framework.apollo.internals.RemoteConfigRepository#RemoteConfigRepository
-public RemoteConfigRepository(String namespace) {
-    m_namespace = namespace;
-    m_configCache = new AtomicReference<>();
-    m_configUtil = ApolloInjector.getInstance(ConfigUtil.class);
-    m_httpUtil = ApolloInjector.getInstance(HttpUtil.class);
-    m_serviceLocator = ApolloInjector.getInstance(ConfigServiceLocator.class);
-    remoteConfigLongPollService = ApolloInjector.getInstance(RemoteConfigLongPollService.class);
-    m_longPollServiceDto = new AtomicReference<>();
-    m_remoteMessages = new AtomicReference<>();
-    m_loadConfigRateLimiter = RateLimiter.create(m_configUtil.getLoadConfigQPS());
-    m_configNeedForceRefresh = new AtomicBoolean(true);
-    m_loadConfigFailSchedulePolicy = new ExponentialSchedulePolicy(m_configUtil.getOnErrorRetryInterval(),
-        m_configUtil.getOnErrorRetryInterval() * 8);
-    gson = new Gson();
-    // 尝试同步
-    this.trySync();
-    this.schedulePeriodicRefresh();
-    this.scheduleLongPollingRefresh();
-  }
-

然后是同步配置,下面的日志异常经常可以看到,比如配置拉取地址不通

-
com.ctrip.framework.apollo.internals.AbstractConfigRepository#trySync
-  protected boolean trySync() {
-    try {
-      sync();
-      return true;
-    } catch (Throwable ex) {
-      Tracer.logEvent("ApolloConfigException", ExceptionUtil.getDetailMessage(ex));
-      logger
-          .warn("Sync config failed, will retry. Repository {}, reason: {}", this.getClass(), ExceptionUtil
-              .getDetailMessage(ex));
+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;
     }
-    return false;
-  }
-

实际的同步方法,加了synchronized 锁,

-
com.ctrip.framework.apollo.internals.RemoteConfigRepository#sync
-@Override
-  protected synchronized void sync() {
-    Transaction transaction = Tracer.newTransaction("Apollo.ConfigService", "syncRemoteConfig");
 
-    try {
-      // 获取本地配置
-      ApolloConfig previous = m_configCache.get();
-      // 获取配置
-      ApolloConfig current = loadApolloConfig();
+/**
+     * 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);
 
-      //reference equals means HTTP 304
-      if (previous != current) {
-        logger.debug("Remote Config refreshed!");
-        m_configCache.set(current);
-        this.fireRepositoryChange(m_namespace, this.getConfig());
-      }
+        /*
+         * 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);
+    }
- if (current != null) { - Tracer.logEvent(String.format("Apollo.Client.Configs.%s", current.getNamespaceName()), - current.getReleaseKey()); - } - transaction.setStatus(Transaction.SUCCESS); - } catch (Throwable ex) { - transaction.setStatus(ex); - throw ex; - } finally { - transaction.complete(); - } - }
-

然后走到这

-
com.ctrip.framework.apollo.internals.RemoteConfigRepository#loadApolloConfig
-private ApolloConfig loadApolloConfig() {
-    if (!m_loadConfigRateLimiter.tryAcquire(5, TimeUnit.SECONDS)) {
-      //wait at most 5 seconds
-      try {
-        TimeUnit.SECONDS.sleep(5);
-      } catch (InterruptedException e) {
-      }
-    }
-    String appId = m_configUtil.getAppId();
-    String cluster = m_configUtil.getCluster();
-    String dataCenter = m_configUtil.getDataCenter();
-    Tracer.logEvent("Apollo.Client.ConfigMeta", STRING_JOINER.join(appId, cluster, m_namespace));
-    int maxRetries = m_configNeedForceRefresh.get() ? 2 : 1;
-    long onErrorSleepTime = 0; // 0 means no sleep
-    Throwable exception = null;
-
-	// 获取配置
-    List<ServiceDTO> configServices = getConfigServices();
-    String url = null;
-    for (int i = 0; i < maxRetries; i++) {
-      List<ServiceDTO> randomConfigServices = Lists.newLinkedList(configServices);
-      Collections.shuffle(randomConfigServices);
-      //Access the server which notifies the client first
-      if (m_longPollServiceDto.get() != null) {
-        randomConfigServices.add(0, m_longPollServiceDto.getAndSet(null));
-      }
-
-      for (ServiceDTO configService : randomConfigServices) {
-        if (onErrorSleepTime > 0) {
-          logger.warn(
-              "Load config failed, will retry in {} {}. appId: {}, cluster: {}, namespaces: {}",
-              onErrorSleepTime, m_configUtil.getOnErrorRetryIntervalTimeUnit(), appId, cluster, m_namespace);
-
-          try {
-            m_configUtil.getOnErrorRetryIntervalTimeUnit().sleep(onErrorSleepTime);
-          } catch (InterruptedException e) {
-            //ignore
-          }
-        }
-
-        url = assembleQueryConfigUrl(configService.getHomepageUrl(), appId, cluster, m_namespace,
-                dataCenter, m_remoteMessages.get(), m_configCache.get());
-
-        logger.debug("Loading config from {}", url);
-        HttpRequest request = new HttpRequest(url);
-
-        Transaction transaction = Tracer.newTransaction("Apollo.ConfigService", "queryConfig");
-        transaction.addData("Url", url);
-        try {
-
-          HttpResponse<ApolloConfig> response = m_httpUtil.doGet(request, ApolloConfig.class);
-          m_configNeedForceRefresh.set(false);
-          m_loadConfigFailSchedulePolicy.success();
-
-          transaction.addData("StatusCode", response.getStatusCode());
-          transaction.setStatus(Transaction.SUCCESS);
-
-          if (response.getStatusCode() == 304) {
-            logger.debug("Config server responds with 304 HTTP status code.");
-            return m_configCache.get();
-          }
-
-          ApolloConfig result = response.getBody();
-
-          logger.debug("Loaded config for {}: {}", m_namespace, result);
-
-          return result;
-        } catch (ApolloConfigStatusCodeException ex) {
-          ApolloConfigStatusCodeException statusCodeException = ex;
-          //config not found
-          if (ex.getStatusCode() == 404) {
-            String message = String.format(
-                "Could not find config for namespace - appId: %s, cluster: %s, namespace: %s, " +
-                    "please check whether the configs are released in Apollo!",
-                appId, cluster, m_namespace);
-            statusCodeException = new ApolloConfigStatusCodeException(ex.getStatusCode(),
-                message);
-          }
-          Tracer.logEvent("ApolloConfigException", ExceptionUtil.getDetailMessage(statusCodeException));
-          transaction.setStatus(statusCodeException);
-          exception = statusCodeException;
-        } catch (Throwable ex) {
-          Tracer.logEvent("ApolloConfigException", ExceptionUtil.getDetailMessage(ex));
-          transaction.setStatus(ex);
-          exception = ex;
-        } finally {
-          transaction.complete();
-        }
-
-        // if force refresh, do normal sleep, if normal config load, do exponential sleep
-        onErrorSleepTime = m_configNeedForceRefresh.get() ? m_configUtil.getOnErrorRetryInterval() :
-            m_loadConfigFailSchedulePolicy.fail();
-      }
-
-    }
-    String message = String.format(
-        "Load Apollo Config failed - appId: %s, cluster: %s, namespace: %s, url: %s",
-        appId, cluster, m_namespace, url);
-    throw new ApolloConfigException(message, exception);
-  }
- - -
com.ctrip.framework.apollo.internals.RemoteConfigRepository#getConfigServices
-  private List<ServiceDTO> getConfigServices() {
-    List<ServiceDTO> services = m_serviceLocator.getConfigServices();
-    if (services.size() == 0) {
-      throw new ApolloConfigException("No available config service");
-    }
-
-    return services;
-  }
- -
com.ctrip.framework.apollo.internals.ConfigServiceLocator#getConfigServices
-  public List<ServiceDTO> getConfigServices() {
-    if (m_configServices.get().isEmpty()) {
-      updateConfigServices();
-    }
-
-    return m_configServices.get();
-  }
-

更新配置服务

-
com.ctrip.framework.apollo.internals.ConfigServiceLocator#updateConfigServices
-private synchronized void updateConfigServices() {
-    String url = assembleMetaServiceUrl();
-
-    HttpRequest request = new HttpRequest(url);
-    int maxRetries = 2;
-    Throwable exception = null;
-
-    for (int i = 0; i < maxRetries; i++) {
-      Transaction transaction = Tracer.newTransaction("Apollo.MetaService", "getConfigService");
-      transaction.addData("Url", url);
-      try {
-        // 发起 http 请求获取配置
-        HttpResponse<List<ServiceDTO>> response = m_httpUtil.doGet(request, m_responseType);
-        transaction.setStatus(Transaction.SUCCESS);
-        List<ServiceDTO> services = response.getBody();
-        if (services == null || services.isEmpty()) {
-          logConfigService("Empty response!");
-          continue;
-        }
-        setConfigServices(services);
-        return;
-      } catch (Throwable ex) {
-        Tracer.logEvent("ApolloConfigException", ExceptionUtil.getDetailMessage(ex));
-        transaction.setStatus(ex);
-        exception = ex;
-      } finally {
-        transaction.complete();
-      }
-
-      try {
-        m_configUtil.getOnErrorRetryIntervalTimeUnit().sleep(m_configUtil.getOnErrorRetryInterval());
-      } catch (InterruptedException ex) {
-        //ignore
-      }
-    }
 
-    throw new ApolloConfigException(
-        String.format("Get config services failed from %s", url), exception);
-  }
]]>
Java + 并发 - Java - Apollo + java + 并发 + j.u.c + aqs - 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;
-    }
-
-    public void setId(Long id) {
-        this.id = id;
-    }
-
-    public Long getSortValue() {
-        return sortValue;
-    }
-
-    public void setSortValue(Long sortValue) {
-        this.sortValue = sortValue;
-    }
-}
+ add-two-number + /2015/04/14/Add-Two-Number/ + problem

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

+

Input:(2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

+

分析(不用英文装逼了)
这个代码是抄来的,链接原作是这位大大。

+ +

一开始没看懂题,后来发现是要进位的,自己写的时候想把长短不同时长的串接到结果
串的后面,试了下因为进位会有些问题比较难搞定,这样的话就是在其中一个为空的
时候还是会循环操作,在链表太大的时候可能会有问题,就这样(逃
原来是有个小错误没发现,改进后的代码也AC了,棒棒哒!

+

正确代码

/**
+ * Definition for singly-linked list.
+ * struct ListNode {
+ *     int val;
+ *     ListNode *next;
+ *     ListNode(int x) : val(x), next(NULL) {}
+ * };
+ */
+class Solution {
+public:
+    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
+        ListNode dummy(0);
+        ListNode* p = &dummy;
 
-

Comparator

-
public class MyComparator implements Comparator {
-    @Override
-    public int compare(Object o1, Object o2) {
-        Entity e1 = (Entity) o1;
-        Entity e2 = (Entity) o2;
-        if (e1.getSortValue() < e2.getSortValue()) {
-            return -1;
-        } else if (e1.getSortValue().equals(e2.getSortValue())) {
-            return 0;
-        } else {
-            return 1;
-        }
-    }
-}
+ int cn = 0; + while(l1 || l2){ + int val = cn + (l1 ? l1->val : 0) + (l2 ? l2->val : 0); + cn = val / 10; + val = val % 10; + p->next = new ListNode(val); + p = p->next; + if(l1){ + l1 = l1->next; + } + if(l2){ + l2 = l2->next; + } + } + if(cn != 0){ + p->next = new ListNode(cn); + p = p->next; + } + return dummy.next; + } +};
-

比较代码

-
private static MyComparator myComparator = new MyComparator();
+

失败的代码

/**
+ * Definition for singly-linked list.
+ * struct ListNode {
+ *     int val;
+ *     ListNode *next;
+ *     ListNode(int x) : val(x), next(NULL) {}
+ * };
+ */
+class Solution {
+public:
+    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
+        ListNode dummy(0);
+        ListNode* p = &dummy;
 
-    public static void main(String[] args) {
-        List<Entity> list = new ArrayList<Entity>();
-        Entity e1 = new Entity();
-        e1.setId(1L);
-        e1.setSortValue(1L);
-        list.add(e1);
-        Entity e2 = new Entity();
-        e2.setId(2L);
-        e2.setSortValue(null);
-        list.add(e2);
-        Collections.sort(list, myComparator);
- -

看到这里的e2的排序值是null,在Comparator中如果要正常运行的话,就得判空之类的,这里有两点需要,一个是不想写这个MyComparator,然后也没那么好排除掉list里排序值,那么有什么办法能解决这种问题呢,应该说java的这方面真的是很强大

-

-

看一下nullsFirst的实现

-
final static class NullComparator<T> implements Comparator<T>, Serializable {
-        private static final long serialVersionUID = -7569533591570686392L;
-        private final boolean nullFirst;
-        // if null, non-null Ts are considered equal
-        private final Comparator<T> real;
-
-        @SuppressWarnings("unchecked")
-        NullComparator(boolean nullFirst, Comparator<? super T> real) {
-            this.nullFirst = nullFirst;
-            this.real = (Comparator<T>) real;
-        }
-
-        @Override
-        public int compare(T a, T b) {
-            if (a == null) {
-                return (b == null) ? 0 : (nullFirst ? -1 : 1);
-            } else if (b == null) {
-                return nullFirst ? 1: -1;
-            } else {
-                return (real == null) ? 0 : real.compare(a, b);
-            }
-        }
- -

核心代码就是下面这段,其实就是帮我们把前面要做的事情做掉了,是不是挺方便的,小记一下哈

+ int cn = 0; + int flag = 0; + while(l1 || l2){ + int val = cn + (l1 ? l1->val : 0) + (l2 ? l2->val : 0); + cn = val / 10; + val = val % 10; + p->next = new ListNode(val); + p = p->next; + if(!l1 && cn == 0){ + flag = 1; + break; + } + if(!l2 && cn == 0){ + flag = 1; + break; + } + if(l1){ + l1 = l1->next; + } + if(l2){ + l2 = l2->next; + } + } + if(!l1 && cn == 0 && flag == 1){ + p->next = l2->next; + } + if(!l2 && cn == 0 && flag == 1){ + p->next = l1->next; + } + if(cn != 0){ + p->next = new ListNode(cn); + p = p->next; + } + return dummy.next; + } +};
]]>
- Java - 集合 + leetcode - Java - Stream - Comparator - 排序 - sort - nullsfirst + leetcode + c++
@@ -1495,887 +1115,717 @@ public: - 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.
+    Apollo 客户端启动过程分析
+    /2022/09/18/Apollo-%E5%AE%A2%E6%88%B7%E7%AB%AF%E5%90%AF%E5%8A%A8%E8%BF%87%E7%A8%8B%E5%88%86%E6%9E%90/
+    入口是可以在 springboot 的启动类上打上EnableApolloConfig 注解

+
@Import(ApolloConfigRegistrar.class)
+public @interface EnableApolloConfig {
+

这个 import 实现了

+
public class ApolloConfigRegistrar implements ImportBeanDefinitionRegistrar {
 
-A graph is defined below:
-struct Node {
-vector neighbors;
-}
+ private ApolloConfigRegistrarHelper helper = ServiceBootstrap.loadPrimary(ApolloConfigRegistrarHelper.class); - -

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++ - - - - AbstractQueuedSynchronizer - /2019/09/23/AbstractQueuedSynchronizer/ - 最近看了大神的 AQS 的文章,之前总是断断续续地看一点,每次都知难而退,下次看又从头开始,昨天总算硬着头皮看完了第一部分
首先 AQS 只要有这些属性

-
// 头结点,你直接把它当做 当前持有锁的线程 可能是最好理解的
-private transient volatile Node head;
+  @Override
+  public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
+    helper.registerBeanDefinitions(importingClassMetadata, registry);
+  }
+}
-// 阻塞的尾节点,每个新的节点进来,都插入到最后,也就形成了一个链表 -private transient volatile Node tail; +

然后就调用了

+
com.ctrip.framework.apollo.spring.spi.DefaultApolloConfigRegistrarHelper#registerBeanDefinitions
+

接着是注册了这个 bean,com.ctrip.framework.apollo.spring.config.PropertySourcesProcessor

+
@Override
+public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
+  AnnotationAttributes attributes = AnnotationAttributes
+      .fromMap(importingClassMetadata.getAnnotationAttributes(EnableApolloConfig.class.getName()));
+  String[] namespaces = attributes.getStringArray("value");
+  int order = attributes.getNumber("order");
+  PropertySourcesProcessor.addNamespaces(Lists.newArrayList(namespaces), order);
 
-// 这个是最重要的,代表当前锁的状态,0代表没有被占用,大于 0 代表有线程持有当前锁
-// 这个值可以大于 1,是因为锁可以重入,每次重入都加上 1
-private volatile int state;
+  Map<String, Object> propertySourcesPlaceholderPropertyValues = new HashMap<>();
+  // to make sure the default PropertySourcesPlaceholderConfigurer's priority is higher than PropertyPlaceholderConfigurer
+  propertySourcesPlaceholderPropertyValues.put("order", 0);
 
-// 代表当前持有独占锁的线程,举个最重要的使用例子,因为锁可以重入
-// reentrantLock.lock()可以嵌套调用多次,所以每次用这个来判断当前线程是否已经拥有了锁
-// if (currentThread == getExclusiveOwnerThread()) {state++}
-private transient Thread exclusiveOwnerThread; //继承自AbstractOwnableSynchronizer
-

大概了解了 aqs 底层的双向等待队列,
结构是这样的

每个 node 里面主要是的代码结构也比较简单

-
static final class Node {
-    // 标识节点当前在共享模式下
-    static final Node SHARED = new Node();
-    // 标识节点当前在独占模式下
-    static final Node EXCLUSIVE = null;
+  BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, PropertySourcesPlaceholderConfigurer.class.getName(),
+      PropertySourcesPlaceholderConfigurer.class, propertySourcesPlaceholderPropertyValues);
+  // 注册了这个 bean
+  BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, PropertySourcesProcessor.class.getName(),
+      PropertySourcesProcessor.class);
- // ======== 下面的几个int常量是给waitStatus用的 =========== - /** waitStatus value to indicate thread has cancelled */ - // 代码此线程取消了争抢这个锁 - static final int CANCELLED = 1; - /** waitStatus value to indicate successor's thread needs unparking */ - // 官方的描述是,其表示当前node的后继节点对应的线程需要被唤醒 - static final int SIGNAL = -1; - /** waitStatus value to indicate thread is waiting on condition */ - // 本文不分析condition,所以略过吧,下一篇文章会介绍这个 - static final int CONDITION = -2; - /** - * waitStatus value to indicate the next acquireShared should - * unconditionally propagate - */ - // 同样的不分析,略过吧 - static final int PROPAGATE = -3; - // ===================================================== +

而com.ctrip.framework.apollo.spring.config.PropertySourcesProcessor 实现了 org.springframework.beans.factory.config.BeanFactoryPostProcessor
它里面的 com.ctrip.framework.apollo.spring.config.PropertySourcesProcessor#postProcessBeanFactory 方法就会被 spring 调用,

+
private void initializePropertySources() {
+    if (environment.getPropertySources().contains(PropertySourcesConstants.APOLLO_PROPERTY_SOURCE_NAME)) {
+      //already initialized
+      return;
+    }
+    CompositePropertySource composite = new CompositePropertySource(PropertySourcesConstants.APOLLO_PROPERTY_SOURCE_NAME);
 
+    //sort by order asc
+    ImmutableSortedSet<Integer> orders = ImmutableSortedSet.copyOf(NAMESPACE_NAMES.keySet());
+    Iterator<Integer> iterator = orders.iterator();
 
-    // 取值为上面的1、-1、-2、-3,或者0(以后会讲到)
-    // 这么理解,暂时只需要知道如果这个值 大于0 代表此线程取消了等待,
-    //    ps: 半天抢不到锁,不抢了,ReentrantLock是可以指定timeouot的。。。
-    volatile int waitStatus;
-    // 前驱节点的引用
-    volatile Node prev;
-    // 后继节点的引用
-    volatile Node next;
-    // 这个就是线程本尊
-    volatile Thread thread;
+    while (iterator.hasNext()) {
+      int order = iterator.next();
+      for (String namespace : NAMESPACE_NAMES.get(order)) {
+      // 这里获取每个 namespace 的配置
+        Config config = ConfigService.getConfig(namespace);
 
-}
-

其实可以主要关注这个 waitStatus 因为这个是后面的节点给前面的节点设置的,等于-1 的时候代表后面有节点等待,需要去唤醒,
这里使用了一个变种的 CLH 队列实现,CLH 队列相关内容可以查看这篇 自旋锁、排队自旋锁、MCS锁、CLH锁

-]]>
- - java - - - java - aqs - -
- - Apollo 的 value 注解是怎么自动更新的 - /2020/11/01/Apollo-%E7%9A%84-value-%E6%B3%A8%E8%A7%A3%E6%98%AF%E6%80%8E%E4%B9%88%E8%87%AA%E5%8A%A8%E6%9B%B4%E6%96%B0%E7%9A%84/ - 在前司和目前公司,用的配置中心都是使用的 Apollo,经过了业界验证,比较强大的配置管理系统,特别是在0.10 后开始支持对使用 value 注解的配置值进行自动更新,今天刚好有个同学问到我,就顺便写篇文章记录下,其实也是借助于 spring 强大的 bean 生命周期管理,可以实现BeanPostProcessor接口,使用postProcessBeforeInitialization方法,来对bean 内部的属性和方法进行判断,是否有 value 注解,如果有就是将它注册到一个 map 中,可以看到这个方法com.ctrip.framework.apollo.spring.annotation.SpringValueProcessor#processField

+ composite.addPropertySource(configPropertySourceFactory.getConfigPropertySource(namespace, config)); + } + }
+

然后是 com.ctrip.framework.apollo.ConfigService#getConfig
接着就是它
com.ctrip.framework.apollo.internals.DefaultConfigManager#getConfig

@Override
-  protected void processField(Object bean, String beanName, Field field) {
-    // register @Value on field
-    Value value = field.getAnnotation(Value.class);
-    if (value == null) {
-      return;
-    }
-    Set<String> keys = placeholderHelper.extractPlaceholderKeys(value.value());
+  public Config getConfig(String namespace) {
+    Config config = m_configs.get(namespace);
 
-    if (keys.isEmpty()) {
-      return;
-    }
+    if (config == null) {
+      synchronized (this) {
+        config = m_configs.get(namespace);
 
-    for (String key : keys) {
-      SpringValue springValue = new SpringValue(key, value.value(), bean, beanName, field, false);
-      springValueRegistry.register(beanFactory, key, springValue);
-      logger.debug("Monitoring {}", springValue);
-    }
-  }
-

然后我们看下这个springValueRegistry是啥玩意

-
public class SpringValueRegistry {
-  private static final long CLEAN_INTERVAL_IN_SECONDS = 5;
-  private final Map<BeanFactory, Multimap<String, SpringValue>> registry = Maps.newConcurrentMap();
-  private final AtomicBoolean initialized = new AtomicBoolean(false);
-  private final Object LOCK = new Object();
+        if (config == null) {
+          ConfigFactory factory = m_factoryManager.getFactory(namespace);
 
-  public void register(BeanFactory beanFactory, String key, SpringValue springValue) {
-    if (!registry.containsKey(beanFactory)) {
-      synchronized (LOCK) {
-        if (!registry.containsKey(beanFactory)) {
-          registry.put(beanFactory, LinkedListMultimap.<String, SpringValue>create());
+// 通过 factory 来创建配置获取
+          config = factory.create(namespace);
+          m_configs.put(namespace, config);
         }
       }
+    }
+

创建配置

+
com.ctrip.framework.apollo.spi.DefaultConfigFactory#create
+@Override
+  public Config create(String namespace) {
+    ConfigFileFormat format = determineFileFormat(namespace);
+    if (ConfigFileFormat.isPropertiesCompatible(format)) {
+      return new DefaultConfig(namespace, createPropertiesCompatibleFileConfigRepository(namespace, format));
     }
-
-    registry.get(beanFactory).put(key, springValue);
-
-    // lazy initialize
-    if (initialized.compareAndSet(false, true)) {
-      initialize();
+    // 调用到这
+    return new DefaultConfig(namespace, createLocalConfigRepository(namespace));
+  }
+

然后

+
LocalFileConfigRepository createLocalConfigRepository(String namespace) {
+    if (m_configUtil.isInLocalMode()) {
+      logger.warn(
+          "==== Apollo is in local mode! Won't pull configs from remote server for namespace {} ! ====",
+          namespace);
+      return new LocalFileConfigRepository(namespace);
     }
-  }
-

这类其实就是个 map 来存放 springvalue,然后有com.ctrip.framework.apollo.spring.property.AutoUpdateConfigChangeListener来监听更新操作,当有变更时

-
@Override
- public void onChange(ConfigChangeEvent changeEvent) {
-   Set<String> keys = changeEvent.changedKeys();
-   if (CollectionUtils.isEmpty(keys)) {
-     return;
-   }
-   for (String key : keys) {
-     // 1. check whether the changed key is relevant
-     Collection<SpringValue> targetValues = springValueRegistry.get(beanFactory, key);
-     if (targetValues == null || targetValues.isEmpty()) {
-       continue;
-     }
-
-     // 2. check whether the value is really changed or not (since spring property sources have hierarchies)
-     // 这里其实有一点比较绕,是因为 Apollo 里的 namespace 划分,会出现 key 相同,但是 namespace 不同的情况,所以会有个优先级存在,所以需要去校验 environment 里面的是否已经更新,如果未更新则表示不需要更新
-     if (!shouldTriggerAutoUpdate(changeEvent, key)) {
-       continue;
-     }
+    // 正常会走这个,因为要从配置中心获取
+    return new LocalFileConfigRepository(namespace, createRemoteConfigRepository(namespace));
+  }
- // 3. update the value - for (SpringValue val : targetValues) { - updateSpringValue(val); - } - } - }
-

其实原理很简单,就是得了解知道下

-]]>
- - Java - Apollo - value - - - Java - Apollo - environment - value - 注解 - -
- - 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;
-}
+

然后是创建远程配置仓库

+
com.ctrip.framework.apollo.spi.DefaultConfigFactory#createRemoteConfigRepository
+  RemoteConfigRepository createRemoteConfigRepository(String namespace) {
+    return new RemoteConfigRepository(namespace);
+  }
+

继续对当前的 namespace 创建远程配置仓库

+
com.ctrip.framework.apollo.internals.RemoteConfigRepository#RemoteConfigRepository
+public RemoteConfigRepository(String namespace) {
+    m_namespace = namespace;
+    m_configCache = new AtomicReference<>();
+    m_configUtil = ApolloInjector.getInstance(ConfigUtil.class);
+    m_httpUtil = ApolloInjector.getInstance(HttpUtil.class);
+    m_serviceLocator = ApolloInjector.getInstance(ConfigServiceLocator.class);
+    remoteConfigLongPollService = ApolloInjector.getInstance(RemoteConfigLongPollService.class);
+    m_longPollServiceDto = new AtomicReference<>();
+    m_remoteMessages = new AtomicReference<>();
+    m_loadConfigRateLimiter = RateLimiter.create(m_configUtil.getLoadConfigQPS());
+    m_configNeedForceRefresh = new AtomicBoolean(true);
+    m_loadConfigFailSchedulePolicy = new ExponentialSchedulePolicy(m_configUtil.getOnErrorRetryInterval(),
+        m_configUtil.getOnErrorRetryInterval() * 8);
+    gson = new Gson();
+    // 尝试同步
+    this.trySync();
+    this.schedulePeriodicRefresh();
+    this.scheduleLongPollingRefresh();
+  }
+

然后是同步配置,下面的日志异常经常可以看到,比如配置拉取地址不通

+
com.ctrip.framework.apollo.internals.AbstractConfigRepository#trySync
+  protected boolean trySync() {
+    try {
+      sync();
+      return true;
+    } catch (Throwable ex) {
+      Tracer.logEvent("ApolloConfigException", ExceptionUtil.getDetailMessage(ex));
+      logger
+          .warn("Sync config failed, will retry. Repository {}, reason: {}", this.getClass(), ExceptionUtil
+              .getDetailMessage(ex));
+    }
+    return false;
+  }
+

实际的同步方法,加了synchronized 锁,

+
com.ctrip.framework.apollo.internals.RemoteConfigRepository#sync
+@Override
+  protected synchronized void sync() {
+    Transaction transaction = Tracer.newTransaction("Apollo.ConfigService", "syncRemoteConfig");
 
-class Value extends LhsPadding
-{
-    protected volatile long value;
-}
+    try {
+      // 获取本地配置
+      ApolloConfig previous = m_configCache.get();
+      // 获取配置
+      ApolloConfig current = loadApolloConfig();
 
-class RhsPadding extends Value
-{
-    protected long p9, p10, p11, p12, p13, p14, p15;
-}
+      //reference equals means HTTP 304
+      if (previous != current) {
+        logger.debug("Remote Config refreshed!");
+        m_configCache.set(current);
+        this.fireRepositoryChange(m_namespace, this.getConfig());
+      }
 
-/**
- * <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.
- *
- * <p>Also attempts to be more efficient with regards to false
- * sharing by adding padding around the volatile field.
- */
-public class Sequence extends RhsPadding
-{
-

通过代码可以看到,sequence 中其实真正有意义的是 value 字段,因为需要在多线程环境下可见也
使用了volatile 关键字,而 LhsPaddingRhsPadding 分别在value 前后填充了各
7 个 long 型的变量,long 型的变量在 Java 中是占用 8 bytes,这样就相当于不管怎么样,
value 都会单独使用一个缓存行,使得其不会产生 false sharing 的问题。

-]]> - - Java - - - Java - Disruptor - - - - Disruptor 系列一 - /2022/02/13/Disruptor-%E7%B3%BB%E5%88%97%E4%B8%80/ - 很久之前就听说过这个框架,不过之前有点跟消息队列混起来,这个也是种队列,但不是跟 rocketmq,nsq 那种一样的,而是在进程内部提供队列服务的,偏向于取代ArrayBlockingQueue,因为这个阻塞队列是使用了锁来控制阻塞,关于并发其实有一些通用的最佳实践,就是用锁,即使是 JDK 提供的锁,也是比较耗资源的,当然这是跟不加锁的对比,同样是锁,JDK 的实现还是性能比较优秀的。常见的阻塞队列中例如 ArrayBlockingQueueLinkedBlockingQueue 都有锁的身影的存在,区别在于 ArrayBlockingQueue 是一把锁,后者是两把锁,不过重点不在几把锁,这里其实是两个问题,一个是所谓的 lock free, 对于一个单生产者的 disruptor 来说,因为写入是只有一个线程的,是可以不用加锁,多生产者的时候使用的是 cas 来获取对应的写入坑位,另一个是解决“伪共享”问题,后面可以详细点分析,先介绍下使用
首先是数据源

-
public class LongEvent {
-    private long value;
+      if (current != null) {
+        Tracer.logEvent(String.format("Apollo.Client.Configs.%s", current.getNamespaceName()),
+            current.getReleaseKey());
+      }
 
-    public void set(long value) {
-        this.value = value;
+      transaction.setStatus(Transaction.SUCCESS);
+    } catch (Throwable ex) {
+      transaction.setStatus(ex);
+      throw ex;
+    } finally {
+      transaction.complete();
     }
-
-    public long getValue() {
-        return value;
+  }
+

然后走到这

+
com.ctrip.framework.apollo.internals.RemoteConfigRepository#loadApolloConfig
+private ApolloConfig loadApolloConfig() {
+    if (!m_loadConfigRateLimiter.tryAcquire(5, TimeUnit.SECONDS)) {
+      //wait at most 5 seconds
+      try {
+        TimeUnit.SECONDS.sleep(5);
+      } catch (InterruptedException e) {
+      }
     }
+    String appId = m_configUtil.getAppId();
+    String cluster = m_configUtil.getCluster();
+    String dataCenter = m_configUtil.getDataCenter();
+    Tracer.logEvent("Apollo.Client.ConfigMeta", STRING_JOINER.join(appId, cluster, m_namespace));
+    int maxRetries = m_configNeedForceRefresh.get() ? 2 : 1;
+    long onErrorSleepTime = 0; // 0 means no sleep
+    Throwable exception = null;
 
-    public void setValue(long value) {
-        this.value = value;
-    }
-}
-

事件生产

-
public class LongEventFactory implements EventFactory<LongEvent>
-{
-    public LongEvent newInstance()
-    {
-        return new LongEvent();
-    }
-}
-

事件处理器

-
public class LongEventHandler implements EventHandler<LongEvent> {
+	// 获取配置
+    List<ServiceDTO> configServices = getConfigServices();
+    String url = null;
+    for (int i = 0; i < maxRetries; i++) {
+      List<ServiceDTO> randomConfigServices = Lists.newLinkedList(configServices);
+      Collections.shuffle(randomConfigServices);
+      //Access the server which notifies the client first
+      if (m_longPollServiceDto.get() != null) {
+        randomConfigServices.add(0, m_longPollServiceDto.getAndSet(null));
+      }
 
-    // event 事件,
-    // sequence 当前的序列 
-    // 是否当前批次最后一个数据
-    public void onEvent(LongEvent event, long sequence, boolean endOfBatch)
-    {
-        String str = String.format("long event : %s l:%s b:%s", event.getValue(), sequence, endOfBatch);
-        System.out.println(str);
-    }
-}
-
-

主方法代码

-
package disruptor;
+      for (ServiceDTO configService : randomConfigServices) {
+        if (onErrorSleepTime > 0) {
+          logger.warn(
+              "Load config failed, will retry in {} {}. appId: {}, cluster: {}, namespaces: {}",
+              onErrorSleepTime, m_configUtil.getOnErrorRetryIntervalTimeUnit(), appId, cluster, m_namespace);
 
-import com.lmax.disruptor.RingBuffer;
-import com.lmax.disruptor.dsl.Disruptor;
-import com.lmax.disruptor.util.DaemonThreadFactory;
+          try {
+            m_configUtil.getOnErrorRetryIntervalTimeUnit().sleep(onErrorSleepTime);
+          } catch (InterruptedException e) {
+            //ignore
+          }
+        }
 
-import java.nio.ByteBuffer;
+        url = assembleQueryConfigUrl(configService.getHomepageUrl(), appId, cluster, m_namespace,
+                dataCenter, m_remoteMessages.get(), m_configCache.get());
 
-public class LongEventMain
-{
-    public static void main(String[] args) throws Exception
-    {
-        // 这个需要是 2 的幂次,这样在定位的时候只需要位移操作,也能减少各种计算操作
-        int bufferSize = 1024; 
+        logger.debug("Loading config from {}", url);
+        HttpRequest request = new HttpRequest(url);
 
-        Disruptor<LongEvent> disruptor = 
-                new Disruptor<>(LongEvent::new, bufferSize, DaemonThreadFactory.INSTANCE);
+        Transaction transaction = Tracer.newTransaction("Apollo.ConfigService", "queryConfig");
+        transaction.addData("Url", url);
+        try {
 
-        // 类似于注册处理器
-        disruptor.handleEventsWith(new LongEventHandler());
-        // 或者直接用 lambda
-        disruptor.handleEventsWith((event, sequence, endOfBatch) ->
-                System.out.println("Event: " + event));
-        // 启动我们的 disruptor
-        disruptor.start(); 
+          HttpResponse<ApolloConfig> response = m_httpUtil.doGet(request, ApolloConfig.class);
+          m_configNeedForceRefresh.set(false);
+          m_loadConfigFailSchedulePolicy.success();
+
+          transaction.addData("StatusCode", response.getStatusCode());
+          transaction.setStatus(Transaction.SUCCESS);
 
+          if (response.getStatusCode() == 304) {
+            logger.debug("Config server responds with 304 HTTP status code.");
+            return m_configCache.get();
+          }
 
-        RingBuffer<LongEvent> ringBuffer = disruptor.getRingBuffer(); 
-        ByteBuffer bb = ByteBuffer.allocate(8);
-        for (long l = 0; true; l++)
-        {
-            bb.putLong(0, l);
-            // 生产事件
-            ringBuffer.publishEvent((event, sequence, buffer) -> event.set(buffer.getLong(0)), bb);
-            Thread.sleep(1000);
+          ApolloConfig result = response.getBody();
+
+          logger.debug("Loaded config for {}: {}", m_namespace, result);
+
+          return result;
+        } catch (ApolloConfigStatusCodeException ex) {
+          ApolloConfigStatusCodeException statusCodeException = ex;
+          //config not found
+          if (ex.getStatusCode() == 404) {
+            String message = String.format(
+                "Could not find config for namespace - appId: %s, cluster: %s, namespace: %s, " +
+                    "please check whether the configs are released in Apollo!",
+                appId, cluster, m_namespace);
+            statusCodeException = new ApolloConfigStatusCodeException(ex.getStatusCode(),
+                message);
+          }
+          Tracer.logEvent("ApolloConfigException", ExceptionUtil.getDetailMessage(statusCodeException));
+          transaction.setStatus(statusCodeException);
+          exception = statusCodeException;
+        } catch (Throwable ex) {
+          Tracer.logEvent("ApolloConfigException", ExceptionUtil.getDetailMessage(ex));
+          transaction.setStatus(ex);
+          exception = ex;
+        } finally {
+          transaction.complete();
         }
+
+        // if force refresh, do normal sleep, if normal config load, do exponential sleep
+        onErrorSleepTime = m_configNeedForceRefresh.get() ? m_configUtil.getOnErrorRetryInterval() :
+            m_loadConfigFailSchedulePolicy.fail();
+      }
+
     }
-}
-

运行下可以看到运行结果

这里其实就只是最简单的使用,生产者只有一个,然后也不是批量的。

-]]>
- - Java - - - Java - Disruptor - -
- - G1收集器概述 - /2020/02/09/G1%E6%94%B6%E9%9B%86%E5%99%A8%E6%A6%82%E8%BF%B0/ - 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
- //   minor type (eden / survivor, starts / cont hum, etc.) : bottom 1 bit
- //
- // If there's need to increase the number of minor types in the
- // future, we'll have to increase the size of the latter and hence
- // decrease the size of the former.
- //
- // 00000 0 [ 0] Free
- //
- // 00001 0 [ 2] Young Mask
- // 00001 0 [ 2] Eden
- // 00001 1 [ 3] Survivor
- //
- // 00010 0 [ 4] Humongous Mask
- // 00100 0 [ 8] Pinned Mask
- // 00110 0 [12] Starts Humongous
- // 00110 1 [13] Continues Humongous
- //
- // 01000 0 [16] Old Mask
- //
- // 10000 0 [32] Archive Mask
- // 11100 0 [56] Open Archive
- // 11100 1 [57] Closed Archive
- //
- typedef enum {
-   FreeTag               = 0,
+    String message = String.format(
+        "Load Apollo Config failed - appId: %s, cluster: %s, namespace: %s, url: %s",
+        appId, cluster, m_namespace, url);
+    throw new ApolloConfigException(message, exception);
+  }
- YoungMask = 2, - EdenTag = YoungMask, - SurvTag = YoungMask + 1, - HumongousMask = 4, - PinnedMask = 8, - StartsHumongousTag = HumongousMask | PinnedMask, - ContinuesHumongousTag = HumongousMask | PinnedMask + 1, +
com.ctrip.framework.apollo.internals.RemoteConfigRepository#getConfigServices
+  private List<ServiceDTO> getConfigServices() {
+    List<ServiceDTO> services = m_serviceLocator.getConfigServices();
+    if (services.size() == 0) {
+      throw new ApolloConfigException("No available config service");
+    }
 
-   OldMask               = 16,
-   OldTag                = OldMask,
+    return services;
+  }
- // Archive regions are regions with immutable content (i.e. not reclaimed, and - // not allocated into during regular operation). They differ in the kind of references - // allowed for the contained objects: - // - Closed archive regions form a separate self-contained (closed) object graph - // within the set of all of these regions. No references outside of closed - // archive regions are allowed. - // - Open archive regions have no restrictions on the references of their objects. - // Objects within these regions are allowed to have references to objects - // contained in any other kind of regions. - ArchiveMask = 32, - OpenArchiveTag = ArchiveMask | PinnedMask | OldMask, - ClosedArchiveTag = ArchiveMask | PinnedMask | OldMask + 1 - } Tag;
+
com.ctrip.framework.apollo.internals.ConfigServiceLocator#getConfigServices
+  public List<ServiceDTO> getConfigServices() {
+    if (m_configServices.get().isEmpty()) {
+      updateConfigServices();
+    }
+
+    return m_configServices.get();
+  }
+

更新配置服务

+
com.ctrip.framework.apollo.internals.ConfigServiceLocator#updateConfigServices
+private synchronized void updateConfigServices() {
+    String url = assembleMetaServiceUrl();
+
+    HttpRequest request = new HttpRequest(url);
+    int maxRetries = 2;
+    Throwable exception = null;
+
+    for (int i = 0; i < maxRetries; i++) {
+      Transaction transaction = Tracer.newTransaction("Apollo.MetaService", "getConfigService");
+      transaction.addData("Url", url);
+      try {
+        // 发起 http 请求获取配置
+        HttpResponse<List<ServiceDTO>> response = m_httpUtil.doGet(request, m_responseType);
+        transaction.setStatus(Transaction.SUCCESS);
+        List<ServiceDTO> services = response.getBody();
+        if (services == null || services.isEmpty()) {
+          logConfigService("Empty response!");
+          continue;
+        }
+        setConfigServices(services);
+        return;
+      } catch (Throwable ex) {
+        Tracer.logEvent("ApolloConfigException", ExceptionUtil.getDetailMessage(ex));
+        transaction.setStatus(ex);
+        exception = ex;
+      } finally {
+        transaction.complete();
+      }
+
+      try {
+        m_configUtil.getOnErrorRetryIntervalTimeUnit().sleep(m_configUtil.getOnErrorRetryInterval());
+      } catch (InterruptedException ex) {
+        //ignore
+      }
+    }
+
+    throw new ApolloConfigException(
+        String.format("Get config services failed from %s", url), exception);
+  }
-

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 的一大特点。

]]>
Java - JVM - GC - C++ Java - JVM - C++ - G1 - GC - Garbage-First Collector + Apollo
- 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;
+    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.
 
-import java.io.IOException;
+A graph is defined below:
+struct Node {
+vector neighbors;
+}
-/** - * 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 { + +

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 + + + + Apollo 的 value 注解是怎么自动更新的 + /2020/11/01/Apollo-%E7%9A%84-value-%E6%B3%A8%E8%A7%A3%E6%98%AF%E6%80%8E%E4%B9%88%E8%87%AA%E5%8A%A8%E6%9B%B4%E6%96%B0%E7%9A%84/ + 在前司和目前公司,用的配置中心都是使用的 Apollo,经过了业界验证,比较强大的配置管理系统,特别是在0.10 后开始支持对使用 value 注解的配置值进行自动更新,今天刚好有个同学问到我,就顺便写篇文章记录下,其实也是借助于 spring 强大的 bean 生命周期管理,可以实现BeanPostProcessor接口,使用postProcessBeforeInitialization方法,来对bean 内部的属性和方法进行判断,是否有 value 注解,如果有就是将它注册到一个 map 中,可以看到这个方法com.ctrip.framework.apollo.spring.annotation.SpringValueProcessor#processField

+
@Override
+  protected void processField(Object bean, String beanName, Field field) {
+    // register @Value on field
+    Value value = field.getAnnotation(Value.class);
+    if (value == null) {
+      return;
+    }
+    Set<String> keys = placeholderHelper.extractPlaceholderKeys(value.value());
 
-    /**
-     * 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;
+    if (keys.isEmpty()) {
+      return;
+    }
 
-    /**
-     *
-     * Returns a {@link ServletConfig} object, which contains initialization and
-     * startup parameters for this servlet. The <code>ServletConfig</code>
-     * object returned is the one passed to the <code>init</code> method.
-     *
-     * <p>
-     * Implementations of this interface are responsible for storing the
-     * <code>ServletConfig</code> object so that this method can return it. The
-     * {@link GenericServlet} class, which implements this interface, already
-     * does this.
-     *
-     * @return the <code>ServletConfig</code> object that initializes this
-     *         servlet
-     *
-     * @see #init
-     */
-    public ServletConfig getServletConfig();
+    for (String key : keys) {
+      SpringValue springValue = new SpringValue(key, value.value(), bean, beanName, field, false);
+      springValueRegistry.register(beanFactory, key, springValue);
+      logger.debug("Monitoring {}", springValue);
+    }
+  }
+

然后我们看下这个springValueRegistry是啥玩意

+
public class SpringValueRegistry {
+  private static final long CLEAN_INTERVAL_IN_SECONDS = 5;
+  private final Map<BeanFactory, Multimap<String, SpringValue>> registry = Maps.newConcurrentMap();
+  private final AtomicBoolean initialized = new AtomicBoolean(false);
+  private final Object LOCK = new Object();
 
-    /**
-     * Called by the servlet container to allow the servlet to respond to a
-     * request.
-     *
-     * <p>
-     * This method is only called after the servlet's <code>init()</code> method
-     * has completed successfully.
-     *
-     * <p>
-     * The status code of the response always should be set for a servlet that
-     * throws or sends an error.
-     *
-     *
-     * <p>
-     * Servlets typically run inside multithreaded servlet containers that can
-     * handle multiple requests concurrently. Developers must be aware to
-     * synchronize access to any shared resources such as files, network
-     * connections, and as well as the servlet's class and instance variables.
-     * More information on multithreaded programming in Java is available in <a
-     * href
-     * ="http://java.sun.com/Series/Tutorial/java/threads/multithreaded.html">
-     * the Java tutorial on multi-threaded programming</a>.
-     *
-     *
-     * @param req
-     *            the <code>ServletRequest</code> object that contains the
-     *            client's request
-     *
-     * @param res
-     *            the <code>ServletResponse</code> object that contains the
-     *            servlet's response
-     *
-     * @exception ServletException
-     *                if an exception occurs that interferes with the servlet's
-     *                normal operation
-     *
-     * @exception IOException
-     *                if an input or output exception occurs
-     */
-    public void service(ServletRequest req, ServletResponse res)
-            throws ServletException, IOException;
+  public void register(BeanFactory beanFactory, String key, SpringValue springValue) {
+    if (!registry.containsKey(beanFactory)) {
+      synchronized (LOCK) {
+        if (!registry.containsKey(beanFactory)) {
+          registry.put(beanFactory, LinkedListMultimap.<String, SpringValue>create());
+        }
+      }
+    }
 
-    /**
-     * Returns information about the servlet, such as author, version, and
-     * copyright.
-     *
-     * <p>
-     * The string that this method returns should be plain text and not markup
-     * of any kind (such as HTML, XML, etc.).
-     *
-     * @return a <code>String</code> containing servlet information
-     */
-    public String getServletInfo();
+    registry.get(beanFactory).put(key, springValue);
 
-    /**
-     * Called by the servlet container to indicate to a servlet that the servlet
-     * is being taken out of service. This method is only called once all
-     * threads within the servlet's <code>service</code> method have exited or
-     * after a timeout period has passed. After the servlet container calls this
-     * method, it will not call the <code>service</code> method again on this
-     * servlet.
-     *
-     * <p>
-     * This method gives the servlet an opportunity to clean up any resources
-     * that are being held (for example, memory, file handles, threads) and make
-     * sure that any persistent state is synchronized with the servlet's current
-     * state in memory.
-     */
-    public void destroy();
-}
-
-

重点看 servlet 的 service方法,就是接受请求,处理完了给响应,不说细节,不然光 Tomcat 的能说半年,所以呢再进一步去理解,其实就能知道,就是一个先后的问题,盗个图

filter 跟后两者最大的不一样其实是一个基于 servlet,在非常外层做的处理,然后是 interceptor 的 prehandle 跟 posthandle,接着才是我们常规的 aop,就这么点事情,做个小试验吧(还是先补段代码吧)

-

Filter

// ---------------------------------------------------- FilterChain Methods
+    // lazy initialize
+    if (initialized.compareAndSet(false, true)) {
+      initialize();
+    }
+  }
+

这类其实就是个 map 来存放 springvalue,然后有com.ctrip.framework.apollo.spring.property.AutoUpdateConfigChangeListener来监听更新操作,当有变更时

+
@Override
+ public void onChange(ConfigChangeEvent changeEvent) {
+   Set<String> keys = changeEvent.changedKeys();
+   if (CollectionUtils.isEmpty(keys)) {
+     return;
+   }
+   for (String key : keys) {
+     // 1. check whether the changed key is relevant
+     Collection<SpringValue> targetValues = springValueRegistry.get(beanFactory, key);
+     if (targetValues == null || targetValues.isEmpty()) {
+       continue;
+     }
 
-    /**
-     * Invoke the next filter in this chain, passing the specified request
-     * and response.  If there are no more filters in this chain, invoke
-     * the <code>service()</code> method of the servlet itself.
-     *
-     * @param request The servlet request we are processing
-     * @param response The servlet response we are creating
-     *
-     * @exception IOException if an input/output error occurs
-     * @exception ServletException if a servlet exception occurs
-     */
-    @Override
-    public void doFilter(ServletRequest request, ServletResponse response)
-        throws IOException, ServletException {
+     // 2. check whether the value is really changed or not (since spring property sources have hierarchies)
+     // 这里其实有一点比较绕,是因为 Apollo 里的 namespace 划分,会出现 key 相同,但是 namespace 不同的情况,所以会有个优先级存在,所以需要去校验 environment 里面的是否已经更新,如果未更新则表示不需要更新
+     if (!shouldTriggerAutoUpdate(changeEvent, key)) {
+       continue;
+     }
 
-        if( Globals.IS_SECURITY_ENABLED ) {
-            final ServletRequest req = request;
-            final ServletResponse res = response;
-            try {
-                java.security.AccessController.doPrivileged(
-                    new java.security.PrivilegedExceptionAction<Void>() {
-                        @Override
-                        public Void run()
-                            throws ServletException, IOException {
-                            internalDoFilter(req,res);
-                            return null;
-                        }
-                    }
-                );
-            } catch( PrivilegedActionException pe) {
-                Exception e = pe.getException();
-                if (e instanceof ServletException)
-                    throw (ServletException) e;
-                else if (e instanceof IOException)
-                    throw (IOException) e;
-                else if (e instanceof RuntimeException)
-                    throw (RuntimeException) e;
-                else
-                    throw new ServletException(e.getMessage(), e);
-            }
-        } else {
-            internalDoFilter(request,response);
-        }
+     // 3. update the value
+     for (SpringValue val : targetValues) {
+       updateSpringValue(val);
+     }
+   }
+ }
+

其实原理很简单,就是得了解知道下

+]]>
+ + Java + Apollo + value + + + Java + Apollo + environment + value + 注解 + +
+ + Disruptor 系列一 + /2022/02/13/Disruptor-%E7%B3%BB%E5%88%97%E4%B8%80/ + 很久之前就听说过这个框架,不过之前有点跟消息队列混起来,这个也是种队列,但不是跟 rocketmq,nsq 那种一样的,而是在进程内部提供队列服务的,偏向于取代ArrayBlockingQueue,因为这个阻塞队列是使用了锁来控制阻塞,关于并发其实有一些通用的最佳实践,就是用锁,即使是 JDK 提供的锁,也是比较耗资源的,当然这是跟不加锁的对比,同样是锁,JDK 的实现还是性能比较优秀的。常见的阻塞队列中例如 ArrayBlockingQueueLinkedBlockingQueue 都有锁的身影的存在,区别在于 ArrayBlockingQueue 是一把锁,后者是两把锁,不过重点不在几把锁,这里其实是两个问题,一个是所谓的 lock free, 对于一个单生产者的 disruptor 来说,因为写入是只有一个线程的,是可以不用加锁,多生产者的时候使用的是 cas 来获取对应的写入坑位,另一个是解决“伪共享”问题,后面可以详细点分析,先介绍下使用
首先是数据源

+
public class LongEvent {
+    private long value;
+
+    public void set(long value) {
+        this.value = value;
     }
-    private void internalDoFilter(ServletRequest request,
-                                  ServletResponse response)
-        throws IOException, ServletException {
 
-        // Call the next filter if there is one
-        if (pos < n) {
-            ApplicationFilterConfig filterConfig = filters[pos++];
-            try {
-                Filter filter = filterConfig.getFilter();
+    public long getValue() {
+        return value;
+    }
 
-                if (request.isAsyncSupported() && "false".equalsIgnoreCase(
-                        filterConfig.getFilterDef().getAsyncSupported())) {
-                    request.setAttribute(Globals.ASYNC_SUPPORTED_ATTR, Boolean.FALSE);
-                }
-                if( Globals.IS_SECURITY_ENABLED ) {
-                    final ServletRequest req = request;
-                    final ServletResponse res = response;
-                    Principal principal =
-                        ((HttpServletRequest) req).getUserPrincipal();
+    public void setValue(long value) {
+        this.value = value;
+    }
+}
+

事件生产

+
public class LongEventFactory implements EventFactory<LongEvent>
+{
+    public LongEvent newInstance()
+    {
+        return new LongEvent();
+    }
+}
+

事件处理器

+
public class LongEventHandler implements EventHandler<LongEvent> {
 
-                    Object[] args = new Object[]{req, res, this};
-                    SecurityUtil.doAsPrivilege ("doFilter", filter, classType, args, principal);
-                } else {
-                    filter.doFilter(request, response, this);
-                }
-            } catch (IOException | ServletException | RuntimeException e) {
-                throw e;
-            } catch (Throwable e) {
-                e = ExceptionUtils.unwrapInvocationTargetException(e);
-                ExceptionUtils.handleThrowable(e);
-                throw new ServletException(sm.getString("filterChain.filter"), e);
-            }
-            return;
-        }
+    // event 事件,
+    // sequence 当前的序列 
+    // 是否当前批次最后一个数据
+    public void onEvent(LongEvent event, long sequence, boolean endOfBatch)
+    {
+        String str = String.format("long event : %s l:%s b:%s", event.getValue(), sequence, endOfBatch);
+        System.out.println(str);
+    }
+}
+
+

主方法代码

+
package disruptor;
 
-        // We fell off the end of the chain -- call the servlet instance
-        try {
-            if (ApplicationDispatcher.WRAP_SAME_OBJECT) {
-                lastServicedRequest.set(request);
-                lastServicedResponse.set(response);
-            }
+import com.lmax.disruptor.RingBuffer;
+import com.lmax.disruptor.dsl.Disruptor;
+import com.lmax.disruptor.util.DaemonThreadFactory;
 
-            if (request.isAsyncSupported() && !servletSupportsAsync) {
-                request.setAttribute(Globals.ASYNC_SUPPORTED_ATTR,
-                        Boolean.FALSE);
-            }
-            // Use potentially wrapped request from this point
-            if ((request instanceof HttpServletRequest) &&
-                    (response instanceof HttpServletResponse) &&
-                    Globals.IS_SECURITY_ENABLED ) {
-                final ServletRequest req = request;
-                final ServletResponse res = response;
-                Principal principal =
-                    ((HttpServletRequest) req).getUserPrincipal();
-                Object[] args = new Object[]{req, res};
-                SecurityUtil.doAsPrivilege("service",
-                                           servlet,
-                                           classTypeUsedInService,
-                                           args,
-                                           principal);
-            } else {
-                servlet.service(request, response);
-            }
-        } catch (IOException | ServletException | RuntimeException e) {
-            throw e;
-        } catch (Throwable e) {
-            e = ExceptionUtils.unwrapInvocationTargetException(e);
-            ExceptionUtils.handleThrowable(e);
-            throw new ServletException(sm.getString("filterChain.servlet"), e);
-        } finally {
-            if (ApplicationDispatcher.WRAP_SAME_OBJECT) {
-                lastServicedRequest.set(null);
-                lastServicedResponse.set(null);
-            }
-        }
-    }
-

注意看这一行
filter.doFilter(request, response, this);
是不是看懂了,就是个 filter 链,但是这个代码在哪呢,org.apache.catalina.core.ApplicationFilterChain#doFilter
然后是interceptor,

-
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
-        HttpServletRequest processedRequest = request;
-        HandlerExecutionChain mappedHandler = null;
-        boolean multipartRequestParsed = false;
-        WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
+import java.nio.ByteBuffer;
 
-        try {
-            try {
-                ModelAndView mv = null;
-                Object dispatchException = null;
+public class LongEventMain
+{
+    public static void main(String[] args) throws Exception
+    {
+        // 这个需要是 2 的幂次,这样在定位的时候只需要位移操作,也能减少各种计算操作
+        int bufferSize = 1024; 
 
-                try {
-                    processedRequest = this.checkMultipart(request);
-                    multipartRequestParsed = processedRequest != request;
-                    mappedHandler = this.getHandler(processedRequest);
-                    if (mappedHandler == null) {
-                        this.noHandlerFound(processedRequest, response);
-                        return;
-                    }
+        Disruptor<LongEvent> disruptor = 
+                new Disruptor<>(LongEvent::new, bufferSize, DaemonThreadFactory.INSTANCE);
 
-                    HandlerAdapter ha = this.getHandlerAdapter(mappedHandler.getHandler());
-                    String method = request.getMethod();
-                    boolean isGet = "GET".equals(method);
-                    if (isGet || "HEAD".equals(method)) {
-                        long lastModified = ha.getLastModified(request, mappedHandler.getHandler());
-                        if ((new ServletWebRequest(request, response)).checkNotModified(lastModified) && isGet) {
-                            return;
-                        }
-                    }
+        // 类似于注册处理器
+        disruptor.handleEventsWith(new LongEventHandler());
+        // 或者直接用 lambda
+        disruptor.handleEventsWith((event, sequence, endOfBatch) ->
+                System.out.println("Event: " + event));
+        // 启动我们的 disruptor
+        disruptor.start(); 
 
-                    /** 
-                     * 看这里看这里‼️
-                     */
-                    if (!mappedHandler.applyPreHandle(processedRequest, response)) {
-                        return;
-                    }
 
-                    mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
-                    if (asyncManager.isConcurrentHandlingStarted()) {
-                        return;
-                    }
+        RingBuffer<LongEvent> ringBuffer = disruptor.getRingBuffer(); 
+        ByteBuffer bb = ByteBuffer.allocate(8);
+        for (long l = 0; true; l++)
+        {
+            bb.putLong(0, l);
+            // 生产事件
+            ringBuffer.publishEvent((event, sequence, buffer) -> event.set(buffer.getLong(0)), bb);
+            Thread.sleep(1000);
+        }
+    }
+}
+

运行下可以看到运行结果

这里其实就只是最简单的使用,生产者只有一个,然后也不是批量的。

+]]>
+ + Java + + + Java + Disruptor + +
+ + 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 {
 
-                    this.applyDefaultViewName(processedRequest, mv);
-                    /** 
-                     * 再看这里看这里‼️
-                     */
-                    mappedHandler.applyPostHandle(processedRequest, response, mv);
-                } catch (Exception var20) {
-                    dispatchException = var20;
-                } catch (Throwable var21) {
-                    dispatchException = new NestedServletException("Handler dispatch failed", var21);
-                }
-
-                this.processDispatchResult(processedRequest, response, mappedHandler, mv, (Exception)dispatchException);
-            } catch (Exception var22) {
-                this.triggerAfterCompletion(processedRequest, response, mappedHandler, var22);
-            } catch (Throwable var23) {
-                this.triggerAfterCompletion(processedRequest, response, mappedHandler, new NestedServletException("Handler processing failed", var23));
-            }
+    private Long id;
 
-        } finally {
-            if (asyncManager.isConcurrentHandlingStarted()) {
-                if (mappedHandler != null) {
-                    mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);
-                }
-            } else if (multipartRequestParsed) {
-                this.cleanupMultipart(processedRequest);
-            }
+    private Long sortValue;
 
-        }
-    }
-

代码在哪呢,org.springframework.web.servlet.DispatcherServlet#doDispatch,然后才是我们自己写的 aop,是不是差不多明白了,嗯,接下来是例子
写个 filter

-
public class DemoFilter extends HttpServlet implements Filter {
-    @Override
-    public void init(FilterConfig filterConfig) throws ServletException {
-        System.out.println("==>DemoFilter启动");
+    public Long getId() {
+        return id;
     }
 
-    @Override
-    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
-        // 将请求转换成HttpServletRequest 请求
-        HttpServletRequest req = (HttpServletRequest) servletRequest;
-        HttpServletResponse resp = (HttpServletResponse) servletResponse;
-        System.out.println("before filter");
-        filterChain.doFilter(req, resp);
-        System.out.println("after filter");
+    public void setId(Long id) {
+        this.id = id;
     }
 
-    @Override
-    public void destroy() {
-
-    }
-}
-

因为用的springboot,所以就不写 web.xml 了,写个配置类

-
@Configuration
-public class FilterConfiguration {
-    @Bean
-    public FilterRegistrationBean filterDemo4Registration() {
-        FilterRegistrationBean registration = new FilterRegistrationBean();
-        //注入过滤器
-        registration.setFilter(new DemoFilter());
-        //拦截规则
-        registration.addUrlPatterns("/*");
-        //过滤器名称
-        registration.setName("DemoFilter");
-        //是否自动注册 false 取消Filter的自动注册
-        registration.setEnabled(true);
-        //过滤器顺序
-        registration.setOrder(1);
-        return registration;
+    public Long getSortValue() {
+        return sortValue;
     }
 
-}
-

然后再来个 interceptor 和 aop,以及一个简单的请求处理

-
public class DemoInterceptor extends HandlerInterceptorAdapter {
-    @Override
-    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
-        System.out.println("preHandle test");
-        return true;
+    public void setSortValue(Long sortValue) {
+        this.sortValue = sortValue;
     }
+}
+

Comparator

+
public class MyComparator implements Comparator {
     @Override
-    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
-        System.out.println("postHandle test");
+    public int compare(Object o1, Object o2) {
+        Entity e1 = (Entity) o1;
+        Entity e2 = (Entity) o2;
+        if (e1.getSortValue() < e2.getSortValue()) {
+            return -1;
+        } else if (e1.getSortValue().equals(e2.getSortValue())) {
+            return 0;
+        } else {
+            return 1;
+        }
     }
-}
-@Aspect
-@Component
-public class DemoAspect {
+}
- @Pointcut("execution( public * com.nicksxs.springbootdemo.demo.DemoController.*())") - public void point() { +

比较代码

+
private static MyComparator myComparator = new MyComparator();
 
-    }
+    public static void main(String[] args) {
+        List<Entity> list = new ArrayList<Entity>();
+        Entity e1 = new Entity();
+        e1.setId(1L);
+        e1.setSortValue(1L);
+        list.add(e1);
+        Entity e2 = new Entity();
+        e2.setId(2L);
+        e2.setSortValue(null);
+        list.add(e2);
+        Collections.sort(list, myComparator);
- @Before("point()") - public void doBefore(){ - System.out.println("==doBefore=="); - } +

看到这里的e2的排序值是null,在Comparator中如果要正常运行的话,就得判空之类的,这里有两点需要,一个是不想写这个MyComparator,然后也没那么好排除掉list里排序值,那么有什么办法能解决这种问题呢,应该说java的这方面真的是很强大

+

+

看一下nullsFirst的实现

+
final static class NullComparator<T> implements Comparator<T>, Serializable {
+        private static final long serialVersionUID = -7569533591570686392L;
+        private final boolean nullFirst;
+        // if null, non-null Ts are considered equal
+        private final Comparator<T> real;
 
-    @After("point()")
-    public void doAfter(){
-        System.out.println("==doAfter==");
-    }
+        @SuppressWarnings("unchecked")
+        NullComparator(boolean nullFirst, Comparator<? super T> real) {
+            this.nullFirst = nullFirst;
+            this.real = (Comparator<T>) real;
+        }
+
+        @Override
+        public int compare(T a, T b) {
+            if (a == null) {
+                return (b == null) ? 0 : (nullFirst ? -1 : 1);
+            } else if (b == null) {
+                return nullFirst ? 1: -1;
+            } else {
+                return (real == null) ? 0 : real.compare(a, b);
+            }
+        }
+ +

核心代码就是下面这段,其实就是帮我们把前面要做的事情做掉了,是不是挺方便的,小记一下哈

+]]>
+ + Java + 集合 + + + Java + Stream + Comparator + 排序 + sort + nullsfirst + +
+ + 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;
 }
-@RestController
-public class DemoController {
 
-    @RequestMapping("/hello")
-    @ResponseBody
-    public String hello() {
-        return "hello world";
-    }
-}
-

好了,请求一下,看看 stdout,

搞定完事儿~

+class Value extends LhsPadding +{ + protected volatile long value; +} + +class RhsPadding extends Value +{ + protected long p9, p10, p11, p12, p13, p14, p15; +} + +/** + * <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. + * + * <p>Also attempts to be more efficient with regards to false + * sharing by adding padding around the volatile field. + */ +public class Sequence extends RhsPadding +{
+

通过代码可以看到,sequence 中其实真正有意义的是 value 字段,因为需要在多线程环境下可见也
使用了volatile 关键字,而 LhsPaddingRhsPadding 分别在value 前后填充了各
7 个 long 型的变量,long 型的变量在 Java 中是占用 8 bytes,这样就相当于不管怎么样,
value 都会单独使用一个缓存行,使得其不会产生 false sharing 的问题。

]]>
Java - Filter - Interceptor - AOP - Spring - Servlet - Interceptor - AOP Java - Filter - Interceptor - AOP - Spring - Tomcat - Servlet - Web + Disruptor
@@ -2401,493 +1851,932 @@ Node *clone(Node *graph) { - 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;
-    }
+ G1收集器概述 + /2020/02/09/G1%E6%94%B6%E9%9B%86%E5%99%A8%E6%A6%82%E8%BF%B0/ + 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
+ //   minor type (eden / survivor, starts / cont hum, etc.) : bottom 1 bit
+ //
+ // If there's need to increase the number of minor types in the
+ // future, we'll have to increase the size of the latter and hence
+ // decrease the size of the former.
+ //
+ // 00000 0 [ 0] Free
+ //
+ // 00001 0 [ 2] Young Mask
+ // 00001 0 [ 2] Eden
+ // 00001 1 [ 3] Survivor
+ //
+ // 00010 0 [ 4] Humongous Mask
+ // 00100 0 [ 8] Pinned Mask
+ // 00110 0 [12] Starts Humongous
+ // 00110 1 [13] Continues Humongous
+ //
+ // 01000 0 [16] Old Mask
+ //
+ // 10000 0 [32] Archive Mask
+ // 11100 0 [56] Open Archive
+ // 11100 1 [57] Closed Archive
+ //
+ typedef enum {
+   FreeTag               = 0,
 
-

结果

+ YoungMask = 2, + EdenTag = YoungMask, + SurvTag = YoungMask + 1, + + HumongousMask = 4, + PinnedMask = 8, + StartsHumongousTag = HumongousMask | PinnedMask, + ContinuesHumongousTag = HumongousMask | PinnedMask + 1, + + OldMask = 16, + OldTag = OldMask, + + // Archive regions are regions with immutable content (i.e. not reclaimed, and + // not allocated into during regular operation). They differ in the kind of references + // allowed for the contained objects: + // - Closed archive regions form a separate self-contained (closed) object graph + // within the set of all of these regions. No references outside of closed + // archive regions are allowed. + // - Open archive regions have no restrictions on the references of their objects. + // Objects within these regions are allowed to have references to objects + // contained in any other kind of regions. + 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 的一大特点。

]]>
Java - leetcode - - - leetcode - java - 题解 - -
- - Leetcode 053 最大子序和 ( Maximum Subarray ) 题解分析 - /2021/11/28/Leetcode-053-%E6%9C%80%E5%A4%A7%E5%AD%90%E5%BA%8F%E5%92%8C-Maximum-Subarray-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/ - 题目介绍

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++) {
-            // 这里最重要的就是这一行了,其实就是如果前面的 sum 是小于 0 的,那么就不需要前面的 sum,反正加上了还不如不加大
-            sum = Math.max(nums[i], sum + nums[i]);
-            // max 是用来承载最大值的
-            max = Math.max(max, sum);
-        }
-        return max;
-    }
]]>
- - Java - leetcode + JVM + GC + C++ - leetcode - java - 题解 + Java + JVM + C++ + 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");
+    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;
 
-  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;
-    }
-  }
+import java.io.IOException;
 
-  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();
+/**
+ * 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 {
 
-    // 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);
+    /**
+     * 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;
 
-    // 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;
-    }
-  }
-
-  // Try a partial collection of some kind.
-  _pause_succeeded = g1h->do_collection_pause_at_safepoint(_target_pause_time_ms);
-
-  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");
-
-  if (GCLocker::check_active_before_gc()) {
-    return false;
-  }
-
-  _gc_timer_stw->register_gc_start();
+    /**
+     *
+     * Returns a {@link ServletConfig} object, which contains initialization and
+     * startup parameters for this servlet. The <code>ServletConfig</code>
+     * object returned is the one passed to the <code>init</code> method.
+     *
+     * <p>
+     * Implementations of this interface are responsible for storing the
+     * <code>ServletConfig</code> object so that this method can return it. The
+     * {@link GenericServlet} class, which implements this interface, already
+     * does this.
+     *
+     * @return the <code>ServletConfig</code> object that initializes this
+     *         servlet
+     *
+     * @see #init
+     */
+    public ServletConfig getServletConfig();
 
-  GCIdMark gc_id_mark;
-  _gc_tracer_stw->report_gc_start(gc_cause(), _gc_timer_stw->gc_start());
+    /**
+     * Called by the servlet container to allow the servlet to respond to a
+     * request.
+     *
+     * <p>
+     * This method is only called after the servlet's <code>init()</code> method
+     * has completed successfully.
+     *
+     * <p>
+     * The status code of the response always should be set for a servlet that
+     * throws or sends an error.
+     *
+     *
+     * <p>
+     * Servlets typically run inside multithreaded servlet containers that can
+     * handle multiple requests concurrently. Developers must be aware to
+     * synchronize access to any shared resources such as files, network
+     * connections, and as well as the servlet's class and instance variables.
+     * More information on multithreaded programming in Java is available in <a
+     * href
+     * ="http://java.sun.com/Series/Tutorial/java/threads/multithreaded.html">
+     * the Java tutorial on multi-threaded programming</a>.
+     *
+     *
+     * @param req
+     *            the <code>ServletRequest</code> object that contains the
+     *            client's request
+     *
+     * @param res
+     *            the <code>ServletResponse</code> object that contains the
+     *            servlet's response
+     *
+     * @exception ServletException
+     *                if an exception occurs that interferes with the servlet's
+     *                normal operation
+     *
+     * @exception IOException
+     *                if an input or output exception occurs
+     */
+    public void service(ServletRequest req, ServletResponse res)
+            throws ServletException, IOException;
 
-  SvcGCMarker sgcm(SvcGCMarker::MINOR);
-  ResourceMark rm;
+    /**
+     * Returns information about the servlet, such as author, version, and
+     * copyright.
+     *
+     * <p>
+     * The string that this method returns should be plain text and not markup
+     * of any kind (such as HTML, XML, etc.).
+     *
+     * @return a <code>String</code> containing servlet information
+     */
+    public String getServletInfo();
 
-  g1_policy()->note_gc_start();
+    /**
+     * Called by the servlet container to indicate to a servlet that the servlet
+     * is being taken out of service. This method is only called once all
+     * threads within the servlet's <code>service</code> method have exited or
+     * after a timeout period has passed. After the servlet container calls this
+     * method, it will not call the <code>service</code> method again on this
+     * servlet.
+     *
+     * <p>
+     * This method gives the servlet an opportunity to clean up any resources
+     * that are being held (for example, memory, file handles, threads) and make
+     * sure that any persistent state is synchronized with the servlet's current
+     * state in memory.
+     */
+    public void destroy();
+}
+
+

重点看 servlet 的 service方法,就是接受请求,处理完了给响应,不说细节,不然光 Tomcat 的能说半年,所以呢再进一步去理解,其实就能知道,就是一个先后的问题,盗个图

filter 跟后两者最大的不一样其实是一个基于 servlet,在非常外层做的处理,然后是 interceptor 的 prehandle 跟 posthandle,接着才是我们常规的 aop,就这么点事情,做个小试验吧(还是先补段代码吧)

+

Filter

// ---------------------------------------------------- FilterChain Methods
 
-  wait_for_root_region_scanning();
+    /**
+     * Invoke the next filter in this chain, passing the specified request
+     * and response.  If there are no more filters in this chain, invoke
+     * the <code>service()</code> method of the servlet itself.
+     *
+     * @param request The servlet request we are processing
+     * @param response The servlet response we are creating
+     *
+     * @exception IOException if an input/output error occurs
+     * @exception ServletException if a servlet exception occurs
+     */
+    @Override
+    public void doFilter(ServletRequest request, ServletResponse response)
+        throws IOException, ServletException {
 
-  print_heap_before_gc();
-  print_heap_regions();
-  trace_heap_before_gc(_gc_tracer_stw);
+        if( Globals.IS_SECURITY_ENABLED ) {
+            final ServletRequest req = request;
+            final ServletResponse res = response;
+            try {
+                java.security.AccessController.doPrivileged(
+                    new java.security.PrivilegedExceptionAction<Void>() {
+                        @Override
+                        public Void run()
+                            throws ServletException, IOException {
+                            internalDoFilter(req,res);
+                            return null;
+                        }
+                    }
+                );
+            } catch( PrivilegedActionException pe) {
+                Exception e = pe.getException();
+                if (e instanceof ServletException)
+                    throw (ServletException) e;
+                else if (e instanceof IOException)
+                    throw (IOException) e;
+                else if (e instanceof RuntimeException)
+                    throw (RuntimeException) e;
+                else
+                    throw new ServletException(e.getMessage(), e);
+            }
+        } else {
+            internalDoFilter(request,response);
+        }
+    }
+    private void internalDoFilter(ServletRequest request,
+                                  ServletResponse response)
+        throws IOException, ServletException {
 
-  _verifier->verify_region_sets_optional();
-  _verifier->verify_dirty_young_regions();
+        // Call the next filter if there is one
+        if (pos < n) {
+            ApplicationFilterConfig filterConfig = filters[pos++];
+            try {
+                Filter filter = filterConfig.getFilter();
 
-  // 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();
-  }
+                if (request.isAsyncSupported() && "false".equalsIgnoreCase(
+                        filterConfig.getFilterDef().getAsyncSupported())) {
+                    request.setAttribute(Globals.ASYNC_SUPPORTED_ATTR, Boolean.FALSE);
+                }
+                if( Globals.IS_SECURITY_ENABLED ) {
+                    final ServletRequest req = request;
+                    final ServletResponse res = response;
+                    Principal principal =
+                        ((HttpServletRequest) req).getUserPrincipal();
 
-  // 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");
+                    Object[] args = new Object[]{req, res, this};
+                    SecurityUtil.doAsPrivilege ("doFilter", filter, classType, args, principal);
+                } else {
+                    filter.doFilter(request, response, this);
+                }
+            } catch (IOException | ServletException | RuntimeException e) {
+                throw e;
+            } catch (Throwable e) {
+                e = ExceptionUtils.unwrapInvocationTargetException(e);
+                ExceptionUtils.handleThrowable(e);
+                throw new ServletException(sm.getString("filterChain.filter"), e);
+            }
+            return;
+        }
 
-  // We also do not allow mixed GCs during marking.
-  assert(!collector_state()->mark_or_rebuild_in_progress() || collector_state()->in_young_only_phase(), "sanity");
+        // We fell off the end of the chain -- call the servlet instance
+        try {
+            if (ApplicationDispatcher.WRAP_SAME_OBJECT) {
+                lastServicedRequest.set(request);
+                lastServicedResponse.set(response);
+            }
 
-  // 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();
-
-  // Inner scope for scope based logging, timers, and stats collection
-  {
-    EvacuationInfo evacuation_info;
-
-    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());
+            if (request.isAsyncSupported() && !servletSupportsAsync) {
+                request.setAttribute(Globals.ASYNC_SUPPORTED_ATTR,
+                        Boolean.FALSE);
+            }
+            // Use potentially wrapped request from this point
+            if ((request instanceof HttpServletRequest) &&
+                    (response instanceof HttpServletResponse) &&
+                    Globals.IS_SECURITY_ENABLED ) {
+                final ServletRequest req = request;
+                final ServletResponse res = response;
+                Principal principal =
+                    ((HttpServletRequest) req).getUserPrincipal();
+                Object[] args = new Object[]{req, res};
+                SecurityUtil.doAsPrivilege("service",
+                                           servlet,
+                                           classTypeUsedInService,
+                                           args,
+                                           principal);
+            } else {
+                servlet.service(request, response);
+            }
+        } catch (IOException | ServletException | RuntimeException e) {
+            throw e;
+        } catch (Throwable e) {
+            e = ExceptionUtils.unwrapInvocationTargetException(e);
+            ExceptionUtils.handleThrowable(e);
+            throw new ServletException(sm.getString("filterChain.servlet"), e);
+        } finally {
+            if (ApplicationDispatcher.WRAP_SAME_OBJECT) {
+                lastServicedRequest.set(null);
+                lastServicedResponse.set(null);
+            }
+        }
+    }
+

注意看这一行
filter.doFilter(request, response, this);
是不是看懂了,就是个 filter 链,但是这个代码在哪呢,org.apache.catalina.core.ApplicationFilterChain#doFilter
然后是interceptor,

+
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
+        HttpServletRequest processedRequest = request;
+        HandlerExecutionChain mappedHandler = null;
+        boolean multipartRequestParsed = false;
+        WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
 
-    TraceCollectorStats tcs(g1mm()->incremental_collection_counters());
-    TraceMemoryManagerStats tms(&_memory_manager, gc_cause(),
-                                collector_state()->yc_type() == Mixed /* allMemoryPoolsAffected */);
+        try {
+            try {
+                ModelAndView mv = null;
+                Object dispatchException = null;
 
-    G1HeapTransition heap_transition(this);
-    size_t heap_used_bytes_before_gc = used();
+                try {
+                    processedRequest = this.checkMultipart(request);
+                    multipartRequestParsed = processedRequest != request;
+                    mappedHandler = this.getHandler(processedRequest);
+                    if (mappedHandler == null) {
+                        this.noHandlerFound(processedRequest, response);
+                        return;
+                    }
 
-    // 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.
+                    HandlerAdapter ha = this.getHandlerAdapter(mappedHandler.getHandler());
+                    String method = request.getMethod();
+                    boolean isGet = "GET".equals(method);
+                    if (isGet || "HEAD".equals(method)) {
+                        long lastModified = ha.getLastModified(request, mappedHandler.getHandler());
+                        if ((new ServletWebRequest(request, response)).checkNotModified(lastModified) && isGet) {
+                            return;
+                        }
+                    }
 
-    { // Call to jvmpi::post_class_unload_events must occur outside of active GC
-      IsGCActiveMark x;
+                    /** 
+                     * 看这里看这里‼️
+                     */
+                    if (!mappedHandler.applyPreHandle(processedRequest, response)) {
+                        return;
+                    }
 
-      gc_prologue(false);
+                    mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
+                    if (asyncManager.isConcurrentHandlingStarted()) {
+                        return;
+                    }
 
-      if (VerifyRememberedSets) {
-        log_info(gc, verify)("[Verifying RemSets before GC]");
-        VerifyRegionRemSetClosure v_cl;
-        heap_region_iterate(&v_cl);
-      }
+                    this.applyDefaultViewName(processedRequest, mv);
+                    /** 
+                     * 再看这里看这里‼️
+                     */
+                    mappedHandler.applyPostHandle(processedRequest, response, mv);
+                } catch (Exception var20) {
+                    dispatchException = var20;
+                } catch (Throwable var21) {
+                    dispatchException = new NestedServletException("Handler dispatch failed", var21);
+                }
 
-      _verifier->verify_before_gc(verify_type);
+                this.processDispatchResult(processedRequest, response, mappedHandler, mv, (Exception)dispatchException);
+            } catch (Exception var22) {
+                this.triggerAfterCompletion(processedRequest, response, mappedHandler, var22);
+            } catch (Throwable var23) {
+                this.triggerAfterCompletion(processedRequest, response, mappedHandler, new NestedServletException("Handler processing failed", var23));
+            }
 
-      _verifier->check_bitmaps("GC Start");
+        } finally {
+            if (asyncManager.isConcurrentHandlingStarted()) {
+                if (mappedHandler != null) {
+                    mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);
+                }
+            } else if (multipartRequestParsed) {
+                this.cleanupMultipart(processedRequest);
+            }
 
-#if COMPILER2_OR_JVMCI
-      DerivedPointerTable::clear();
-#endif
+        }
+    }
+

代码在哪呢,org.springframework.web.servlet.DispatcherServlet#doDispatch,然后才是我们自己写的 aop,是不是差不多明白了,嗯,接下来是例子
写个 filter

+
public class DemoFilter extends HttpServlet implements Filter {
+    @Override
+    public void init(FilterConfig filterConfig) throws ServletException {
+        System.out.println("==>DemoFilter启动");
+    }
 
-      // Please see comment in g1CollectedHeap.hpp and
-      // G1CollectedHeap::ref_processing_init() to see how
-      // reference processing currently works in G1.
+    @Override
+    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
+        // 将请求转换成HttpServletRequest 请求
+        HttpServletRequest req = (HttpServletRequest) servletRequest;
+        HttpServletResponse resp = (HttpServletResponse) servletResponse;
+        System.out.println("before filter");
+        filterChain.doFilter(req, resp);
+        System.out.println("after filter");
+    }
 
-      // Enable discovery in the STW reference processor
-      _ref_processor_stw->enable_discovery();
+    @Override
+    public void destroy() {
 
-      {
-        // 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);
+    }
+}
+

因为用的springboot,所以就不写 web.xml 了,写个配置类

+
@Configuration
+public class FilterConfiguration {
+    @Bean
+    public FilterRegistrationBean filterDemo4Registration() {
+        FilterRegistrationBean registration = new FilterRegistrationBean();
+        //注入过滤器
+        registration.setFilter(new DemoFilter());
+        //拦截规则
+        registration.addUrlPatterns("/*");
+        //过滤器名称
+        registration.setName("DemoFilter");
+        //是否自动注册 false 取消Filter的自动注册
+        registration.setEnabled(true);
+        //过滤器顺序
+        registration.setOrder(1);
+        return registration;
+    }
 
-        // Forget the current alloc region (we might even choose it to be part
-        // of the collection set!).
-        _allocator->release_mutator_alloc_region();
+}
+

然后再来个 interceptor 和 aop,以及一个简单的请求处理

+
public class DemoInterceptor extends HandlerInterceptorAdapter {
+    @Override
+    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
+        System.out.println("preHandle test");
+        return true;
+    }
 
-        // 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();
+    @Override
+    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
+        System.out.println("postHandle test");
+    }
+}
+@Aspect
+@Component
+public class DemoAspect {
 
-        g1_policy()->record_collection_pause_start(sample_start_time_sec);
+    @Pointcut("execution( public * com.nicksxs.springbootdemo.demo.DemoController.*())")
+    public void point() {
 
-        if (collector_state()->in_initial_mark_gc()) {
-          concurrent_mark()->pre_initial_mark();
-        }
+    }
 
-        g1_policy()->finalize_collection_set(target_pause_time_ms, &_survivor);
+    @Before("point()")
+    public void doBefore(){
+        System.out.println("==doBefore==");
+    }
 
-        evacuation_info.set_collectionset_regions(collection_set()->region_length());
+    @After("point()")
+    public void doAfter(){
+        System.out.println("==doAfter==");
+    }
+}
+@RestController
+public class DemoController {
 
-        // 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();
+    @RequestMapping("/hello")
+    @ResponseBody
+    public String hello() {
+        return "hello world";
+    }
+}
+

好了,请求一下,看看 stdout,

搞定完事儿~

+]]>
+ + Java + Filter + Interceptor - AOP + Spring + Servlet + Interceptor + AOP + + + Java + Filter + Interceptor + AOP + Spring + Tomcat + Servlet + Web + + + + 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);
 
-        assert(_verifier->check_cset_fast_test(), "Inconsistency in the InCSetState table.");
+  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;
 
-        // We call this after finalize_cset() to
-        // ensure that the CSet has been finalized.
-        _cm->verify_no_cset_oops();
+  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 (_hr_printer.is_active()) {
-          G1PrintCollectionSetClosure cl(&_hr_printer);
-          _collection_set.iterate(&cl);
-        }
+  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;
+    }
+  }
 
-        // Initialize the GC alloc regions.
-        _allocator->init_gc_alloc_regions(evacuation_info);
+  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();
 
-        G1ParScanThreadStateSet per_thread_states(this, workers()->active_workers(), collection_set()->young_region_length());
-        pre_evacuate_collection_set();
+    // 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);
 
-        // Actually do the work...
-        evacuate_collection_set(&per_thread_states);
+    // 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;
+    }
+  }
 
-        post_evacuate_collection_set(evacuation_info, &per_thread_states);
+  // Try a partial collection of some kind.
+  _pause_succeeded = g1h->do_collection_pause_at_safepoint(_target_pause_time_ms);
 
-        const size_t* surviving_young_words = per_thread_states.surviving_young_words();
-        free_collection_set(&_collection_set, evacuation_info, surviving_young_words);
+  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");
 
-        eagerly_reclaim_humongous_regions();
+  if (GCLocker::check_active_before_gc()) {
+    return false;
+  }
 
-        record_obj_copy_mem_stats();
-        _survivor_evac_stats.adjust_desired_plab_sz();
-        _old_evac_stats.adjust_desired_plab_sz();
+  _gc_timer_stw->register_gc_start();
 
-        double start = os::elapsedTime();
-        start_new_collection_set();
-        g1_policy()->phase_times()->record_start_new_cset_time_ms((os::elapsedTime() - start) * 1000.0);
+  GCIdMark gc_id_mark;
+  _gc_tracer_stw->report_gc_start(gc_cause(), _gc_timer_stw->gc_start());
 
-        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());
-        }
+  SvcGCMarker sgcm(SvcGCMarker::MINOR);
+  ResourceMark rm;
 
-        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.
-        }
+  g1_policy()->note_gc_start();
 
-        allocate_dummy_regions();
+  wait_for_root_region_scanning();
 
-        _allocator->init_mutator_alloc_region();
+  print_heap_before_gc();
+  print_heap_regions();
+  trace_heap_before_gc(_gc_tracer_stw);
 
-        {
-          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);
-          }
-        }
+  _verifier->verify_region_sets_optional();
+  _verifier->verify_dirty_young_regions();
 
-        // 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();
+  // 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();
+  }
 
-        // 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);
+  // 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");
 
-        evacuation_info.set_collectionset_used_before(collection_set()->bytes_used_before());
-        evacuation_info.set_bytes_copied(g1_policy()->bytes_copied_during_gc());
+  // We also do not allow mixed GCs during marking.
+  assert(!collector_state()->mark_or_rebuild_in_progress() || collector_state()->in_young_only_phase(), "sanity");
 
-        if (VerifyRememberedSets) {
-          log_info(gc, verify)("[Verifying RemSets after GC]");
-          VerifyRegionRemSetClosure v_cl;
-          heap_region_iterate(&v_cl);
-        }
+  // 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();
 
-        _verifier->verify_after_gc(verify_type);
-        _verifier->check_bitmaps("GC End");
+  // Inner scope for scope based logging, timers, and stats collection
+  {
+    EvacuationInfo evacuation_info;
+
+    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();
@@ -3118,47 +3007,233 @@ Node *clone(Node *graph) {
       
   
   
-    Leetcode 104 二叉树的最大深度(Maximum Depth of Binary Tree) 题解分析
-    /2020/10/25/Leetcode-104-%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E6%9C%80%E5%A4%A7%E6%B7%B1%E5%BA%A6-Maximum-Depth-of-Binary-Tree-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/
-    题目介绍

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

-

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

-

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

-

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

-
  3
- / \
-9  20
-  /  \
- 15   7
-

返回它的最大深度 3 。

-

代码

// 主体是个递归的应用
-public int maxDepth(TreeNode root) {
-    // 节点的退出条件之一
-    if (root == null) {
-        return 0;
-    }
-    int left = 0;
-    int right = 0;
-    // 存在左子树,就递归左子树
-    if (root.left != null) {
-        left = maxDepth(root.left);
-    }
-    // 存在右子树,就递归右子树
-    if (root.right != null) {
-        right = maxDepth(root.right);
-    }
-    // 前面返回后,左右取大者
-    return Math.max(left + 1, right + 1);
-}
-

分析

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

-]]>
- - Java - leetcode - Binary Tree - java - Binary Tree - DFS - + 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 + + + leetcode + java + 题解 + +
+ + 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 算法也是很厉害

+

code

public int strStr(String haystack, String needle) {
+        // 如果两个字符串都为空,返回 -1
+        if (haystack == null || needle == null) {
+            return -1;
+        }
+        // 如果 haystack 长度小于 needle 长度,返回 -1
+        if (haystack.length() < needle.length()) {
+            return -1;
+        }
+        // 如果 needle 为空字符串,返回 0
+        if (needle.equals("")) {
+            return 0;
+        }
+        // 如果两者相等,返回 0
+        if (haystack.equals(needle)) {
+            return 0;
+        }
+        int needleLength = needle.length();
+        int haystackLength = haystack.length();
+        for (int i = needleLength - 1; i <= haystackLength - 1; i++) {
+            // 比较 needle 最后一个字符,倒着比较稍微节省点时间
+            if (needle.charAt(needleLength - 1) == haystack.charAt(i)) {
+                // 如果needle 是 1 的话直接可以返回 i 作为位置了
+                if (needle.length() == 1) {
+                    return i;
+                }
+                boolean flag = true;
+                // 原来比的是 needle 的最后一个位置,然后这边从倒数第二个位置开始
+                int j = needle.length() - 2;
+                for (; j >= 0; j--) {
+                    // 这里的 i- (needleLength - j) + 1 ) 比较绕,其实是外循环的 i 表示当前 i 位置的字符跟 needle 最后一个字符
+                    // 相同,j 在上面的循环中--,对应的 haystack 也要在 i 这个位置 -- ,对应的位置就是 i - (needleLength - j) + 1
+                    if (needle.charAt(j) != haystack.charAt(i - (needleLength - j) + 1)) {
+                        flag = false;
+                        break;
+                    }
+                }
+                // 循环完了之后,如果 flag 为 true 说明 从 i 开始倒着对比都相同,但是这里需要起始位置,就需要
+                // i - needleLength + 1
+                if (flag) {
+                    return i - needleLength + 1;
+                }
+            }
+        }
+        // 这里表示未找到
+        return  -1;
+    }
]]>
+ + Java + leetcode + + + leetcode + java + 题解 + +
+ + Leetcode 053 最大子序和 ( Maximum Subarray ) 题解分析 + /2021/11/28/Leetcode-053-%E6%9C%80%E5%A4%A7%E5%AD%90%E5%BA%8F%E5%92%8C-Maximum-Subarray-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/ + 题目介绍

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++) {
+            // 这里最重要的就是这一行了,其实就是如果前面的 sum 是小于 0 的,那么就不需要前面的 sum,反正加上了还不如不加大
+            sum = Math.max(nums[i], sum + nums[i]);
+            // max 是用来承载最大值的
+            max = Math.max(max, sum);
+        }
+        return max;
+    }
]]>
+ + Java + leetcode + + + leetcode + java + 题解 + +
+ + Leetcode 104 二叉树的最大深度(Maximum Depth of Binary Tree) 题解分析 + /2020/10/25/Leetcode-104-%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E6%9C%80%E5%A4%A7%E6%B7%B1%E5%BA%A6-Maximum-Depth-of-Binary-Tree-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/ + 题目介绍

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

+

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

+

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

+

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

+
  3
+ / \
+9  20
+  /  \
+ 15   7
+

返回它的最大深度 3 。

+

代码

// 主体是个递归的应用
+public int maxDepth(TreeNode root) {
+    // 节点的退出条件之一
+    if (root == null) {
+        return 0;
+    }
+    int left = 0;
+    int right = 0;
+    // 存在左子树,就递归左子树
+    if (root.left != null) {
+        left = maxDepth(root.left);
+    }
+    // 存在右子树,就递归右子树
+    if (root.right != null) {
+        right = maxDepth(root.right);
+    }
+    // 前面返回后,左右取大者
+    return Math.max(left + 1, right + 1);
+}
+

分析

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

+]]>
+ + Java + leetcode + Binary Tree + java + Binary Tree + DFS + leetcode java @@ -3239,108 +3314,6 @@ Node *clone(Node *graph) { Print FooBar Alternately
- - Leetcode 121 买卖股票的最佳时机(Best Time to Buy and Sell Stock) 题解分析 - /2021/03/14/Leetcode-121-%E4%B9%B0%E5%8D%96%E8%82%A1%E7%A5%A8%E7%9A%84%E6%9C%80%E4%BD%B3%E6%97%B6%E6%9C%BA-Best-Time-to-Buy-and-Sell-Stock-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/ - 题目介绍

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;
-    }
-    int maxIn = prices[0];
-    int maxOut = prices[0];
-    for (int i = 1; i < prices.length; i++) {
-        if (maxIn > prices[i]) {
-            // 当循环当前值小于之前的买入值时就当成买入值,同时卖出也要更新
-            maxIn = prices[i];
-            maxOut = prices[i];
-        }
-        if (prices[i] > maxOut) {
-            // 表示一个可卖出点,即比买入值高时
-            maxOut = prices[i];
-            // 需要设置一个历史值
-            maxSofar = Math.max(maxSofar, maxOut - maxIn);
-        }
-    }
-    return maxSofar;
-}
- -

总结下

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

-]]>
- - Java - leetcode - java - DP - DP - - - leetcode - java - 题解 - DP - -
- - Leetcode 124 二叉树中的最大路径和(Binary Tree Maximum Path Sum) 题解分析 - /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/ - 题目介绍

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;
-    }
-    
-public int maxSumNew(TreeNode root) {
-    if (root == null) {
-        return 0;
-    }
-    // 这里是个简单的递归,就是去递归左右子树,但是这里其实有个概念,当这样处理时,其实相当于把子树的内部的最大路径和已经算出来了
-    int left = maxSumNew(root.left);
-    int right = maxSumNew(root.right);
-    // 这里前面我有点没想明白,但是看到 ansNew 的比较,其实相当于,返回的是三种情况里的最大值,一个是左子树+根,一个是右子树+根,一个是单独根节点,
-    // 这样这个递归的返回才会有意义,不然像原来的方法,它可能是跳着的,但是这种情况其实是借助于 ansNew 这个全局的最大值,因为原来我觉得要比较的是
-    // left, right, left + root , right + root, root, left + right + root 这些的最大值,这里是分成了两个阶段,left 跟 right 的最大值已经在上面的
-    // 调用过程中赋值给 ansNew 了    
-    int currentSum = Math.max(Math.max(root.val + left , root.val + right), root.val);
-    // 这边返回的是 currentSum,然后再用它跟 left + right + root 进行对比,然后再去更新 ans
-    // PS: 有个小点也是这边的破局点,就是这个 ansNew
-    int res = Math.max(left + right + root.val, currentSum);
-    ans = Math.max(res, ans);
-    return currentSum;
-}
- -

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

-

结果图

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

-]]>
- - Java - leetcode - Binary Tree - java - Binary Tree - - - leetcode - java - Binary Tree - 二叉树 - 题解 - -
Leetcode 105 从前序与中序遍历序列构造二叉树(Construct Binary Tree from Preorder and Inorder Traversal) 题解分析 /2020/12/13/Leetcode-105-%E4%BB%8E%E5%89%8D%E5%BA%8F%E4%B8%8E%E4%B8%AD%E5%BA%8F%E9%81%8D%E5%8E%86%E5%BA%8F%E5%88%97%E6%9E%84%E9%80%A0%E4%BA%8C%E5%8F%89%E6%A0%91-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/ @@ -3408,6 +3381,55 @@ inorder = [9,3,15,20,7] + + Leetcode 121 买卖股票的最佳时机(Best Time to Buy and Sell Stock) 题解分析 + /2021/03/14/Leetcode-121-%E4%B9%B0%E5%8D%96%E8%82%A1%E7%A5%A8%E7%9A%84%E6%9C%80%E4%BD%B3%E6%97%B6%E6%9C%BA-Best-Time-to-Buy-and-Sell-Stock-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/ + 题目介绍

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;
+    }
+    int maxIn = prices[0];
+    int maxOut = prices[0];
+    for (int i = 1; i < prices.length; i++) {
+        if (maxIn > prices[i]) {
+            // 当循环当前值小于之前的买入值时就当成买入值,同时卖出也要更新
+            maxIn = prices[i];
+            maxOut = prices[i];
+        }
+        if (prices[i] > maxOut) {
+            // 表示一个可卖出点,即比买入值高时
+            maxOut = prices[i];
+            // 需要设置一个历史值
+            maxSofar = Math.max(maxSofar, maxOut - maxIn);
+        }
+    }
+    return maxSofar;
+}
+ +

总结下

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

+]]>
+ + Java + leetcode + java + DP + DP + + + leetcode + java + 题解 + DP + +
Disruptor 系列三 /2022/09/25/Disruptor-%E7%B3%BB%E5%88%97%E4%B8%89/ @@ -3553,70 +3575,63 @@ inorder = [9,3,15,20,7] - 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 算法也是很厉害

-

code

public int strStr(String haystack, String needle) {
-        // 如果两个字符串都为空,返回 -1
-        if (haystack == null || needle == null) {
-            return -1;
-        }
-        // 如果 haystack 长度小于 needle 长度,返回 -1
-        if (haystack.length() < needle.length()) {
-            return -1;
-        }
-        // 如果 needle 为空字符串,返回 0
-        if (needle.equals("")) {
-            return 0;
-        }
-        // 如果两者相等,返回 0
-        if (haystack.equals(needle)) {
-            return 0;
-        }
-        int needleLength = needle.length();
-        int haystackLength = haystack.length();
-        for (int i = needleLength - 1; i <= haystackLength - 1; i++) {
-            // 比较 needle 最后一个字符,倒着比较稍微节省点时间
-            if (needle.charAt(needleLength - 1) == haystack.charAt(i)) {
-                // 如果needle 是 1 的话直接可以返回 i 作为位置了
-                if (needle.length() == 1) {
-                    return i;
-                }
-                boolean flag = true;
-                // 原来比的是 needle 的最后一个位置,然后这边从倒数第二个位置开始
-                int j = needle.length() - 2;
-                for (; j >= 0; j--) {
-                    // 这里的 i- (needleLength - j) + 1 ) 比较绕,其实是外循环的 i 表示当前 i 位置的字符跟 needle 最后一个字符
-                    // 相同,j 在上面的循环中--,对应的 haystack 也要在 i 这个位置 -- ,对应的位置就是 i - (needleLength - j) + 1
-                    if (needle.charAt(j) != haystack.charAt(i - (needleLength - j) + 1)) {
-                        flag = false;
-                        break;
+    Leetcode 16 最接近的三数之和 ( 3Sum Closest *Medium* ) 题解分析
+    /2022/08/06/Leetcode-16-%E6%9C%80%E6%8E%A5%E8%BF%91%E7%9A%84%E4%B8%89%E6%95%B0%E4%B9%8B%E5%92%8C-3Sum-Closest-Medium-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/
+    题目介绍

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];
+        for (int i = 0; i < nums.length - 2; i++) {
+            if (i == 0 || nums[i] != nums[i - 1]) {
+                // 左指针
+                int left = i + 1;
+                // 右指针
+                int right = nums.length - 1;
+                // 判断是否遍历完了
+                while (left < right) {
+                    // 当前的和
+                    int sum = nums[i] + nums[left] + nums[right];
+                    // 小优化,相等就略过了
+                    while (left < right && nums[left] == nums[left + 1]) {
+                        left++;
+                    }
+                    while (left < right && nums[right] == nums[right - 1]) {
+                        right--;
+                    }
+                    // 这里判断,其实也还是希望趋近目标值
+                    if (sum < target) {
+                        left++;
+                    } else {
+                        right--;
+                    }
+                    // 判断是否需要替换
+                    if (Math.abs(sum - target) < Math.abs(closestSum - target)) {
+                        closestSum = sum;
                     }
-                }
-                // 循环完了之后,如果 flag 为 true 说明 从 i 开始倒着对比都相同,但是这里需要起始位置,就需要
-                // i - needleLength + 1
-                if (flag) {
-                    return i - needleLength + 1;
                 }
             }
         }
-        // 这里表示未找到
-        return  -1;
-    }
]]>
+ return closestSum; + }
+ +

结果

+]]>
Java leetcode @@ -3625,29 +3640,164 @@ Output: 0
- Leetcode 155 最小栈(Min Stack) 题解分析 - /2020/12/06/Leetcode-155-%E6%9C%80%E5%B0%8F%E6%A0%88-Min-Stack-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/ - 题目介绍

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],[],[],[],[]]
-
-Output
-[null,null,null,null,-3,null,0,-2]
-
-Explanation
-MinStack minStack = new MinStack();
-minStack.push(-2);
+    Leetcode 1260 二维网格迁移 ( Shift 2D Grid *Easy* ) 题解分析
+    /2022/07/22/Leetcode-1260-%E4%BA%8C%E7%BB%B4%E7%BD%91%E6%A0%BC%E8%BF%81%E7%A7%BB-Shift-2D-Grid-Easy-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/
+    题目介绍

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;
+        // 列数
+        int n = grid[0].length;
+        // 偏移值,取下模
+        k = k % (m * n);
+        // 反向取下数量,因为我打算直接从头填充新的矩阵
+        /*
+         *    比如
+         *    1 2 3
+         *    4 5 6
+         *    7 8 9
+         *    需要变成
+         *    9 1 2
+         *    3 4 5
+         *    6 7 8
+         *    就要从 9 开始填充
+         */
+        int reverseK = m * n - k;
+        List<List<Integer>> matrix = new ArrayList<>();
+        // 这类就是两层循环
+        for (int i = 0; i < m; i++) {
+            List<Integer> line = new ArrayList<>();
+            for (int j = 0; j < n; j++) {
+                // 数量会随着循环迭代增长, 确认是第几个
+                int currentNum = reverseK + i * n +  (j + 1);
+                // 这里处理下到达矩阵末尾后减掉 m * n
+                if (currentNum > m * n) {
+                    currentNum -= m * n;
+                }
+                // 根据矩阵列数 n 算出在原来矩阵的位置
+                int last = (currentNum - 1) % n;
+                int passLine = (currentNum - 1) / n;
+
+                line.add(grid[passLine][last]);
+            }
+            matrix.add(line);
+        }
+        return matrix;
+    }
+ +

结果数据


比较慢

+]]>
+ + Java + leetcode + + + leetcode + java + 题解 + Shift 2D Grid + + + + Leetcode 124 二叉树中的最大路径和(Binary Tree Maximum Path Sum) 题解分析 + /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/ + 题目介绍

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;
+    }
+    
+public int maxSumNew(TreeNode root) {
+    if (root == null) {
+        return 0;
+    }
+    // 这里是个简单的递归,就是去递归左右子树,但是这里其实有个概念,当这样处理时,其实相当于把子树的内部的最大路径和已经算出来了
+    int left = maxSumNew(root.left);
+    int right = maxSumNew(root.right);
+    // 这里前面我有点没想明白,但是看到 ansNew 的比较,其实相当于,返回的是三种情况里的最大值,一个是左子树+根,一个是右子树+根,一个是单独根节点,
+    // 这样这个递归的返回才会有意义,不然像原来的方法,它可能是跳着的,但是这种情况其实是借助于 ansNew 这个全局的最大值,因为原来我觉得要比较的是
+    // left, right, left + root , right + root, root, left + right + root 这些的最大值,这里是分成了两个阶段,left 跟 right 的最大值已经在上面的
+    // 调用过程中赋值给 ansNew 了    
+    int currentSum = Math.max(Math.max(root.val + left , root.val + right), root.val);
+    // 这边返回的是 currentSum,然后再用它跟 left + right + root 进行对比,然后再去更新 ans
+    // PS: 有个小点也是这边的破局点,就是这个 ansNew
+    int res = Math.max(left + right + root.val, currentSum);
+    ans = Math.max(res, ans);
+    return currentSum;
+}
+ +

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

+

结果图

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

+]]>
+ + Java + leetcode + Binary Tree + java + Binary Tree + + + leetcode + java + Binary Tree + 二叉树 + 题解 + +
+ + Leetcode 155 最小栈(Min Stack) 题解分析 + /2020/12/06/Leetcode-155-%E6%9C%80%E5%B0%8F%E6%A0%88-Min-Stack-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/ + 题目介绍

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],[],[],[],[]]
+
+Output
+[null,null,null,null,-3,null,0,-2]
+
+Explanation
+MinStack minStack = new MinStack();
+minStack.push(-2);
 minStack.push(0);
 minStack.push(-3);
 minStack.getMin(); // return -3
@@ -3715,62 +3865,151 @@ minStack.getMin(); // return -2

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

@@ -4225,72 +4294,6 @@ Output: [8,9,9,9,0,0,0,1]
-

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]]

+ Leetcode 83 删除排序链表中的重复元素 ( Remove Duplicates from Sorted List *Easy* ) 题解分析 + /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/ + 题目介绍

给定一个已排序的链表的头 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;
+    }
+    ListNode tail = head;
+    // 以处理节点还有后续节点作为循环边界条件
+    while (tail.next != null) {
+        ListNode temp = tail.next;
+        // 如果前后相同,那么可以跳过这个节点,将 Tail  ---->   temp  ---> temp.next 
+        // 更新成  Tail ---->  temp.next
+        if (temp.val == tail.val) {
+            tail.next = temp.next;
+        } else {
+            // 不相同,则更新 tail
+            tail = tail.next;
+        }
+    }
+    // 最后返回头结点
+    return head;
+}
+

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

+]]>
+ + Java + leetcode + + + leetcode + java + 题解 + Remove Duplicates from Sorted List + + + + leetcode no.3 + /2015/04/15/Leetcode-No-3/ + **Longest Substring Without Repeating Characters **

+ +

description

Given a string, find the length of the longest substring without repeating characters.
For example, the longest substring without repeating letters for “abcabcbb” is “abc”,
which the length is 3. For “bbbbb” the longest substring is “b”, with the length of 1.

+

分析

源码这次是参考了这个代码,
tail 表示的当前子串的起始点位置,tail从-1开始就包括的串的长度是1的边界。其实我
也是猜的(逃

+
int ct[256];
+    memset(ct, -1, sizeof(ct));
+	int tail = -1;
+	int max = 0;
+	for (int i = 0; i < s.size(); i++){
+		if (ct[s[i]] > tail)
+			tail = ct[s[i]];
+		if (i - tail > max)
+			max = i - tail;
+		ct[s[i]] = i;
+	}
+	return max;
+]]>
+ + leetcode + + + leetcode + c++ + +
+ + Linux 下 grep 命令的一点小技巧 + /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/ + 用了比较久的 grep 命令,其实都只是用了最最基本的功能来查日志,

+

譬如

+

+grep 'xxx' xxxx.log
+
+ +

然后有挺多情况比如想要找日志里带一些符号什么的,就需要用到一些特殊的

+

比如这样\"userId\":\"123456\",因为比如用户 ID 有时候会跟其他的 id 一样,只用具体的值 123456 来查的话干扰信息太多了,如果直接这样

+

+grep '\"userId\":\"123456\"' xxxx.log
+
+ +

好像不行,盲猜就是符号的问题,特别是\"这两个,

+

之前一直是想试一下,但是没成功,昨天在排查一个问题的时候发现了,只要把这些都转义了就行了

+

grep '\\\"userId\\\":\\\"123456\\\"' xxxx.log

+

+]]>
+ + Linux + 命令 + 小技巧 + grep + grep + 查日志 + + + linux + grep + 转义 + +
+ + Leetcode 885 螺旋矩阵 III ( Spiral Matrix III *Medium* ) 题解分析 + /2022/08/23/Leetcode-885-%E8%9E%BA%E6%97%8B%E7%9F%A9%E9%98%B5-III-Spiral-Matrix-III-Medium-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/ + 题目介绍

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:

    @@ -4804,86 +4918,6 @@ maxR[n -题解 - - leetcode no.3 - /2015/04/15/Leetcode-No-3/ - **Longest Substring Without Repeating Characters **

    - -

    description

    Given a string, find the length of the longest substring without repeating characters.
    For example, the longest substring without repeating letters for “abcabcbb” is “abc”,
    which the length is 3. For “bbbbb” the longest substring is “b”, with the length of 1.

    -

    分析

    源码这次是参考了这个代码,
    tail 表示的当前子串的起始点位置,tail从-1开始就包括的串的长度是1的边界。其实我
    也是猜的(逃

    -
    int ct[256];
    -    memset(ct, -1, sizeof(ct));
    -	int tail = -1;
    -	int max = 0;
    -	for (int i = 0; i < s.size(); i++){
    -		if (ct[s[i]] > tail)
    -			tail = ct[s[i]];
    -		if (i - tail > max)
    -			max = i - tail;
    -		ct[s[i]] = i;
    -	}
    -	return max;
    -]]>
    - - leetcode - - - leetcode - c++ - -
    - - Leetcode 83 删除排序链表中的重复元素 ( Remove Duplicates from Sorted List *Easy* ) 题解分析 - /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/ - 题目介绍

    给定一个已排序的链表的头 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;
    -    }
    -    ListNode tail = head;
    -    // 以处理节点还有后续节点作为循环边界条件
    -    while (tail.next != null) {
    -        ListNode temp = tail.next;
    -        // 如果前后相同,那么可以跳过这个节点,将 Tail  ---->   temp  ---> temp.next 
    -        // 更新成  Tail ---->  temp.next
    -        if (temp.val == tail.val) {
    -            tail.next = temp.next;
    -        } else {
    -            // 不相同,则更新 tail
    -            tail = tail.next;
    -        }
    -    }
    -    // 最后返回头结点
    -    return head;
    -}
    -

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

    -]]>
    - - Java - leetcode - - - leetcode - java - 题解 - Remove Duplicates from Sorted List - -
    MFC 模态对话框 /2014/12/24/MFC%20%E6%A8%A1%E6%80%81%E5%AF%B9%E8%AF%9D%E6%A1%86/ @@ -4983,6 +5017,36 @@ OS name: "mac os x", version: "10.14.6", arch: "x86_64& Maven + + Number of 1 Bits + /2015/03/11/Number-Of-1-Bits/ + Number of 1 Bits

    Write a function that takes an unsigned integer and returns the number of ’1’ bits it has (also known as the Hamming weight). For example, the 32-bit integer ‘11’ has binary representation 00000000000000000000000000001011, so the function should return 3.

    + +

    分析

    从1位到2位到4位逐步的交换

    +
    +

    code

    int hammingWeight(uint32_t n) {
    +        const uint32_t m1  = 0x55555555; //binary: 0101...  
    +        const uint32_t m2  = 0x33333333; //binary: 00110011..  
    +        const uint32_t m4  = 0x0f0f0f0f; //binary:  4 zeros,  4 ones ...  
    +        const uint32_t m8  = 0x00ff00ff; //binary:  8 zeros,  8 ones ...  
    +        const uint32_t m16 = 0x0000ffff; //binary: 16 zeros, 16 ones ...  
    +        
    +        n = (n & m1 ) + ((n >>  1) & m1 ); //put count of each  2 bits into those  2 bits   
    +        n = (n & m2 ) + ((n >>  2) & m2 ); //put count of each  4 bits into those  4 bits   
    +        n = (n & m4 ) + ((n >>  4) & m4 ); //put count of each  8 bits into those  8 bits   
    +        n = (n & m8 ) + ((n >>  8) & m8 ); //put count of each 16 bits into those 16 bits   
    +        n = (n & m16) + ((n >> 16) & m16); //put count of each 32 bits into those 32 bits   
    +        return n; 
    +
    +}
    ]]>
    + + leetcode + + + leetcode + c++ + +
    Path Sum /2015/01/04/Path-Sum/ @@ -5036,139 +5100,18 @@ public: - Linux 下 grep 命令的一点小技巧 - /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/ - 用了比较久的 grep 命令,其实都只是用了最最基本的功能来查日志,

    -

    譬如

    -
    
    -grep 'xxx' xxxx.log
    -
    - -

    然后有挺多情况比如想要找日志里带一些符号什么的,就需要用到一些特殊的

    -

    比如这样\"userId\":\"123456\",因为比如用户 ID 有时候会跟其他的 id 一样,只用具体的值 123456 来查的话干扰信息太多了,如果直接这样

    -
    
    -grep '\"userId\":\"123456\"' xxxx.log
    -
    - -

    好像不行,盲猜就是符号的问题,特别是\"这两个,

    -

    之前一直是想试一下,但是没成功,昨天在排查一个问题的时候发现了,只要把这些都转义了就行了

    -

    grep '\\\"userId\\\":\\\"123456\\\"' xxxx.log

    -

    -]]>
    - - Linux - 命令 - 小技巧 - grep - grep - 查日志 - - - linux - grep - 转义 - -
    - - Number of 1 Bits - /2015/03/11/Number-Of-1-Bits/ - Number of 1 Bits

    Write a function that takes an unsigned integer and returns the number of ’1’ bits it has (also known as the Hamming weight). For example, the 32-bit integer ‘11’ has binary representation 00000000000000000000000000001011, so the function should return 3.

    - -

    分析

    从1位到2位到4位逐步的交换

    -
    -

    code

    int hammingWeight(uint32_t n) {
    -        const uint32_t m1  = 0x55555555; //binary: 0101...  
    -        const uint32_t m2  = 0x33333333; //binary: 00110011..  
    -        const uint32_t m4  = 0x0f0f0f0f; //binary:  4 zeros,  4 ones ...  
    -        const uint32_t m8  = 0x00ff00ff; //binary:  8 zeros,  8 ones ...  
    -        const uint32_t m16 = 0x0000ffff; //binary: 16 zeros, 16 ones ...  
    -        
    -        n = (n & m1 ) + ((n >>  1) & m1 ); //put count of each  2 bits into those  2 bits   
    -        n = (n & m2 ) + ((n >>  2) & m2 ); //put count of each  4 bits into those  4 bits   
    -        n = (n & m4 ) + ((n >>  4) & m4 ); //put count of each  8 bits into those  8 bits   
    -        n = (n & m8 ) + ((n >>  8) & m8 ); //put count of each 16 bits into those 16 bits   
    -        n = (n & m16) + ((n >> 16) & m16); //put count of each 32 bits into those 32 bits   
    -        return n; 
    -
    -}
    ]]>
    - - leetcode - - - leetcode - c++ - -
    - - Redis_分布式锁 - /2019/12/10/Redis-Part-1/ - 今天看了一下 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节点发起释放锁的操作,不管这些节点当时在获取锁的时候成功与否。这里为什么要向所有的节点发送释放锁的操作呢,这里是因为有部分的节点的失败原因可能是加锁时阻塞,加锁成功的结果没有及时返回,所以为了防止这种情况还是需要向所有发起这个释放锁的操作。
      初步记录就先到这。
    • -
    -]]>
    - - Redis - Distributed Lock - C - Redis - - - C - Redis - Distributed Lock - 分布式锁 - -
    - - ambari-summary - /2017/05/09/ambari-summary/ - 初识ambari

    ambari是一个大数据平台的管理工具,包含了hadoop, yarn, hive, hbase, spark等大数据的基础架构和工具,简化了数据平台的搭建,之前只是在同事搭建好平台后的一些使用,这次有机会从头开始用ambari来搭建一个测试的数据平台,过程中也踩到不少坑,简单记录下。

    -

    简单过程

      -
    • 第一个坑
      在刚开始是按照官网的指南,用maven构建,因为GFW的原因,导致反复失败等待,也就是这个guide,因为对maven不熟悉导致有些按图索骥,浪费了很多时间,之后才知道可以直接加repo用yum安装,然而用yum安装马上就出现了第二个坑。
    • -
    • 第二个坑
      因为在线的repo还是因为网络原因很慢很慢,用proxychains勉强把ambari-server本身安装好了,ambari.repo将这个放进/etc/yum.repos.d/路径下,然后yum update && yum install ambari-server安装即可,如果有条件就用proxychains走下代理。
    • -
    • 第三步
      安装好ambari-server后先执行ambari-server setup做一些初始化设置,其中包含了JDK路径的设置,数据库设置,设置好就OK了,然后执行ambari-server start启动服务,这里有个小插曲,因为ambari-server涉及到这么多服务,所以管理控制监控之类的模块是必不可少的,这部分可以在ambari-server的web ui界面安装,也可以命令行提前安装,这部分被称为HDF Management Pack,运行ambari-server install-mpack \ --mpack=http://public-repo-1.hortonworks.com/HDF/centos7/2.x/updates/2.1.4.0/tars/hdf_ambari_mp/hdf-ambari-mpack-2.1.4.0-5.tar.gz \ --purge \ --verbose
      安装,当然这个压缩包可以下载之后指到本地路径安装,然后就可以重启ambari-server
    • -
    -]]>
    - - data analysis - - - hadoop - cluster - -
    - - Reverse Integer - /2015/03/13/Reverse-Integer/ - Reverse Integer

    Reverse digits of an integer.

    Example1: x = 123, return 321
    Example2: x = -123, return -321

    - -

    spoilers

    Have you thought about this?
    Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

    -

    If the integer’s last digit is 0, what should the output be? ie, cases such as 10, 100.

    -

    Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

    -

    For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

    -
    -

    code

    class Solution {
    -public:
    -    int reverse(int x) {
    +    Reverse Integer
    +    /2015/03/13/Reverse-Integer/
    +    Reverse Integer

    Reverse digits of an integer.

    Example1: x = 123, return 321
    Example2: x = -123, return -321

    + +

    spoilers

    Have you thought about this?
    Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

    +

    If the integer’s last digit is 0, what should the output be? ie, cases such as 10, 100.

    +

    Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

    +

    For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

    +
    +

    code

    class Solution {
    +public:
    +    int reverse(int x) {
     
             int max = 1 << 31 - 1;
             int ret = 0;
    @@ -5191,6 +5134,33 @@ public:
             return ret;
         }
     };
    +]]>
    + + leetcode + + + leetcode + c++ + + + + Reverse Bits + /2015/03/11/Reverse-Bits/ + Reverse Bits

    Reverse bits of a given 32 bits unsigned integer.

    For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).

    + +

    Follow up:
    If this function is called many times, how would you optimize it?

    +
    +

    code

    class Solution {
    +public:
    +    uint32_t reverseBits(uint32_t n) {
    +        n = ((n >> 1) & 0x55555555) | ((n & 0x55555555) << 1);
    +        n = ((n >> 2) & 0x33333333) | ((n & 0x33333333) << 2);
    +        n = ((n >> 4) & 0x0f0f0f0f) | ((n & 0x0f0f0f0f) << 4);
    +        n = ((n >> 8) & 0x00ff00ff) | ((n & 0x00ff00ff) << 8);
    +        n = ((n >> 16) & 0x0000ffff) | ((n & 0x0000ffff) << 16);
    +        return n;
    +    }
    +};
    ]]>
    leetcode @@ -5269,33 +5239,6 @@ public: c++
    - - docker-mysql-cluster - /2016/08/14/docker-mysql-cluster/ - docker-mysql-cluster

    基于docker搭了个mysql集群,稍微记一下,
    首先是新建mysql主库容

    docker run -d -e MYSQL_ROOT_PASSWORD=admin --name mysql-master -p 3307:3306 mysql:latest
    -d表示容器运行在后台,-e表示设置环境变量,即MYSQL_ROOT_PASSWORD=admin,设置了mysql的root密码,
    --name表示容器名,-p表示端口映射,将内部mysql:3306映射为外部的3307,最后的mysql:latest表示镜像名
    此外还可以用-v /local_path/my-master.cnf:/etc/mysql/my.cnf来映射配置文件
    然后同理启动从库
    docker run -d -e MYSQL_ROOT_PASSWORD=admin --name mysql-slave -p 3308:3306 mysql:latest
    然后进入主库改下配置文件
    docker-enter mysql-master如果无法进入就用docker ps -a看下容器是否在正常运行,如果status显示
    未正常运行,则用docker logs mysql-master看下日志哪里出错了。
    进入容器后,我这边使用的镜像的mysqld配置文件是在/etc/mysql下面,这个最新版本的mysql的配置文件包含
    三部分,/etc/mysql/my.cnf/etc/mysql/conf.d/mysql.cnf,还有/etc/mysql/mysql.conf.d/mysqld.cnf
    这里需要改的是最后一个,加上

    -
    log-bin = mysql-bin
    -server_id = 1
    -

    保存后退出容器重启主库容器,然后进入从库更改相同文件,

    -
    log-bin = mysql-bin
    -server_id = 2
    -

    主从配置

    同样退出重启容器,然后是配置主从,首先进入主库,用命令mysql -u root -pxxxx进入mysql,然后赋予一个同步
    权限GRANT REPLICATION SLAVE ON *.* to 'backup'@'%' identified by '123456';还是同样说明下,ON *.*表示了数
    据库全部的权限,如果要指定数据库/表的话可以使用类似testDb/testTable,然后是'backup'@'%'表示给予同步
    权限的用户名及其主机ip,%表示不限制ip,当然如果有防火墙的话还是会有限制的,最后的identified by '123456'
    表示同步用户的密码,然后就查看下主库的状态信息show master status,如下图:
    9G5FE[9%@7%G(B`Q7]E)5@R.png
    把file跟position记下来,然后再开一个terminal,进入从库容器,登陆mysql,然后设置主库

    -
    change master to
    -master_host='xxx.xxx.xxx.xxx',   //如果主从库的容器都在同一个宿主机上,这里的ip是docker容器的ip
    -master_user='backup',            //就是上面的赋予权限的用户
    -master_password='123456',
    -master_log_file='mysql-bin.000004',  //主库中查看到的file
    -master_log_pos=312,                  //主库中查看到的position
    -master_port=3306;                    //如果是同一宿主机,这里使用真实的3306端口,3308及主库的3307是给外部连接使用的
    -

    通过docker-ip mysql-master可以查看容器的ip
    S(GP)P(M$N3~N1764@OW3E0.png
    这里有一点是要注意的,也是我踩的坑,就是如果是同一宿主机下两个mysql容器互联,我这里只能通过docker-ip和真实
    的3306端口能够连接成功。
    本文参考了这位同学的文章

    -]]>
    - - docker - - - docker - mysql - -
    binary-watch /2016/09/29/binary-watch/ @@ -5335,60 +5278,209 @@ public: - Reverse Bits - /2015/03/11/Reverse-Bits/ - Reverse Bits

    Reverse bits of a given 32 bits unsigned integer.

    For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).

    - -

    Follow up:
    If this function is called many times, how would you optimize it?

    -
    -

    code

    class Solution {
    -public:
    -    uint32_t reverseBits(uint32_t n) {
    -        n = ((n >> 1) & 0x55555555) | ((n & 0x55555555) << 1);
    -        n = ((n >> 2) & 0x33333333) | ((n & 0x33333333) << 2);
    -        n = ((n >> 4) & 0x0f0f0f0f) | ((n & 0x0f0f0f0f) << 4);
    -        n = ((n >> 8) & 0x00ff00ff) | ((n & 0x00ff00ff) << 8);
    -        n = ((n >> 16) & 0x0000ffff) | ((n & 0x0000ffff) << 16);
    -        return n;
    -    }
    -};
    + Redis_分布式锁 + /2019/12/10/Redis-Part-1/ + 今天看了一下 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节点发起释放锁的操作,不管这些节点当时在获取锁的时候成功与否。这里为什么要向所有的节点发送释放锁的操作呢,这里是因为有部分的节点的失败原因可能是加锁时阻塞,加锁成功的结果没有及时返回,所以为了防止这种情况还是需要向所有发起这个释放锁的操作。
      初步记录就先到这。
    • +
    ]]>
    - leetcode + Redis + Distributed Lock + C + Redis - leetcode - c++ + C + Redis + Distributed Lock + 分布式锁
    - 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);
    -
    -}
    + ambari-summary + /2017/05/09/ambari-summary/ + 初识ambari

    ambari是一个大数据平台的管理工具,包含了hadoop, yarn, hive, hbase, spark等大数据的基础架构和工具,简化了数据平台的搭建,之前只是在同事搭建好平台后的一些使用,这次有机会从头开始用ambari来搭建一个测试的数据平台,过程中也踩到不少坑,简单记录下。

    +

    简单过程

      +
    • 第一个坑
      在刚开始是按照官网的指南,用maven构建,因为GFW的原因,导致反复失败等待,也就是这个guide,因为对maven不熟悉导致有些按图索骥,浪费了很多时间,之后才知道可以直接加repo用yum安装,然而用yum安装马上就出现了第二个坑。
    • +
    • 第二个坑
      因为在线的repo还是因为网络原因很慢很慢,用proxychains勉强把ambari-server本身安装好了,ambari.repo将这个放进/etc/yum.repos.d/路径下,然后yum update && yum install ambari-server安装即可,如果有条件就用proxychains走下代理。
    • +
    • 第三步
      安装好ambari-server后先执行ambari-server setup做一些初始化设置,其中包含了JDK路径的设置,数据库设置,设置好就OK了,然后执行ambari-server start启动服务,这里有个小插曲,因为ambari-server涉及到这么多服务,所以管理控制监控之类的模块是必不可少的,这部分可以在ambari-server的web ui界面安装,也可以命令行提前安装,这部分被称为HDF Management Pack,运行ambari-server install-mpack \ --mpack=http://public-repo-1.hortonworks.com/HDF/centos7/2.x/updates/2.1.4.0/tars/hdf_ambari_mp/hdf-ambari-mpack-2.1.4.0-5.tar.gz \ --purge \ --verbose
      安装,当然这个压缩包可以下载之后指到本地路径安装,然后就可以重启ambari-server
    • +
    +]]>
    + + data analysis + + + hadoop + cluster + +
    + + docker-mysql-cluster + /2016/08/14/docker-mysql-cluster/ + docker-mysql-cluster

    基于docker搭了个mysql集群,稍微记一下,
    首先是新建mysql主库容

    docker run -d -e MYSQL_ROOT_PASSWORD=admin --name mysql-master -p 3307:3306 mysql:latest
    -d表示容器运行在后台,-e表示设置环境变量,即MYSQL_ROOT_PASSWORD=admin,设置了mysql的root密码,
    --name表示容器名,-p表示端口映射,将内部mysql:3306映射为外部的3307,最后的mysql:latest表示镜像名
    此外还可以用-v /local_path/my-master.cnf:/etc/mysql/my.cnf来映射配置文件
    然后同理启动从库
    docker run -d -e MYSQL_ROOT_PASSWORD=admin --name mysql-slave -p 3308:3306 mysql:latest
    然后进入主库改下配置文件
    docker-enter mysql-master如果无法进入就用docker ps -a看下容器是否在正常运行,如果status显示
    未正常运行,则用docker logs mysql-master看下日志哪里出错了。
    进入容器后,我这边使用的镜像的mysqld配置文件是在/etc/mysql下面,这个最新版本的mysql的配置文件包含
    三部分,/etc/mysql/my.cnf/etc/mysql/conf.d/mysql.cnf,还有/etc/mysql/mysql.conf.d/mysqld.cnf
    这里需要改的是最后一个,加上

    +
    log-bin = mysql-bin
    +server_id = 1
    +

    保存后退出容器重启主库容器,然后进入从库更改相同文件,

    +
    log-bin = mysql-bin
    +server_id = 2
    +

    主从配置

    同样退出重启容器,然后是配置主从,首先进入主库,用命令mysql -u root -pxxxx进入mysql,然后赋予一个同步
    权限GRANT REPLICATION SLAVE ON *.* to 'backup'@'%' identified by '123456';还是同样说明下,ON *.*表示了数
    据库全部的权限,如果要指定数据库/表的话可以使用类似testDb/testTable,然后是'backup'@'%'表示给予同步
    权限的用户名及其主机ip,%表示不限制ip,当然如果有防火墙的话还是会有限制的,最后的identified by '123456'
    表示同步用户的密码,然后就查看下主库的状态信息show master status,如下图:
    9G5FE[9%@7%G(B`Q7]E)5@R.png
    把file跟position记下来,然后再开一个terminal,进入从库容器,登陆mysql,然后设置主库

    +
    change master to
    +master_host='xxx.xxx.xxx.xxx',   //如果主从库的容器都在同一个宿主机上,这里的ip是docker容器的ip
    +master_user='backup',            //就是上面的赋予权限的用户
    +master_password='123456',
    +master_log_file='mysql-bin.000004',  //主库中查看到的file
    +master_log_pos=312,                  //主库中查看到的position
    +master_port=3306;                    //如果是同一宿主机,这里使用真实的3306端口,3308及主库的3307是给外部连接使用的
    +

    通过docker-ip mysql-master可以查看容器的ip
    S(GP)P(M$N3~N1764@OW3E0.png
    这里有一点是要注意的,也是我踩的坑,就是如果是同一宿主机下两个mysql容器互联,我这里只能通过docker-ip和真实
    的3306端口能够连接成功。
    本文参考了这位同学的文章

    +]]>
    + + docker + + + docker + mysql + +
    + + docker比一般多一点的初学者介绍三 + /2020/03/21/docker%E6%AF%94%E4%B8%80%E8%88%AC%E5%A4%9A%E4%B8%80%E7%82%B9%E7%9A%84%E5%88%9D%E5%AD%A6%E8%80%85%E4%BB%8B%E7%BB%8D%E4%B8%89/ + 运行第一个 Dockerfile

    上一篇的 Dockerfile 我们停留在构建阶段,现在来把它跑起来

    +
    docker run -d -p 80 --name static_web nicksxs/static_web \
    +nginx -g "daemon off;"
    +

    这里的-d表示以分离模型运行docker (detached),然后-p 是表示将容器的 80 端口开放给宿主机,然后容器名就叫 static_web,使用了我们上次构建的 static_web 镜像,后面的是让 nginx 在前台运行

    可以看到返回了个容器 id,但是具体情况没出现,也没连上去,那我们想看看怎么访问在 Dockerfile 里写的静态页面,我们来看下docker 进程

    发现为我们随机分配了一个宿主机的端口,32768,去服务器的防火墙把这个外网端口开一下,看看是不是符合我们的预期呢

    好像不太对额,应该是 ubuntu 安装的 nginx 的默认工作目录不对,我们来进容器看看,再熟悉下命令docker exec -it 4792455ca2ed /bin/bash
    记得容器 id 换成自己的,进入容器后得找找 nginx 的配置文件,通常在/etc/nginx,/usr/local/etc等目录下,然后找到我们的目录是在这

    所以把刚才的内容复制过去再试试

    目标达成,give me five✌️

    +

    第二个 Dockerfile

    然后就想来动态一点的,毕竟写过 PHP,就来试试 PHP
    再建一个目录叫 dynamic_web,里面创建 src 目录,放一个 index.php
    内容是

    +
    <?php
    +echo "Hello World!";
    +

    然后在 dynamic_web 目录下创建 Dockerfile,

    +
    FROM trafex/alpine-nginx-php7:latest
    +COPY src/ /var/www/html
    +EXPOSE 80
    +

    Dockerfile 虽然只有三行,不过要着重说明下,这个底包其实不是docker 官方的,有两点考虑,一点是官方的基本都是 php apache 的镜像,还有就是 alpine这个,截取一段中文介绍

    +
    +

    Alpine 操作系统是一个面向安全的轻型 Linux 发行版。它不同于通常 Linux 发行版,Alpine 采用了 musl libc 和 busybox 以减小系统的体积和运行时资源消耗,但功能上比 busybox 又完善的多,因此得到开源社区越来越多的青睐。在保持瘦身的同时,Alpine 还提供了自己的包管理工具 apk,可以通过 https://pkgs.alpinelinux.org/packages 网站上查询包信息,也可以直接通过 apk 命令直接查询和安装各种软件。
    Alpine 由非商业组织维护的,支持广泛场景的 Linux发行版,它特别为资深/重度Linux用户而优化,关注安全,性能和资源效能。Alpine 镜像可以适用于更多常用场景,并且是一个优秀的可以适用于生产的基础系统/环境。

    +
    +
    +

    Alpine Docker 镜像也继承了 Alpine Linux 发行版的这些优势。相比于其他 Docker 镜像,它的容量非常小,仅仅只有 5 MB 左右(对比 Ubuntu 系列镜像接近 200 MB),且拥有非常友好的包管理机制。官方镜像来自 docker-alpine 项目。

    +
    +
    +

    目前 Docker 官方已开始推荐使用 Alpine 替代之前的 Ubuntu 做为基础镜像环境。这样会带来多个好处。包括镜像下载速度加快,镜像安全性提高,主机之间的切换更方便,占用更少磁盘空间等。

    +
    +

    一方面在没有镜像的情况下,拉取 docker 镜像还是比较费力的,第二个就是也能节省硬盘空间,所以目前有大部分的 docker 镜像都将 alpine 作为基础镜像了
    然后再来构建下

    这里还有个点,就是上面的那个镜像我们也是 EXPOSE 80端口,然后外部宿主机会随机映射一个端口,为了偷个懒,我们就直接指定外部端口了
    docker run -d -p 80:80 dynamic_web打开浏览器发现访问不了,咋回事呢
    因为我们没看trafex/alpine-nginx-php7:latest这个镜像说明,它内部的服务是 8080 端口的,所以我们映射的暴露端口应该是 8080,再用 docker run -d -p 80:8080 dynamic_web这个启动,

    +]]>
    + + Docker + 介绍 + + + Docker + namespace + Dockerfile + +
    + + docker比一般多一点的初学者介绍 + /2020/03/08/docker%E6%AF%94%E4%B8%80%E8%88%AC%E5%A4%9A%E4%B8%80%E7%82%B9%E7%9A%84%E5%88%9D%E5%AD%A6%E8%80%85%E4%BB%8B%E7%BB%8D/ + 因为最近想搭一个phabricator用来做看板和任务管理,一开始了解这个是Easy大大有在微博推荐过,后来苏洋也在群里和博客里说到了,看上去还不错的样子,因为主角是docker所以就不介绍太多,后面有机会写一下。

    +

    docker最开始是之前在某位大佬的博客看到的,看上去有点神奇,感觉是一种轻量级的虚拟机,但是能做的事情好像差不多,那时候是在Ubuntu系统的vps里起一个Ubuntu的docker,然后在里面装个nginx,配置端口映射就可以访问了,后来也草草写过一篇使用docker搭建mysql集群,但是最近看了下好像是因为装docker的大佬做了一些别名还是什么操作,导致里面用的操作都不具有普遍性,而且主要是把搭的过程写了下,属于囫囵吞枣,没理解docker是干啥的,为啥用docker,就是操作了下,这几天借着搭phabricator的过程,把一些原来不理解,或者原来理解错误的地方重新理一下。

    +

    之前写的 mysql 集群,一主二备,这种架构在很多小型应用里都是这么配置的,而且一般是直接在三台 vps 里启动三个 mysql 实例,但是如果换成 docker 会有什么好处呢,其实就是方便部署,比如其中一台备库挂了,我要加一台,或者说备库的 qps 太高了,需要再加一个,如果要在 vps 上搭建的话,首先要买一台机器,等初始化,然后在上面修改源,更新,装 mysql ,然后配置主从,可能还要处理防火墙等等,如果把这些打包成一个 docker 镜像,并且放在自己的 docker registry,那就直接run 一下就可以了;还有比如在公司要给一个新同学整一套开发测试环境,以 Java 开发为例,要装 git,maven,jdk,配置 maven settings 和各种 rc,整合在一个镜像里的话,就会很方便了;再比如微服务的水平扩展。

    +

    但是为啥 docker 会有这种优势,听起来好像虚拟机也可以干这个事,但是虚拟机动辄上 G,而且需要 VMware,virtual box 等支持,不适合在Linux服务器环境使用,而且占用资源也会非常大。说得这么好,那么 docker 是啥呢

    +

    docker 主要使用 Linux 中已经存在的两种技术的一个整合升级,一个是 namespace,一个是cgroups,相比于虚拟机需要完整虚拟出一个操作系统运行基础,docker 基于宿主机内核,通过 namespace 和 cgroups 分隔进程,理念就是提供一个隔离的最小化运行依赖,这样子相对于虚拟机就有了巨大的便利性,具体的 namespace 和 cgroups 就先不展开讲,可以参考耗子叔的文章

    +

    安装

    那么我们先安装下 docker,参考官方的教程,安装,我的系统是 ubuntu 的,就贴了 ubuntu 的链接,用其他系统的可以找到对应的系统文档安装,安装完了的话看看 docker 的信息

    +
    sudo docker info
    + +

    输出以下信息

    +

    简单运行

    然后再来运行个 hello world 呗,

    +
    sudo docker run hello-world
    + +

    输出了这些

    +

    看看这个运行命令是怎么用的,一般都会看到这样子的,sudo docker run -it ubuntu bash, 前面的 docker run 反正就是运行一个容器的意思,-it是啥呢,还有这个什么 ubuntu bash,来看看docker run`的命令帮助信息

    +
    -i, --interactive                    Keep STDIN open even if not attached
    + +

    就是要有输入,我们运行的时候能输入

    +
    -t, --tty                            Allocate a pseudo-TTY
    + +

    要有个虚拟终端,

    +
    Usage:	docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
    +
    +Run a command in a new container
    + +

    镜像

    上面说的-it 就是这里的 options,后面那个 ubuntu 就是 image 辣,image 是啥呢

    +

    Docker 把应用程序及其依赖,打包在 image 文件里面,可以把它理解成为类似于虚拟机的镜像或者运行一个进程的代码,跑起来了的叫docker 容器或者进程,比如我们将要运行的docker run -it ubuntu bash的ubuntu 就是个 ubuntu 容器的镜像,将这个镜像运行起来后,我们可以进入容器像使用 ubuntu 一样使用它,来看下我们的镜像,使用sudo docker image ls就能列出我们宿主机上的 docker 镜像了

    +

    +

    一个 ubuntu 镜像才 64MB,非常小巧,然后是后面的bash,我通过交互式启动了一个 ubuntu 容器,然后在这个启动的容器里运行了 bash 命令,这样就可以在容器里玩一下了

    +

    在容器里看下进程,

    +

    只有刚才运行容器的 bash 进程和我刚执行的 ps,这里有个可以注意下的,bash 这个进程的 pid 是 1,其实这里就用到了 linux 中的PID Namespace,容器会隔离出一个 pid 的名字空间,这里面的进程跟外部的 pid 命名独立

    +

    查看宿主机上的容器

    sudo docker ps -a
    + +

    +

    如何进入一个正在运行中的 docker 容器

    这个应该是比较常用的,因为比如是一个微服务容器,有时候就像看下运行状态,日志啥的

    +
    sudo docker exec -it [containerID] bash
    + +

    +

    查看日志

    sudo docker logs [containerID]
    + +

    我在运行容器的终端里胡乱输入点啥,然后通过上面的命令就可以看到啦

    +

    +

    +]]>
    + + Docker + 介绍 + + + Docker + namespace + cgroup + +
    + + 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>
    @@ -5479,6 +5571,93 @@ EXPOSE 80
    Syntax:	access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]];
    @@ -6207,19 +6220,6 @@ access_log /path/to/access.log combined 缓存
           
       
    -  
    -    C++ 指针使用中的一个小问题
    -    /2014/12/23/my-new-post/
    -    在工作中碰到的一点C++指针上的一点小问题
    -

    在C++中,应该是从C语言就开始了,除了void型指针之外都是需要有分配对应的内存才可以使用,同时mallocfree成对使用,newdelete成对使用,否则造成内存泄漏。

    -]]>
    - - C++ - - - 博客,文章 - -
    openresty /2019/06/18/openresty/ @@ -6334,6 +6334,58 @@ int pcre_exec(const pcre *code, const pcre_extra *extra, const char *subject, in mfc + + php-abstract-class-and-interface + /2016/11/10/php-abstract-class-and-interface/ + PHP抽象类和接口
      +
    • 抽象类与接口
    • +
    • 抽象类内可以包含非抽象函数,即可实现函数
    • +
    • 抽象类内必须包含至少一个抽象方法,抽象类和接口均不能实例化
    • +
    • 抽象类可以设置访问级别,接口默认都是public
    • +
    • 类可以实现多个接口但不能继承多个抽象类
    • +
    • 类必须实现抽象类和接口里的抽象方法,不一定要实现抽象类的非抽象方法
    • +
    • 接口内不能定义变量,但是可以定义常量
    • +
    +

    示例代码

    <?php
    +interface int1{
    +    const INTER1 = 111;
    +    function inter1();
    +}
    +interface int2{
    +    const INTER1 = 222;
    +    function inter2();
    +}
    +abstract class abst1{
    +    public function abstr1(){
    +        echo 1111;
    +    }
    +    abstract function abstra1(){
    +        echo 'ahahahha';
    +    }
    +}
    +abstract class abst2{
    +    public function abstr2(){
    +        echo 1111;
    +    }
    +    abstract function abstra2();
    +}
    +class normal1 extends abst1{
    +    protected function abstr2(){
    +        echo 222;
    +    }
    +}
    + +

    result

    PHP Fatal error:  Abstract function abst1::abstra1() cannot contain body in new.php on line 17
    +
    +Fatal error: Abstract function abst1::abstra1() cannot contain body in php on line 17
    +]]>
    + + php + + + php + +
    redis 的 rdb 和 COW 介绍 /2021/08/15/redis-%E7%9A%84-rdb-%E5%92%8C-COW-%E4%BB%8B%E7%BB%8D/ @@ -6350,34 +6402,44 @@ int pcre_exec(const pcre *code, const pcre_extra *extra, const char *subject, in - rabbitmq-tips - /2017/04/25/rabbitmq-tips/ - rabbitmq 介绍

    接触了一下rabbitmq,原来在选型的时候是在rabbitmq跟kafka之间做选择,网上搜了一下之后发现kafka的优势在于吞吐量,而rabbitmq相对注重可靠性,因为应用在im上,需要保证消息不能丢失所以就暂时选定rabbitmq,
    Message Queue的需求由来已久,80年代最早在金融交易中,高盛等公司采用Teknekron公司的产品,当时的Message queuing软件叫做:the information bus(TIB)。 TIB被电信和通讯公司采用,路透社收购了Teknekron公司。之后,IBM开发了MQSeries,微软开发了Microsoft Message Queue(MSMQ)。这些商业MQ供应商的问题是厂商锁定,价格高昂。2001年,Java Message queuing试图解决锁定和交互性的问题,但对应用来说反而更加麻烦了。
    RabbitMQ采用Erlang语言开发。Erlang语言由Ericson设计,专门为开发concurrent和distribution系统的一种语言,在电信领域使用广泛。OTP(Open Telecom Platform)作为Erlang语言的一部分,包含了很多基于Erlang开发的中间件/库/工具,如mnesia/SASL,极大方便了Erlang应用的开发。OTP就类似于Python语言中众多的module,用户借助这些module可以很方便的开发应用。
    于是2004年,摩根大通和iMatrix开始着手Advanced Message Queuing Protocol (AMQP)开放标准的开发。2006年,AMQP规范发布。2007年,Rabbit技术公司基于AMQP标准开发的RabbitMQ 1.0 发布。所有主要的编程语言均有与代理接口通讯的客户端库。

    -

    简单的使用经验

    通俗的理解

    这里介绍下其中的一些概念,connection表示和队列服务器的连接,一般情况下是tcp连接, channel表示通道,可以在一个连接上建立多个通道,这里主要是节省了tcp连接握手的成本,exchange可以理解成一个路由器,将消息推送给对应的队列queue,其实是像一个订阅的模式。

    -

    集群经验

    rabbitmqctl stop这个是关闭rabbitmq,在搭建集群时候先关闭服务,然后使用rabbitmq-server -detached静默启动,这时候使用rabbitmqctl cluster_status查看集群状态,因为还没将节点加入集群,所以只能看到类似

    -
    Cluster status of node rabbit@rabbit1 ...
    -[{nodes,[{disc,[rabbit@rabbit1,rabbit@rabbit2,rabbit@rabbit3]}]},
    - {running_nodes,[rabbit@rabbit2,rabbit@rabbit1]}]
    -...done.
    -

    然后就可以把当前节点加入集群,

    -
    rabbit2$ rabbitmqctl stop_app #这个stop_app与stop的区别是前者停的是rabbitmq应用,保留erlang节点,
    -                              #后者是停止了rabbitmq和erlang节点
    -Stopping node rabbit@rabbit2 ...done.
    -rabbit2$ rabbitmqctl join_cluster rabbit@rabbit1 #这里可以用--ram指定将当前节点作为内存节点加入集群
    -Clustering node rabbit@rabbit2 with [rabbit@rabbit1] ...done.
    -rabbit2$ rabbitmqctl start_app
    -Starting node rabbit@rabbit2 ...done.
    -

    其他可以参考官方文档

    -

    一些坑

    消息丢失

    这里碰到过一个坑,对于使用exchange来做消息路由的,会有一个情况,就是在routing_key没被订阅的时候,会将该条找不到路由对应的queue的消息丢掉What happens if we break our contract and send a message with one or four words, like "orange" or "quick.orange.male.rabbit"? Well, these messages won't match any bindings and will be lost.对应链接,而当使用空的exchange时,会保留消息,当出现消费者的时候就可以将收到之前生产者所推送的消息对应链接,这里就是用了空的exchange。

    -

    集群搭建

    集群搭建的时候有个erlang vm生成的random cookie,这个是用来做集群之间认证的,相同的cookie才能连接,但是如果通过vim打开复制后在其他几点新建文件写入会多一个换行,导致集群建立是报错,所以这里最好使用scp等传输命令直接传输cookie文件,同时要注意下cookie的文件权限。
    另外在集群搭建的时候如果更改过hostname,那么要把rabbitmq的数据库删除,否则启动后会马上挂掉

    + 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

    ]]>
    - php + Redis + 数据结构 + C + 源码 + Redis - mq - php - im + redis + 数据结构 + 源码
    @@ -6467,132 +6529,39 @@ typedef struct dict { - 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;
    +    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;
     
    -/* 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 - 数据结构 - 源码 - - - - php-abstract-class-and-interface - /2016/11/10/php-abstract-class-and-interface/ - PHP抽象类和接口
      -
    • 抽象类与接口
    • -
    • 抽象类内可以包含非抽象函数,即可实现函数
    • -
    • 抽象类内必须包含至少一个抽象方法,抽象类和接口均不能实例化
    • -
    • 抽象类可以设置访问级别,接口默认都是public
    • -
    • 类可以实现多个接口但不能继承多个抽象类
    • -
    • 类必须实现抽象类和接口里的抽象方法,不一定要实现抽象类的非抽象方法
    • -
    • 接口内不能定义变量,但是可以定义常量
    • -
    -

    示例代码

    <?php
    -interface int1{
    -    const INTER1 = 111;
    -    function inter1();
    -}
    -interface int2{
    -    const INTER1 = 222;
    -    function inter2();
    -}
    -abstract class abst1{
    -    public function abstr1(){
    -        echo 1111;
    -    }
    -    abstract function abstra1(){
    -        echo 'ahahahha';
    -    }
    -}
    -abstract class abst2{
    -    public function abstr2(){
    -        echo 1111;
    -    }
    -    abstract function abstra2();
    -}
    -class normal1 extends abst1{
    -    protected function abstr2(){
    -        echo 222;
    -    }
    -}
    - -

    result

    PHP Fatal error:  Abstract function abst1::abstra1() cannot contain body in new.php on line 17
    -
    -Fatal error: Abstract function abst1::abstra1() cannot contain body in php on line 17
    -]]>
    - - php - - - php - -
    - - 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) 依次递推。

    +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 @@ -6670,333 +6639,619 @@ typedef struct redisObject {
    - 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系列介绍八-淘汰策略

    + rabbitmq-tips + /2017/04/25/rabbitmq-tips/ + rabbitmq 介绍

    接触了一下rabbitmq,原来在选型的时候是在rabbitmq跟kafka之间做选择,网上搜了一下之后发现kafka的优势在于吞吐量,而rabbitmq相对注重可靠性,因为应用在im上,需要保证消息不能丢失所以就暂时选定rabbitmq,
    Message Queue的需求由来已久,80年代最早在金融交易中,高盛等公司采用Teknekron公司的产品,当时的Message queuing软件叫做:the information bus(TIB)。 TIB被电信和通讯公司采用,路透社收购了Teknekron公司。之后,IBM开发了MQSeries,微软开发了Microsoft Message Queue(MSMQ)。这些商业MQ供应商的问题是厂商锁定,价格高昂。2001年,Java Message queuing试图解决锁定和交互性的问题,但对应用来说反而更加麻烦了。
    RabbitMQ采用Erlang语言开发。Erlang语言由Ericson设计,专门为开发concurrent和distribution系统的一种语言,在电信领域使用广泛。OTP(Open Telecom Platform)作为Erlang语言的一部分,包含了很多基于Erlang开发的中间件/库/工具,如mnesia/SASL,极大方便了Erlang应用的开发。OTP就类似于Python语言中众多的module,用户借助这些module可以很方便的开发应用。
    于是2004年,摩根大通和iMatrix开始着手Advanced Message Queuing Protocol (AMQP)开放标准的开发。2006年,AMQP规范发布。2007年,Rabbit技术公司基于AMQP标准开发的RabbitMQ 1.0 发布。所有主要的编程语言均有与代理接口通讯的客户端库。

    +

    简单的使用经验

    通俗的理解

    这里介绍下其中的一些概念,connection表示和队列服务器的连接,一般情况下是tcp连接, channel表示通道,可以在一个连接上建立多个通道,这里主要是节省了tcp连接握手的成本,exchange可以理解成一个路由器,将消息推送给对应的队列queue,其实是像一个订阅的模式。

    +

    集群经验

    rabbitmqctl stop这个是关闭rabbitmq,在搭建集群时候先关闭服务,然后使用rabbitmq-server -detached静默启动,这时候使用rabbitmqctl cluster_status查看集群状态,因为还没将节点加入集群,所以只能看到类似

    +
    Cluster status of node rabbit@rabbit1 ...
    +[{nodes,[{disc,[rabbit@rabbit1,rabbit@rabbit2,rabbit@rabbit3]}]},
    + {running_nodes,[rabbit@rabbit2,rabbit@rabbit1]}]
    +...done.
    +

    然后就可以把当前节点加入集群,

    +
    rabbit2$ rabbitmqctl stop_app #这个stop_app与stop的区别是前者停的是rabbitmq应用,保留erlang节点,
    +                              #后者是停止了rabbitmq和erlang节点
    +Stopping node rabbit@rabbit2 ...done.
    +rabbit2$ rabbitmqctl join_cluster rabbit@rabbit1 #这里可以用--ram指定将当前节点作为内存节点加入集群
    +Clustering node rabbit@rabbit2 with [rabbit@rabbit1] ...done.
    +rabbit2$ rabbitmqctl start_app
    +Starting node rabbit@rabbit2 ...done.
    +

    其他可以参考官方文档

    +

    一些坑

    消息丢失

    这里碰到过一个坑,对于使用exchange来做消息路由的,会有一个情况,就是在routing_key没被订阅的时候,会将该条找不到路由对应的queue的消息丢掉What happens if we break our contract and send a message with one or four words, like "orange" or "quick.orange.male.rabbit"? Well, these messages won't match any bindings and will be lost.对应链接,而当使用空的exchange时,会保留消息,当出现消费者的时候就可以将收到之前生产者所推送的消息对应链接,这里就是用了空的exchange。

    +

    集群搭建

    集群搭建的时候有个erlang vm生成的random cookie,这个是用来做集群之间认证的,相同的cookie才能连接,但是如果通过vim打开复制后在其他几点新建文件写入会多一个换行,导致集群建立是报错,所以这里最好使用scp等传输命令直接传输cookie文件,同时要注意下cookie的文件权限。
    另外在集群搭建的时候如果更改过hostname,那么要把rabbitmq的数据库删除,否则启动后会马上挂掉

    ]]>
    - redis + php - redis - 淘汰策略 - 应用 - Evict + php + mq + im
    - 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;
    +    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;
     
    -    /* 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;
    +/* 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;
     
    -    /* 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);
    +/* 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;
     }
     
    -/* 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 */
    +/* Optimization levels for size-based filling */
    +static const size_t optimization_level[] = {4096, 8192, 16384, 32768, 65536};
     
    -    /* Don't expire anything while loading. It will be done later. */
    -    if (server.loading) return 0;
    +/* Create a new quicklist.
    + * Free with quicklistRelease(). */
    +quicklist *quicklistCreate(void) {
    +    struct quicklist *quicklist;
     
    -    /* 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();
    +    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);
         }
    -
    -    /* 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;
    +/* 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);
     
    -    /* 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();
    -        }
    +        quicklistNodeUpdateSz(node);
    +        _quicklistInsertNodeBefore(quicklist, quicklist->head, node);
         }
    +    quicklist->count++;
    +    quicklist->head->count++;
    +    return (orig_head != quicklist->head);
    +}
     
    -    /* Defrag keys gradually. */
    -    activeDefragCycle();
    +/* 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);
     
    -    /* 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;
    +        quicklistNodeUpdateSz(node);
    +        _quicklistInsertNodeAfter(quicklist, quicklist->tail, node);
    +    }
    +    quicklist->count++;
    +    quicklist->tail->count++;
    +    return (orig_tail != quicklist->tail);
    +}
     
    -        /* Don't test more DBs than we have. */
    -        if (dbs_per_call > server.dbnum) dbs_per_call = server.dbnum;
    +/* 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);
    +}
     
    -        /* Resize */
    -        for (j = 0; j < dbs_per_call; j++) {
    -            tryResizeHashTables(resize_db % server.dbnum);
    -            resize_db++;
    -        }
    +REDIS_STATIC void _quicklistInsertNodeAfter(quicklist *quicklist,
    +                                            quicklistNode *old_node,
    +                                            quicklistNode *new_node) {
    +    __quicklistInsertNode(quicklist, old_node, new_node, 1);
    +}
     
    -        /* 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;
    -                }
    -            }
    +/* 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;
         }
    -}
    -/* 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 this insert creates the only element so far, initialize head/tail. */
    +    if (quicklist->len == 0) {
    +        quicklist->head = quicklist->tail = new_node;
    +    }
    +
    +    if (old_node)
    +        quicklistCompress(quicklist, old_node);
    +
    +    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

    +]]>
    + + 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过期策略复习 + /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 + 应用 + 过期策略 + +
    + + 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.
      *
    - * 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.
    + * 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).
      *
    - * 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.
    + * 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 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;
    + * 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;
     
    -    /* This function has some global state in order to continue the work
    -     * incrementally across calls. */
    +    /* 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;
    +
    +    /* 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();
    +        }
    +    }
    +
    +    /* 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;
    +
    +    /* 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. */
    @@ -7210,6 +7465,70 @@ timelimit = config_cycle_slow_time_perc*1000000/server.hz/100;源码
           
       
    +  
    +    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!
    +
    +    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 + 所有权 + 内存分布 + 新语言 + 可变引用 + 不可变引用 + 切片 + +
    Leetcode 747 至少是其他数字两倍的最大数 ( Largest Number At Least Twice of Others *Easy* ) 题解分析 /2022/10/02/Leetcode-747-%E8%87%B3%E5%B0%91%E6%98%AF%E5%85%B6%E4%BB%96%E6%95%B0%E5%AD%97%E4%B8%A4%E5%80%8D%E7%9A%84%E6%9C%80%E5%A4%A7%E6%95%B0-Largest-Number-At-Least-Twice-of-Others-Easy-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/ @@ -7262,261 +7581,6 @@ timelimit = config_cycle_slow_time_perc*1000000/server.hz/100;题解 - - 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;
    -
    -/* 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;
    -
    -/* 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;
    -    }
    -
    -    if (old_node)
    -        quicklistCompress(quicklist, old_node);
    -
    -    quicklist->len++;
    -}
    -

    前面第一步先根据插入的是头还是尾选择不同的 push 函数,quicklistPushHead 或者 quicklistPushTail,举例分析下从头插入的 quicklistPushHead,先判断当前的 quicklistNode 节点还能不能允许再往 ziplist 里添加元素,如果可以就添加,如果不允许就新建一个 quicklistNode,然后调用 _quicklistInsertNodeBefore 将节点插进去,具体插入quicklist节点的操作类似链表的插入。

    -]]>
    - - 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 - 应用 - 过期策略 - -
    redis系列介绍八-淘汰策略 /2020/04/18/redis%E7%B3%BB%E5%88%97%E4%BB%8B%E7%BB%8D%E5%85%AB/ @@ -8046,131 +8110,6 @@ uint8_t LFULogIncr(uint8_t counter) { 源码 - - 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!
    -
    -    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 - 所有权 - 内存分布 - 新语言 - 可变引用 - 不可变引用 - 切片 - -
    - - 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(_)
    - - -

    结果

    (3, 2)
    -(1, 2)
    -(4, 2)
    -(2, 2)
    -(5, 2)
    -]]>
    - - data analysis - - - spark - python - -
    - - 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;
    -
    -println!("{}, world!", s1);
    -

    有可能认为有两种内存分布可能
    先看下 string 的内存结构

    第一种可能是

    第二种是

    我们来尝试编译下

    发现有这个错误,其实在 rust 中let y = x这个行为的实质是移动,在赋值给 y 之后 x 就无效了

    这样子就不会造成脱离作用域时,对同一块内存区域的二次释放,如果需要复制,可以使用 clone 方法

    -
    let s1 = String::from("hello");
    -let s2 = s1.clone();
    -
    -println!("s1 = {}, s2 = {}", s1, s2);
    -

    这里其实会有点疑惑,为什么前面的x, y 的行为跟 s1, s2 的不一样,其实主要是基本类型和 string 这类的不定大小的类型的内存分配方式不同,x, y这类整型可以直接确定大小,可以直接在栈上分配,而像 string 和其他的变体结构体,其大小都是不能在编译时确定,所以需要在堆上进行分配

    -]]>
    - - 语言 - Rust - - - 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/ @@ -8259,186 +8198,82 @@ for _ in data: - swoole-websocket-test - /2016/07/13/swoole-websocket-test/ - 玩一下swoole的websocket

    WebSocket是HTML5开始提供的一种在单个TCP连接上进行全双工通讯的协议。WebSocket通信协议于2011年被IETF定为标准RFC 6455,WebSocketAPI被W3C定为标准。
    ,在web私信,im等应用较多。背景和优缺点可以参看wiki

    -

    环境准备

    因为swoole官方还不支持windows,所以需要装下linux,之前都是用ubuntu,
    这次就试一下centos7,还是满好看的,虽然虚拟机会默认最小安装,需要在安装
    时自己选择带gnome的,当然最小安装也是可以的,只是最后需要改下防火墙。
    然后是装下PHP,Nginx什么的,我是用Oneinstack,可以按需安装
    给做这个的大大点个赞。

    - + 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;
     
    -

    swoole

    1.install via pecl

    -
    pecl install swoole
    +println!("{}, world!", s1);
    +

    有可能认为有两种内存分布可能
    先看下 string 的内存结构

    第一种可能是

    第二种是

    我们来尝试编译下

    发现有这个错误,其实在 rust 中let y = x这个行为的实质是移动,在赋值给 y 之后 x 就无效了

    这样子就不会造成脱离作用域时,对同一块内存区域的二次释放,如果需要复制,可以使用 clone 方法

    +
    let s1 = String::from("hello");
    +let s2 = s1.clone();
     
    -

    2.install from source

    -
    sudo apt-get install php5-dev
    -git clone https://github.com/swoole/swoole-src.git
    -cd swoole-src
    -phpize
    -./configure
    -make && make install
    -

    3.add extension

    -
    extension = swoole.so
    +println!("s1 = {}, s2 = {}", s1, s2);
    +

    这里其实会有点疑惑,为什么前面的x, y 的行为跟 s1, s2 的不一样,其实主要是基本类型和 string 这类的不定大小的类型的内存分配方式不同,x, y这类整型可以直接确定大小,可以直接在栈上分配,而像 string 和其他的变体结构体,其大小都是不能在编译时确定,所以需要在堆上进行分配

    +]]>
    + + 语言 + Rust + + + Rust + 所有权 + 内存分布 + 新语言 + +
    + + spring event 介绍 + /2022/01/30/spring-event-%E4%BB%8B%E7%BB%8D/ + spring框架中如果想使用一些一部操作,除了依赖第三方中间件的消息队列,还可以用spring自己的event,简单介绍下使用方法
    首先我们可以建一个event,继承ApplicationEvent

    +
    
    +public class CustomSpringEvent extends ApplicationEvent {
     
    -

    4.test extension

    -
    php -m | grep swoole
    -

    如果存在就代表安装成功啦

    -

    Exec

    实现代码看了这位仁兄的代码

    -

    还是贴一下代码
    服务端:

    -
    //创建websocket服务器对象,监听0.0.0.0:9502端口
    -$ws = new swoole_websocket_server("0.0.0.0", 9502);
    +    private String message;
     
    -//监听WebSocket连接打开事件
    -$ws->on('open', function ($ws, $request) {
    -    $fd[] = $request->fd;
    -    $GLOBALS['fd'][] = $fd;
    -    //区别下当前用户
    -    $ws->push($request->fd, "hello user{$request->fd}, welcome\n"); 
    -});
    +    public CustomSpringEvent(Object source, String message) {
    +        super(source);
    +        this.message = message;
    +    }
    +    public String getMessage() {
    +        return message;
    +    }
    +}
    +

    这个 ApplicationEvent 其实也比较简单,内部就一个 Object 类型的 source,可以自行扩展,我们在自定义的这个 Event 里加了个 Message ,只是简单介绍下使用

    +
    public abstract class ApplicationEvent extends EventObject {
    +    private static final long serialVersionUID = 7099057708183571937L;
    +    private final long timestamp;
     
    -//监听WebSocket消息事件
    -$ws->on('message', function ($ws, $frame) {
    -    $msg =  'from'.$frame->fd.":{$frame->data}\n";
    +    public ApplicationEvent(Object source) {
    +        super(source);
    +        this.timestamp = System.currentTimeMillis();
    +    }
     
    -    foreach($GLOBALS['fd'] as $aa){
    -        foreach($aa as $i){
    -            if($i != $frame->fd) {
    -                # code...
    -                $ws->push($i,$msg);
    -            }
    -        }
    +    public ApplicationEvent(Object source, Clock clock) {
    +        super(source);
    +        this.timestamp = clock.millis();
         }
    -});
     
    -//监听WebSocket连接关闭事件
    -$ws->on('close', function ($ws, $fd) {
    -    echo "client-{$fd} is closed\n";
    -});
    +    public final long getTimestamp() {
    +        return this.timestamp;
    +    }
    +}
    -$ws->start();
    - -

    客户端:

    -
    <!DOCTYPE html>
    -<html lang="en">
    -<head>
    -    <meta charset="UTF-8">
    -    <title>Title</title>
    -</head>
    -<body>
    -<div id="msg"></div>
    -<input type="text" id="text">
    -<input type="submit" value="发送数据" onclick="song()">
    -</body>
    -<script>
    -    var msg = document.getElementById("msg");
    -    var wsServer = 'ws://0.0.0.0:9502';
    -    //调用websocket对象建立连接:
    -    //参数:ws/wss(加密)://ip:port (字符串)
    -    var websocket = new WebSocket(wsServer);
    -    //onopen监听连接打开
    -    websocket.onopen = function (evt) {
    -        //websocket.readyState 属性:
    -        /*
    -        CONNECTING    0    The connection is not yet open.
    -        OPEN    1    The connection is open and ready to communicate.
    -        CLOSING    2    The connection is in the process of closing.
    -        CLOSED    3    The connection is closed or couldn't be opened.
    -        */
    -        msg.innerHTML = websocket.readyState;
    -    };
    -
    -    function song(){
    -        var text = document.getElementById('text').value;
    -        document.getElementById('text').value = '';
    -        //向服务器发送数据
    -        websocket.send(text);
    -    }
    -      //监听连接关闭
    -//    websocket.onclose = function (evt) {
    -//        console.log("Disconnected");
    -//    };
    -
    -    //onmessage 监听服务器数据推送
    -    websocket.onmessage = function (evt) {
    -        msg.innerHTML += evt.data +'<br>';
    -//        console.log('Retrieved data from server: ' + evt.data);
    -    };
    -//监听连接错误信息
    -//    websocket.onerror = function (evt, e) {
    -//        console.log('Error occured: ' + evt.data);
    -//    };
    -
    -</script>
    -</html>
    - -

    做了个循环,将当前用户的消息发送给同时在线的其他用户,比较简陋,如下图
    user1:
    NH}()5}1DTLTKZ%HUQ`4L(V.png](https://ooo.0o0.ooo/2016/07/13/578665c07d94c.png)
-user2:
-![QA_$_$MEL6ALWF48UZFRY1L.png](https://ooo.0o0.ooo/2016/07/13/578665c08a2d1.png)
-user3:
-![QK8EU5`9TQNYIG_4YFU@DJN.png

    -]]>
    - - php - - - websocket - swoole - -
    - - 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 - 小技巧 - -
    - - spring event 介绍 - /2022/01/30/spring-event-%E4%BB%8B%E7%BB%8D/ - spring框架中如果想使用一些一部操作,除了依赖第三方中间件的消息队列,还可以用spring自己的event,简单介绍下使用方法
    首先我们可以建一个event,继承ApplicationEvent

    -
    
    -public class CustomSpringEvent extends ApplicationEvent {
    -
    -    private String message;
    -
    -    public CustomSpringEvent(Object source, String message) {
    -        super(source);
    -        this.message = message;
    -    }
    -    public String getMessage() {
    -        return message;
    -    }
    -}
    -

    这个 ApplicationEvent 其实也比较简单,内部就一个 Object 类型的 source,可以自行扩展,我们在自定义的这个 Event 里加了个 Message ,只是简单介绍下使用

    -
    public abstract class ApplicationEvent extends EventObject {
    -    private static final long serialVersionUID = 7099057708183571937L;
    -    private final long timestamp;
    -
    -    public ApplicationEvent(Object source) {
    -        super(source);
    -        this.timestamp = System.currentTimeMillis();
    -    }
    -
    -    public ApplicationEvent(Object source, Clock clock) {
    -        super(source);
    -        this.timestamp = clock.millis();
    -    }
    -
    -    public final long getTimestamp() {
    -        return this.timestamp;
    -    }
    -}
    - -

    然后就是事件生产者和监听消费者

    -
    @Component
    -public class CustomSpringEventPublisher {
    +

    然后就是事件生产者和监听消费者

    +
    @Component
    +public class CustomSpringEventPublisher {
     
         @Resource
         private ApplicationEventPublisher applicationEventPublisher;
    @@ -8500,81 +8335,128 @@ user3:
           
       
       
    -    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;
    -    }
    -};
    ]]>
    + swoole-websocket-test + /2016/07/13/swoole-websocket-test/ + 玩一下swoole的websocket

    WebSocket是HTML5开始提供的一种在单个TCP连接上进行全双工通讯的协议。WebSocket通信协议于2011年被IETF定为标准RFC 6455,WebSocketAPI被W3C定为标准。
    ,在web私信,im等应用较多。背景和优缺点可以参看wiki

    +

    环境准备

    因为swoole官方还不支持windows,所以需要装下linux,之前都是用ubuntu,
    这次就试一下centos7,还是满好看的,虽然虚拟机会默认最小安装,需要在安装
    时自己选择带gnome的,当然最小安装也是可以的,只是最后需要改下防火墙。
    然后是装下PHP,Nginx什么的,我是用Oneinstack,可以按需安装
    给做这个的大大点个赞。

    + + +

    swoole

    1.install via pecl

    +
    pecl install swoole
    + +

    2.install from source

    +
    sudo apt-get install php5-dev
    +git clone https://github.com/swoole/swoole-src.git
    +cd swoole-src
    +phpize
    +./configure
    +make && make install
    +

    3.add extension

    +
    extension = swoole.so
    + +

    4.test extension

    +
    php -m | grep swoole
    +

    如果存在就代表安装成功啦

    +

    Exec

    实现代码看了这位仁兄的代码

    +

    还是贴一下代码
    服务端:

    +
    //创建websocket服务器对象,监听0.0.0.0:9502端口
    +$ws = new swoole_websocket_server("0.0.0.0", 9502);
    +
    +//监听WebSocket连接打开事件
    +$ws->on('open', function ($ws, $request) {
    +    $fd[] = $request->fd;
    +    $GLOBALS['fd'][] = $fd;
    +    //区别下当前用户
    +    $ws->push($request->fd, "hello user{$request->fd}, welcome\n"); 
    +});
    +
    +//监听WebSocket消息事件
    +$ws->on('message', function ($ws, $frame) {
    +    $msg =  'from'.$frame->fd.":{$frame->data}\n";
    +
    +    foreach($GLOBALS['fd'] as $aa){
    +        foreach($aa as $i){
    +            if($i != $frame->fd) {
    +                # code...
    +                $ws->push($i,$msg);
    +            }
    +        }
    +    }
    +});
    +
    +//监听WebSocket连接关闭事件
    +$ws->on('close', function ($ws, $fd) {
    +    echo "client-{$fd} is closed\n";
    +});
    +
    +$ws->start();
    + +

    客户端:

    +
    <!DOCTYPE html>
    +<html lang="en">
    +<head>
    +    <meta charset="UTF-8">
    +    <title>Title</title>
    +</head>
    +<body>
    +<div id="msg"></div>
    +<input type="text" id="text">
    +<input type="submit" value="发送数据" onclick="song()">
    +</body>
    +<script>
    +    var msg = document.getElementById("msg");
    +    var wsServer = 'ws://0.0.0.0:9502';
    +    //调用websocket对象建立连接:
    +    //参数:ws/wss(加密)://ip:port (字符串)
    +    var websocket = new WebSocket(wsServer);
    +    //onopen监听连接打开
    +    websocket.onopen = function (evt) {
    +        //websocket.readyState 属性:
    +        /*
    +        CONNECTING    0    The connection is not yet open.
    +        OPEN    1    The connection is open and ready to communicate.
    +        CLOSING    2    The connection is in the process of closing.
    +        CLOSED    3    The connection is closed or couldn't be opened.
    +        */
    +        msg.innerHTML = websocket.readyState;
    +    };
    +
    +    function song(){
    +        var text = document.getElementById('text').value;
    +        document.getElementById('text').value = '';
    +        //向服务器发送数据
    +        websocket.send(text);
    +    }
    +      //监听连接关闭
    +//    websocket.onclose = function (evt) {
    +//        console.log("Disconnected");
    +//    };
    +
    +    //onmessage 监听服务器数据推送
    +    websocket.onmessage = function (evt) {
    +        msg.innerHTML += evt.data +'<br>';
    +//        console.log('Retrieved data from server: ' + evt.data);
    +    };
    +//监听连接错误信息
    +//    websocket.onerror = function (evt, e) {
    +//        console.log('Error occured: ' + evt.data);
    +//    };
    +
    +</script>
    +</html>
    + +

    做了个循环,将当前用户的消息发送给同时在线的其他用户,比较简陋,如下图
    user1:
    NH}()5}1DTLTKZ%HUQ`4L(V.png](https://ooo.0o0.ooo/2016/07/13/578665c07d94c.png)
+user2:
+![QA_$_$MEL6ALWF48UZFRY1L.png](https://ooo.0o0.ooo/2016/07/13/578665c08a2d1.png)
+user3:
+![QK8EU5`9TQNYIG_4YFU@DJN.png

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

    -]]>
    - - 读后感 - 生活 - - - 生活 - 读后感 - -
    - - 上次的其他 外行聊国足 - /2022/03/06/%E4%B8%8A%E6%AC%A1%E7%9A%84%E5%85%B6%E4%BB%96-%E5%A4%96%E8%A1%8C%E8%81%8A%E5%9B%BD%E8%B6%B3/ - 上次本来想在换车牌后面聊下这个话题,为啥要聊这个话题呢,也很简单,在地铁上看到一对猜测是情侣或者比较关系好的男女同学在聊,因为是这位男同学是大学学的工科,然后自己爱好设计绘画相关的,可能还以此赚了点钱,在地铁上讨论男的要不要好好努力把大学课程完成好,大致的观点是没必要,本来就不适合,这一段我就不说了,恋爱人的嘴,信你个鬼。
    后面男的说在家里又跟他爹吵了关于男足的,估计是那次输了越南,实话说我不是个足球迷,对各方面技术相关也不熟,只是对包括这个人的解释和网上一些观点的看法,纯主观,这次地铁上这位说的大概意思是足球这个训练什么的很难的,要想赢越南也很难的,不是我们能嘴炮的;在网上看到一个赞同数很多的一个回答,说什么中国是个体育弱国,但是由于有一些乒乓球,跳水等小众项目比较厉害,让民众给误解了,首先我先来反驳下这个偷换概念的观点,第一所谓的体育弱国,跟我们觉得足球不应该这么差没半毛钱关系,因为体育弱国,我们的足球本来就不是顶尖的,也并不是去跟顶尖的球队去争,以足球为例,跟巴西,阿根廷,英国,德国,西班牙,意大利,法国这些足球强国,去比较,我相信没有一个足球迷会这么去做对比,因为我们足球历史最高排名是 1998 年的 37 名,最差是 100 名,把能数出来的强队都数完,估计都还不会到 37,所以根本没有跟强队去做对比,第二体育弱国,我们的体育投入是在逐年降低吗,我们是因战乱没法好好训练踢球?还是这帮傻逼就不争气,前面也说了我们足球世界排名最高 37,最低 100,那么前阵子我们输的越南是第几,目前我们的排名 77 名,越南 92 名,看明白了么,轮排名我们都不至于输越南,然后就是这个排名,这也是我想回应那位地铁上的兄弟,我觉得除了造核弹这种高精尖技术,绝大部分包含足球这类运动,遵循类二八原则,比如满分是 100 分,从 80 提到 90 分或者 90 分提到 100 分非常难,30 分提到 40 分,50 分提到 60 分我觉得都是可以凭后天努力达成的,基本不受天赋限制,这里可以以篮球来类比下,相对足球的确篮球没有那么火,或者行业市值没法比,但是也算是相对大众了,中国在篮球方面相对比较好一点,在 08 年奥运会冲进过八强,那也不是唯一的巅峰,但是我说这个其实是想说明两方面的事情,第一,像篮球一样,状态是有起起伏伏,排名也会变动,但是我觉得至少能维持一个相对稳定的总体排名和持平或者上升的趋势,这恰恰是我们这种所谓的“体育弱国”应该走的路线,第二就是去支持我的类二八原则的,可以看到我们的篮球这两年也很垃圾,排名跌到 29 了,那问题我觉得跟足球是一样的,就是不能脚踏实地,如斯科拉说的,中国篮球太缺少竞争,打得好不好都是这些人打,打输了还是照样拿钱,相对足球,篮球的技术我还是懂一些的,对比 08 年的中国男篮,的确像姚明跟王治郅这样的天赋型+努力型球员少了以后竞争力下降在所难免,但是去对比下基本功,传球,投篮,罚球稳定性,也完全不是一个水平的,这些就是我说的,可以通过努力训练拿 80 分的,只要拿到 80 分,甚至只要拿到 60 分,我觉得应该就还算对得起球迷了,就像 NBA 里球队也会有核心球员的更替,战绩起起伏伏,但是基本功这东西,防守积极性,我觉得不随核心球员的变化而变化,就像姚明这样的天赋,其实他应该还有一些先天缺陷,大脚趾较长等,但是他从 CBA 到 NBA,在 NBA 适应并且打成顶尖中锋,离不开刻苦训练,任何的成功都不是纯天赋的,必须要付出足够的努力。
    说回足球,如果像前面那么洗地(体育弱国),那能给我维持住一个稳定的排名我也能接受,问题是我们的经济物质资源比 2000 年前应该有了质的变化,身体素质也越来越好,即使是体育弱国,这么继续走下坡路,半死不活的,不觉得是打了自己的脸么。足球也需要基本功,基本的体能,力量这些,看看现在这些国足运动员的体型,对比下女足,说实话,如果男足这些运动员都练得不错的体脂率,耐力等,成绩即使不好,也不会比现在更差。
    纯主观吐槽,勿喷。

    -]]>
    - - 生活 - 运动 - - - 生活 + websocket + swoole
    @@ -8612,6 +8494,111 @@ public: nginx + + 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(_)
    + + +

    结果

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

    +]]>
    + + 读后感 + 生活 + + + 生活 + 读后感 + +
    + + 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/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 + +
    介绍下最近比较实用的端口转发 /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/ @@ -8638,43 +8625,36 @@ public: - 从丁仲礼被美国制裁聊点啥 - /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/ - 几年前看了柴静的《穹顶之下》觉得这个记者调查得很深入,挺有水平,然后再看到了她跟丁仲礼的采访,其实没看完整,也没试着去理解,就觉得环境问题挺严重的,为啥柴静这个对面的这位好像对这个很不屑的样子,最近因为丁仲礼上了美国制裁名单,B 站又有人把这个视频发了出来,就完整看了下,就觉得自己挺惭愧的,就抱着对柴静的好感而没来由的否定了丁老的看法和说法,所以人也需要不断地学习,改正之前错误的观点,当然不是说我现在说的就是百分百正确,只是个人的一些浅显的见解

    -

    先聊聊这个事情,整体看下来我的一些理解,IPCC给中国的方案其实是个很大的陷阱,它里面有几个隐藏的点是容易被我们外行忽略的,第一点是基数,首先发达国家目前(指2010年采访或者IPCC方案时间)的人均碳排放量已经是远高于发展中国家的了,这也就导致了所谓的发达国家承诺减排80%是个非常有诚意的承诺其实就是忽悠;第二点是碳排放是个累计过程,从1900年开始到2050年,或者说到2010年,发达国家已经排的量是远超过发展中国家的,这是非常不公平的;第三点其实是通过前两点推导出来的,也就是即使发达国家这么有诚意地说减排80%,扒开这层虚伪的外衣,其实是给他们11亿人分走了48%的碳排放量,留给发展中国家55亿人口的只剩下了52%;第四点,人是否因为国家的发达与否而应受到不平等待遇,如果按国家维度,丁老说的,摩纳哥要跟中国分同样的排放量么,中国人还算不算人;第五点,这点算是我自己想的,也可能是柴静屁股决定脑袋想不到的点,她作为一个物质生活条件已经足够好了,那么对于那些生活在物质条件平均线以下的,他们是否能像城里人那样有空调地暖,洗澡有热水器浴霸,上下班能开车,这些其实都直接或者间接地导致了碳排放;他们有没有改善物质生活条件地权利呢,并且再说回来,其实丁老也给了我们觉得合理地方案,我们保证不管发达国家不管减排多少,我们都不会超过他们的80%,我觉得这是真正的诚意,而不是接着减排80%的噱头来忽悠人,也是像丁老这样的专家才能看破这个陷阱,碳排放权其实就是发展权,就是人权,中国人就不是人了么,或者说站在贫困线以下的人民是否有改善物质条件的权利,而不是说像柴静这样,只是管她自己,可能觉得小孩因为空气污染导致身体不好,所以做了穹顶之下这个纪录片,想去改善这个事情,空气污染不是说对的,只是每个国家都有这个过程,如果不发展,哪里有资源去让人活得好,活得好了是前提,然后再去各方面都改善。

    -

    对于这个问题其实更想说的是人的认知偏差,之前总觉得美帝是更自由民主,公平啥的,或者说觉得美帝啥都好,有种无脑愤青的感觉,外国的月亮比较圆,但是经历了像川普当选美国总统以来的各种魔幻操作,还有对于疫情的种种不可思议的美国民众的反应,其实更让人明白第一是外国的月亮没比较圆,第二是事情总是没那么简单粗暴非黑即白,美国不像原先设想地那么领先优秀,但是的确有很多方面是全球领先的,天朝也有体制所带来的优势,不可妄自菲薄,也不能忙不自大,还是要多学习知识,提升认知水平。

    + 从清华美院学姐聊聊我们身边的恶人 + /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 站看了个吐槽这个的,然后刚好晚上乘公交的时候又碰到了有点类似的问题
    故事描述下,我们从始发站做了公交,这辆公交司机上次碰到过一回,就是会比较关注乘客的佩戴情况,主要考虑到目前国内疫情,然后这次在差不多人都坐满的情况下,可能在提示了三次让车内乘客戴好口罩,但是他指的那个中年女性还是没有反应,司机就转头比较大声指着这个乘客(中年女性)让戴好口罩,然后这个乘客(中年女性)就大声的说“我口罩是滑下来了,你指着我干嘛,你态度这么差,要吃了我一样,我要投诉你”等等,然后可能跟她一块的一个中年女性也是这么帮腔指责司机,比较基本的理解,车子里这么多乘客,假如是处于这位乘客口罩滑下来了而不自知的情况下,司机在提示了三次以后回头指着她说,我想的是没什么问题的,但是这位却反而指责这位司机指着她,并且说是态度差,要吃了她,完全是不可理喻的,并且一直喋喋不休说她口罩滑掉了有什么错,要投诉这个司机,让他可以提前退休了,在其他乘客的劝说下司机准备继续开车时,又口吐芬芳“你个傻,你来打我呀”,真的是让我再次体会到了所谓的恶人先告状的又一完美呈现,后面还有个乘客还是表示要打死司机这个傻,让我有点不明所以,俗话说有人是得理不饶人,前提是得理,这种理亏不饶人真的是挺让人长见识的,试想下,司机在提示三次后,这位乘客还是没有把口罩戴好,如何在不指着这位乘客的情况下能准确的提示到她呢,并且觉得语气态度不好,司机要载着一车的人,因为你这一个乘客不戴好口罩而不能正常出发,有些着急应该很正常吧,可能是平时自己在家里耀武扬威的使唤别人习惯了吧,别人不敢这么大声跟她说话,其实想想这位中年女性应该年纪不会很大,还比较时髦的吧,像一些常见的中年杭州本地人可能是不会说傻*这个词的吧。
    杭州的公交可能是在二月份疫情还比较严重的时候是要求上车出示健康码,后面比较缓和以后只要求佩戴好口罩,但是在我们小绍兴,目前还是一律要求检验健康码和佩戴口罩,对于疫情中,并且目前阶段国内也时有报出小范围的疫情的情况下,司机尽职要求佩戴好口罩其实也是为了乘客着想,另一种情况如果司机不严格要求,万一车上有个感染者,这位中年女性被传染了,如果能找到这个司机的话,是不是想“打死”这个司机,竟然让感染者上了车,反正她自己是不可能有错的,上来就是对方态度差,要投诉,自己不戴好口罩啥都没错,我就想知道如果因为自己没戴好口罩被感染了,是不是也是司机的错,毕竟没有像仆人那样点头哈腰求着她戴好口罩。
    再说回来,整个车就她一个人没戴好口罩,并且还有个细节,其实这个乘客是上了车之后就没戴好了,本来上车的时候是戴好的,这种比较有可能是觉得上车的时候司机那看一眼就好了,如果好好戴着口罩,一点事情都没有,唉,纯粹是太气愤了,调理逻辑什么的就忽略吧

    ]]>
    生活 吐槽 疫情 - 美国 + 口罩 生活 吐槽 疫情 - 美国 + 公交车 + 口罩 + 杀人诛心
    - 从清华美院学姐聊聊我们身边的恶人 - /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 站看了个吐槽这个的,然后刚好晚上乘公交的时候又碰到了有点类似的问题
    故事描述下,我们从始发站做了公交,这辆公交司机上次碰到过一回,就是会比较关注乘客的佩戴情况,主要考虑到目前国内疫情,然后这次在差不多人都坐满的情况下,可能在提示了三次让车内乘客戴好口罩,但是他指的那个中年女性还是没有反应,司机就转头比较大声指着这个乘客(中年女性)让戴好口罩,然后这个乘客(中年女性)就大声的说“我口罩是滑下来了,你指着我干嘛,你态度这么差,要吃了我一样,我要投诉你”等等,然后可能跟她一块的一个中年女性也是这么帮腔指责司机,比较基本的理解,车子里这么多乘客,假如是处于这位乘客口罩滑下来了而不自知的情况下,司机在提示了三次以后回头指着她说,我想的是没什么问题的,但是这位却反而指责这位司机指着她,并且说是态度差,要吃了她,完全是不可理喻的,并且一直喋喋不休说她口罩滑掉了有什么错,要投诉这个司机,让他可以提前退休了,在其他乘客的劝说下司机准备继续开车时,又口吐芬芳“你个傻,你来打我呀”,真的是让我再次体会到了所谓的恶人先告状的又一完美呈现,后面还有个乘客还是表示要打死司机这个傻,让我有点不明所以,俗话说有人是得理不饶人,前提是得理,这种理亏不饶人真的是挺让人长见识的,试想下,司机在提示三次后,这位乘客还是没有把口罩戴好,如何在不指着这位乘客的情况下能准确的提示到她呢,并且觉得语气态度不好,司机要载着一车的人,因为你这一个乘客不戴好口罩而不能正常出发,有些着急应该很正常吧,可能是平时自己在家里耀武扬威的使唤别人习惯了吧,别人不敢这么大声跟她说话,其实想想这位中年女性应该年纪不会很大,还比较时髦的吧,像一些常见的中年杭州本地人可能是不会说傻*这个词的吧。
    杭州的公交可能是在二月份疫情还比较严重的时候是要求上车出示健康码,后面比较缓和以后只要求佩戴好口罩,但是在我们小绍兴,目前还是一律要求检验健康码和佩戴口罩,对于疫情中,并且目前阶段国内也时有报出小范围的疫情的情况下,司机尽职要求佩戴好口罩其实也是为了乘客着想,另一种情况如果司机不严格要求,万一车上有个感染者,这位中年女性被传染了,如果能找到这个司机的话,是不是想“打死”这个司机,竟然让感染者上了车,反正她自己是不可能有错的,上来就是对方态度差,要投诉,自己不戴好口罩啥都没错,我就想知道如果因为自己没戴好口罩被感染了,是不是也是司机的错,毕竟没有像仆人那样点头哈腰求着她戴好口罩。
    再说回来,整个车就她一个人没戴好口罩,并且还有个细节,其实这个乘客是上了车之后就没戴好了,本来上车的时候是戴好的,这种比较有可能是觉得上车的时候司机那看一眼就好了,如果好好戴着口罩,一点事情都没有,唉,纯粹是太气愤了,调理逻辑什么的就忽略吧

    + 上次的其他 外行聊国足 + /2022/03/06/%E4%B8%8A%E6%AC%A1%E7%9A%84%E5%85%B6%E4%BB%96-%E5%A4%96%E8%A1%8C%E8%81%8A%E5%9B%BD%E8%B6%B3/ + 上次本来想在换车牌后面聊下这个话题,为啥要聊这个话题呢,也很简单,在地铁上看到一对猜测是情侣或者比较关系好的男女同学在聊,因为是这位男同学是大学学的工科,然后自己爱好设计绘画相关的,可能还以此赚了点钱,在地铁上讨论男的要不要好好努力把大学课程完成好,大致的观点是没必要,本来就不适合,这一段我就不说了,恋爱人的嘴,信你个鬼。
    后面男的说在家里又跟他爹吵了关于男足的,估计是那次输了越南,实话说我不是个足球迷,对各方面技术相关也不熟,只是对包括这个人的解释和网上一些观点的看法,纯主观,这次地铁上这位说的大概意思是足球这个训练什么的很难的,要想赢越南也很难的,不是我们能嘴炮的;在网上看到一个赞同数很多的一个回答,说什么中国是个体育弱国,但是由于有一些乒乓球,跳水等小众项目比较厉害,让民众给误解了,首先我先来反驳下这个偷换概念的观点,第一所谓的体育弱国,跟我们觉得足球不应该这么差没半毛钱关系,因为体育弱国,我们的足球本来就不是顶尖的,也并不是去跟顶尖的球队去争,以足球为例,跟巴西,阿根廷,英国,德国,西班牙,意大利,法国这些足球强国,去比较,我相信没有一个足球迷会这么去做对比,因为我们足球历史最高排名是 1998 年的 37 名,最差是 100 名,把能数出来的强队都数完,估计都还不会到 37,所以根本没有跟强队去做对比,第二体育弱国,我们的体育投入是在逐年降低吗,我们是因战乱没法好好训练踢球?还是这帮傻逼就不争气,前面也说了我们足球世界排名最高 37,最低 100,那么前阵子我们输的越南是第几,目前我们的排名 77 名,越南 92 名,看明白了么,轮排名我们都不至于输越南,然后就是这个排名,这也是我想回应那位地铁上的兄弟,我觉得除了造核弹这种高精尖技术,绝大部分包含足球这类运动,遵循类二八原则,比如满分是 100 分,从 80 提到 90 分或者 90 分提到 100 分非常难,30 分提到 40 分,50 分提到 60 分我觉得都是可以凭后天努力达成的,基本不受天赋限制,这里可以以篮球来类比下,相对足球的确篮球没有那么火,或者行业市值没法比,但是也算是相对大众了,中国在篮球方面相对比较好一点,在 08 年奥运会冲进过八强,那也不是唯一的巅峰,但是我说这个其实是想说明两方面的事情,第一,像篮球一样,状态是有起起伏伏,排名也会变动,但是我觉得至少能维持一个相对稳定的总体排名和持平或者上升的趋势,这恰恰是我们这种所谓的“体育弱国”应该走的路线,第二就是去支持我的类二八原则的,可以看到我们的篮球这两年也很垃圾,排名跌到 29 了,那问题我觉得跟足球是一样的,就是不能脚踏实地,如斯科拉说的,中国篮球太缺少竞争,打得好不好都是这些人打,打输了还是照样拿钱,相对足球,篮球的技术我还是懂一些的,对比 08 年的中国男篮,的确像姚明跟王治郅这样的天赋型+努力型球员少了以后竞争力下降在所难免,但是去对比下基本功,传球,投篮,罚球稳定性,也完全不是一个水平的,这些就是我说的,可以通过努力训练拿 80 分的,只要拿到 80 分,甚至只要拿到 60 分,我觉得应该就还算对得起球迷了,就像 NBA 里球队也会有核心球员的更替,战绩起起伏伏,但是基本功这东西,防守积极性,我觉得不随核心球员的变化而变化,就像姚明这样的天赋,其实他应该还有一些先天缺陷,大脚趾较长等,但是他从 CBA 到 NBA,在 NBA 适应并且打成顶尖中锋,离不开刻苦训练,任何的成功都不是纯天赋的,必须要付出足够的努力。
    说回足球,如果像前面那么洗地(体育弱国),那能给我维持住一个稳定的排名我也能接受,问题是我们的经济物质资源比 2000 年前应该有了质的变化,身体素质也越来越好,即使是体育弱国,这么继续走下坡路,半死不活的,不觉得是打了自己的脸么。足球也需要基本功,基本的体能,力量这些,看看现在这些国足运动员的体型,对比下女足,说实话,如果男足这些运动员都练得不错的体脂率,耐力等,成绩即使不好,也不会比现在更差。
    纯主观吐槽,勿喷。

    ]]>
    生活 - 吐槽 - 疫情 - 口罩 + 运动 生活 - 吐槽 - 疫情 - 公交车 - 口罩 - 杀人诛心
    @@ -8747,25 +8727,42 @@ public: - 关于公共交通再吐个槽 - /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 这种的车反而想加速冲过去,如果少看一下可能我已经残了,交规考的靠近人行道要减速好像基本都是个摆设了,杭州也只有公交车因为一些考核指标原因会主动礼让,人其实需要有同理心,虽然可能有些人是开车多于骑车走路的,但是总也不可能永远不穿人行道吧,甚至这些人可能还会在人行道红灯的时候走过去。这个事情不是吐槽公共交通的,只是也有些许关系,想起来还有一件事也是刚才来杭州的时候看到的,等公交的时候看到有辆路虎要加塞,而目标车道刚好是辆大货车,大货车看到按了喇叭,路虎犹豫了下还是挤进去了,可能是对路虎的扛撞性能非常自信吧,反正我是挺后怕的,这种级别的车,被撞了的话估计还是鸡蛋撞石头,吨位惯性在那,这里再延伸下,挺多开豪车的人好像都觉得这路上路权更大一些,谁谁都得让着他,可能实际吃亏的不多,所以越加巩固了这种思维,当真的碰到不管的可能就会明白了,路权这个事情在天朝也基本没啥人重视,也没想说个结论,就到这吧

    + 从丁仲礼被美国制裁聊点啥 + /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/ + 几年前看了柴静的《穹顶之下》觉得这个记者调查得很深入,挺有水平,然后再看到了她跟丁仲礼的采访,其实没看完整,也没试着去理解,就觉得环境问题挺严重的,为啥柴静这个对面的这位好像对这个很不屑的样子,最近因为丁仲礼上了美国制裁名单,B 站又有人把这个视频发了出来,就完整看了下,就觉得自己挺惭愧的,就抱着对柴静的好感而没来由的否定了丁老的看法和说法,所以人也需要不断地学习,改正之前错误的观点,当然不是说我现在说的就是百分百正确,只是个人的一些浅显的见解

    +

    先聊聊这个事情,整体看下来我的一些理解,IPCC给中国的方案其实是个很大的陷阱,它里面有几个隐藏的点是容易被我们外行忽略的,第一点是基数,首先发达国家目前(指2010年采访或者IPCC方案时间)的人均碳排放量已经是远高于发展中国家的了,这也就导致了所谓的发达国家承诺减排80%是个非常有诚意的承诺其实就是忽悠;第二点是碳排放是个累计过程,从1900年开始到2050年,或者说到2010年,发达国家已经排的量是远超过发展中国家的,这是非常不公平的;第三点其实是通过前两点推导出来的,也就是即使发达国家这么有诚意地说减排80%,扒开这层虚伪的外衣,其实是给他们11亿人分走了48%的碳排放量,留给发展中国家55亿人口的只剩下了52%;第四点,人是否因为国家的发达与否而应受到不平等待遇,如果按国家维度,丁老说的,摩纳哥要跟中国分同样的排放量么,中国人还算不算人;第五点,这点算是我自己想的,也可能是柴静屁股决定脑袋想不到的点,她作为一个物质生活条件已经足够好了,那么对于那些生活在物质条件平均线以下的,他们是否能像城里人那样有空调地暖,洗澡有热水器浴霸,上下班能开车,这些其实都直接或者间接地导致了碳排放;他们有没有改善物质生活条件地权利呢,并且再说回来,其实丁老也给了我们觉得合理地方案,我们保证不管发达国家不管减排多少,我们都不会超过他们的80%,我觉得这是真正的诚意,而不是接着减排80%的噱头来忽悠人,也是像丁老这样的专家才能看破这个陷阱,碳排放权其实就是发展权,就是人权,中国人就不是人了么,或者说站在贫困线以下的人民是否有改善物质条件的权利,而不是说像柴静这样,只是管她自己,可能觉得小孩因为空气污染导致身体不好,所以做了穹顶之下这个纪录片,想去改善这个事情,空气污染不是说对的,只是每个国家都有这个过程,如果不发展,哪里有资源去让人活得好,活得好了是前提,然后再去各方面都改善。

    +

    对于这个问题其实更想说的是人的认知偏差,之前总觉得美帝是更自由民主,公平啥的,或者说觉得美帝啥都好,有种无脑愤青的感觉,外国的月亮比较圆,但是经历了像川普当选美国总统以来的各种魔幻操作,还有对于疫情的种种不可思议的美国民众的反应,其实更让人明白第一是外国的月亮没比较圆,第二是事情总是没那么简单粗暴非黑即白,美国不像原先设想地那么领先优秀,但是的确有很多方面是全球领先的,天朝也有体制所带来的优势,不可妄自菲薄,也不能忙不自大,还是要多学习知识,提升认知水平。

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

    +]]>
    + + 生活 + 读后感 + 白岩松 + 幸福了吗 + + + 读后感 + 读书 + 打卡 + 幸福了吗 + 足球
    @@ -8806,6 +8803,28 @@ public: scp + + 关于公共交通再吐个槽 + /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 这种的车反而想加速冲过去,如果少看一下可能我已经残了,交规考的靠近人行道要减速好像基本都是个摆设了,杭州也只有公交车因为一些考核指标原因会主动礼让,人其实需要有同理心,虽然可能有些人是开车多于骑车走路的,但是总也不可能永远不穿人行道吧,甚至这些人可能还会在人行道红灯的时候走过去。这个事情不是吐槽公共交通的,只是也有些许关系,想起来还有一件事也是刚才来杭州的时候看到的,等公交的时候看到有辆路虎要加塞,而目标车道刚好是辆大货车,大货车看到按了喇叭,路虎犹豫了下还是挤进去了,可能是对路虎的扛撞性能非常自信吧,反正我是挺后怕的,这种级别的车,被撞了的话估计还是鸡蛋撞石头,吨位惯性在那,这里再延伸下,挺多开豪车的人好像都觉得这路上路权更大一些,谁谁都得让着他,可能实际吃亏的不多,所以越加巩固了这种思维,当真的碰到不管的可能就会明白了,路权这个事情在天朝也基本没啥人重视,也没想说个结论,就到这吧

    +]]>
    + + 生活 + 公交 + + + 生活 + 开车 + 加塞 + 糟心事 + 规则 + 公交 + 路政规划 + 基础设施 + 杭州 + 健康码 + +
    周末我在老丈人家打了天小工 /2020/08/16/%E5%91%A8%E6%9C%AB%E6%88%91%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/ @@ -8826,34 +8845,15 @@ public: - 关于读书打卡与分享 - /2021/02/07/%E5%85%B3%E4%BA%8E%E8%AF%BB%E4%B9%A6%E6%89%93%E5%8D%A1%E4%B8%8E%E5%88%86%E4%BA%AB/ - 最近群里大佬发起了一个读书打卡活动,需要每天读一会书,在群里打卡分享感悟,争取一个月能读完一本书,说实话一天十分钟的读书时间倒是问题不大,不过每天都要打卡,而且一个月要读完一本书,其实难度还是有点大的,不过也想试试看。
    之前某某老大给自己立了个 flag,说要读一百本书,这对我来说挺难实现的,一则我也不喜欢书只读一小半,二则感觉对于喜欢看的内容范围还是比较有限制,可能也算是比较矫情,不爱追热门的各类东西,因为往往会有一些跟大众不一致的观点看法,显得格格不入。所以还是这个打卡活动可能会比较适合我,书是人类进步的阶梯。
    到现在是打卡了三天了,读的主要是白岩松的《幸福了吗》,对于白岩松,我们这一代人是比较熟悉,并且整体印象比较不错的一个央视主持人,从《焦点访谈》开始,到疫情期间的各类一线节目,可能对我来说是个三观比较正,敢于说一些真话的主持人,这中间其实是有个空档期,没怎么看电视,也不太关注了,只是在疫情期间的节目,还是一如既往地给人一种可靠的感觉,正好有一次偶然微信读书推荐了白岩松的这本书,就看了一部分,正好这次继续往下看,因为相对来讲不会很晦涩,并且从这位知名央视主持人的角度分享他的过往和想法看法,还是比较有意思的。
    从对汶川地震,08 年奥运等往事的回忆和一些细节的呈现,也让我了解比较多当时所不知道的,特别是汶川地震,那时的我还在读高中,真的是看着电视,作为“猛男”都忍不住泪目了,共和国之殇,多难兴邦,但是这对于当事人来说,都是一场醒不过来的噩梦。
    然后是对于足球的热爱,其实光这个就能掰扯很多,因为我不爱足球,只爱篮球,其中原因有的没的也挺多可以说的,但是看了他的书,才能比较深入的了解一个足球迷,对足球,对中国足球,对世界杯,对阿根廷的感情。
    接下去还是想能继续坚持下去,加油!

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

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

    ]]>
    生活 @@ -8917,27 +8917,6 @@ public: 囤物资
    - - 寄生虫观后感 - /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 - - - 生活 - 影评 - 寄生虫 - -
    我是如何走上跑步这条不归路的 /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/ @@ -8959,6 +8938,27 @@ public: 跑步 + + 寄生虫观后感 + /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 + + + 生活 + 影评 + 寄生虫 + +
    搬运两个 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/ @@ -9055,2838 +9055,2903 @@ public:

    而对于其他的人感觉演技都不错,只是最后有一些虎头蛇尾吧,不知道是不是审核的原因,也不细说了怕被请喝茶,还有提一点就是麦佳的这个事情,她其实是里面很惨的一个人,把高明远当成最亲近的人,而其实真相令人感觉不寒而栗,杀父杀母的仇人,对于麦佳这个演员,一直觉得印象深刻,后来才想起来就是在爱情公寓里演被关谷救了要以身相遇的那个女孩,长相其实蛮令人印象深刻的,但好像也一直不温不火,不过也不能说演技很好吧,只是在这里演的任务真的是很可怜了,剧情设计里也应该是个很重要的串联人物,最终被高明远献给了大佬,这里扯开一点,好像有的观点说贺芸之前也是这样的,只是一种推测了。

    看完这部剧其实有很多想说的,但是也为了不被请喝茶,尽量少说了,只想说珍爱生命,还是自己小心吧

    ]]> - - 生活 - - - 生活 - 影评 - -
    - - 是何原因竟让两人深夜奔袭十公里 - /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

    -]]>
    - - 生活 - - - 生活 - -
    - - 给小电驴上牌 - /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 的小车子,后来发现还是有点不方便的点就是没有比较大的筐,也不好装,这样就是下雨天雨衣什么的比较不方便放。

    -

    聊回来主题上牌这个事情,这个事情也是颇费心力,提车的时候店里的让我跟他早上一起去,但是因为不确定时间,也比较远就没跟着去,因为我是线上买的,线下自提,线下的店可能没啥利润可以拿,就不肯帮忙代上牌,朋友说在线下店里买是可以代上的,自己上牌过程也比较曲折,一开始是头盔没到,然后是等开发票,主要的东西就是需要骑着车子去车管所,不能只自己去,然后需要预约,附近比较近的都是提前一周就预约完了号了,要提前在支付宝上进行预约,比较空的就是店里推荐的景区大队,但是随之而来就是比较蛋疼的,这个景区大队太远了,看下骑车距离有十几公里,所以就有点拖延症,但是总归要上的,不然一直不能开是白买了,上牌的材料主要是车辆合格证,发票,然后车子上的浙品码,在车架上和电池上,然后车架号什么的都要跟合格证上完全对应,整体车子要跟合格证上一毛一样,如果有额外的反光镜,后面副座都需要拆掉,脚踏板要装上,到了那其实还比较顺利,就是十几公里外加那天比较冷,吹得头疼。

    -]]>
    - - 生活 - - - 生活 - -
    - - 聊一下 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 - -
    - - 聊一下 RocketMQ 的 NameServer 源码 - /2020/07/05/%E8%81%8A%E4%B8%80%E4%B8%8B-RocketMQ-%E7%9A%84-NameServer-%E6%BA%90%E7%A0%81/ - 前面介绍了,nameserver相当于dubbo的注册中心,用与管理broker,broker会在启动的时候注册到nameserver,并且会发送心跳给namaserver,nameserver负责保存活跃的broker,包括master和slave,同时保存topic和topic下的队列,以及filter列表,然后为producer和consumer的请求提供服务。

    -

    启动过程

    public static void main(String[] args) {
    -        main0(args);
    -    }
    -
    -    public static NamesrvController main0(String[] args) {
    -
    -        try {
    -            NamesrvController controller = createNamesrvController(args);
    -            start(controller);
    -            String tip = "The Name Server boot success. serializeType=" + RemotingCommand.getSerializeTypeConfigInThisServer();
    -            log.info(tip);
    -            System.out.printf("%s%n", tip);
    -            return controller;
    -        } catch (Throwable e) {
    -            e.printStackTrace();
    -            System.exit(-1);
    -        }
    -
    -        return null;
    -    }
    - -

    入口的代码时这样子,其实主要的逻辑在createNamesrvController和start方法,来看下这两个的实现

    -
    public static NamesrvController createNamesrvController(String[] args) throws IOException, JoranException {
    -        System.setProperty(RemotingCommand.REMOTING_VERSION_KEY, Integer.toString(MQVersion.CURRENT_VERSION));
    -        //PackageConflictDetect.detectFastjson();
    -
    -        Options options = ServerUtil.buildCommandlineOptions(new Options());
    -        commandLine = ServerUtil.parseCmdLine("mqnamesrv", args, buildCommandlineOptions(options), new PosixParser());
    -        if (null == commandLine) {
    -            System.exit(-1);
    -            return null;
    -        }
    -
    -        final NamesrvConfig namesrvConfig = new NamesrvConfig();
    -        final NettyServerConfig nettyServerConfig = new NettyServerConfig();
    -        nettyServerConfig.setListenPort(9876);
    -        if (commandLine.hasOption('c')) {
    -            String file = commandLine.getOptionValue('c');
    -            if (file != null) {
    -                InputStream in = new BufferedInputStream(new FileInputStream(file));
    -                properties = new Properties();
    -                properties.load(in);
    -                MixAll.properties2Object(properties, namesrvConfig);
    -                MixAll.properties2Object(properties, nettyServerConfig);
    -
    -                namesrvConfig.setConfigStorePath(file);
    -
    -                System.out.printf("load config properties file OK, %s%n", file);
    -                in.close();
    -            }
    -        }
    -
    -        if (commandLine.hasOption('p')) {
    -            InternalLogger console = InternalLoggerFactory.getLogger(LoggerName.NAMESRV_CONSOLE_NAME);
    -            MixAll.printObjectProperties(console, namesrvConfig);
    -            MixAll.printObjectProperties(console, nettyServerConfig);
    -            System.exit(0);
    -        }
    -
    -        MixAll.properties2Object(ServerUtil.commandLine2Properties(commandLine), namesrvConfig);
    -
    -        if (null == namesrvConfig.getRocketmqHome()) {
    -            System.out.printf("Please set the %s variable in your environment to match the location of the RocketMQ installation%n", MixAll.ROCKETMQ_HOME_ENV);
    -            System.exit(-2);
    -        }
    -
    -        LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    -        JoranConfigurator configurator = new JoranConfigurator();
    -        configurator.setContext(lc);
    -        lc.reset();
    -        configurator.doConfigure(namesrvConfig.getRocketmqHome() + "/conf/logback_namesrv.xml");
    -
    -        log = InternalLoggerFactory.getLogger(LoggerName.NAMESRV_LOGGER_NAME);
    -
    -        MixAll.printObjectProperties(log, namesrvConfig);
    -        MixAll.printObjectProperties(log, nettyServerConfig);
    -
    -        final NamesrvController controller = new NamesrvController(namesrvConfig, nettyServerConfig);
    -
    -        // remember all configs to prevent discard
    -        controller.getConfiguration().registerConfig(properties);
    -
    -        return controller;
    -    }
    - -

    这个方法里其实主要是读取一些配置啥的,不是很复杂,

    -
    public static NamesrvController start(final NamesrvController controller) throws Exception {
    -
    -        if (null == controller) {
    -            throw new IllegalArgumentException("NamesrvController is null");
    -        }
    -
    -        boolean initResult = controller.initialize();
    -        if (!initResult) {
    -            controller.shutdown();
    -            System.exit(-3);
    -        }
    -
    -        Runtime.getRuntime().addShutdownHook(new ShutdownHookThread(log, new Callable<Void>() {
    -            @Override
    -            public Void call() throws Exception {
    -                controller.shutdown();
    -                return null;
    -            }
    -        }));
    -
    -        controller.start();
    -
    -        return controller;
    -    }
    - -

    这个start里主要关注initialize方法,后面就是一个停机的hook,来看下initialize方法

    -
    public boolean initialize() {
    -
    -        this.kvConfigManager.load();
    -
    -        this.remotingServer = new NettyRemotingServer(this.nettyServerConfig, this.brokerHousekeepingService);
    -
    -        this.remotingExecutor =
    -            Executors.newFixedThreadPool(nettyServerConfig.getServerWorkerThreads(), new ThreadFactoryImpl("RemotingExecutorThread_"));
    -
    -        this.registerProcessor();
    -
    -        this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
    -
    -            @Override
    -            public void run() {
    -                NamesrvController.this.routeInfoManager.scanNotActiveBroker();
    -            }
    -        }, 5, 10, TimeUnit.SECONDS);
    -
    -        this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
    -
    -            @Override
    -            public void run() {
    -                NamesrvController.this.kvConfigManager.printAllPeriodically();
    -            }
    -        }, 1, 10, TimeUnit.MINUTES);
    -
    -        if (TlsSystemConfig.tlsMode != TlsMode.DISABLED) {
    -            // Register a listener to reload SslContext
    -            try {
    -                fileWatchService = new FileWatchService(
    -                    new String[] {
    -                        TlsSystemConfig.tlsServerCertPath,
    -                        TlsSystemConfig.tlsServerKeyPath,
    -                        TlsSystemConfig.tlsServerTrustCertPath
    -                    },
    -                    new FileWatchService.Listener() {
    -                        boolean certChanged, keyChanged = false;
    -                        @Override
    -                        public void onChanged(String path) {
    -                            if (path.equals(TlsSystemConfig.tlsServerTrustCertPath)) {
    -                                log.info("The trust certificate changed, reload the ssl context");
    -                                reloadServerSslContext();
    -                            }
    -                            if (path.equals(TlsSystemConfig.tlsServerCertPath)) {
    -                                certChanged = true;
    -                            }
    -                            if (path.equals(TlsSystemConfig.tlsServerKeyPath)) {
    -                                keyChanged = true;
    -                            }
    -                            if (certChanged && keyChanged) {
    -                                log.info("The certificate and private key changed, reload the ssl context");
    -                                certChanged = keyChanged = false;
    -                                reloadServerSslContext();
    -                            }
    -                        }
    -                        private void reloadServerSslContext() {
    -                            ((NettyRemotingServer) remotingServer).loadSslContext();
    -                        }
    -                    });
    -            } catch (Exception e) {
    -                log.warn("FileWatchService created error, can't load the certificate dynamically");
    -            }
    -        }
    -
    -        return true;
    -    }
    - -

    这里的kvConfigManager主要是来加载NameServer的配置参数,存到org.apache.rocketmq.namesrv.kvconfig.KVConfigManager#configTable中,然后是以BrokerHousekeepingService对象为参数初始化NettyRemotingServer对象,BrokerHousekeepingService对象作为该Netty连接中Socket链接的监听器(ChannelEventListener);监听与Broker建立的渠道的状态(空闲、关闭、异常三个状态),并调用BrokerHousekeepingService的相应onChannel方法。其中渠道的空闲、关闭、异常状态均调用RouteInfoManager.onChannelDestory方法处理。这个BrokerHousekeepingService可以字面化地理解为broker的管家服务,这个类内部三个状态方法其实都是调用的org.apache.rocketmq.namesrv.NamesrvController#getRouteInfoManager方法,而这个RouteInfoManager里面的对象有这些

    -
    public class RouteInfoManager {
    -    private static final InternalLogger log = InternalLoggerFactory.getLogger(LoggerName.NAMESRV_LOGGER_NAME);
    -    private final static long BROKER_CHANNEL_EXPIRED_TIME = 1000 * 60 * 2;
    -    private final ReadWriteLock lock = new ReentrantReadWriteLock();
    -  // topic与queue的对应关系
    -    private final HashMap<String/* topic */, List<QueueData>> topicQueueTable;
    -  // Broker名称与broker属性的map
    -    private final HashMap<String/* brokerName */, BrokerData> brokerAddrTable;
    -  // 集群与broker集合的对应关系
    -    private final HashMap<String/* clusterName */, Set<String/* brokerName */>> clusterAddrTable;
    -  // 活跃的broker信息
    -    private final HashMap<String/* brokerAddr */, BrokerLiveInfo> brokerLiveTable;
    -  // Broker地址与过滤器
    -    private final HashMap<String/* brokerAddr */, List<String>/* Filter Server */> filterServerTable;
    - -

    然后接下去就是初始化了一个线程池,然后注册默认的处理类this.registerProcessor();默认都是这个处理器去处理请求 org.apache.rocketmq.namesrv.processor.DefaultRequestProcessor#DefaultRequestProcessor然后是初始化两个定时任务

    -

    第一是每10秒检查一遍Broker的状态的定时任务,调用scanNotActiveBroker方法;遍历brokerLiveTable集合,查看每个broker的最后更新时间(BrokerLiveInfo.lastUpdateTimestamp)是否超过2分钟,若超过则关闭该broker的渠道并调用RouteInfoManager.onChannelDestory方法清理RouteInfoManager类的topicQueueTable、brokerAddrTable、clusterAddrTable、filterServerTable成员变量。

    -
    this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
    -
    -            @Override
    -            public void run() {
    -                NamesrvController.this.routeInfoManager.scanNotActiveBroker();
    -            }
    -        }, 5, 10, TimeUnit.SECONDS);
    -public void scanNotActiveBroker() {
    -        Iterator<Entry<String, BrokerLiveInfo>> it = this.brokerLiveTable.entrySet().iterator();
    -        while (it.hasNext()) {
    -            Entry<String, BrokerLiveInfo> next = it.next();
    -            long last = next.getValue().getLastUpdateTimestamp();
    -            if ((last + BROKER_CHANNEL_EXPIRED_TIME) < System.currentTimeMillis()) {
    -                RemotingUtil.closeChannel(next.getValue().getChannel());
    -                it.remove();
    -                log.warn("The broker channel expired, {} {}ms", next.getKey(), BROKER_CHANNEL_EXPIRED_TIME);
    -                this.onChannelDestroy(next.getKey(), next.getValue().getChannel());
    -            }
    -        }
    -    }
    -
    -    public void onChannelDestroy(String remoteAddr, Channel channel) {
    -        String brokerAddrFound = null;
    -        if (channel != null) {
    -            try {
    -                try {
    -                    this.lock.readLock().lockInterruptibly();
    -                    Iterator<Entry<String, BrokerLiveInfo>> itBrokerLiveTable =
    -                        this.brokerLiveTable.entrySet().iterator();
    -                    while (itBrokerLiveTable.hasNext()) {
    -                        Entry<String, BrokerLiveInfo> entry = itBrokerLiveTable.next();
    -                        if (entry.getValue().getChannel() == channel) {
    -                            brokerAddrFound = entry.getKey();
    -                            break;
    -                        }
    -                    }
    -                } finally {
    -                    this.lock.readLock().unlock();
    -                }
    -            } catch (Exception e) {
    -                log.error("onChannelDestroy Exception", e);
    -            }
    -        }
    -
    -        if (null == brokerAddrFound) {
    -            brokerAddrFound = remoteAddr;
    -        } else {
    -            log.info("the broker's channel destroyed, {}, clean it's data structure at once", brokerAddrFound);
    -        }
    -
    -        if (brokerAddrFound != null && brokerAddrFound.length() > 0) {
    -
    -            try {
    -                try {
    -                    this.lock.writeLock().lockInterruptibly();
    -                    this.brokerLiveTable.remove(brokerAddrFound);
    -                    this.filterServerTable.remove(brokerAddrFound);
    -                    String brokerNameFound = null;
    -                    boolean removeBrokerName = false;
    -                    Iterator<Entry<String, BrokerData>> itBrokerAddrTable =
    -                        this.brokerAddrTable.entrySet().iterator();
    -                    while (itBrokerAddrTable.hasNext() && (null == brokerNameFound)) {
    -                        BrokerData brokerData = itBrokerAddrTable.next().getValue();
    -
    -                        Iterator<Entry<Long, String>> it = brokerData.getBrokerAddrs().entrySet().iterator();
    -                        while (it.hasNext()) {
    -                            Entry<Long, String> entry = it.next();
    -                            Long brokerId = entry.getKey();
    -                            String brokerAddr = entry.getValue();
    -                            if (brokerAddr.equals(brokerAddrFound)) {
    -                                brokerNameFound = brokerData.getBrokerName();
    -                                it.remove();
    -                                log.info("remove brokerAddr[{}, {}] from brokerAddrTable, because channel destroyed",
    -                                    brokerId, brokerAddr);
    -                                break;
    -                            }
    -                        }
    -
    -                        if (brokerData.getBrokerAddrs().isEmpty()) {
    -                            removeBrokerName = true;
    -                            itBrokerAddrTable.remove();
    -                            log.info("remove brokerName[{}] from brokerAddrTable, because channel destroyed",
    -                                brokerData.getBrokerName());
    -                        }
    -                    }
    +      
    +        生活
    +      
    +      
    +        生活
    +        影评
    +      
    +  
    +  
    +    给小电驴上牌
    +    /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 的小车子,后来发现还是有点不方便的点就是没有比较大的筐,也不好装,这样就是下雨天雨衣什么的比较不方便放。

    +

    聊回来主题上牌这个事情,这个事情也是颇费心力,提车的时候店里的让我跟他早上一起去,但是因为不确定时间,也比较远就没跟着去,因为我是线上买的,线下自提,线下的店可能没啥利润可以拿,就不肯帮忙代上牌,朋友说在线下店里买是可以代上的,自己上牌过程也比较曲折,一开始是头盔没到,然后是等开发票,主要的东西就是需要骑着车子去车管所,不能只自己去,然后需要预约,附近比较近的都是提前一周就预约完了号了,要提前在支付宝上进行预约,比较空的就是店里推荐的景区大队,但是随之而来就是比较蛋疼的,这个景区大队太远了,看下骑车距离有十几公里,所以就有点拖延症,但是总归要上的,不然一直不能开是白买了,上牌的材料主要是车辆合格证,发票,然后车子上的浙品码,在车架上和电池上,然后车架号什么的都要跟合格证上完全对应,整体车子要跟合格证上一毛一样,如果有额外的反光镜,后面副座都需要拆掉,脚踏板要装上,到了那其实还比较顺利,就是十几公里外加那天比较冷,吹得头疼。

    +]]>
    + + 生活 + + + 生活 + +
    + + 聊一下 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);
    - if (brokerNameFound != null && removeBrokerName) { - Iterator<Entry<String, Set<String>>> it = this.clusterAddrTable.entrySet().iterator(); - while (it.hasNext()) { - Entry<String, Set<String>> entry = it.next(); - String clusterName = entry.getKey(); - Set<String> brokerNames = entry.getValue(); - boolean removed = brokerNames.remove(brokerNameFound); - if (removed) { - log.info("remove brokerName[{}], clusterName[{}] from clusterAddrTable, because channel destroyed", - brokerNameFound, clusterName); - if (brokerNames.isEmpty()) { - log.info("remove the clusterName[{}] from clusterAddrTable, because channel destroyed and no broker in this cluster", - clusterName); - it.remove(); - } - break; - } - } - } +

    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);
    - if (removeBrokerName) { - Iterator<Entry<String, List<QueueData>>> itTopicQueueTable = - this.topicQueueTable.entrySet().iterator(); - while (itTopicQueueTable.hasNext()) { - Entry<String, List<QueueData>> entry = itTopicQueueTable.next(); - String topic = entry.getKey(); - List<QueueData> queueDataList = entry.getValue(); +

    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 + +
    + + 是何原因竟让两人深夜奔袭十公里 + /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

    +]]>
    + + 生活 + + + 生活 + +
    + + 聊一下 RocketMQ 的 DefaultMQPushConsumer 源码 + /2020/06/26/%E8%81%8A%E4%B8%80%E4%B8%8B-RocketMQ-%E7%9A%84-Consumer/ + 首先看下官方的小 demo

    +
    public static void main(String[] args) throws InterruptedException, MQClientException {
     
    -                            Iterator<QueueData> itQueueData = queueDataList.iterator();
    -                            while (itQueueData.hasNext()) {
    -                                QueueData queueData = itQueueData.next();
    -                                if (queueData.getBrokerName().equals(brokerNameFound)) {
    -                                    itQueueData.remove();
    -                                    log.info("remove topic[{} {}], from topicQueueTable, because channel destroyed",
    -                                        topic, queueData);
    -                                }
    -                            }
    +        /*
    +         * Instantiate with specified consumer group name.
    +         * 首先是new 一个对象出来,然后指定 Consumer 的 Group
    +         * 同一类Consumer的集合,这类Consumer通常消费同一类消息且消费逻辑一致。消费者组使得在消息消费方面,实现负载均衡和容错的目标变得非常容易。要注意的是,消费者组的消费者实例必须订阅完全相同的Topic。RocketMQ 支持两种消息模式:集群消费(Clustering)和广播消费(Broadcasting)。
    +         */
    +        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("please_rename_unique_group_name_4");
     
    -                            if (queueDataList.isEmpty()) {
    -                                itTopicQueueTable.remove();
    -                                log.info("remove topic[{}] all queue, from topicQueueTable, because channel destroyed",
    -                                    topic);
    -                            }
    -                        }
    -                    }
    -                } finally {
    -                    this.lock.writeLock().unlock();
    -                }
    -            } catch (Exception e) {
    -                log.error("onChannelDestroy Exception", e);
    -            }
    -        }
    -    }
    + /* + * Specify name server addresses. + * <p/> + * 这里可以通知指定环境变量或者设置对象参数的形式指定名字空间服务的地址 + * + * Alternatively, you may specify name server addresses via exporting environmental variable: NAMESRV_ADDR + * <pre> + * {@code + * consumer.setNamesrvAddr("name-server1-ip:9876;name-server2-ip:9876"); + * } + * </pre> + */ -

    第二个是每10分钟打印一次NameServer的配置参数。即KVConfigManager.configTable变量的内容。

    -
    this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
    +        /*
    +         * Specify where to start in case the specified consumer group is a brand new one.
    +         * 指定消费起始点
    +         */
    +        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
     
    -            @Override
    -            public void run() {
    -                NamesrvController.this.kvConfigManager.printAllPeriodically();
    -            }
    -        }, 1, 10, TimeUnit.MINUTES);
    + /* + * Subscribe one more more topics to consume. + * 指定订阅的 topic 跟 tag,注意后面的是个表达式,可以以 tag1 || tag2 || tag3 传入 + */ + consumer.subscribe("TopicTest", "*"); -

    然后这个初始化就差不多完成了,后面只需要把remotingServer start一下就好了

    -

    处理请求

    直接上代码,其实主体是swtich case去判断

    -
    @Override
    -    public RemotingCommand processRequest(ChannelHandlerContext ctx,
    -        RemotingCommand request) throws RemotingCommandException {
    +        /*
    +         *  Register callback to execute on arrival of messages fetched from brokers.
    +         *  注册具体获得消息后的处理方法
    +         */
    +        consumer.registerMessageListener(new MessageListenerConcurrently() {
     
    -        if (ctx != null) {
    -            log.debug("receive request, {} {} {}",
    -                request.getCode(),
    -                RemotingHelper.parseChannelRemoteAddr(ctx.channel()),
    -                request);
    -        }
    +            @Override
    +            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
    +                ConsumeConcurrentlyContext context) {
    +                System.out.printf("%s Receive New Messages: %s %n", Thread.currentThread().getName(), msgs);
    +                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    +            }
    +        });
     
    +        /*
    +         *  Launch the consumer instance.
    +         * 启动消费者
    +         */
    +        consumer.start();
     
    -        switch (request.getCode()) {
    -            case RequestCode.PUT_KV_CONFIG:
    -                return this.putKVConfig(ctx, request);
    -            case RequestCode.GET_KV_CONFIG:
    -                return this.getKVConfig(ctx, request);
    -            case RequestCode.DELETE_KV_CONFIG:
    -                return this.deleteKVConfig(ctx, request);
    -            case RequestCode.QUERY_DATA_VERSION:
    -                return queryBrokerTopicConfig(ctx, request);
    -            case RequestCode.REGISTER_BROKER:
    -                Version brokerVersion = MQVersion.value2Version(request.getVersion());
    -                if (brokerVersion.ordinal() >= MQVersion.Version.V3_0_11.ordinal()) {
    -                    return this.registerBrokerWithFilterServer(ctx, request);
    -                } else {
    -                    return this.registerBroker(ctx, request);
    -                }
    -            case RequestCode.UNREGISTER_BROKER:
    -                return this.unregisterBroker(ctx, request);
    -            case RequestCode.GET_ROUTEINTO_BY_TOPIC:
    -                return this.getRouteInfoByTopic(ctx, request);
    -            case RequestCode.GET_BROKER_CLUSTER_INFO:
    -                return this.getBrokerClusterInfo(ctx, request);
    -            case RequestCode.WIPE_WRITE_PERM_OF_BROKER:
    -                return this.wipeWritePermOfBroker(ctx, request);
    -            case RequestCode.GET_ALL_TOPIC_LIST_FROM_NAMESERVER:
    -                return getAllTopicListFromNameserver(ctx, request);
    -            case RequestCode.DELETE_TOPIC_IN_NAMESRV:
    -                return deleteTopicInNamesrv(ctx, request);
    -            case RequestCode.GET_KVLIST_BY_NAMESPACE:
    -                return this.getKVListByNamespace(ctx, request);
    -            case RequestCode.GET_TOPICS_BY_CLUSTER:
    -                return this.getTopicsByCluster(ctx, request);
    -            case RequestCode.GET_SYSTEM_TOPIC_LIST_FROM_NS:
    -                return this.getSystemTopicListFromNs(ctx, request);
    -            case RequestCode.GET_UNIT_TOPIC_LIST:
    -                return this.getUnitTopicList(ctx, request);
    -            case RequestCode.GET_HAS_UNIT_SUB_TOPIC_LIST:
    -                return this.getHasUnitSubTopicList(ctx, request);
    -            case RequestCode.GET_HAS_UNIT_SUB_UNUNIT_TOPIC_LIST:
    -                return this.getHasUnitSubUnUnitTopicList(ctx, request);
    -            case RequestCode.UPDATE_NAMESRV_CONFIG:
    -                return this.updateConfig(ctx, request);
    -            case RequestCode.GET_NAMESRV_CONFIG:
    -                return this.getConfig(ctx, request);
    -            default:
    -                break;
    -        }
    -        return null;
    -    }
    + System.out.printf("Consumer Started.%n"); + }
    -

    以broker注册为例,

    -
    case RequestCode.REGISTER_BROKER:
    -                Version brokerVersion = MQVersion.value2Version(request.getVersion());
    -                if (brokerVersion.ordinal() >= MQVersion.Version.V3_0_11.ordinal()) {
    -                    return this.registerBrokerWithFilterServer(ctx, request);
    -                } else {
    -                    return this.registerBroker(ctx, request);
    -                }
    +

    然后就是看看 start 的过程了

    +
    /**
    +     * This method gets internal infrastructure readily to serve. Instances must call this method after configuration.
    +     *
    +     * @throws MQClientException if there is any client error.
    +     */
    +    @Override
    +    public void start() throws MQClientException {
    +        setConsumerGroup(NamespaceUtil.wrapNamespace(this.getNamespace(), this.consumerGroup));
    +        this.defaultMQPushConsumerImpl.start();
    +        if (null != traceDispatcher) {
    +            try {
    +                traceDispatcher.start(this.getNamesrvAddr(), this.getAccessChannel());
    +            } catch (MQClientException e) {
    +                log.warn("trace dispatcher start failed ", e);
    +            }
    +        }
    +    }
    +

    具体的逻辑在this.defaultMQPushConsumerImpl.start(),这个 defaultMQPushConsumerImpl 就是

    +
    /**
    +     * Internal implementation. Most of the functions herein are delegated to it.
    +     */
    +    protected final transient DefaultMQPushConsumerImpl defaultMQPushConsumerImpl;
    -

    做了个简单的版本管理,我们看下前面一个的代码

    -
    public RemotingCommand registerBrokerWithFilterServer(ChannelHandlerContext ctx, RemotingCommand request)
    -    throws RemotingCommandException {
    -    final RemotingCommand response = RemotingCommand.createResponseCommand(RegisterBrokerResponseHeader.class);
    -    final RegisterBrokerResponseHeader responseHeader = (RegisterBrokerResponseHeader) response.readCustomHeader();
    -    final RegisterBrokerRequestHeader requestHeader =
    -        (RegisterBrokerRequestHeader) request.decodeCommandCustomHeader(RegisterBrokerRequestHeader.class);
    +
    public synchronized void start() throws MQClientException {
    +        switch (this.serviceState) {
    +            case CREATE_JUST:
    +                log.info("the consumer [{}] start beginning. messageModel={}, isUnitMode={}", this.defaultMQPushConsumer.getConsumerGroup(),
    +                    this.defaultMQPushConsumer.getMessageModel(), this.defaultMQPushConsumer.isUnitMode());
    +                // 这里比较巧妙,相当于想设立了个屏障,防止并发启动,不过这里并不是悲观锁,也不算个严格的乐观锁
    +                this.serviceState = ServiceState.START_FAILED;
     
    -    if (!checksum(ctx, request, requestHeader)) {
    -        response.setCode(ResponseCode.SYSTEM_ERROR);
    -        response.setRemark("crc32 not match");
    -        return response;
    -    }
    +                this.checkConfig();
     
    -    RegisterBrokerBody registerBrokerBody = new RegisterBrokerBody();
    +                this.copySubscription();
     
    -    if (request.getBody() != null) {
    -        try {
    -            registerBrokerBody = RegisterBrokerBody.decode(request.getBody(), requestHeader.isCompressed());
    -        } catch (Exception e) {
    -            throw new RemotingCommandException("Failed to decode RegisterBrokerBody", e);
    -        }
    -    } else {
    -        registerBrokerBody.getTopicConfigSerializeWrapper().getDataVersion().setCounter(new AtomicLong(0));
    -        registerBrokerBody.getTopicConfigSerializeWrapper().getDataVersion().setTimestamp(0);
    -    }
    +                if (this.defaultMQPushConsumer.getMessageModel() == MessageModel.CLUSTERING) {
    +                    this.defaultMQPushConsumer.changeInstanceNameToPID();
    +                }
     
    -    RegisterBrokerResult result = this.namesrvController.getRouteInfoManager().registerBroker(
    -        requestHeader.getClusterName(),
    -        requestHeader.getBrokerAddr(),
    -        requestHeader.getBrokerName(),
    -        requestHeader.getBrokerId(),
    -        requestHeader.getHaServerAddr(),
    -        registerBrokerBody.getTopicConfigSerializeWrapper(),
    -        registerBrokerBody.getFilterServerList(),
    -        ctx.channel());
    +                // 这个mQClientFactory,负责管理client(consumer、producer),并提供多中功能接口供各个Service(Rebalance、PullMessage等)调用;大部分逻辑均在这个类中完成
    +                this.mQClientFactory = MQClientManager.getInstance().getOrCreateMQClientInstance(this.defaultMQPushConsumer, this.rpcHook);
     
    -    responseHeader.setHaServerAddr(result.getHaServerAddr());
    -    responseHeader.setMasterAddr(result.getMasterAddr());
    +                // 这个 rebalanceImpl 主要负责决定,当前的consumer应该从哪些Queue中消费消息;
    +                this.rebalanceImpl.setConsumerGroup(this.defaultMQPushConsumer.getConsumerGroup());
    +                this.rebalanceImpl.setMessageModel(this.defaultMQPushConsumer.getMessageModel());
    +                this.rebalanceImpl.setAllocateMessageQueueStrategy(this.defaultMQPushConsumer.getAllocateMessageQueueStrategy());
    +                this.rebalanceImpl.setmQClientFactory(this.mQClientFactory);
     
    -    byte[] jsonValue = this.namesrvController.getKvConfigManager().getKVListByNamespace(NamesrvUtil.NAMESPACE_ORDER_TOPIC_CONFIG);
    -    response.setBody(jsonValue);
    +                // 长连接,负责从broker处拉取消息,然后利用ConsumeMessageService回调用户的Listener执行消息消费逻辑
    +                this.pullAPIWrapper = new PullAPIWrapper(
    +                    mQClientFactory,
    +                    this.defaultMQPushConsumer.getConsumerGroup(), isUnitMode());
    +                this.pullAPIWrapper.registerFilterMessageHook(filterMessageHookList);
     
    -    response.setCode(ResponseCode.SUCCESS);
    -    response.setRemark(null);
    -    return response;
    -}
    + if (this.defaultMQPushConsumer.getOffsetStore() != null) { + this.offsetStore = this.defaultMQPushConsumer.getOffsetStore(); + } else { + switch (this.defaultMQPushConsumer.getMessageModel()) { + case BROADCASTING: + this.offsetStore = new LocalFileOffsetStore(this.mQClientFactory, this.defaultMQPushConsumer.getConsumerGroup()); + break; + case CLUSTERING: + this.offsetStore = new RemoteBrokerOffsetStore(this.mQClientFactory, this.defaultMQPushConsumer.getConsumerGroup()); + break; + default: + break; + } + this.defaultMQPushConsumer.setOffsetStore(this.offsetStore); + } + // offsetStore 维护当前consumer的消费记录(offset);有两种实现,Local和Rmote,Local存储在本地磁盘上,适用于BROADCASTING广播消费模式;而Remote则将消费进度存储在Broker上,适用于CLUSTERING集群消费模式; + this.offsetStore.load(); -

    可以看到主要的逻辑还是在org.apache.rocketmq.namesrv.routeinfo.RouteInfoManager#registerBroker这个方法里

    -
    public RegisterBrokerResult registerBroker(
    -        final String clusterName,
    -        final String brokerAddr,
    -        final String brokerName,
    -        final long brokerId,
    -        final String haServerAddr,
    -        final TopicConfigSerializeWrapper topicConfigWrapper,
    -        final List<String> filterServerList,
    -        final Channel channel) {
    -        RegisterBrokerResult result = new RegisterBrokerResult();
    -        try {
    -            try {
    -                this.lock.writeLock().lockInterruptibly();
    +                if (this.getMessageListenerInner() instanceof MessageListenerOrderly) {
    +                    this.consumeOrderly = true;
    +                    this.consumeMessageService =
    +                        new ConsumeMessageOrderlyService(this, (MessageListenerOrderly) this.getMessageListenerInner());
    +                } else if (this.getMessageListenerInner() instanceof MessageListenerConcurrently) {
    +                    this.consumeOrderly = false;
    +                    this.consumeMessageService =
    +                        new ConsumeMessageConcurrentlyService(this, (MessageListenerConcurrently) this.getMessageListenerInner());
    +                }
     
    -              // 更新这个clusterAddrTable
    -                Set<String> brokerNames = this.clusterAddrTable.get(clusterName);
    -                if (null == brokerNames) {
    -                    brokerNames = new HashSet<String>();
    -                    this.clusterAddrTable.put(clusterName, brokerNames);
    -                }
    -                brokerNames.add(brokerName);
    +                // 实现所谓的"Push-被动"消费机制;从Broker拉取的消息后,封装成ConsumeRequest提交给ConsumeMessageSerivce,此service负责回调用户的Listener消费消息;
    +                this.consumeMessageService.start();
     
    -                boolean registerFirst = false;
    +                boolean registerOK = mQClientFactory.registerConsumer(this.defaultMQPushConsumer.getConsumerGroup(), this);
    +                if (!registerOK) {
    +                    this.serviceState = ServiceState.CREATE_JUST;
    +                    this.consumeMessageService.shutdown();
    +                    throw new MQClientException("The consumer group[" + this.defaultMQPushConsumer.getConsumerGroup()
    +                        + "] has been created before, specify another name please." + FAQUrl.suggestTodo(FAQUrl.GROUP_NAME_DUPLICATE_URL),
    +                        null);
    +                }
     
    -              // 更新brokerAddrTable
    -                BrokerData brokerData = this.brokerAddrTable.get(brokerName);
    -                if (null == brokerData) {
    -                    registerFirst = true;
    -                    brokerData = new BrokerData(clusterName, brokerName, new HashMap<Long, String>());
    -                    this.brokerAddrTable.put(brokerName, brokerData);
    -                }
    -                Map<Long, String> brokerAddrsMap = brokerData.getBrokerAddrs();
    -                //Switch slave to master: first remove <1, IP:PORT> in namesrv, then add <0, IP:PORT>
    -                //The same IP:PORT must only have one record in brokerAddrTable
    -                Iterator<Entry<Long, String>> it = brokerAddrsMap.entrySet().iterator();
    -                while (it.hasNext()) {
    -                    Entry<Long, String> item = it.next();
    -                    if (null != brokerAddr && brokerAddr.equals(item.getValue()) && brokerId != item.getKey()) {
    -                        it.remove();
    -                    }
    -                }
    +                mQClientFactory.start();
    +                log.info("the consumer [{}] start OK.", this.defaultMQPushConsumer.getConsumerGroup());
    +                this.serviceState = ServiceState.RUNNING;
    +                break;
    +            case RUNNING:
    +            case START_FAILED:
    +            case SHUTDOWN_ALREADY:
    +                throw new MQClientException("The PushConsumer service state not OK, maybe started once, "
    +                    + this.serviceState
    +                    + FAQUrl.suggestTodo(FAQUrl.CLIENT_SERVICE_NOT_OK),
    +                    null);
    +            default:
    +                break;
    +        }
     
    -                String oldAddr = brokerData.getBrokerAddrs().put(brokerId, brokerAddr);
    -                registerFirst = registerFirst || (null == oldAddr);
    +        this.updateTopicSubscribeInfoWhenSubscriptionChanged();
    +        this.mQClientFactory.checkClientInBroker();
    +        this.mQClientFactory.sendHeartbeatToAllBrokerWithLock();
    +        this.mQClientFactory.rebalanceImmediately();
    +    }
    +

    然后我们往下看主要的目光聚焦mQClientFactory.start()

    +
    public void start() throws MQClientException {
    +
    +        synchronized (this) {
    +            switch (this.serviceState) {
    +                case CREATE_JUST:
    +                    this.serviceState = ServiceState.START_FAILED;
    +                    // If not specified,looking address from name server
    +                    if (null == this.clientConfig.getNamesrvAddr()) {
    +                        this.mQClientAPIImpl.fetchNameServerAddr();
    +                    }
    +                    // Start request-response channel
    +                    // 这里主要是初始化了个网络客户端
    +                    this.mQClientAPIImpl.start();
    +                    // Start various schedule tasks
    +                    // 定时任务
    +                    this.startScheduledTask();
    +                    // Start pull service
    +                    // 这里重点说下
    +                    this.pullMessageService.start();
    +                    // Start rebalance service
    +                    this.rebalanceService.start();
    +                    // Start push service
    +                    this.defaultMQProducer.getDefaultMQProducerImpl().start(false);
    +                    log.info("the client factory [{}] start OK", this.clientId);
    +                    this.serviceState = ServiceState.RUNNING;
    +                    break;
    +                case START_FAILED:
    +                    throw new MQClientException("The Factory object[" + this.getClientId() + "] has been created before, and failed.", null);
    +                default:
    +                    break;
    +            }
    +        }
    +    }
    +

    我们来看下这个 pullMessageService,org.apache.rocketmq.client.impl.consumer.PullMessageService,

    实现了 runnable 接口,
    然后可以看到 run 方法

    +
    public void run() {
    +        log.info(this.getServiceName() + " service started");
    +
    +        while (!this.isStopped()) {
    +            try {
    +                PullRequest pullRequest = this.pullRequestQueue.take();
    +                this.pullMessage(pullRequest);
    +            } catch (InterruptedException ignored) {
    +            } catch (Exception e) {
    +                log.error("Pull Message Service Run Method exception", e);
    +            }
    +        }
    +
    +        log.info(this.getServiceName() + " service end");
    +    }
    +

    接着在看 pullMessage 方法

    +
    private void pullMessage(final PullRequest pullRequest) {
    +        final MQConsumerInner consumer = this.mQClientFactory.selectConsumer(pullRequest.getConsumerGroup());
    +        if (consumer != null) {
    +            DefaultMQPushConsumerImpl impl = (DefaultMQPushConsumerImpl) consumer;
    +            impl.pullMessage(pullRequest);
    +        } else {
    +            log.warn("No matched consumer for the PullRequest {}, drop it", pullRequest);
    +        }
    +    }
    +

    实际上调用了这个方法,这个方法很长,我在代码里注释下下每一段的功能

    +
    public void pullMessage(final PullRequest pullRequest) {
    +        final ProcessQueue processQueue = pullRequest.getProcessQueue();
    +        // 这里开始就是检查状态,确定是否往下执行
    +        if (processQueue.isDropped()) {
    +            log.info("the pull request[{}] is dropped.", pullRequest.toString());
    +            return;
    +        }
     
    -              // 更新了org.apache.rocketmq.namesrv.routeinfo.RouteInfoManager#topicQueueTable中的数据
    -                if (null != topicConfigWrapper
    -                    && MixAll.MASTER_ID == brokerId) {
    -                    if (this.isBrokerTopicConfigChanged(brokerAddr, topicConfigWrapper.getDataVersion())
    -                        || registerFirst) {
    -                        ConcurrentMap<String, TopicConfig> tcTable =
    -                            topicConfigWrapper.getTopicConfigTable();
    -                        if (tcTable != null) {
    -                            for (Map.Entry<String, TopicConfig> entry : tcTable.entrySet()) {
    -                                this.createAndUpdateQueueData(brokerName, entry.getValue());
    -                            }
    -                        }
    -                    }
    -                }
    +        pullRequest.getProcessQueue().setLastPullTimestamp(System.currentTimeMillis());
     
    -              // 更新活跃broker信息
    -                BrokerLiveInfo prevBrokerLiveInfo = this.brokerLiveTable.put(brokerAddr,
    -                    new BrokerLiveInfo(
    -                        System.currentTimeMillis(),
    -                        topicConfigWrapper.getDataVersion(),
    -                        channel,
    -                        haServerAddr));
    -                if (null == prevBrokerLiveInfo) {
    -                    log.info("new broker registered, {} HAServer: {}", brokerAddr, haServerAddr);
    -                }
    +        try {
    +            this.makeSureStateOK();
    +        } catch (MQClientException e) {
    +            log.warn("pullMessage exception, consumer state not ok", e);
    +            this.executePullRequestLater(pullRequest, pullTimeDelayMillsWhenException);
    +            return;
    +        }
     
    -              // 处理filter
    -                if (filterServerList != null) {
    -                    if (filterServerList.isEmpty()) {
    -                        this.filterServerTable.remove(brokerAddr);
    -                    } else {
    -                        this.filterServerTable.put(brokerAddr, filterServerList);
    -                    }
    -                }
    +        if (this.isPause()) {
    +            log.warn("consumer was paused, execute pull request later. instanceName={}, group={}", this.defaultMQPushConsumer.getInstanceName(), this.defaultMQPushConsumer.getConsumerGroup());
    +            this.executePullRequestLater(pullRequest, PULL_TIME_DELAY_MILLS_WHEN_SUSPEND);
    +            return;
    +        }
     
    -              // 当当前broker非master时返回master信息
    -                if (MixAll.MASTER_ID != brokerId) {
    -                    String masterAddr = brokerData.getBrokerAddrs().get(MixAll.MASTER_ID);
    -                    if (masterAddr != null) {
    -                        BrokerLiveInfo brokerLiveInfo = this.brokerLiveTable.get(masterAddr);
    -                        if (brokerLiveInfo != null) {
    -                            result.setHaServerAddr(brokerLiveInfo.getHaServerAddr());
    -                            result.setMasterAddr(masterAddr);
    -                        }
    -                    }
    -                }
    -            } finally {
    -                this.lock.writeLock().unlock();
    -            }
    -        } catch (Exception e) {
    -            log.error("registerBroker Exception", e);
    -        }
    +        // 这块其实是个类似于限流的功能块,对消息数量和消息大小做限制
    +        long cachedMessageCount = processQueue.getMsgCount().get();
    +        long cachedMessageSizeInMiB = processQueue.getMsgSize().get() / (1024 * 1024);
     
    -        return result;
    -    }
    + if (cachedMessageCount > this.defaultMQPushConsumer.getPullThresholdForQueue()) { + this.executePullRequestLater(pullRequest, PULL_TIME_DELAY_MILLS_WHEN_FLOW_CONTROL); + if ((queueFlowControlTimes++ % 1000) == 0) { + log.warn( + "the cached message count exceeds the threshold {}, so do flow control, minOffset={}, maxOffset={}, count={}, size={} MiB, pullRequest={}, flowControlTimes={}", + this.defaultMQPushConsumer.getPullThresholdForQueue(), processQueue.getMsgTreeMap().firstKey(), processQueue.getMsgTreeMap().lastKey(), cachedMessageCount, cachedMessageSizeInMiB, pullRequest, queueFlowControlTimes); + } + return; + } -

    这个是注册 broker 的逻辑,再看下根据 topic 获取 broker 信息和 topic 信息,org.apache.rocketmq.namesrv.processor.DefaultRequestProcessor#getRouteInfoByTopic 主要是这个方法的逻辑

    -
    public RemotingCommand getRouteInfoByTopic(ChannelHandlerContext ctx,
    -        RemotingCommand request) throws RemotingCommandException {
    -        final RemotingCommand response = RemotingCommand.createResponseCommand(null);
    -        final GetRouteInfoRequestHeader requestHeader =
    -            (GetRouteInfoRequestHeader) request.decodeCommandCustomHeader(GetRouteInfoRequestHeader.class);
    +        if (cachedMessageSizeInMiB > this.defaultMQPushConsumer.getPullThresholdSizeForQueue()) {
    +            this.executePullRequestLater(pullRequest, PULL_TIME_DELAY_MILLS_WHEN_FLOW_CONTROL);
    +            if ((queueFlowControlTimes++ % 1000) == 0) {
    +                log.warn(
    +                    "the cached message size exceeds the threshold {} MiB, so do flow control, minOffset={}, maxOffset={}, count={}, size={} MiB, pullRequest={}, flowControlTimes={}",
    +                    this.defaultMQPushConsumer.getPullThresholdSizeForQueue(), processQueue.getMsgTreeMap().firstKey(), processQueue.getMsgTreeMap().lastKey(), cachedMessageCount, cachedMessageSizeInMiB, pullRequest, queueFlowControlTimes);
    +            }
    +            return;
    +        }
     
    -        TopicRouteData topicRouteData = this.namesrvController.getRouteInfoManager().pickupTopicRouteData(requestHeader.getTopic());
    +        // 若不是顺序消费(即DefaultMQPushConsumerImpl.consumeOrderly等于false),则检查ProcessQueue对象的msgTreeMap:TreeMap<Long,MessageExt>变量的第一个key值与最后一个key值之间的差额,该key值表示查询的队列偏移量queueoffset;若差额大于阈值(由DefaultMQPushConsumer. consumeConcurrentlyMaxSpan指定,默认是2000),则调用PullMessageService.executePullRequestLater方法,在50毫秒之后重新将该PullRequest请求放入PullMessageService.pullRequestQueue队列中;并跳出该方法;这里的意思主要就是消息有堆积了,等会再来拉取
    +        if (!this.consumeOrderly) {
    +            if (processQueue.getMaxSpan() > this.defaultMQPushConsumer.getConsumeConcurrentlyMaxSpan()) {
    +                this.executePullRequestLater(pullRequest, PULL_TIME_DELAY_MILLS_WHEN_FLOW_CONTROL);
    +                if ((queueMaxSpanFlowControlTimes++ % 1000) == 0) {
    +                    log.warn(
    +                        "the queue's messages, span too long, so do flow control, minOffset={}, maxOffset={}, maxSpan={}, pullRequest={}, flowControlTimes={}",
    +                        processQueue.getMsgTreeMap().firstKey(), processQueue.getMsgTreeMap().lastKey(), processQueue.getMaxSpan(),
    +                        pullRequest, queueMaxSpanFlowControlTimes);
    +                }
    +                return;
    +            }
    +        } else {
    +            if (processQueue.isLocked()) {
    +                if (!pullRequest.isLockedFirst()) {
    +                    final long offset = this.rebalanceImpl.computePullFromWhere(pullRequest.getMessageQueue());
    +                    boolean brokerBusy = offset < pullRequest.getNextOffset();
    +                    log.info("the first time to pull message, so fix offset from broker. pullRequest: {} NewOffset: {} brokerBusy: {}",
    +                        pullRequest, offset, brokerBusy);
    +                    if (brokerBusy) {
    +                        log.info("[NOTIFYME]the first time to pull message, but pull request offset larger than broker consume offset. pullRequest: {} NewOffset: {}",
    +                            pullRequest, offset);
    +                    }
     
    -        if (topicRouteData != null) {
    -            if (this.namesrvController.getNamesrvConfig().isOrderMessageEnable()) {
    -                String orderTopicConf =
    -                    this.namesrvController.getKvConfigManager().getKVConfig(NamesrvUtil.NAMESPACE_ORDER_TOPIC_CONFIG,
    -                        requestHeader.getTopic());
    -                topicRouteData.setOrderTopicConf(orderTopicConf);
    -            }
    +                    pullRequest.setLockedFirst(true);
    +                    pullRequest.setNextOffset(offset);
    +                }
    +            } else {
    +                this.executePullRequestLater(pullRequest, pullTimeDelayMillsWhenException);
    +                log.info("pull message later because not locked in broker, {}", pullRequest);
    +                return;
    +            }
    +        }
     
    -            byte[] content = topicRouteData.encode();
    -            response.setBody(content);
    -            response.setCode(ResponseCode.SUCCESS);
    -            response.setRemark(null);
    -            return response;
    -        }
    +        // 以PullRequest.messageQueue对象的topic值为参数从RebalanceImpl.subscriptionInner: ConcurrentHashMap, SubscriptionData>中获取对应的SubscriptionData对象,若该对象为null,考虑到并发的关系,调用executePullRequestLater方法,稍后重试;并跳出该方法;
    +        final SubscriptionData subscriptionData = this.rebalanceImpl.getSubscriptionInner().get(pullRequest.getMessageQueue().getTopic());
    +        if (null == subscriptionData) {
    +            this.executePullRequestLater(pullRequest, pullTimeDelayMillsWhenException);
    +            log.warn("find the consumer's subscription failed, {}", pullRequest);
    +            return;
    +        }
     
    -        response.setCode(ResponseCode.TOPIC_NOT_EXIST);
    -        response.setRemark("No topic route info in name server for the topic: " + requestHeader.getTopic()
    -            + FAQUrl.suggestTodo(FAQUrl.APPLY_TOPIC_URL));
    -        return response;
    -    }
    + final long beginTimestamp = System.currentTimeMillis(); -

    首先调用org.apache.rocketmq.namesrv.routeinfo.RouteInfoManager#pickupTopicRouteDataorg.apache.rocketmq.namesrv.routeinfo.RouteInfoManager#topicQueueTable获取到org.apache.rocketmq.common.protocol.route.QueueData这里面存了 brokerName,再通过org.apache.rocketmq.namesrv.routeinfo.RouteInfoManager#brokerAddrTable里获取到 broker 的地址信息等,然后再获取 orderMessage 的配置。

    -

    简要分析了下 RocketMQ 的 NameServer 的代码,比较粗粒度。

    -]]> - - MQ - RocketMQ - 消息队列 - RocketMQ - 中间件 - RocketMQ - - - MQ - 消息队列 - RocketMQ - 削峰填谷 - 中间件 - NameServer - 源码解析 - - - - 聊一下 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 {
    +        // 异步拉取回调,先不讨论细节
    +        PullCallback pullCallback = new PullCallback() {
    +            @Override
    +            public void onSuccess(PullResult pullResult) {
    +                if (pullResult != null) {
    +                    pullResult = DefaultMQPushConsumerImpl.this.pullAPIWrapper.processPullResult(pullRequest.getMessageQueue(), pullResult,
    +                        subscriptionData);
     
    -    @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;
    -            }
    +                    switch (pullResult.getPullStatus()) {
    +                        case FOUND:
    +                            long prevRequestOffset = pullRequest.getNextOffset();
    +                            pullRequest.setNextOffset(pullResult.getNextBeginOffset());
    +                            long pullRT = System.currentTimeMillis() - beginTimestamp;
    +                            DefaultMQPushConsumerImpl.this.getConsumerStatsManager().incPullRT(pullRequest.getConsumerGroup(),
    +                                pullRequest.getMessageQueue().getTopic(), pullRT);
     
    -            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;
    -            }
    +                            long firstMsgOffset = Long.MAX_VALUE;
    +                            if (pullResult.getMsgFoundList() == null || pullResult.getMsgFoundList().isEmpty()) {
    +                                DefaultMQPushConsumerImpl.this.executePullRequestImmediately(pullRequest);
    +                            } else {
    +                                firstMsgOffset = pullResult.getMsgFoundList().get(0).getQueueOffset();
     
    -            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;
    -                }
    -            }
    +                                DefaultMQPushConsumerImpl.this.getConsumerStatsManager().incPullTPS(pullRequest.getConsumerGroup(),
    +                                    pullRequest.getMessageQueue().getTopic(), pullResult.getMsgFoundList().size());
     
    -            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");
    -        }
    -    }
    + boolean dispatchToConsume = processQueue.putMessage(pullResult.getMsgFoundList()); + DefaultMQPushConsumerImpl.this.consumeMessageService.submitConsumeRequest( + pullResult.getMsgFoundList(), + processQueue, + pullRequest.getMessageQueue(), + dispatchToConsume); -

    配置的数量

    -
    private boolean messageIndexEnable = true;
    -private int maxHashSlotNum = 5000000;
    -private int maxIndexNum = 5000000 * 4;
    + if (DefaultMQPushConsumerImpl.this.defaultMQPushConsumer.getPullInterval() > 0) { + DefaultMQPushConsumerImpl.this.executePullRequestLater(pullRequest, + DefaultMQPushConsumerImpl.this.defaultMQPushConsumer.getPullInterval()); + } else { + DefaultMQPushConsumerImpl.this.executePullRequestImmediately(pullRequest); + } + } -

    最核心的其实是 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;
    +                            if (pullResult.getNextBeginOffset() < prevRequestOffset
    +                                || firstMsgOffset < prevRequestOffset) {
    +                                log.warn(
    +                                    "[BUG] pull message result maybe data wrong, nextBeginOffset: {} firstMsgOffset: {} prevRequestOffset: {}",
    +                                    pullResult.getNextBeginOffset(),
    +                                    firstMsgOffset,
    +                                    prevRequestOffset);
    +                            }
     
    -            FileLock fileLock = null;
    +                            break;
    +                        case NO_NEW_MSG:
    +                            pullRequest.setNextOffset(pullResult.getNextBeginOffset());
     
    -            try {
    +                            DefaultMQPushConsumerImpl.this.correctTagsOffset(pullRequest);
     
    -                // fileLock = this.fileChannel.lock(absSlotPos, hashSlotSize,
    -                // false);
    -                int slotValue = this.mappedByteBuffer.getInt(absSlotPos);
    -                if (slotValue <= invalidIndex || slotValue > this.indexHeader.getIndexCount()) {
    -                    slotValue = invalidIndex;
    -                }
    +                            DefaultMQPushConsumerImpl.this.executePullRequestImmediately(pullRequest);
    +                            break;
    +                        case NO_MATCHED_MSG:
    +                            pullRequest.setNextOffset(pullResult.getNextBeginOffset());
     
    -                long timeDiff = storeTimestamp - this.indexHeader.getBeginTimestamp();
    +                            DefaultMQPushConsumerImpl.this.correctTagsOffset(pullRequest);
     
    -                timeDiff = timeDiff / 1000;
    +                            DefaultMQPushConsumerImpl.this.executePullRequestImmediately(pullRequest);
    +                            break;
    +                        case OFFSET_ILLEGAL:
    +                            log.warn("the pull request offset illegal, {} {}",
    +                                pullRequest.toString(), pullResult.toString());
    +                            pullRequest.setNextOffset(pullResult.getNextBeginOffset());
     
    -                if (this.indexHeader.getBeginTimestamp() <= 0) {
    -                    timeDiff = 0;
    -                } else if (timeDiff > Integer.MAX_VALUE) {
    -                    timeDiff = Integer.MAX_VALUE;
    -                } else if (timeDiff < 0) {
    -                    timeDiff = 0;
    -                }
    +                            pullRequest.getProcessQueue().setDropped(true);
    +                            DefaultMQPushConsumerImpl.this.executeTaskLater(new Runnable() {
     
    -              // 计算索引存放位置,头部 + 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);
    +                                @Override
    +                                public void run() {
    +                                    try {
    +                                        DefaultMQPushConsumerImpl.this.offsetStore.updateOffset(pullRequest.getMessageQueue(),
    +                                            pullRequest.getNextOffset(), false);
     
    -              // 存放的是数量位移,不是绝对位置
    -                this.mappedByteBuffer.putInt(absSlotPos, this.indexHeader.getIndexCount());
    +                                        DefaultMQPushConsumerImpl.this.offsetStore.persist(pullRequest.getMessageQueue());
     
    -                if (this.indexHeader.getIndexCount() <= 1) {
    -                    this.indexHeader.setBeginPhyOffset(phyOffset);
    -                    this.indexHeader.setBeginTimestamp(storeTimestamp);
    -                }
    +                                        DefaultMQPushConsumerImpl.this.rebalanceImpl.removeProcessQueue(pullRequest.getMessageQueue());
     
    -                this.indexHeader.incHashSlotCount();
    -                this.indexHeader.incIndexCount();
    -                this.indexHeader.setEndPhyOffset(phyOffset);
    -                this.indexHeader.setEndTimestamp(storeTimestamp);
    +                                        log.warn("fix the pull request offset, {}", pullRequest);
    +                                    } catch (Throwable e) {
    +                                        log.error("executeTaskLater Exception", e);
    +                                    }
    +                                }
    +                            }, 10000);
    +                            break;
    +                        default:
    +                            break;
    +                    }
    +                }
    +            }
     
    -                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);
    -        }
    +            @Override
    +            public void onException(Throwable e) {
    +                if (!pullRequest.getMessageQueue().getTopic().startsWith(MixAll.RETRY_GROUP_TOPIC_PREFIX)) {
    +                    log.warn("execute the pull request exception", e);
    +                }
     
    -        return false;
    -    }
    + DefaultMQPushConsumerImpl.this.executePullRequestLater(pullRequest, pullTimeDelayMillsWhenException); + } + }; + // 如果为集群模式,即可置commitOffsetEnable为 true + boolean commitOffsetEnable = false; + long commitOffsetValue = 0L; + if (MessageModel.CLUSTERING == this.defaultMQPushConsumer.getMessageModel()) { + commitOffsetValue = this.offsetStore.readOffset(pullRequest.getMessageQueue(), ReadOffsetType.READ_FROM_MEMORY); + if (commitOffsetValue > 0) { + commitOffsetEnable = true; + } + } -

    具体可以看一下这个简略的示意图

    -]]>
    - - 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/ - ConsumeQueue 其实是定位到一个 topic 下的消息在 CommitLog 下的偏移量,它也是固定大小的

    -
    // ConsumeQueue file size,default is 30W
    -private int mapedFileSizeConsumeQueue = 300000 * ConsumeQueue.CQ_STORE_UNIT_SIZE;
    +        // 将上面获得的commitOffsetEnable更新到订阅关系里
    +        String subExpression = null;
    +        boolean classFilter = false;
    +        SubscriptionData sd = this.rebalanceImpl.getSubscriptionInner().get(pullRequest.getMessageQueue().getTopic());
    +        if (sd != null) {
    +            if (this.defaultMQPushConsumer.isPostSubscriptionWhenPull() && !sd.isClassFilterMode()) {
    +                subExpression = sd.getSubString();
    +            }
     
    -public static final int CQ_STORE_UNIT_SIZE = 20;
    + classFilter = sd.isClassFilterMode(); + } -

    所以文件大小是5.7M 左右

    -

    5udpag

    -

    ConsumeQueue 的构建是通过org.apache.rocketmq.store.DefaultMessageStore.ReputMessageService运行后的 doReput 方法,而启动是的 reputFromOffset 则是通过org.apache.rocketmq.store.DefaultMessageStore#start中下面代码设置并启动

    -
    log.info("[SetReputOffset] maxPhysicalPosInLogicQueue={} clMinOffset={} clMaxOffset={} clConfirmedOffset={}",
    -                maxPhysicalPosInLogicQueue, this.commitLog.getMinOffset(), this.commitLog.getMaxOffset(), this.commitLog.getConfirmOffset());
    -            this.reputMessageService.setReputFromOffset(maxPhysicalPosInLogicQueue);
    -            this.reputMessageService.start();
    + // 组成 sysFlag + int sysFlag = PullSysFlag.buildSysFlag( + commitOffsetEnable, // commitOffset + true, // suspend + subExpression != null, // subscription + classFilter // class filter + ); + // 调用真正的拉取消息接口 + try { + this.pullAPIWrapper.pullKernelImpl( + pullRequest.getMessageQueue(), + subExpression, + subscriptionData.getExpressionType(), + subscriptionData.getSubVersion(), + pullRequest.getNextOffset(), + this.defaultMQPushConsumer.getPullBatchSize(), + sysFlag, + commitOffsetValue, + BROKER_SUSPEND_MAX_TIME_MILLIS, + CONSUMER_TIMEOUT_MILLIS_WHEN_SUSPEND, + CommunicationMode.ASYNC, + pullCallback + ); + } catch (Exception e) { + log.error("pullKernelImpl exception", e); + this.executePullRequestLater(pullRequest, pullTimeDelayMillsWhenException); + } + }
    +

    以下就是拉取消息的底层 api,不够不是特别复杂,主要是在找 broker,和设置请求参数

    +
    public PullResult pullKernelImpl(
    +    final MessageQueue mq,
    +    final String subExpression,
    +    final String expressionType,
    +    final long subVersion,
    +    final long offset,
    +    final int maxNums,
    +    final int sysFlag,
    +    final long commitOffset,
    +    final long brokerSuspendMaxTimeMillis,
    +    final long timeoutMillis,
    +    final CommunicationMode communicationMode,
    +    final PullCallback pullCallback
    +) throws MQClientException, RemotingException, MQBrokerException, InterruptedException {
    +    FindBrokerResult findBrokerResult =
    +        this.mQClientFactory.findBrokerAddressInSubscribe(mq.getBrokerName(),
    +            this.recalculatePullFromWhichNode(mq), false);
    +    if (null == findBrokerResult) {
    +        this.mQClientFactory.updateTopicRouteInfoFromNameServer(mq.getTopic());
    +        findBrokerResult =
    +            this.mQClientFactory.findBrokerAddressInSubscribe(mq.getBrokerName(),
    +                this.recalculatePullFromWhichNode(mq), false);
    +    }
     
    -

    看一下 doReput 的逻辑

    -
    private void doReput() {
    -            if (this.reputFromOffset < DefaultMessageStore.this.commitLog.getMinOffset()) {
    -                log.warn("The reputFromOffset={} is smaller than minPyOffset={}, this usually indicate that the dispatch behind too much and the commitlog has expired.",
    -                    this.reputFromOffset, DefaultMessageStore.this.commitLog.getMinOffset());
    -                this.reputFromOffset = DefaultMessageStore.this.commitLog.getMinOffset();
    -            }
    -            for (boolean doNext = true; this.isCommitLogAvailable() && doNext; ) {
    +    if (findBrokerResult != null) {
    +        {
    +            // check version
    +            if (!ExpressionType.isTagType(expressionType)
    +                && findBrokerResult.getBrokerVersion() < MQVersion.Version.V4_1_0_SNAPSHOT.ordinal()) {
    +                throw new MQClientException("The broker[" + mq.getBrokerName() + ", "
    +                    + findBrokerResult.getBrokerVersion() + "] does not upgrade to support for filter message by " + expressionType, null);
    +            }
    +        }
    +        int sysFlagInner = sysFlag;
     
    -                if (DefaultMessageStore.this.getMessageStoreConfig().isDuplicationEnable()
    -                    && this.reputFromOffset >= DefaultMessageStore.this.getConfirmOffset()) {
    -                    break;
    -                }
    +        if (findBrokerResult.isSlave()) {
    +            sysFlagInner = PullSysFlag.clearCommitOffsetFlag(sysFlagInner);
    +        }
    +
    +        PullMessageRequestHeader requestHeader = new PullMessageRequestHeader();
    +        requestHeader.setConsumerGroup(this.consumerGroup);
    +        requestHeader.setTopic(mq.getTopic());
    +        requestHeader.setQueueId(mq.getQueueId());
    +        requestHeader.setQueueOffset(offset);
    +        requestHeader.setMaxMsgNums(maxNums);
    +        requestHeader.setSysFlag(sysFlagInner);
    +        requestHeader.setCommitOffset(commitOffset);
    +        requestHeader.setSuspendTimeoutMillis(brokerSuspendMaxTimeMillis);
    +        requestHeader.setSubscription(subExpression);
    +        requestHeader.setSubVersion(subVersion);
    +        requestHeader.setExpressionType(expressionType);
     
    -              // 根据偏移量获取消息
    -                SelectMappedBufferResult result = DefaultMessageStore.this.commitLog.getData(reputFromOffset);
    -                if (result != null) {
    -                    try {
    -                        this.reputFromOffset = result.getStartOffset();
    +        String brokerAddr = findBrokerResult.getBrokerAddr();
    +        if (PullSysFlag.hasClassFilterFlag(sysFlagInner)) {
    +            brokerAddr = computPullFromWhichFilterServer(mq.getTopic(), brokerAddr);
    +        }
     
    -                        for (int readSize = 0; readSize < result.getSize() && doNext; ) {
    -                          // 消息校验和转换
    -                            DispatchRequest dispatchRequest =
    -                                DefaultMessageStore.this.commitLog.checkMessageAndReturnSize(result.getByteBuffer(), false, false);
    -                            int size = dispatchRequest.getBufferSize() == -1 ? dispatchRequest.getMsgSize() : dispatchRequest.getBufferSize();
    +        PullResult pullResult = this.mQClientFactory.getMQClientAPIImpl().pullMessage(
    +            brokerAddr,
    +            requestHeader,
    +            timeoutMillis,
    +            communicationMode,
    +            pullCallback);
     
    -                            if (dispatchRequest.isSuccess()) {
    -                                if (size > 0) {
    -                                  // 进行分发处理,包括 ConsumeQueue 和 IndexFile
    -                                    DefaultMessageStore.this.doDispatch(dispatchRequest);
    +        return pullResult;
    +    }
     
    -                                    if (BrokerRole.SLAVE != DefaultMessageStore.this.getMessageStoreConfig().getBrokerRole()
    -                                        && DefaultMessageStore.this.brokerConfig.isLongPollingEnable()) {
    -                                        DefaultMessageStore.this.messageArrivingListener.arriving(dispatchRequest.getTopic(),
    -                                            dispatchRequest.getQueueId(), dispatchRequest.getConsumeQueueOffset() + 1,
    -                                            dispatchRequest.getTagsCode(), dispatchRequest.getStoreTimestamp(),
    -                                            dispatchRequest.getBitMap(), dispatchRequest.getPropertiesMap());
    -                                    }
    +    throw new MQClientException("The broker[" + mq.getBrokerName() + "] not exist", null);
    +}
    +

    再看下一步的

    +
    public PullResult pullMessage(
    +    final String addr,
    +    final PullMessageRequestHeader requestHeader,
    +    final long timeoutMillis,
    +    final CommunicationMode communicationMode,
    +    final PullCallback pullCallback
    +) throws RemotingException, MQBrokerException, InterruptedException {
    +    RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.PULL_MESSAGE, requestHeader);
     
    -                                    this.reputFromOffset += size;
    -                                    readSize += size;
    -                                    if (DefaultMessageStore.this.getMessageStoreConfig().getBrokerRole() == BrokerRole.SLAVE) {
    -                                        DefaultMessageStore.this.storeStatsService
    -                                            .getSinglePutMessageTopicTimesTotal(dispatchRequest.getTopic()).incrementAndGet();
    -                                        DefaultMessageStore.this.storeStatsService
    -                                            .getSinglePutMessageTopicSizeTotal(dispatchRequest.getTopic())
    -                                            .addAndGet(dispatchRequest.getMsgSize());
    -                                    }
    -                                } else if (size == 0) {
    -                                    this.reputFromOffset = DefaultMessageStore.this.commitLog.rollNextFile(this.reputFromOffset);
    -                                    readSize = result.getSize();
    -                                }
    -                            } else if (!dispatchRequest.isSuccess()) {
    +    switch (communicationMode) {
    +        case ONEWAY:
    +            assert false;
    +            return null;
    +        case ASYNC:
    +            this.pullMessageAsync(addr, request, timeoutMillis, pullCallback);
    +            return null;
    +        case SYNC:
    +            return this.pullMessageSync(addr, request, timeoutMillis);
    +        default:
    +            assert false;
    +            break;
    +    }
     
    -                                if (size > 0) {
    -                                    log.error("[BUG]read total count not equals msg total size. reputFromOffset={}", reputFromOffset);
    -                                    this.reputFromOffset += size;
    -                                } else {
    -                                    doNext = false;
    -                                    // If user open the dledger pattern or the broker is master node,
    -                                    // it will not ignore the exception and fix the reputFromOffset variable
    -                                    if (DefaultMessageStore.this.getMessageStoreConfig().isEnableDLegerCommitLog() ||
    -                                        DefaultMessageStore.this.brokerConfig.getBrokerId() == MixAll.MASTER_ID) {
    -                                        log.error("[BUG]dispatch message to consume queue error, COMMITLOG OFFSET: {}",
    -                                            this.reputFromOffset);
    -                                        this.reputFromOffset += result.getSize() - readSize;
    -                                    }
    -                                }
    -                            }
    -                        }
    -                    } finally {
    -                        result.release();
    -                    }
    -                } else {
    -                    doNext = false;
    -                }
    -            }
    -        }
    + return null; +}
    +

    通过 communicationMode 判断是同步拉取还是异步拉取,异步就调用

    +
    private void pullMessageAsync(
    +        final String addr,
    +        final RemotingCommand request,
    +        final long timeoutMillis,
    +        final PullCallback pullCallback
    +    ) throws RemotingException, InterruptedException {
    +        this.remotingClient.invokeAsync(addr, request, timeoutMillis, new InvokeCallback() {
    +            @Override
    +            public void operationComplete(ResponseFuture responseFuture) {
    +                异步
    +                RemotingCommand response = responseFuture.getResponseCommand();
    +                if (response != null) {
    +                    try {
    +                        PullResult pullResult = MQClientAPIImpl.this.processPullResponse(response);
    +                        assert pullResult != null;
    +                        pullCallback.onSuccess(pullResult);
    +                    } catch (Exception e) {
    +                        pullCallback.onException(e);
    +                    }
    +                } else {
    +                    if (!responseFuture.isSendRequestOK()) {
    +                        pullCallback.onException(new MQClientException("send request failed to " + addr + ". Request: " + request, responseFuture.getCause()));
    +                    } else if (responseFuture.isTimeout()) {
    +                        pullCallback.onException(new MQClientException("wait response from " + addr + " timeout :" + responseFuture.getTimeoutMillis() + "ms" + ". Request: " + request,
    +                            responseFuture.getCause()));
    +                    } else {
    +                        pullCallback.onException(new MQClientException("unknown reason. addr: " + addr + ", timeoutMillis: " + timeoutMillis + ". Request: " + request, responseFuture.getCause()));
    +                    }
    +                }
    +            }
    +        });
    +    }
    +

    并且会调用前面 pullCallback 的onSuccess和onException方法,同步的就是调用

    +
    private PullResult pullMessageSync(
    +        final String addr,
    +        final RemotingCommand request,
    +        final long timeoutMillis
    +    ) throws RemotingException, InterruptedException, MQBrokerException {
    +        RemotingCommand response = this.remotingClient.invokeSync(addr, request, timeoutMillis);
    +        assert response != null;
    +        return this.processPullResponse(response);
    +    }
    +

    然后就是这个 remotingClient 的 invokeAsync 跟 invokeSync 方法

    +
    @Override
    +    public void invokeAsync(String addr, RemotingCommand request, long timeoutMillis, InvokeCallback invokeCallback)
    +        throws InterruptedException, RemotingConnectException, RemotingTooMuchRequestException, RemotingTimeoutException,
    +        RemotingSendRequestException {
    +        long beginStartTime = System.currentTimeMillis();
    +        final Channel channel = this.getAndCreateChannel(addr);
    +        if (channel != null && channel.isActive()) {
    +            try {
    +                doBeforeRpcHooks(addr, request);
    +                long costTime = System.currentTimeMillis() - beginStartTime;
    +                if (timeoutMillis < costTime) {
    +                    throw new RemotingTooMuchRequestException("invokeAsync call timeout");
    +                }
    +                this.invokeAsyncImpl(channel, request, timeoutMillis - costTime, invokeCallback);
    +            } catch (RemotingSendRequestException e) {
    +                log.warn("invokeAsync: send request exception, so close the channel[{}]", addr);
    +                this.closeChannel(addr, channel);
    +                throw e;
    +            }
    +        } else {
    +            this.closeChannel(addr, channel);
    +            throw new RemotingConnectException(addr);
    +        }
    +    }
    +@Override
    +    public RemotingCommand invokeSync(String addr, final RemotingCommand request, long timeoutMillis)
    +        throws InterruptedException, RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException {
    +        long beginStartTime = System.currentTimeMillis();
    +        final Channel channel = this.getAndCreateChannel(addr);
    +        if (channel != null && channel.isActive()) {
    +            try {
    +                doBeforeRpcHooks(addr, request);
    +                long costTime = System.currentTimeMillis() - beginStartTime;
    +                if (timeoutMillis < costTime) {
    +                    throw new RemotingTimeoutException("invokeSync call timeout");
    +                }
    +                RemotingCommand response = this.invokeSyncImpl(channel, request, timeoutMillis - costTime);
    +                doAfterRpcHooks(RemotingHelper.parseChannelRemoteAddr(channel), request, response);
    +                return response;
    +            } catch (RemotingSendRequestException e) {
    +                log.warn("invokeSync: send request exception, so close the channel[{}]", addr);
    +                this.closeChannel(addr, channel);
    +                throw e;
    +            } catch (RemotingTimeoutException e) {
    +                if (nettyClientConfig.isClientCloseSocketIfTimeout()) {
    +                    this.closeChannel(addr, channel);
    +                    log.warn("invokeSync: close socket because of timeout, {}ms, {}", timeoutMillis, addr);
    +                }
    +                log.warn("invokeSync: wait response timeout exception, the channel[{}]", addr);
    +                throw e;
    +            }
    +        } else {
    +            this.closeChannel(addr, channel);
    +            throw new RemotingConnectException(addr);
    +        }
    +    }
    +

    再往下看

    +
    public RemotingCommand invokeSyncImpl(final Channel channel, final RemotingCommand request,
    +        final long timeoutMillis)
    +        throws InterruptedException, RemotingSendRequestException, RemotingTimeoutException {
    +        final int opaque = request.getOpaque();
     
    -

    分发的逻辑看到这

    -
        class CommitLogDispatcherBuildConsumeQueue implements CommitLogDispatcher {
    +        try {
    +            同步跟异步都是会把结果用ResponseFuture抱起来
    +            final ResponseFuture responseFuture = new ResponseFuture(channel, opaque, timeoutMillis, null, null);
    +            this.responseTable.put(opaque, responseFuture);
    +            final SocketAddress addr = channel.remoteAddress();
    +            channel.writeAndFlush(request).addListener(new ChannelFutureListener() {
    +                @Override
    +                public void operationComplete(ChannelFuture f) throws Exception {
    +                    if (f.isSuccess()) {
    +                        responseFuture.setSendRequestOK(true);
    +                        return;
    +                    } else {
    +                        responseFuture.setSendRequestOK(false);
    +                    }
     
    -        @Override
    -        public void dispatch(DispatchRequest request) {
    -            final int tranType = MessageSysFlag.getTransactionValue(request.getSysFlag());
    -            switch (tranType) {
    -                case MessageSysFlag.TRANSACTION_NOT_TYPE:
    -                case MessageSysFlag.TRANSACTION_COMMIT_TYPE:
    -                    DefaultMessageStore.this.putMessagePositionInfo(request);
    -                    break;
    -                case MessageSysFlag.TRANSACTION_PREPARED_TYPE:
    -                case MessageSysFlag.TRANSACTION_ROLLBACK_TYPE:
    -                    break;
    -            }
    -        }
    -    }
    -public void putMessagePositionInfo(DispatchRequest dispatchRequest) {
    -        ConsumeQueue cq = this.findConsumeQueue(dispatchRequest.getTopic(), dispatchRequest.getQueueId());
    -        cq.putMessagePositionInfoWrapper(dispatchRequest);
    -    }
    + responseTable.remove(opaque); + responseFuture.setCause(f.cause()); + responseFuture.putResponse(null); + log.warn("send a request command to channel <" + addr + "> failed."); + } + }); + // 区别是同步的是在这等待 + RemotingCommand responseCommand = responseFuture.waitResponse(timeoutMillis); + if (null == responseCommand) { + if (responseFuture.isSendRequestOK()) { + throw new RemotingTimeoutException(RemotingHelper.parseSocketAddressAddr(addr), timeoutMillis, + responseFuture.getCause()); + } else { + throw new RemotingSendRequestException(RemotingHelper.parseSocketAddressAddr(addr), responseFuture.getCause()); + } + } -

    真正存储的是在这

    -
    private boolean putMessagePositionInfo(final long offset, final int size, final long tagsCode,
    -    final long cqOffset) {
    +            return responseCommand;
    +        } finally {
    +            this.responseTable.remove(opaque);
    +        }
    +    }
    +
    +    public void invokeAsyncImpl(final Channel channel, final RemotingCommand request, final long timeoutMillis,
    +        final InvokeCallback invokeCallback)
    +        throws InterruptedException, RemotingTooMuchRequestException, RemotingTimeoutException, RemotingSendRequestException {
    +        long beginStartTime = System.currentTimeMillis();
    +        final int opaque = request.getOpaque();
    +        boolean acquired = this.semaphoreAsync.tryAcquire(timeoutMillis, TimeUnit.MILLISECONDS);
    +        if (acquired) {
    +            final SemaphoreReleaseOnlyOnce once = new SemaphoreReleaseOnlyOnce(this.semaphoreAsync);
    +            long costTime = System.currentTimeMillis() - beginStartTime;
    +            if (timeoutMillis < costTime) {
    +                once.release();
    +                throw new RemotingTimeoutException("invokeAsyncImpl call timeout");
    +            }
    +
    +            final ResponseFuture responseFuture = new ResponseFuture(channel, opaque, timeoutMillis - costTime, invokeCallback, once);
    +            this.responseTable.put(opaque, responseFuture);
    +            try {
    +                channel.writeAndFlush(request).addListener(new ChannelFutureListener() {
    +                    @Override
    +                    public void operationComplete(ChannelFuture f) throws Exception {
    +                        if (f.isSuccess()) {
    +                            responseFuture.setSendRequestOK(true);
    +                            return;
    +                        }
    +                        requestFail(opaque);
    +                        log.warn("send a request command to channel <{}> failed.", RemotingHelper.parseChannelRemoteAddr(channel));
    +                    }
    +                });
    +            } catch (Exception e) {
    +                responseFuture.release();
    +                log.warn("send a request command to channel <" + RemotingHelper.parseChannelRemoteAddr(channel) + "> Exception", e);
    +                throw new RemotingSendRequestException(RemotingHelper.parseChannelRemoteAddr(channel), e);
    +            }
    +        } else {
    +            if (timeoutMillis <= 0) {
    +                throw new RemotingTooMuchRequestException("invokeAsyncImpl invoke too fast");
    +            } else {
    +                String info =
    +                    String.format("invokeAsyncImpl tryAcquire semaphore timeout, %dms, waiting thread nums: %d semaphoreAsyncValue: %d",
    +                        timeoutMillis,
    +                        this.semaphoreAsync.getQueueLength(),
    +                        this.semaphoreAsync.availablePermits()
    +                    );
    +                log.warn(info);
    +                throw new RemotingTimeoutException(info);
    +            }
    +        }
    +    }
    - if (offset + size <= this.maxPhysicOffset) { - log.warn("Maybe try to build consume queue repeatedly maxPhysicOffset={} phyOffset={}", maxPhysicOffset, offset); - return true; - } - this.byteBufferIndex.flip(); - this.byteBufferIndex.limit(CQ_STORE_UNIT_SIZE); - this.byteBufferIndex.putLong(offset); - this.byteBufferIndex.putInt(size); - this.byteBufferIndex.putLong(tagsCode);
    -

    这里也可以看到 ConsumeQueue 的存储格式,

    -

    AA6Tve

    -

    偏移量,消息大小,跟 tag 的 hashCode

    ]]>
    MQ RocketMQ 消息队列 + RocketMQ + 中间件 + RocketMQ MQ 消息队列 RocketMQ + 削峰填谷 + 中间件 + DefaultMQPushConsumer + 源码解析
    - 聊一下 RocketMQ 的消息存储二 - /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/ - CommitLog 结构

    CommitLog 是 rocketmq 的服务端,也就是 broker 存储消息的的文件,跟 kafka 一样,也是顺序写入,当然消息是变长的,生成的规则是每个文件的默认1G =1024 * 1024 * 1024,commitlog的文件名fileName,名字长度为20位,左边补零,剩余为起始偏移量;比如00000000000000000000代表了第一个文件,起始偏移量为0,文件大小为1G=1 073 741 824Byte;当这个文件满了,第二个文件名字为00000000001073741824,起始偏移量为1073741824, 消息存储的时候会顺序写入文件,当文件满了则写入下一个文件,代码中的定义

    -
    // CommitLog file size,default is 1G
    -private int mapedFileSizeCommitLog = 1024 * 1024 * 1024;
    + 聊一下 RocketMQ 的 NameServer 源码 + /2020/07/05/%E8%81%8A%E4%B8%80%E4%B8%8B-RocketMQ-%E7%9A%84-NameServer-%E6%BA%90%E7%A0%81/ + 前面介绍了,nameserver相当于dubbo的注册中心,用与管理broker,broker会在启动的时候注册到nameserver,并且会发送心跳给namaserver,nameserver负责保存活跃的broker,包括master和slave,同时保存topic和topic下的队列,以及filter列表,然后为producer和consumer的请求提供服务。

    +

    启动过程

    public static void main(String[] args) {
    +        main0(args);
    +    }
     
    -

    kLahwW

    -

    本地跑个 demo 验证下,也是这样,这里奇妙有几个比较巧妙的点(个人观点),首先文件就刚好是 1G,并且按照大小偏移量去生成下一个文件,这样获取消息的时候按大小算一下就知道在哪个文件里了,

    -

    代码中写入 CommitLog 的逻辑可以从这开始看

    -
    public PutMessageResult putMessage(final MessageExtBrokerInner msg) {
    -        // Set the storage time
    -        msg.setStoreTimestamp(System.currentTimeMillis());
    -        // Set the message body BODY CRC (consider the most appropriate setting
    -        // on the client)
    -        msg.setBodyCRC(UtilAll.crc32(msg.getBody()));
    -        // Back to Results
    -        AppendMessageResult result = null;
    +    public static NamesrvController main0(String[] args) {
     
    -        StoreStatsService storeStatsService = this.defaultMessageStore.getStoreStatsService();
    +        try {
    +            NamesrvController controller = createNamesrvController(args);
    +            start(controller);
    +            String tip = "The Name Server boot success. serializeType=" + RemotingCommand.getSerializeTypeConfigInThisServer();
    +            log.info(tip);
    +            System.out.printf("%s%n", tip);
    +            return controller;
    +        } catch (Throwable e) {
    +            e.printStackTrace();
    +            System.exit(-1);
    +        }
     
    -        String topic = msg.getTopic();
    -        int queueId = msg.getQueueId();
    +        return null;
    +    }
    - final int tranType = MessageSysFlag.getTransactionValue(msg.getSysFlag()); - if (tranType == MessageSysFlag.TRANSACTION_NOT_TYPE - || tranType == MessageSysFlag.TRANSACTION_COMMIT_TYPE) { - // Delay Delivery - if (msg.getDelayTimeLevel() > 0) { - if (msg.getDelayTimeLevel() > this.defaultMessageStore.getScheduleMessageService().getMaxDelayLevel()) { - msg.setDelayTimeLevel(this.defaultMessageStore.getScheduleMessageService().getMaxDelayLevel()); - } +

    入口的代码时这样子,其实主要的逻辑在createNamesrvController和start方法,来看下这两个的实现

    +
    public static NamesrvController createNamesrvController(String[] args) throws IOException, JoranException {
    +        System.setProperty(RemotingCommand.REMOTING_VERSION_KEY, Integer.toString(MQVersion.CURRENT_VERSION));
    +        //PackageConflictDetect.detectFastjson();
     
    -                topic = ScheduleMessageService.SCHEDULE_TOPIC;
    -                queueId = ScheduleMessageService.delayLevel2QueueId(msg.getDelayTimeLevel());
    +        Options options = ServerUtil.buildCommandlineOptions(new Options());
    +        commandLine = ServerUtil.parseCmdLine("mqnamesrv", args, buildCommandlineOptions(options), new PosixParser());
    +        if (null == commandLine) {
    +            System.exit(-1);
    +            return null;
    +        }
     
    -                // Backup real topic, queueId
    -                MessageAccessor.putProperty(msg, MessageConst.PROPERTY_REAL_TOPIC, msg.getTopic());
    -                MessageAccessor.putProperty(msg, MessageConst.PROPERTY_REAL_QUEUE_ID, String.valueOf(msg.getQueueId()));
    -                msg.setPropertiesString(MessageDecoder.messageProperties2String(msg.getProperties()));
    +        final NamesrvConfig namesrvConfig = new NamesrvConfig();
    +        final NettyServerConfig nettyServerConfig = new NettyServerConfig();
    +        nettyServerConfig.setListenPort(9876);
    +        if (commandLine.hasOption('c')) {
    +            String file = commandLine.getOptionValue('c');
    +            if (file != null) {
    +                InputStream in = new BufferedInputStream(new FileInputStream(file));
    +                properties = new Properties();
    +                properties.load(in);
    +                MixAll.properties2Object(properties, namesrvConfig);
    +                MixAll.properties2Object(properties, nettyServerConfig);
     
    -                msg.setTopic(topic);
    -                msg.setQueueId(queueId);
    +                namesrvConfig.setConfigStorePath(file);
    +
    +                System.out.printf("load config properties file OK, %s%n", file);
    +                in.close();
                 }
             }
     
    -        long eclipseTimeInLock = 0;
    -        MappedFile unlockMappedFile = null;
    -        MappedFile mappedFile = this.mappedFileQueue.getLastMappedFile();
    +        if (commandLine.hasOption('p')) {
    +            InternalLogger console = InternalLoggerFactory.getLogger(LoggerName.NAMESRV_CONSOLE_NAME);
    +            MixAll.printObjectProperties(console, namesrvConfig);
    +            MixAll.printObjectProperties(console, nettyServerConfig);
    +            System.exit(0);
    +        }
     
    -        putMessageLock.lock(); //spin or ReentrantLock ,depending on store config
    -        try {
    -            long beginLockTimestamp = this.defaultMessageStore.getSystemClock().now();
    -            this.beginTimeInLock = beginLockTimestamp;
    +        MixAll.properties2Object(ServerUtil.commandLine2Properties(commandLine), namesrvConfig);
     
    -            // Here settings are stored timestamp, in order to ensure an orderly
    -            // global
    -            msg.setStoreTimestamp(beginLockTimestamp);
    +        if (null == namesrvConfig.getRocketmqHome()) {
    +            System.out.printf("Please set the %s variable in your environment to match the location of the RocketMQ installation%n", MixAll.ROCKETMQ_HOME_ENV);
    +            System.exit(-2);
    +        }
     
    -            if (null == mappedFile || mappedFile.isFull()) {
    -                mappedFile = this.mappedFileQueue.getLastMappedFile(0); // Mark: NewFile may be cause noise
    -            }
    -            if (null == mappedFile) {
    -                log.error("create mapped file1 error, topic: " + msg.getTopic() + " clientAddr: " + msg.getBornHostString());
    -                beginTimeInLock = 0;
    -                return new PutMessageResult(PutMessageStatus.CREATE_MAPEDFILE_FAILED, null);
    -            }
    +        LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    +        JoranConfigurator configurator = new JoranConfigurator();
    +        configurator.setContext(lc);
    +        lc.reset();
    +        configurator.doConfigure(namesrvConfig.getRocketmqHome() + "/conf/logback_namesrv.xml");
     
    -            result = mappedFile.appendMessage(msg, this.appendMessageCallback);
    -            switch (result.getStatus()) {
    -                case PUT_OK:
    -                    break;
    -                case END_OF_FILE:
    -                    unlockMappedFile = mappedFile;
    -                    // Create a new file, re-write the message
    -                    mappedFile = this.mappedFileQueue.getLastMappedFile(0);
    -                    if (null == mappedFile) {
    -                        // XXX: warn and notify me
    -                        log.error("create mapped file2 error, topic: " + msg.getTopic() + " clientAddr: " + msg.getBornHostString());
    -                        beginTimeInLock = 0;
    -                        return new PutMessageResult(PutMessageStatus.CREATE_MAPEDFILE_FAILED, result);
    -                    }
    -                    result = mappedFile.appendMessage(msg, this.appendMessageCallback);
    -                    break;
    -                case MESSAGE_SIZE_EXCEEDED:
    -                case PROPERTIES_SIZE_EXCEEDED:
    -                    beginTimeInLock = 0;
    -                    return new PutMessageResult(PutMessageStatus.MESSAGE_ILLEGAL, result);
    -                case UNKNOWN_ERROR:
    -                    beginTimeInLock = 0;
    -                    return new PutMessageResult(PutMessageStatus.UNKNOWN_ERROR, result);
    -                default:
    -                    beginTimeInLock = 0;
    -                    return new PutMessageResult(PutMessageStatus.UNKNOWN_ERROR, result);
    -            }
    +        log = InternalLoggerFactory.getLogger(LoggerName.NAMESRV_LOGGER_NAME);
     
    -            eclipseTimeInLock = this.defaultMessageStore.getSystemClock().now() - beginLockTimestamp;
    -            beginTimeInLock = 0;
    -        } finally {
    -            putMessageLock.unlock();
    -        }
    +        MixAll.printObjectProperties(log, namesrvConfig);
    +        MixAll.printObjectProperties(log, nettyServerConfig);
     
    -        if (eclipseTimeInLock > 500) {
    -            log.warn("[NOTIFYME]putMessage in lock cost time(ms)={}, bodyLength={} AppendMessageResult={}", eclipseTimeInLock, msg.getBody().length, result);
    +        final NamesrvController controller = new NamesrvController(namesrvConfig, nettyServerConfig);
    +
    +        // remember all configs to prevent discard
    +        controller.getConfiguration().registerConfig(properties);
    +
    +        return controller;
    +    }
    + +

    这个方法里其实主要是读取一些配置啥的,不是很复杂,

    +
    public static NamesrvController start(final NamesrvController controller) throws Exception {
    +
    +        if (null == controller) {
    +            throw new IllegalArgumentException("NamesrvController is null");
             }
     
    -        if (null != unlockMappedFile && this.defaultMessageStore.getMessageStoreConfig().isWarmMapedFileEnable()) {
    -            this.defaultMessageStore.unlockMappedFile(unlockMappedFile);
    +        boolean initResult = controller.initialize();
    +        if (!initResult) {
    +            controller.shutdown();
    +            System.exit(-3);
             }
     
    -        PutMessageResult putMessageResult = new PutMessageResult(PutMessageStatus.PUT_OK, result);
    +        Runtime.getRuntime().addShutdownHook(new ShutdownHookThread(log, new Callable<Void>() {
    +            @Override
    +            public Void call() throws Exception {
    +                controller.shutdown();
    +                return null;
    +            }
    +        }));
    +
    +        controller.start();
     
    -        // Statistics
    -        storeStatsService.getSinglePutMessageTopicTimesTotal(msg.getTopic()).incrementAndGet();
    -        storeStatsService.getSinglePutMessageTopicSizeTotal(topic).addAndGet(result.getWroteBytes());
    +        return controller;
    +    }
    - handleDiskFlush(result, putMessageResult, msg); - handleHA(result, putMessageResult, msg); +

    这个start里主要关注initialize方法,后面就是一个停机的hook,来看下initialize方法

    +
    public boolean initialize() {
     
    -        return putMessageResult;
    -    }
    + this.kvConfigManager.load(); -

    前面也看到在CommitLog 目录下是有大小为 1G 的文件组成,在实现逻辑中,其实是通过 org.apache.rocketmq.store.MappedFileQueue ,内部是存的一个MappedFile的队列,对于写入的场景每次都是通过org.apache.rocketmq.store.MappedFileQueue#getLastMappedFile() 获取最后一个文件,如果还没有创建,或者最后这个文件已经满了,那就调用 org.apache.rocketmq.store.MappedFileQueue#getLastMappedFile(long)

    -
    public MappedFile getLastMappedFile(final long startOffset, boolean needCreate) {
    -        long createOffset = -1;
    -  			// 调用前面的方法,只是从 mappedFileQueue 获取最后一个
    -        MappedFile mappedFileLast = getLastMappedFile();
    +        this.remotingServer = new NettyRemotingServer(this.nettyServerConfig, this.brokerHousekeepingService);
     
    -        // 如果为空,计算下创建的偏移量
    -        if (mappedFileLast == null) {
    -            createOffset = startOffset - (startOffset % this.mappedFileSize);
    -        }
    -  
    -				// 如果不为空,但是当前的文件写满了
    -        if (mappedFileLast != null && mappedFileLast.isFull()) {
    -            // 前一个的偏移量加上单个文件的偏移量,也就是 1G
    -            createOffset = mappedFileLast.getFileFromOffset() + this.mappedFileSize;
    -        }
    +        this.remotingExecutor =
    +            Executors.newFixedThreadPool(nettyServerConfig.getServerWorkerThreads(), new ThreadFactoryImpl("RemotingExecutorThread_"));
     
    -        if (createOffset != -1 && needCreate) {
    -            // 根据 createOffset 转换成文件名进行创建
    -            String nextFilePath = this.storePath + File.separator + UtilAll.offset2FileName(createOffset);
    -            String nextNextFilePath = this.storePath + File.separator
    -                + UtilAll.offset2FileName(createOffset + this.mappedFileSize);
    -            MappedFile mappedFile = null;
    +        this.registerProcessor();
     
    -          	// 这里如果allocateMappedFileService 存在,就提交请求
    -            if (this.allocateMappedFileService != null) {
    -                mappedFile = this.allocateMappedFileService.putRequestAndReturnMappedFile(nextFilePath,
    -                    nextNextFilePath, this.mappedFileSize);
    -            } else {
    -                try {
    -                  // 否则就直接创建
    -                    mappedFile = new MappedFile(nextFilePath, this.mappedFileSize);
    -                } catch (IOException e) {
    -                    log.error("create mappedFile exception", e);
    -                }
    +        this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
    +
    +            @Override
    +            public void run() {
    +                NamesrvController.this.routeInfoManager.scanNotActiveBroker();
                 }
    +        }, 5, 10, TimeUnit.SECONDS);
     
    -            if (mappedFile != null) {
    -                if (this.mappedFiles.isEmpty()) {
    -                    mappedFile.setFirstCreateInQueue(true);
    -                }
    -                this.mappedFiles.add(mappedFile);
    +        this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
    +
    +            @Override
    +            public void run() {
    +                NamesrvController.this.kvConfigManager.printAllPeriodically();
                 }
    +        }, 1, 10, TimeUnit.MINUTES);
     
    -            return mappedFile;
    +        if (TlsSystemConfig.tlsMode != TlsMode.DISABLED) {
    +            // Register a listener to reload SslContext
    +            try {
    +                fileWatchService = new FileWatchService(
    +                    new String[] {
    +                        TlsSystemConfig.tlsServerCertPath,
    +                        TlsSystemConfig.tlsServerKeyPath,
    +                        TlsSystemConfig.tlsServerTrustCertPath
    +                    },
    +                    new FileWatchService.Listener() {
    +                        boolean certChanged, keyChanged = false;
    +                        @Override
    +                        public void onChanged(String path) {
    +                            if (path.equals(TlsSystemConfig.tlsServerTrustCertPath)) {
    +                                log.info("The trust certificate changed, reload the ssl context");
    +                                reloadServerSslContext();
    +                            }
    +                            if (path.equals(TlsSystemConfig.tlsServerCertPath)) {
    +                                certChanged = true;
    +                            }
    +                            if (path.equals(TlsSystemConfig.tlsServerKeyPath)) {
    +                                keyChanged = true;
    +                            }
    +                            if (certChanged && keyChanged) {
    +                                log.info("The certificate and private key changed, reload the ssl context");
    +                                certChanged = keyChanged = false;
    +                                reloadServerSslContext();
    +                            }
    +                        }
    +                        private void reloadServerSslContext() {
    +                            ((NettyRemotingServer) remotingServer).loadSslContext();
    +                        }
    +                    });
    +            } catch (Exception e) {
    +                log.warn("FileWatchService created error, can't load the certificate dynamically");
    +            }
             }
     
    -        return mappedFileLast;
    -    }
    - -

    首先看下直接创建的,

    -
    public MappedFile(final String fileName, final int fileSize) throws IOException {
    -        init(fileName, fileSize);
    -    }
    -private void init(final String fileName, final int fileSize) throws IOException {
    -        this.fileName = fileName;
    -        this.fileSize = fileSize;
    -        this.file = new File(fileName);
    -        this.fileFromOffset = Long.parseLong(this.file.getName());
    -        boolean ok = false;
    +        return true;
    +    }
    - ensureDirOK(this.file.getParent()); +

    这里的kvConfigManager主要是来加载NameServer的配置参数,存到org.apache.rocketmq.namesrv.kvconfig.KVConfigManager#configTable中,然后是以BrokerHousekeepingService对象为参数初始化NettyRemotingServer对象,BrokerHousekeepingService对象作为该Netty连接中Socket链接的监听器(ChannelEventListener);监听与Broker建立的渠道的状态(空闲、关闭、异常三个状态),并调用BrokerHousekeepingService的相应onChannel方法。其中渠道的空闲、关闭、异常状态均调用RouteInfoManager.onChannelDestory方法处理。这个BrokerHousekeepingService可以字面化地理解为broker的管家服务,这个类内部三个状态方法其实都是调用的org.apache.rocketmq.namesrv.NamesrvController#getRouteInfoManager方法,而这个RouteInfoManager里面的对象有这些

    +
    public class RouteInfoManager {
    +    private static final InternalLogger log = InternalLoggerFactory.getLogger(LoggerName.NAMESRV_LOGGER_NAME);
    +    private final static long BROKER_CHANNEL_EXPIRED_TIME = 1000 * 60 * 2;
    +    private final ReadWriteLock lock = new ReentrantReadWriteLock();
    +  // topic与queue的对应关系
    +    private final HashMap<String/* topic */, List<QueueData>> topicQueueTable;
    +  // Broker名称与broker属性的map
    +    private final HashMap<String/* brokerName */, BrokerData> brokerAddrTable;
    +  // 集群与broker集合的对应关系
    +    private final HashMap<String/* clusterName */, Set<String/* brokerName */>> clusterAddrTable;
    +  // 活跃的broker信息
    +    private final HashMap<String/* brokerAddr */, BrokerLiveInfo> brokerLiveTable;
    +  // Broker地址与过滤器
    +    private final HashMap<String/* brokerAddr */, List<String>/* Filter Server */> filterServerTable;
    - try { - // 通过 RandomAccessFile 创建 fileChannel - this.fileChannel = new RandomAccessFile(this.file, "rw").getChannel(); - // 做 mmap 映射 - this.mappedByteBuffer = this.fileChannel.map(MapMode.READ_WRITE, 0, fileSize); - TOTAL_MAPPED_VIRTUAL_MEMORY.addAndGet(fileSize); - TOTAL_MAPPED_FILES.incrementAndGet(); - ok = true; - } catch (FileNotFoundException e) { - log.error("create file channel " + this.fileName + " Failed. ", e); - throw e; - } catch (IOException e) { - log.error("map file " + this.fileName + " Failed. ", e); - throw e; - } finally { - if (!ok && this.fileChannel != null) { - this.fileChannel.close(); - } - } - }
    +

    然后接下去就是初始化了一个线程池,然后注册默认的处理类this.registerProcessor();默认都是这个处理器去处理请求 org.apache.rocketmq.namesrv.processor.DefaultRequestProcessor#DefaultRequestProcessor然后是初始化两个定时任务

    +

    第一是每10秒检查一遍Broker的状态的定时任务,调用scanNotActiveBroker方法;遍历brokerLiveTable集合,查看每个broker的最后更新时间(BrokerLiveInfo.lastUpdateTimestamp)是否超过2分钟,若超过则关闭该broker的渠道并调用RouteInfoManager.onChannelDestory方法清理RouteInfoManager类的topicQueueTable、brokerAddrTable、clusterAddrTable、filterServerTable成员变量。

    +
    this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
     
    -

    如果是提交给AllocateMappedFileService的话就用到了一些异步操作

    -
    public MappedFile putRequestAndReturnMappedFile(String nextFilePath, String nextNextFilePath, int fileSize) {
    -        int canSubmitRequests = 2;
    -        if (this.messageStore.getMessageStoreConfig().isTransientStorePoolEnable()) {
    -            if (this.messageStore.getMessageStoreConfig().isFastFailIfNoBufferInStorePool()
    -                && BrokerRole.SLAVE != this.messageStore.getMessageStoreConfig().getBrokerRole()) { //if broker is slave, don't fast fail even no buffer in pool
    -                canSubmitRequests = this.messageStore.getTransientStorePool().remainBufferNumbs() - this.requestQueue.size();
    -            }
    -        }
    -				// 将请求放在 requestTable 中
    -        AllocateRequest nextReq = new AllocateRequest(nextFilePath, fileSize);
    -        boolean nextPutOK = this.requestTable.putIfAbsent(nextFilePath, nextReq) == null;
    -        // requestTable 使用了 concurrentHashMap,用文件名作为 key,防止并发
    -        if (nextPutOK) {
    -            // 这里判断了是否可以提交到 TransientStorePool,涉及读写分离,后面再细聊
    -            if (canSubmitRequests <= 0) {
    -                log.warn("[NOTIFYME]TransientStorePool is not enough, so create mapped file error, " +
    -                    "RequestQueueSize : {}, StorePoolSize: {}", this.requestQueue.size(), this.messageStore.getTransientStorePool().remainBufferNumbs());
    -                this.requestTable.remove(nextFilePath);
    -                return null;
    +            @Override
    +            public void run() {
    +                NamesrvController.this.routeInfoManager.scanNotActiveBroker();
                 }
    -          // 塞到阻塞队列中
    -            boolean offerOK = this.requestQueue.offer(nextReq);
    -            if (!offerOK) {
    -                log.warn("never expected here, add a request to preallocate queue failed");
    +        }, 5, 10, TimeUnit.SECONDS);
    +public void scanNotActiveBroker() {
    +        Iterator<Entry<String, BrokerLiveInfo>> it = this.brokerLiveTable.entrySet().iterator();
    +        while (it.hasNext()) {
    +            Entry<String, BrokerLiveInfo> next = it.next();
    +            long last = next.getValue().getLastUpdateTimestamp();
    +            if ((last + BROKER_CHANNEL_EXPIRED_TIME) < System.currentTimeMillis()) {
    +                RemotingUtil.closeChannel(next.getValue().getChannel());
    +                it.remove();
    +                log.warn("The broker channel expired, {} {}ms", next.getKey(), BROKER_CHANNEL_EXPIRED_TIME);
    +                this.onChannelDestroy(next.getKey(), next.getValue().getChannel());
                 }
    -            canSubmitRequests--;
             }
    +    }
     
    -        // 这里的两个提交我猜测是为了多生成一个 CommitLog,
    -        AllocateRequest nextNextReq = new AllocateRequest(nextNextFilePath, fileSize);
    -        boolean nextNextPutOK = this.requestTable.putIfAbsent(nextNextFilePath, nextNextReq) == null;
    -        if (nextNextPutOK) {
    -            if (canSubmitRequests <= 0) {
    -                log.warn("[NOTIFYME]TransientStorePool is not enough, so skip preallocate mapped file, " +
    -                    "RequestQueueSize : {}, StorePoolSize: {}", this.requestQueue.size(), this.messageStore.getTransientStorePool().remainBufferNumbs());
    -                this.requestTable.remove(nextNextFilePath);
    -            } else {
    -                boolean offerOK = this.requestQueue.offer(nextNextReq);
    -                if (!offerOK) {
    -                    log.warn("never expected here, add a request to preallocate queue failed");
    +    public void onChannelDestroy(String remoteAddr, Channel channel) {
    +        String brokerAddrFound = null;
    +        if (channel != null) {
    +            try {
    +                try {
    +                    this.lock.readLock().lockInterruptibly();
    +                    Iterator<Entry<String, BrokerLiveInfo>> itBrokerLiveTable =
    +                        this.brokerLiveTable.entrySet().iterator();
    +                    while (itBrokerLiveTable.hasNext()) {
    +                        Entry<String, BrokerLiveInfo> entry = itBrokerLiveTable.next();
    +                        if (entry.getValue().getChannel() == channel) {
    +                            brokerAddrFound = entry.getKey();
    +                            break;
    +                        }
    +                    }
    +                } finally {
    +                    this.lock.readLock().unlock();
                     }
    +            } catch (Exception e) {
    +                log.error("onChannelDestroy Exception", e);
                 }
             }
     
    -        if (hasException) {
    -            log.warn(this.getServiceName() + " service has exception. so return null");
    -            return null;
    +        if (null == brokerAddrFound) {
    +            brokerAddrFound = remoteAddr;
    +        } else {
    +            log.info("the broker's channel destroyed, {}, clean it's data structure at once", brokerAddrFound);
             }
     
    -        AllocateRequest result = this.requestTable.get(nextFilePath);
    -        try {
    -          // 这里就异步等着
    -            if (result != null) {
    -                boolean waitOK = result.getCountDownLatch().await(waitTimeOut, TimeUnit.MILLISECONDS);
    -                if (!waitOK) {
    -                    log.warn("create mmap timeout " + result.getFilePath() + " " + result.getFileSize());
    -                    return null;
    -                } else {
    -                    this.requestTable.remove(nextFilePath);
    -                    return result.getMappedFile();
    -                }
    -            } else {
    -                log.error("find preallocate mmap failed, this never happen");
    -            }
    -        } catch (InterruptedException e) {
    -            log.warn(this.getServiceName() + " service has exception. ", e);
    -        }
    +        if (brokerAddrFound != null && brokerAddrFound.length() > 0) {
     
    -        return null;
    -    }
    + try { + try { + this.lock.writeLock().lockInterruptibly(); + this.brokerLiveTable.remove(brokerAddrFound); + this.filterServerTable.remove(brokerAddrFound); + String brokerNameFound = null; + boolean removeBrokerName = false; + Iterator<Entry<String, BrokerData>> itBrokerAddrTable = + this.brokerAddrTable.entrySet().iterator(); + while (itBrokerAddrTable.hasNext() && (null == brokerNameFound)) { + BrokerData brokerData = itBrokerAddrTable.next().getValue(); -

    而真正去执行文件操作的就是 AllocateMappedFileService的 run 方法

    -
    public void run() {
    -        log.info(this.getServiceName() + " service started");
    +                        Iterator<Entry<Long, String>> it = brokerData.getBrokerAddrs().entrySet().iterator();
    +                        while (it.hasNext()) {
    +                            Entry<Long, String> entry = it.next();
    +                            Long brokerId = entry.getKey();
    +                            String brokerAddr = entry.getValue();
    +                            if (brokerAddr.equals(brokerAddrFound)) {
    +                                brokerNameFound = brokerData.getBrokerName();
    +                                it.remove();
    +                                log.info("remove brokerAddr[{}, {}] from brokerAddrTable, because channel destroyed",
    +                                    brokerId, brokerAddr);
    +                                break;
    +                            }
    +                        }
     
    -        while (!this.isStopped() && this.mmapOperation()) {
    +                        if (brokerData.getBrokerAddrs().isEmpty()) {
    +                            removeBrokerName = true;
    +                            itBrokerAddrTable.remove();
    +                            log.info("remove brokerName[{}] from brokerAddrTable, because channel destroyed",
    +                                brokerData.getBrokerName());
    +                        }
    +                    }
     
    -        }
    -        log.info(this.getServiceName() + " service end");
    -    }
    -private boolean mmapOperation() {
    -        boolean isSuccess = false;
    -        AllocateRequest req = null;
    -        try {
    -          // 从阻塞队列里获取请求
    -            req = this.requestQueue.take();
    -            AllocateRequest expectedRequest = this.requestTable.get(req.getFilePath());
    -            if (null == expectedRequest) {
    -                log.warn("this mmap request expired, maybe cause timeout " + req.getFilePath() + " "
    -                    + req.getFileSize());
    -                return true;
    -            }
    -            if (expectedRequest != req) {
    -                log.warn("never expected here,  maybe cause timeout " + req.getFilePath() + " "
    -                    + req.getFileSize() + ", req:" + req + ", expectedRequest:" + expectedRequest);
    -                return true;
    -            }
    +                    if (brokerNameFound != null && removeBrokerName) {
    +                        Iterator<Entry<String, Set<String>>> it = this.clusterAddrTable.entrySet().iterator();
    +                        while (it.hasNext()) {
    +                            Entry<String, Set<String>> entry = it.next();
    +                            String clusterName = entry.getKey();
    +                            Set<String> brokerNames = entry.getValue();
    +                            boolean removed = brokerNames.remove(brokerNameFound);
    +                            if (removed) {
    +                                log.info("remove brokerName[{}], clusterName[{}] from clusterAddrTable, because channel destroyed",
    +                                    brokerNameFound, clusterName);
     
    -            if (req.getMappedFile() == null) {
    -                long beginTime = System.currentTimeMillis();
    +                                if (brokerNames.isEmpty()) {
    +                                    log.info("remove the clusterName[{}] from clusterAddrTable, because channel destroyed and no broker in this cluster",
    +                                        clusterName);
    +                                    it.remove();
    +                                }
     
    -                MappedFile mappedFile;
    -                if (messageStore.getMessageStoreConfig().isTransientStorePoolEnable()) {
    -                    try {
    -                      // 通过 transientStorePool 创建
    -                        mappedFile = ServiceLoader.load(MappedFile.class).iterator().next();
    -                        mappedFile.init(req.getFilePath(), req.getFileSize(), messageStore.getTransientStorePool());
    -                    } catch (RuntimeException e) {
    -                        log.warn("Use default implementation.");
    -                      // 默认创建
    -                        mappedFile = new MappedFile(req.getFilePath(), req.getFileSize(), messageStore.getTransientStorePool());
    +                                break;
    +                            }
    +                        }
                         }
    -                } else {
    -                  // 默认创建
    -                    mappedFile = new MappedFile(req.getFilePath(), req.getFileSize());
    -                }
     
    -                long eclipseTime = UtilAll.computeEclipseTimeMilliseconds(beginTime);
    -                if (eclipseTime > 10) {
    -                    int queueSize = this.requestQueue.size();
    -                    log.warn("create mappedFile spent time(ms) " + eclipseTime + " queue size " + queueSize
    -                        + " " + req.getFilePath() + " " + req.getFileSize());
    -                }
    +                    if (removeBrokerName) {
    +                        Iterator<Entry<String, List<QueueData>>> itTopicQueueTable =
    +                            this.topicQueueTable.entrySet().iterator();
    +                        while (itTopicQueueTable.hasNext()) {
    +                            Entry<String, List<QueueData>> entry = itTopicQueueTable.next();
    +                            String topic = entry.getKey();
    +                            List<QueueData> queueDataList = entry.getValue();
     
    -                // pre write mappedFile
    -                if (mappedFile.getFileSize() >= this.messageStore.getMessageStoreConfig()
    -                    .getMapedFileSizeCommitLog()
    -                    &&
    -                    this.messageStore.getMessageStoreConfig().isWarmMapedFileEnable()) {
    -                    mappedFile.warmMappedFile(this.messageStore.getMessageStoreConfig().getFlushDiskType(),
    -                        this.messageStore.getMessageStoreConfig().getFlushLeastPagesWhenWarmMapedFile());
    -                }
    +                            Iterator<QueueData> itQueueData = queueDataList.iterator();
    +                            while (itQueueData.hasNext()) {
    +                                QueueData queueData = itQueueData.next();
    +                                if (queueData.getBrokerName().equals(brokerNameFound)) {
    +                                    itQueueData.remove();
    +                                    log.info("remove topic[{} {}], from topicQueueTable, because channel destroyed",
    +                                        topic, queueData);
    +                                }
    +                            }
     
    -                req.setMappedFile(mappedFile);
    -                this.hasException = false;
    -                isSuccess = true;
    -            }
    -        } catch (InterruptedException e) {
    -            log.warn(this.getServiceName() + " interrupted, possibly by shutdown.");
    -            this.hasException = true;
    -            return false;
    -        } catch (IOException e) {
    -            log.warn(this.getServiceName() + " service has exception. ", e);
    -            this.hasException = true;
    -            if (null != req) {
    -                requestQueue.offer(req);
    -                try {
    -                    Thread.sleep(1);
    -                } catch (InterruptedException ignored) {
    +                            if (queueDataList.isEmpty()) {
    +                                itTopicQueueTable.remove();
    +                                log.info("remove topic[{}] all queue, from topicQueueTable, because channel destroyed",
    +                                    topic);
    +                            }
    +                        }
    +                    }
    +                } finally {
    +                    this.lock.writeLock().unlock();
                     }
    +            } catch (Exception e) {
    +                log.error("onChannelDestroy Exception", e);
                 }
    -        } finally {
    -            if (req != null && isSuccess)
    -              // 通知前面等待的
    -                req.getCountDownLatch().countDown();
             }
    -        return true;
    -    }
    + }
    +

    第二个是每10分钟打印一次NameServer的配置参数。即KVConfigManager.configTable变量的内容。

    +
    this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
     
    +            @Override
    +            public void run() {
    +                NamesrvController.this.kvConfigManager.printAllPeriodically();
    +            }
    +        }, 1, 10, TimeUnit.MINUTES);
    +

    然后这个初始化就差不多完成了,后面只需要把remotingServer start一下就好了

    +

    处理请求

    直接上代码,其实主体是swtich case去判断

    +
    @Override
    +    public RemotingCommand processRequest(ChannelHandlerContext ctx,
    +        RemotingCommand request) throws RemotingCommandException {
     
    -]]>
    -      
    -        MQ
    -        RocketMQ
    -        消息队列
    -      
    -      
    -        MQ
    -        消息队列
    -        RocketMQ
    -      
    -  
    -  
    -    聊一下 RocketMQ 的顺序消息
    -    /2021/08/29/%E8%81%8A%E4%B8%80%E4%B8%8B-RocketMQ-%E7%9A%84%E9%A1%BA%E5%BA%8F%E6%B6%88%E6%81%AF/
    -    rocketmq 里有一种比较特殊的用法,就是顺序消息,比如订单的生命周期里,在创建,支付,签收等状态轮转中,会发出来对应的消息,这里面就比较需要去保证他们的顺序,当然在处理的业务代码也可以做对应的处理,结合消息重投,但是如果这里消息就能保证顺序性了,那么业务代码就能更好的关注业务代码的处理。

    -

    首先有一种情况是全局的有序,比如对于一个 topic 里就得发送线程保证只有一个,内部的 queue 也只有一个,消费线程也只有一个,这样就能比较容易的保证全局顺序性了,但是这里的问题就是完全限制了性能,不是很现实,在真实场景里很多都是比如对于同一个订单,需要去保证状态的轮转是按照预期的顺序来,而不必要全局的有序性。

    -

    对于这类的有序性,需要在发送和接收方都有对应的处理,在发送消息中,需要去指定 selector,即MessageQueueSelector,能够以固定的方式是分配到对应的 MessageQueue

    -

    比如像 RocketMQ 中的示例

    -
    SendResult sendResult = producer.send(msg, new MessageQueueSelector() {
    -                @Override
    -                public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {
    -                    Long id = (Long) arg;  //message queue is selected by #salesOrderID
    -                    long index = id % mqs.size();
    -                    return mqs.get((int) index);
    -                }
    -            }, orderList.get(i).getOrderId());
    + if (ctx != null) { + log.debug("receive request, {} {} {}", + request.getCode(), + RemotingHelper.parseChannelRemoteAddr(ctx.channel()), + request); + } -

    而在消费侧有几个点比较重要,首先我们要保证一个 MessageQueue只被一个消费者消费,消费队列存在broker端,要保证 MessageQueue 只被一个消费者消费,那么消费者在进行消息拉取消费时就必须向mq服务器申请队列锁,消费者申请队列锁的代码存在于RebalanceService消息队列负载的实现代码中。

    -
    List<PullRequest> pullRequestList = new ArrayList<PullRequest>();
    -        for (MessageQueue mq : mqSet) {
    -            if (!this.processQueueTable.containsKey(mq)) {
    -              // 判断是否顺序,如果是顺序消费的,则需要加锁
    -                if (isOrder && !this.lock(mq)) {
    -                    log.warn("doRebalance, {}, add a new mq failed, {}, because lock failed", consumerGroup, mq);
    -                    continue;
    +
    +        switch (request.getCode()) {
    +            case RequestCode.PUT_KV_CONFIG:
    +                return this.putKVConfig(ctx, request);
    +            case RequestCode.GET_KV_CONFIG:
    +                return this.getKVConfig(ctx, request);
    +            case RequestCode.DELETE_KV_CONFIG:
    +                return this.deleteKVConfig(ctx, request);
    +            case RequestCode.QUERY_DATA_VERSION:
    +                return queryBrokerTopicConfig(ctx, request);
    +            case RequestCode.REGISTER_BROKER:
    +                Version brokerVersion = MQVersion.value2Version(request.getVersion());
    +                if (brokerVersion.ordinal() >= MQVersion.Version.V3_0_11.ordinal()) {
    +                    return this.registerBrokerWithFilterServer(ctx, request);
    +                } else {
    +                    return this.registerBroker(ctx, request);
                     }
    +            case RequestCode.UNREGISTER_BROKER:
    +                return this.unregisterBroker(ctx, request);
    +            case RequestCode.GET_ROUTEINTO_BY_TOPIC:
    +                return this.getRouteInfoByTopic(ctx, request);
    +            case RequestCode.GET_BROKER_CLUSTER_INFO:
    +                return this.getBrokerClusterInfo(ctx, request);
    +            case RequestCode.WIPE_WRITE_PERM_OF_BROKER:
    +                return this.wipeWritePermOfBroker(ctx, request);
    +            case RequestCode.GET_ALL_TOPIC_LIST_FROM_NAMESERVER:
    +                return getAllTopicListFromNameserver(ctx, request);
    +            case RequestCode.DELETE_TOPIC_IN_NAMESRV:
    +                return deleteTopicInNamesrv(ctx, request);
    +            case RequestCode.GET_KVLIST_BY_NAMESPACE:
    +                return this.getKVListByNamespace(ctx, request);
    +            case RequestCode.GET_TOPICS_BY_CLUSTER:
    +                return this.getTopicsByCluster(ctx, request);
    +            case RequestCode.GET_SYSTEM_TOPIC_LIST_FROM_NS:
    +                return this.getSystemTopicListFromNs(ctx, request);
    +            case RequestCode.GET_UNIT_TOPIC_LIST:
    +                return this.getUnitTopicList(ctx, request);
    +            case RequestCode.GET_HAS_UNIT_SUB_TOPIC_LIST:
    +                return this.getHasUnitSubTopicList(ctx, request);
    +            case RequestCode.GET_HAS_UNIT_SUB_UNUNIT_TOPIC_LIST:
    +                return this.getHasUnitSubUnUnitTopicList(ctx, request);
    +            case RequestCode.UPDATE_NAMESRV_CONFIG:
    +                return this.updateConfig(ctx, request);
    +            case RequestCode.GET_NAMESRV_CONFIG:
    +                return this.getConfig(ctx, request);
    +            default:
    +                break;
    +        }
    +        return null;
    +    }
    - this.removeDirtyOffset(mq); - ProcessQueue pq = new ProcessQueue(); - long nextOffset = this.computePullFromWhere(mq); - if (nextOffset >= 0) { - ProcessQueue pre = this.processQueueTable.putIfAbsent(mq, pq); - if (pre != null) { - log.info("doRebalance, {}, mq already exists, {}", consumerGroup, mq); - } else { - log.info("doRebalance, {}, add a new mq, {}", consumerGroup, mq); - PullRequest pullRequest = new PullRequest(); - pullRequest.setConsumerGroup(consumerGroup); - pullRequest.setNextOffset(nextOffset); - pullRequest.setMessageQueue(mq); - pullRequest.setProcessQueue(pq); - pullRequestList.add(pullRequest); - changed = true; - } +

    以broker注册为例,

    +
    case RequestCode.REGISTER_BROKER:
    +                Version brokerVersion = MQVersion.value2Version(request.getVersion());
    +                if (brokerVersion.ordinal() >= MQVersion.Version.V3_0_11.ordinal()) {
    +                    return this.registerBrokerWithFilterServer(ctx, request);
                     } else {
    -                    log.warn("doRebalance, {}, add new mq failed, {}", consumerGroup, mq);
    -                }
    -            }
    -        }
    + return this.registerBroker(ctx, request); + }
    -

    在申请到锁之后会创建 pullRequest 进行消息拉取,消息拉取部分的代码实现在PullMessageService中,

    -
    @Override
    -    public void run() {
    -        log.info(this.getServiceName() + " service started");
    +

    做了个简单的版本管理,我们看下前面一个的代码

    +
    public RemotingCommand registerBrokerWithFilterServer(ChannelHandlerContext ctx, RemotingCommand request)
    +    throws RemotingCommandException {
    +    final RemotingCommand response = RemotingCommand.createResponseCommand(RegisterBrokerResponseHeader.class);
    +    final RegisterBrokerResponseHeader responseHeader = (RegisterBrokerResponseHeader) response.readCustomHeader();
    +    final RegisterBrokerRequestHeader requestHeader =
    +        (RegisterBrokerRequestHeader) request.decodeCommandCustomHeader(RegisterBrokerRequestHeader.class);
     
    -        while (!this.isStopped()) {
    -            try {
    -                PullRequest pullRequest = this.pullRequestQueue.take();
    -                this.pullMessage(pullRequest);
    -            } catch (InterruptedException ignored) {
    -            } catch (Exception e) {
    -                log.error("Pull Message Service Run Method exception", e);
    -            }
    -        }
    +    if (!checksum(ctx, request, requestHeader)) {
    +        response.setCode(ResponseCode.SYSTEM_ERROR);
    +        response.setRemark("crc32 not match");
    +        return response;
    +    }
     
    -        log.info(this.getServiceName() + " service end");
    -    }
    + RegisterBrokerBody registerBrokerBody = new RegisterBrokerBody(); -

    消息拉取完后,需要提交到ConsumeMessageService中进行消费,顺序消费的实现为ConsumeMessageOrderlyService,提交消息进行消费的方法为ConsumeMessageOrderlyService#submitConsumeRequest,具体实现如下:

    -
    @Override
    -public void submitConsumeRequest(
    -    final List<MessageExt> msgs,
    -    final ProcessQueue processQueue,
    -    final MessageQueue messageQueue,
    -    final boolean dispathToConsume) {
    -    if (dispathToConsume) {
    -        ConsumeRequest consumeRequest = new ConsumeRequest(processQueue, messageQueue);
    -        this.consumeExecutor.submit(consumeRequest);
    +    if (request.getBody() != null) {
    +        try {
    +            registerBrokerBody = RegisterBrokerBody.decode(request.getBody(), requestHeader.isCompressed());
    +        } catch (Exception e) {
    +            throw new RemotingCommandException("Failed to decode RegisterBrokerBody", e);
    +        }
    +    } else {
    +        registerBrokerBody.getTopicConfigSerializeWrapper().getDataVersion().setCounter(new AtomicLong(0));
    +        registerBrokerBody.getTopicConfigSerializeWrapper().getDataVersion().setTimestamp(0);
         }
    -}
    - -

    构建了一个ConsumeRequest对象,它是个实现了 runnable 接口的类,并提交给了线程池来并行消费,看下顺序消费的ConsumeRequest的run方法实现:

    -
    @Override
    -        public void run() {
    -            if (this.processQueue.isDropped()) {
    -                log.warn("run, the message queue not be able to consume, because it's dropped. {}", this.messageQueue);
    -                return;
    -            }
    -						// 获得 Consumer 消息队列锁,即单个线程独占
    -            final Object objLock = messageQueueLock.fetchLockObject(this.messageQueue);
    -            synchronized (objLock) {
    -              // (广播模式) 或者 (集群模式 && Broker消息队列锁有效)
    -                if (MessageModel.BROADCASTING.equals(ConsumeMessageOrderlyService.this.defaultMQPushConsumerImpl.messageModel())
    -                    || (this.processQueue.isLocked() && !this.processQueue.isLockExpired())) {
    -                    final long beginTime = System.currentTimeMillis();
    -                  // 循环
    -                    for (boolean continueConsume = true; continueConsume; ) {
    -                        if (this.processQueue.isDropped()) {
    -                            log.warn("the message queue not be able to consume, because it's dropped. {}", this.messageQueue);
    -                            break;
    -                        }
     
    -                      // 消息队列分布式锁未锁定,提交延迟获得锁并消费请求
    -                        if (MessageModel.CLUSTERING.equals(ConsumeMessageOrderlyService.this.defaultMQPushConsumerImpl.messageModel())
    -                            && !this.processQueue.isLocked()) {
    -                            log.warn("the message queue not locked, so consume later, {}", this.messageQueue);
    -                            ConsumeMessageOrderlyService.this.tryLockLaterAndReconsume(this.messageQueue, this.processQueue, 10);
    -                            break;
    -                        }
    +    RegisterBrokerResult result = this.namesrvController.getRouteInfoManager().registerBroker(
    +        requestHeader.getClusterName(),
    +        requestHeader.getBrokerAddr(),
    +        requestHeader.getBrokerName(),
    +        requestHeader.getBrokerId(),
    +        requestHeader.getHaServerAddr(),
    +        registerBrokerBody.getTopicConfigSerializeWrapper(),
    +        registerBrokerBody.getFilterServerList(),
    +        ctx.channel());
     
    -                      // 消息队列分布式锁已经过期,提交延迟获得锁并消费请求
    -                        if (MessageModel.CLUSTERING.equals(ConsumeMessageOrderlyService.this.defaultMQPushConsumerImpl.messageModel())
    -                            && this.processQueue.isLockExpired()) {
    -                            log.warn("the message queue lock expired, so consume later, {}", this.messageQueue);
    -                            ConsumeMessageOrderlyService.this.tryLockLaterAndReconsume(this.messageQueue, this.processQueue, 10);
    -                            break;
    -                        }
    -												// 当前周期消费时间超过连续时长,默认:60s,提交延迟消费请求。默认情况下,每消费1分钟休息10ms。
    -                        long interval = System.currentTimeMillis() - beginTime;
    -                        if (interval > MAX_TIME_CONSUME_CONTINUOUSLY) {
    -                            ConsumeMessageOrderlyService.this.submitConsumeRequestLater(processQueue, messageQueue, 10);
    -                            break;
    -                        }
    -												// 获取消费消息。此处和并发消息请求不同,并发消息请求已经带了消费哪些消息。
    -                        final int consumeBatchSize =
    -                            ConsumeMessageOrderlyService.this.defaultMQPushConsumer.getConsumeMessageBatchMaxSize();
    +    responseHeader.setHaServerAddr(result.getHaServerAddr());
    +    responseHeader.setMasterAddr(result.getMasterAddr());
     
    -                        List<MessageExt> msgs = this.processQueue.takeMessags(consumeBatchSize);
    -                        defaultMQPushConsumerImpl.resetRetryAndNamespace(msgs, defaultMQPushConsumer.getConsumerGroup());
    -                        if (!msgs.isEmpty()) {
    -                            final ConsumeOrderlyContext context = new ConsumeOrderlyContext(this.messageQueue);
    +    byte[] jsonValue = this.namesrvController.getKvConfigManager().getKVListByNamespace(NamesrvUtil.NAMESPACE_ORDER_TOPIC_CONFIG);
    +    response.setBody(jsonValue);
     
    -                            ConsumeOrderlyStatus status = null;
    +    response.setCode(ResponseCode.SUCCESS);
    +    response.setRemark(null);
    +    return response;
    +}
    - ConsumeMessageContext consumeMessageContext = null; - if (ConsumeMessageOrderlyService.this.defaultMQPushConsumerImpl.hasHook()) { - consumeMessageContext = new ConsumeMessageContext(); - consumeMessageContext - .setConsumerGroup(ConsumeMessageOrderlyService.this.defaultMQPushConsumer.getConsumerGroup()); - consumeMessageContext.setNamespace(defaultMQPushConsumer.getNamespace()); - consumeMessageContext.setMq(messageQueue); - consumeMessageContext.setMsgList(msgs); - consumeMessageContext.setSuccess(false); - // init the consume context type - consumeMessageContext.setProps(new HashMap<String, String>()); - ConsumeMessageOrderlyService.this.defaultMQPushConsumerImpl.executeHookBefore(consumeMessageContext); - } - // 执行消费 - long beginTimestamp = System.currentTimeMillis(); - ConsumeReturnType returnType = ConsumeReturnType.SUCCESS; - boolean hasException = false; - try { - this.processQueue.getLockConsume().lock(); // 锁定处理队列 - if (this.processQueue.isDropped()) { - log.warn("consumeMessage, the message queue not be able to consume, because it's dropped. {}", - this.messageQueue); - break; - } +

    可以看到主要的逻辑还是在org.apache.rocketmq.namesrv.routeinfo.RouteInfoManager#registerBroker这个方法里

    +
    public RegisterBrokerResult registerBroker(
    +        final String clusterName,
    +        final String brokerAddr,
    +        final String brokerName,
    +        final long brokerId,
    +        final String haServerAddr,
    +        final TopicConfigSerializeWrapper topicConfigWrapper,
    +        final List<String> filterServerList,
    +        final Channel channel) {
    +        RegisterBrokerResult result = new RegisterBrokerResult();
    +        try {
    +            try {
    +                this.lock.writeLock().lockInterruptibly();
     
    -                                status = messageListener.consumeMessage(Collections.unmodifiableList(msgs), context);
    -                            } catch (Throwable e) {
    -                                log.warn("consumeMessage exception: {} Group: {} Msgs: {} MQ: {}",
    -                                    RemotingHelper.exceptionSimpleDesc(e),
    -                                    ConsumeMessageOrderlyService.this.consumerGroup,
    -                                    msgs,
    -                                    messageQueue);
    -                                hasException = true;
    -                            } finally {
    -                                this.processQueue.getLockConsume().unlock();  // 解锁
    -                            }
    +              // 更新这个clusterAddrTable
    +                Set<String> brokerNames = this.clusterAddrTable.get(clusterName);
    +                if (null == brokerNames) {
    +                    brokerNames = new HashSet<String>();
    +                    this.clusterAddrTable.put(clusterName, brokerNames);
    +                }
    +                brokerNames.add(brokerName);
     
    -                            if (null == status
    -                                || ConsumeOrderlyStatus.ROLLBACK == status
    -                                || ConsumeOrderlyStatus.SUSPEND_CURRENT_QUEUE_A_MOMENT == status) {
    -                                log.warn("consumeMessage Orderly return not OK, Group: {} Msgs: {} MQ: {}",
    -                                    ConsumeMessageOrderlyService.this.consumerGroup,
    -                                    msgs,
    -                                    messageQueue);
    -                            }
    +                boolean registerFirst = false;
     
    -                            long consumeRT = System.currentTimeMillis() - beginTimestamp;
    -                            if (null == status) {
    -                                if (hasException) {
    -                                    returnType = ConsumeReturnType.EXCEPTION;
    -                                } else {
    -                                    returnType = ConsumeReturnType.RETURNNULL;
    -                                }
    -                            } else if (consumeRT >= defaultMQPushConsumer.getConsumeTimeout() * 60 * 1000) {
    -                                returnType = ConsumeReturnType.TIME_OUT;
    -                            } else if (ConsumeOrderlyStatus.SUSPEND_CURRENT_QUEUE_A_MOMENT == status) {
    -                                returnType = ConsumeReturnType.FAILED;
    -                            } else if (ConsumeOrderlyStatus.SUCCESS == status) {
    -                                returnType = ConsumeReturnType.SUCCESS;
    -                            }
    +              // 更新brokerAddrTable
    +                BrokerData brokerData = this.brokerAddrTable.get(brokerName);
    +                if (null == brokerData) {
    +                    registerFirst = true;
    +                    brokerData = new BrokerData(clusterName, brokerName, new HashMap<Long, String>());
    +                    this.brokerAddrTable.put(brokerName, brokerData);
    +                }
    +                Map<Long, String> brokerAddrsMap = brokerData.getBrokerAddrs();
    +                //Switch slave to master: first remove <1, IP:PORT> in namesrv, then add <0, IP:PORT>
    +                //The same IP:PORT must only have one record in brokerAddrTable
    +                Iterator<Entry<Long, String>> it = brokerAddrsMap.entrySet().iterator();
    +                while (it.hasNext()) {
    +                    Entry<Long, String> item = it.next();
    +                    if (null != brokerAddr && brokerAddr.equals(item.getValue()) && brokerId != item.getKey()) {
    +                        it.remove();
    +                    }
    +                }
     
    -                            if (ConsumeMessageOrderlyService.this.defaultMQPushConsumerImpl.hasHook()) {
    -                                consumeMessageContext.getProps().put(MixAll.CONSUME_CONTEXT_TYPE, returnType.name());
    -                            }
    +                String oldAddr = brokerData.getBrokerAddrs().put(brokerId, brokerAddr);
    +                registerFirst = registerFirst || (null == oldAddr);
     
    -                            if (null == status) {
    -                                status = ConsumeOrderlyStatus.SUSPEND_CURRENT_QUEUE_A_MOMENT;
    +              // 更新了org.apache.rocketmq.namesrv.routeinfo.RouteInfoManager#topicQueueTable中的数据
    +                if (null != topicConfigWrapper
    +                    && MixAll.MASTER_ID == brokerId) {
    +                    if (this.isBrokerTopicConfigChanged(brokerAddr, topicConfigWrapper.getDataVersion())
    +                        || registerFirst) {
    +                        ConcurrentMap<String, TopicConfig> tcTable =
    +                            topicConfigWrapper.getTopicConfigTable();
    +                        if (tcTable != null) {
    +                            for (Map.Entry<String, TopicConfig> entry : tcTable.entrySet()) {
    +                                this.createAndUpdateQueueData(brokerName, entry.getValue());
                                 }
    +                        }
    +                    }
    +                }
     
    -                            if (ConsumeMessageOrderlyService.this.defaultMQPushConsumerImpl.hasHook()) {
    -                                consumeMessageContext.setStatus(status.toString());
    -                                consumeMessageContext
    -                                    .setSuccess(ConsumeOrderlyStatus.SUCCESS == status || ConsumeOrderlyStatus.COMMIT == status);
    -                                ConsumeMessageOrderlyService.this.defaultMQPushConsumerImpl.executeHookAfter(consumeMessageContext);
    -                            }
    +              // 更新活跃broker信息
    +                BrokerLiveInfo prevBrokerLiveInfo = this.brokerLiveTable.put(brokerAddr,
    +                    new BrokerLiveInfo(
    +                        System.currentTimeMillis(),
    +                        topicConfigWrapper.getDataVersion(),
    +                        channel,
    +                        haServerAddr));
    +                if (null == prevBrokerLiveInfo) {
    +                    log.info("new broker registered, {} HAServer: {}", brokerAddr, haServerAddr);
    +                }
     
    -                            ConsumeMessageOrderlyService.this.getConsumerStatsManager()
    -                                .incConsumeRT(ConsumeMessageOrderlyService.this.consumerGroup, messageQueue.getTopic(), consumeRT);
    +              // 处理filter
    +                if (filterServerList != null) {
    +                    if (filterServerList.isEmpty()) {
    +                        this.filterServerTable.remove(brokerAddr);
    +                    } else {
    +                        this.filterServerTable.put(brokerAddr, filterServerList);
    +                    }
    +                }
     
    -                            continueConsume = ConsumeMessageOrderlyService.this.processConsumeResult(msgs, status, context, this);
    -                        } else {
    -                            continueConsume = false;
    +              // 当当前broker非master时返回master信息
    +                if (MixAll.MASTER_ID != brokerId) {
    +                    String masterAddr = brokerData.getBrokerAddrs().get(MixAll.MASTER_ID);
    +                    if (masterAddr != null) {
    +                        BrokerLiveInfo brokerLiveInfo = this.brokerLiveTable.get(masterAddr);
    +                        if (brokerLiveInfo != null) {
    +                            result.setHaServerAddr(brokerLiveInfo.getHaServerAddr());
    +                            result.setMasterAddr(masterAddr);
                             }
                         }
    -                } else {
    -                    if (this.processQueue.isDropped()) {
    -                        log.warn("the message queue not be able to consume, because it's dropped. {}", this.messageQueue);
    -                        return;
    -                    }
    -
    -                    ConsumeMessageOrderlyService.this.tryLockLaterAndReconsume(this.messageQueue, this.processQueue, 100);
                     }
    +            } finally {
    +                this.lock.writeLock().unlock();
                 }
    -        }
    + } catch (Exception e) { + log.error("registerBroker Exception", e); + } -

    获取到锁对象后,使用synchronized尝试申请线程级独占锁。

    -

    如果加锁成功,同一时刻只有一个线程进行消息消费。

    -

    如果加锁失败,会延迟100ms重新尝试向broker端申请锁定messageQueue,锁定成功后重新提交消费请求

    -

    创建消息拉取任务时,消息客户端向broker端申请锁定MessageQueue,使得一个MessageQueue同一个时刻只能被一个消费客户端消费。

    -

    消息消费时,多线程针对同一个消息队列的消费先尝试使用synchronized申请独占锁,加锁成功才能进行消费,使得一个MessageQueue同一个时刻只能被一个消费客户端中一个线程消费。
    这里其实还有很重要的一点是对processQueue的加锁,这里其实是保证了在 rebalance的过程中如果 processQueue 被分配给了另一个 consumer,但是当前已经被我这个 consumer 再消费,但是没提交,就有可能出现被两个消费者消费,所以得进行加锁保证不受 rebalance 影响。

    + return result; + }
    + +

    这个是注册 broker 的逻辑,再看下根据 topic 获取 broker 信息和 topic 信息,org.apache.rocketmq.namesrv.processor.DefaultRequestProcessor#getRouteInfoByTopic 主要是这个方法的逻辑

    +
    public RemotingCommand getRouteInfoByTopic(ChannelHandlerContext ctx,
    +        RemotingCommand request) throws RemotingCommandException {
    +        final RemotingCommand response = RemotingCommand.createResponseCommand(null);
    +        final GetRouteInfoRequestHeader requestHeader =
    +            (GetRouteInfoRequestHeader) request.decodeCommandCustomHeader(GetRouteInfoRequestHeader.class);
    +
    +        TopicRouteData topicRouteData = this.namesrvController.getRouteInfoManager().pickupTopicRouteData(requestHeader.getTopic());
    +
    +        if (topicRouteData != null) {
    +            if (this.namesrvController.getNamesrvConfig().isOrderMessageEnable()) {
    +                String orderTopicConf =
    +                    this.namesrvController.getKvConfigManager().getKVConfig(NamesrvUtil.NAMESPACE_ORDER_TOPIC_CONFIG,
    +                        requestHeader.getTopic());
    +                topicRouteData.setOrderTopicConf(orderTopicConf);
    +            }
    +
    +            byte[] content = topicRouteData.encode();
    +            response.setBody(content);
    +            response.setCode(ResponseCode.SUCCESS);
    +            response.setRemark(null);
    +            return response;
    +        }
    +
    +        response.setCode(ResponseCode.TOPIC_NOT_EXIST);
    +        response.setRemark("No topic route info in name server for the topic: " + requestHeader.getTopic()
    +            + FAQUrl.suggestTodo(FAQUrl.APPLY_TOPIC_URL));
    +        return response;
    +    }
    + +

    首先调用org.apache.rocketmq.namesrv.routeinfo.RouteInfoManager#pickupTopicRouteDataorg.apache.rocketmq.namesrv.routeinfo.RouteInfoManager#topicQueueTable获取到org.apache.rocketmq.common.protocol.route.QueueData这里面存了 brokerName,再通过org.apache.rocketmq.namesrv.routeinfo.RouteInfoManager#brokerAddrTable里获取到 broker 的地址信息等,然后再获取 orderMessage 的配置。

    +

    简要分析了下 RocketMQ 的 NameServer 的代码,比较粗粒度。

    ]]>
    MQ RocketMQ 消息队列 + RocketMQ + 中间件 + RocketMQ MQ 消息队列 RocketMQ + 削峰填谷 + 中间件 + 源码解析 + NameServer
    - 聊一下 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 {
    +    聊一下 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/
    +    ConsumeQueue 其实是定位到一个 topic 下的消息在 CommitLog 下的偏移量,它也是固定大小的

    +
    // ConsumeQueue file size,default is 30W
    +private int mapedFileSizeConsumeQueue = 300000 * ConsumeQueue.CQ_STORE_UNIT_SIZE;
     
    -	/**
    -	 * The application should not run as a web application and should not start an
    -	 * embedded web server.
    -	 */
    -	NONE,
    +public static final int CQ_STORE_UNIT_SIZE = 20;
    - /** - * The application should run as a servlet-based web application and should start an - * embedded servlet web server. - */ - SERVLET, +

    所以文件大小是5.7M 左右

    +

    5udpag

    +

    ConsumeQueue 的构建是通过org.apache.rocketmq.store.DefaultMessageStore.ReputMessageService运行后的 doReput 方法,而启动是的 reputFromOffset 则是通过org.apache.rocketmq.store.DefaultMessageStore#start中下面代码设置并启动

    +
    log.info("[SetReputOffset] maxPhysicalPosInLogicQueue={} clMinOffset={} clMaxOffset={} clConfirmedOffset={}",
    +                maxPhysicalPosInLogicQueue, this.commitLog.getMinOffset(), this.commitLog.getMaxOffset(), this.commitLog.getConfirmOffset());
    +            this.reputMessageService.setReputFromOffset(maxPhysicalPosInLogicQueue);
    +            this.reputMessageService.start();
    - /** - * The application should run as a reactive web application and should start an - * embedded reactive web server. - */ - REACTIVE +

    看一下 doReput 的逻辑

    +
    private void doReput() {
    +            if (this.reputFromOffset < DefaultMessageStore.this.commitLog.getMinOffset()) {
    +                log.warn("The reputFromOffset={} is smaller than minPyOffset={}, this usually indicate that the dispatch behind too much and the commitlog has expired.",
    +                    this.reputFromOffset, DefaultMessageStore.this.commitLog.getMinOffset());
    +                this.reputFromOffset = DefaultMessageStore.this.commitLog.getMinOffset();
    +            }
    +            for (boolean doNext = true; this.isCommitLogAvailable() && doNext; ) {
    +
    +                if (DefaultMessageStore.this.getMessageStoreConfig().isDuplicationEnable()
    +                    && this.reputFromOffset >= DefaultMessageStore.this.getConfirmOffset()) {
    +                    break;
    +                }
    +
    +              // 根据偏移量获取消息
    +                SelectMappedBufferResult result = DefaultMessageStore.this.commitLog.getData(reputFromOffset);
    +                if (result != null) {
    +                    try {
    +                        this.reputFromOffset = result.getStartOffset();
    +
    +                        for (int readSize = 0; readSize < result.getSize() && doNext; ) {
    +                          // 消息校验和转换
    +                            DispatchRequest dispatchRequest =
    +                                DefaultMessageStore.this.commitLog.checkMessageAndReturnSize(result.getByteBuffer(), false, false);
    +                            int size = dispatchRequest.getBufferSize() == -1 ? dispatchRequest.getMsgSize() : dispatchRequest.getBufferSize();
    +
    +                            if (dispatchRequest.isSuccess()) {
    +                                if (size > 0) {
    +                                  // 进行分发处理,包括 ConsumeQueue 和 IndexFile
    +                                    DefaultMessageStore.this.doDispatch(dispatchRequest);
    +
    +                                    if (BrokerRole.SLAVE != DefaultMessageStore.this.getMessageStoreConfig().getBrokerRole()
    +                                        && DefaultMessageStore.this.brokerConfig.isLongPollingEnable()) {
    +                                        DefaultMessageStore.this.messageArrivingListener.arriving(dispatchRequest.getTopic(),
    +                                            dispatchRequest.getQueueId(), dispatchRequest.getConsumeQueueOffset() + 1,
    +                                            dispatchRequest.getTagsCode(), dispatchRequest.getStoreTimestamp(),
    +                                            dispatchRequest.getBitMap(), dispatchRequest.getPropertiesMap());
    +                                    }
    +
    +                                    this.reputFromOffset += size;
    +                                    readSize += size;
    +                                    if (DefaultMessageStore.this.getMessageStoreConfig().getBrokerRole() == BrokerRole.SLAVE) {
    +                                        DefaultMessageStore.this.storeStatsService
    +                                            .getSinglePutMessageTopicTimesTotal(dispatchRequest.getTopic()).incrementAndGet();
    +                                        DefaultMessageStore.this.storeStatsService
    +                                            .getSinglePutMessageTopicSizeTotal(dispatchRequest.getTopic())
    +                                            .addAndGet(dispatchRequest.getMsgSize());
    +                                    }
    +                                } else if (size == 0) {
    +                                    this.reputFromOffset = DefaultMessageStore.this.commitLog.rollNextFile(this.reputFromOffset);
    +                                    readSize = result.getSize();
    +                                }
    +                            } else if (!dispatchRequest.isSuccess()) {
    +
    +                                if (size > 0) {
    +                                    log.error("[BUG]read total count not equals msg total size. reputFromOffset={}", reputFromOffset);
    +                                    this.reputFromOffset += size;
    +                                } else {
    +                                    doNext = false;
    +                                    // If user open the dledger pattern or the broker is master node,
    +                                    // it will not ignore the exception and fix the reputFromOffset variable
    +                                    if (DefaultMessageStore.this.getMessageStoreConfig().isEnableDLegerCommitLog() ||
    +                                        DefaultMessageStore.this.brokerConfig.getBrokerId() == MixAll.MASTER_ID) {
    +                                        log.error("[BUG]dispatch message to consume queue error, COMMITLOG OFFSET: {}",
    +                                            this.reputFromOffset);
    +                                        this.reputFromOffset += result.getSize() - readSize;
    +                                    }
    +                                }
    +                            }
    +                        }
    +                    } finally {
    +                        result.release();
    +                    }
    +                } else {
    +                    doNext = false;
    +                }
    +            }
    +        }
    + +

    分发的逻辑看到这

    +
        class CommitLogDispatcherBuildConsumeQueue implements CommitLogDispatcher {
    +
    +        @Override
    +        public void dispatch(DispatchRequest request) {
    +            final int tranType = MessageSysFlag.getTransactionValue(request.getSysFlag());
    +            switch (tranType) {
    +                case MessageSysFlag.TRANSACTION_NOT_TYPE:
    +                case MessageSysFlag.TRANSACTION_COMMIT_TYPE:
    +                    DefaultMessageStore.this.putMessagePositionInfo(request);
    +                    break;
    +                case MessageSysFlag.TRANSACTION_PREPARED_TYPE:
    +                case MessageSysFlag.TRANSACTION_ROLLBACK_TYPE:
    +                    break;
    +            }
    +        }
    +    }
    +public void putMessagePositionInfo(DispatchRequest dispatchRequest) {
    +        ConsumeQueue cq = this.findConsumeQueue(dispatchRequest.getTopic(), dispatchRequest.getQueueId());
    +        cq.putMessagePositionInfoWrapper(dispatchRequest);
    +    }
    + +

    真正存储的是在这

    +
    private boolean putMessagePositionInfo(final long offset, final int size, final long tagsCode,
    +    final long cqOffset) {
    +
    +    if (offset + size <= this.maxPhysicOffset) {
    +        log.warn("Maybe try to build consume queue repeatedly maxPhysicOffset={} phyOffset={}", maxPhysicOffset, offset);
    +        return true;
    +    }
    +
    +    this.byteBufferIndex.flip();
    +    this.byteBufferIndex.limit(CQ_STORE_UNIT_SIZE);
    +    this.byteBufferIndex.putLong(offset);
    +    this.byteBufferIndex.putInt(size);
    +    this.byteBufferIndex.putLong(tagsCode);
    -}
    -

    相当于是把none 的类型和包括 servlet 和 reactive 放进了枚举类进行控制。

    +

    这里也可以看到 ConsumeQueue 的存储格式,

    +

    AA6Tve

    +

    偏移量,消息大小,跟 tag 的 hashCode

    ]]>
    - Java - SpringBoot + MQ + RocketMQ + 消息队列 - Java - Spring - SpringBoot - 自动装配 - AutoConfiguration + MQ + 消息队列 + RocketMQ
    - 聊一下 SpringBoot 中动态切换数据源的方法 - /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/ - 其实这个表示有点不太对,应该是 Druid 动态切换数据源的方法,只是应用在了 springboot 框架中,准备代码准备了半天,之前在一次数据库迁移中使用了,发现 Druid 还是很强大的,用来做动态数据源切换很方便。

    -

    首先这里的场景跟我原来用的有点点区别,在项目中使用的是通过配置中心控制数据源切换,统一切换,而这里的例子多加了个可以根据接口注解配置

    -

    第一部分是最核心的,如何基于 Spring JDBC 和 Druid 来实现数据源切换,是继承了org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource 这个类,他的determineCurrentLookupKey方法会被调用来获得用来决定选择那个数据源的对象,也就是 lookupKey,也可以通过这个类看到就是通过这个 lookupKey 来路由找到数据源。

    -
    public class DynamicDataSource extends AbstractRoutingDataSource {
    +    聊一下 RocketMQ 的消息存储二
    +    /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/
    +    CommitLog 结构

    CommitLog 是 rocketmq 的服务端,也就是 broker 存储消息的的文件,跟 kafka 一样,也是顺序写入,当然消息是变长的,生成的规则是每个文件的默认1G =1024 * 1024 * 1024,commitlog的文件名fileName,名字长度为20位,左边补零,剩余为起始偏移量;比如00000000000000000000代表了第一个文件,起始偏移量为0,文件大小为1G=1 073 741 824Byte;当这个文件满了,第二个文件名字为00000000001073741824,起始偏移量为1073741824, 消息存储的时候会顺序写入文件,当文件满了则写入下一个文件,代码中的定义

    +
    // CommitLog file size,default is 1G
    +private int mapedFileSizeCommitLog = 1024 * 1024 * 1024;
    - @Override - protected Object determineCurrentLookupKey() { - if (DatabaseContextHolder.getDatabaseType() != null) { - return DatabaseContextHolder.getDatabaseType().getName(); +

    kLahwW

    +

    本地跑个 demo 验证下,也是这样,这里奇妙有几个比较巧妙的点(个人观点),首先文件就刚好是 1G,并且按照大小偏移量去生成下一个文件,这样获取消息的时候按大小算一下就知道在哪个文件里了,

    +

    代码中写入 CommitLog 的逻辑可以从这开始看

    +
    public PutMessageResult putMessage(final MessageExtBrokerInner msg) {
    +        // Set the storage time
    +        msg.setStoreTimestamp(System.currentTimeMillis());
    +        // Set the message body BODY CRC (consider the most appropriate setting
    +        // on the client)
    +        msg.setBodyCRC(UtilAll.crc32(msg.getBody()));
    +        // Back to Results
    +        AppendMessageResult result = null;
    +
    +        StoreStatsService storeStatsService = this.defaultMessageStore.getStoreStatsService();
    +
    +        String topic = msg.getTopic();
    +        int queueId = msg.getQueueId();
    +
    +        final int tranType = MessageSysFlag.getTransactionValue(msg.getSysFlag());
    +        if (tranType == MessageSysFlag.TRANSACTION_NOT_TYPE
    +            || tranType == MessageSysFlag.TRANSACTION_COMMIT_TYPE) {
    +            // Delay Delivery
    +            if (msg.getDelayTimeLevel() > 0) {
    +                if (msg.getDelayTimeLevel() > this.defaultMessageStore.getScheduleMessageService().getMaxDelayLevel()) {
    +                    msg.setDelayTimeLevel(this.defaultMessageStore.getScheduleMessageService().getMaxDelayLevel());
    +                }
    +
    +                topic = ScheduleMessageService.SCHEDULE_TOPIC;
    +                queueId = ScheduleMessageService.delayLevel2QueueId(msg.getDelayTimeLevel());
    +
    +                // Backup real topic, queueId
    +                MessageAccessor.putProperty(msg, MessageConst.PROPERTY_REAL_TOPIC, msg.getTopic());
    +                MessageAccessor.putProperty(msg, MessageConst.PROPERTY_REAL_QUEUE_ID, String.valueOf(msg.getQueueId()));
    +                msg.setPropertiesString(MessageDecoder.messageProperties2String(msg.getProperties()));
    +
    +                msg.setTopic(topic);
    +                msg.setQueueId(queueId);
    +            }
             }
    -        return DatabaseType.MASTER1.getName();
    -    }
    -}
    -

    而如何使用这个 lookupKey 呢,就涉及到我们的 DataSource 配置了,原来就是我们可以直接通过spring 的 jdbc 配置数据源,像这样

    -

    -

    现在我们要使用 Druid 作为数据源了,然后配置 DynamicDataSource 的参数,通过 key 来选择对应的 DataSource,也就是下面配的 master1 和 master2

    -
    <bean id="master1" class="com.alibaba.druid.pool.DruidDataSource" init-method="init"
    -          destroy-method="close"
    -          p:driverClassName="com.mysql.cj.jdbc.Driver"
    -          p:url="${master1.demo.datasource.url}"
    -          p:username="${master1.demo.datasource.username}"
    -          p:password="${master1.demo.datasource.password}"
    -          p:initialSize="5"
    -          p:minIdle="1"
    -          p:maxActive="10"
    -          p:maxWait="60000"
    -          p:timeBetweenEvictionRunsMillis="60000"
    -          p:minEvictableIdleTimeMillis="300000"
    -          p:validationQuery="SELECT 'x'"
    -          p:testWhileIdle="true"
    -          p:testOnBorrow="false"
    -          p:testOnReturn="false"
    -          p:poolPreparedStatements="false"
    -          p:maxPoolPreparedStatementPerConnectionSize="20"
    -          p:connectionProperties="config.decrypt=true"
    -          p:filters="stat,config"/>
    +        long eclipseTimeInLock = 0;
    +        MappedFile unlockMappedFile = null;
    +        MappedFile mappedFile = this.mappedFileQueue.getLastMappedFile();
     
    -    <bean id="master2" class="com.alibaba.druid.pool.DruidDataSource" init-method="init"
    -          destroy-method="close"
    -          p:driverClassName="com.mysql.cj.jdbc.Driver"
    -          p:url="${master2.demo.datasource.url}"
    -          p:username="${master2.demo.datasource.username}"
    -          p:password="${master2.demo.datasource.password}"
    -          p:initialSize="5"
    -          p:minIdle="1"
    -          p:maxActive="10"
    -          p:maxWait="60000"
    -          p:timeBetweenEvictionRunsMillis="60000"
    -          p:minEvictableIdleTimeMillis="300000"
    -          p:validationQuery="SELECT 'x'"
    -          p:testWhileIdle="true"
    -          p:testOnBorrow="false"
    -          p:testOnReturn="false"
    -          p:poolPreparedStatements="false"
    -          p:maxPoolPreparedStatementPerConnectionSize="20"
    -          p:connectionProperties="config.decrypt=true"
    -          p:filters="stat,config"/>
    +        putMessageLock.lock(); //spin or ReentrantLock ,depending on store config
    +        try {
    +            long beginLockTimestamp = this.defaultMessageStore.getSystemClock().now();
    +            this.beginTimeInLock = beginLockTimestamp;
     
    -    <bean id="dataSource" class="com.nicksxs.springdemo.config.DynamicDataSource">
    -        <property name="targetDataSources">
    -            <map key-type="java.lang.String">
    -                <!-- master -->
    -                <entry key="master1" value-ref="master1"/>
    -                <!-- slave -->
    -                <entry key="master2" value-ref="master2"/>
    -            </map>
    -        </property>
    -        <property name="defaultTargetDataSource" ref="master1"/>
    -    </bean>
    + // Here settings are stored timestamp, in order to ensure an orderly + // global + msg.setStoreTimestamp(beginLockTimestamp); -

    现在就要回到头上,介绍下这个DatabaseContextHolder,这里使用了 ThreadLocal 存放这个 DatabaseType,为啥要用这个是因为前面说的我们想要让接口层面去配置不同的数据源,要把持相互隔离不受影响,就使用了 ThreadLocal,关于它也可以看我前面写的一篇文章聊聊传说中的 ThreadLocal,而 DatabaseType 就是个简单的枚举

    -
    public class DatabaseContextHolder {
    -    public static final ThreadLocal<DatabaseType> databaseTypeThreadLocal = new ThreadLocal<>();
    +            if (null == mappedFile || mappedFile.isFull()) {
    +                mappedFile = this.mappedFileQueue.getLastMappedFile(0); // Mark: NewFile may be cause noise
    +            }
    +            if (null == mappedFile) {
    +                log.error("create mapped file1 error, topic: " + msg.getTopic() + " clientAddr: " + msg.getBornHostString());
    +                beginTimeInLock = 0;
    +                return new PutMessageResult(PutMessageStatus.CREATE_MAPEDFILE_FAILED, null);
    +            }
     
    -    public static DatabaseType getDatabaseType() {
    -        return databaseTypeThreadLocal.get();
    -    }
    +            result = mappedFile.appendMessage(msg, this.appendMessageCallback);
    +            switch (result.getStatus()) {
    +                case PUT_OK:
    +                    break;
    +                case END_OF_FILE:
    +                    unlockMappedFile = mappedFile;
    +                    // Create a new file, re-write the message
    +                    mappedFile = this.mappedFileQueue.getLastMappedFile(0);
    +                    if (null == mappedFile) {
    +                        // XXX: warn and notify me
    +                        log.error("create mapped file2 error, topic: " + msg.getTopic() + " clientAddr: " + msg.getBornHostString());
    +                        beginTimeInLock = 0;
    +                        return new PutMessageResult(PutMessageStatus.CREATE_MAPEDFILE_FAILED, result);
    +                    }
    +                    result = mappedFile.appendMessage(msg, this.appendMessageCallback);
    +                    break;
    +                case MESSAGE_SIZE_EXCEEDED:
    +                case PROPERTIES_SIZE_EXCEEDED:
    +                    beginTimeInLock = 0;
    +                    return new PutMessageResult(PutMessageStatus.MESSAGE_ILLEGAL, result);
    +                case UNKNOWN_ERROR:
    +                    beginTimeInLock = 0;
    +                    return new PutMessageResult(PutMessageStatus.UNKNOWN_ERROR, result);
    +                default:
    +                    beginTimeInLock = 0;
    +                    return new PutMessageResult(PutMessageStatus.UNKNOWN_ERROR, result);
    +            }
     
    -    public static void putDatabaseType(DatabaseType databaseType) {
    -        databaseTypeThreadLocal.set(databaseType);
    -    }
    +            eclipseTimeInLock = this.defaultMessageStore.getSystemClock().now() - beginLockTimestamp;
    +            beginTimeInLock = 0;
    +        } finally {
    +            putMessageLock.unlock();
    +        }
     
    -    public static void clearDatabaseType() {
    -        databaseTypeThreadLocal.remove();
    -    }
    -}
    -public enum DatabaseType {
    -    MASTER1("master1", "1"),
    -    MASTER2("master2", "2");
    +        if (eclipseTimeInLock > 500) {
    +            log.warn("[NOTIFYME]putMessage in lock cost time(ms)={}, bodyLength={} AppendMessageResult={}", eclipseTimeInLock, msg.getBody().length, result);
    +        }
    +
    +        if (null != unlockMappedFile && this.defaultMessageStore.getMessageStoreConfig().isWarmMapedFileEnable()) {
    +            this.defaultMessageStore.unlockMappedFile(unlockMappedFile);
    +        }
    +
    +        PutMessageResult putMessageResult = new PutMessageResult(PutMessageStatus.PUT_OK, result);
    +
    +        // Statistics
    +        storeStatsService.getSinglePutMessageTopicTimesTotal(msg.getTopic()).incrementAndGet();
    +        storeStatsService.getSinglePutMessageTopicSizeTotal(topic).addAndGet(result.getWroteBytes());
    +
    +        handleDiskFlush(result, putMessageResult, msg);
    +        handleHA(result, putMessageResult, msg);
    +
    +        return putMessageResult;
    +    }
    + +

    前面也看到在CommitLog 目录下是有大小为 1G 的文件组成,在实现逻辑中,其实是通过 org.apache.rocketmq.store.MappedFileQueue ,内部是存的一个MappedFile的队列,对于写入的场景每次都是通过org.apache.rocketmq.store.MappedFileQueue#getLastMappedFile() 获取最后一个文件,如果还没有创建,或者最后这个文件已经满了,那就调用 org.apache.rocketmq.store.MappedFileQueue#getLastMappedFile(long)

    +
    public MappedFile getLastMappedFile(final long startOffset, boolean needCreate) {
    +        long createOffset = -1;
    +  			// 调用前面的方法,只是从 mappedFileQueue 获取最后一个
    +        MappedFile mappedFileLast = getLastMappedFile();
    +
    +        // 如果为空,计算下创建的偏移量
    +        if (mappedFileLast == null) {
    +            createOffset = startOffset - (startOffset % this.mappedFileSize);
    +        }
    +  
    +				// 如果不为空,但是当前的文件写满了
    +        if (mappedFileLast != null && mappedFileLast.isFull()) {
    +            // 前一个的偏移量加上单个文件的偏移量,也就是 1G
    +            createOffset = mappedFileLast.getFileFromOffset() + this.mappedFileSize;
    +        }
    +
    +        if (createOffset != -1 && needCreate) {
    +            // 根据 createOffset 转换成文件名进行创建
    +            String nextFilePath = this.storePath + File.separator + UtilAll.offset2FileName(createOffset);
    +            String nextNextFilePath = this.storePath + File.separator
    +                + UtilAll.offset2FileName(createOffset + this.mappedFileSize);
    +            MappedFile mappedFile = null;
    +
    +          	// 这里如果allocateMappedFileService 存在,就提交请求
    +            if (this.allocateMappedFileService != null) {
    +                mappedFile = this.allocateMappedFileService.putRequestAndReturnMappedFile(nextFilePath,
    +                    nextNextFilePath, this.mappedFileSize);
    +            } else {
    +                try {
    +                  // 否则就直接创建
    +                    mappedFile = new MappedFile(nextFilePath, this.mappedFileSize);
    +                } catch (IOException e) {
    +                    log.error("create mappedFile exception", e);
    +                }
    +            }
    +
    +            if (mappedFile != null) {
    +                if (this.mappedFiles.isEmpty()) {
    +                    mappedFile.setFirstCreateInQueue(true);
    +                }
    +                this.mappedFiles.add(mappedFile);
    +            }
     
    -    private final String name;
    -    private final String value;
    +            return mappedFile;
    +        }
     
    -    DatabaseType(String name, String value) {
    -        this.name = name;
    -        this.value = value;
    -    }
    +        return mappedFileLast;
    +    }
    - public String getName() { - return name; +

    首先看下直接创建的,

    +
    public MappedFile(final String fileName, final int fileSize) throws IOException {
    +        init(fileName, fileSize);
         }
    +private void init(final String fileName, final int fileSize) throws IOException {
    +        this.fileName = fileName;
    +        this.fileSize = fileSize;
    +        this.file = new File(fileName);
    +        this.fileFromOffset = Long.parseLong(this.file.getName());
    +        boolean ok = false;
     
    -    public String getValue() {
    -        return value;
    -    }
    +        ensureDirOK(this.file.getParent());
     
    -    public static DatabaseType getDatabaseType(String name) {
    -        if (MASTER2.name.equals(name)) {
    -            return MASTER2;
    +        try {
    +          // 通过 RandomAccessFile 创建 fileChannel
    +            this.fileChannel = new RandomAccessFile(this.file, "rw").getChannel();
    +          // 做 mmap 映射
    +            this.mappedByteBuffer = this.fileChannel.map(MapMode.READ_WRITE, 0, fileSize);
    +            TOTAL_MAPPED_VIRTUAL_MEMORY.addAndGet(fileSize);
    +            TOTAL_MAPPED_FILES.incrementAndGet();
    +            ok = true;
    +        } catch (FileNotFoundException e) {
    +            log.error("create file channel " + this.fileName + " Failed. ", e);
    +            throw e;
    +        } catch (IOException e) {
    +            log.error("map file " + this.fileName + " Failed. ", e);
    +            throw e;
    +        } finally {
    +            if (!ok && this.fileChannel != null) {
    +                this.fileChannel.close();
    +            }
             }
    -        return MASTER1;
    -    }
    -}
    + }
    -

    这边可以看到就是通过动态地通过putDatabaseType设置lookupKey来进行数据源切换,要通过接口注解配置来进行设置的话,我们就需要一个注解

    -
    @Retention(RetentionPolicy.RUNTIME)
    -@Target(ElementType.METHOD)
    -public @interface DataSource {
    -    String value();
    -}
    +

    如果是提交给AllocateMappedFileService的话就用到了一些异步操作

    +
    public MappedFile putRequestAndReturnMappedFile(String nextFilePath, String nextNextFilePath, int fileSize) {
    +        int canSubmitRequests = 2;
    +        if (this.messageStore.getMessageStoreConfig().isTransientStorePoolEnable()) {
    +            if (this.messageStore.getMessageStoreConfig().isFastFailIfNoBufferInStorePool()
    +                && BrokerRole.SLAVE != this.messageStore.getMessageStoreConfig().getBrokerRole()) { //if broker is slave, don't fast fail even no buffer in pool
    +                canSubmitRequests = this.messageStore.getTransientStorePool().remainBufferNumbs() - this.requestQueue.size();
    +            }
    +        }
    +				// 将请求放在 requestTable 中
    +        AllocateRequest nextReq = new AllocateRequest(nextFilePath, fileSize);
    +        boolean nextPutOK = this.requestTable.putIfAbsent(nextFilePath, nextReq) == null;
    +        // requestTable 使用了 concurrentHashMap,用文件名作为 key,防止并发
    +        if (nextPutOK) {
    +            // 这里判断了是否可以提交到 TransientStorePool,涉及读写分离,后面再细聊
    +            if (canSubmitRequests <= 0) {
    +                log.warn("[NOTIFYME]TransientStorePool is not enough, so create mapped file error, " +
    +                    "RequestQueueSize : {}, StorePoolSize: {}", this.requestQueue.size(), this.messageStore.getTransientStorePool().remainBufferNumbs());
    +                this.requestTable.remove(nextFilePath);
    +                return null;
    +            }
    +          // 塞到阻塞队列中
    +            boolean offerOK = this.requestQueue.offer(nextReq);
    +            if (!offerOK) {
    +                log.warn("never expected here, add a request to preallocate queue failed");
    +            }
    +            canSubmitRequests--;
    +        }
     
    -

    这个注解可以配置在我的接口方法上,比如这样

    -
    public interface StudentService {
    +        // 这里的两个提交我猜测是为了多生成一个 CommitLog,
    +        AllocateRequest nextNextReq = new AllocateRequest(nextNextFilePath, fileSize);
    +        boolean nextNextPutOK = this.requestTable.putIfAbsent(nextNextFilePath, nextNextReq) == null;
    +        if (nextNextPutOK) {
    +            if (canSubmitRequests <= 0) {
    +                log.warn("[NOTIFYME]TransientStorePool is not enough, so skip preallocate mapped file, " +
    +                    "RequestQueueSize : {}, StorePoolSize: {}", this.requestQueue.size(), this.messageStore.getTransientStorePool().remainBufferNumbs());
    +                this.requestTable.remove(nextNextFilePath);
    +            } else {
    +                boolean offerOK = this.requestQueue.offer(nextNextReq);
    +                if (!offerOK) {
    +                    log.warn("never expected here, add a request to preallocate queue failed");
    +                }
    +            }
    +        }
     
    -    @DataSource("master1")
    -    public Student queryOne();
    +        if (hasException) {
    +            log.warn(this.getServiceName() + " service has exception. so return null");
    +            return null;
    +        }
     
    -    @DataSource("master2")
    -    public Student queryAnother();
    +        AllocateRequest result = this.requestTable.get(nextFilePath);
    +        try {
    +          // 这里就异步等着
    +            if (result != null) {
    +                boolean waitOK = result.getCountDownLatch().await(waitTimeOut, TimeUnit.MILLISECONDS);
    +                if (!waitOK) {
    +                    log.warn("create mmap timeout " + result.getFilePath() + " " + result.getFileSize());
    +                    return null;
    +                } else {
    +                    this.requestTable.remove(nextFilePath);
    +                    return result.getMappedFile();
    +                }
    +            } else {
    +                log.error("find preallocate mmap failed, this never happen");
    +            }
    +        } catch (InterruptedException e) {
    +            log.warn(this.getServiceName() + " service has exception. ", e);
    +        }
     
    -}
    + return null; + }
    -

    通过切面来进行数据源的设置

    -
    @Aspect
    -@Component
    -@Order(-1)
    -public class DataSourceAspect {
    +

    而真正去执行文件操作的就是 AllocateMappedFileService的 run 方法

    +
    public void run() {
    +        log.info(this.getServiceName() + " service started");
     
    -    @Pointcut("execution(* com.nicksxs.springdemo.service..*.*(..))")
    -    public void pointCut() {
    +        while (!this.isStopped() && this.mmapOperation()) {
     
    +        }
    +        log.info(this.getServiceName() + " service end");
         }
    -
    -
    -    @Before("pointCut()")
    -    public void before(JoinPoint point)
    -    {
    -        Object target = point.getTarget();
    -        System.out.println(target.toString());
    -        String method = point.getSignature().getName();
    -        System.out.println(method);
    -        Class<?>[] classz = target.getClass().getInterfaces();
    -        Class<?>[] parameterTypes = ((MethodSignature) point.getSignature())
    -                .getMethod().getParameterTypes();
    +private boolean mmapOperation() {
    +        boolean isSuccess = false;
    +        AllocateRequest req = null;
             try {
    -            Method m = classz[0].getMethod(method, parameterTypes);
    -            System.out.println("method"+ m.getName());
    -            if (m.isAnnotationPresent(DataSource.class)) {
    -                DataSource data = m.getAnnotation(DataSource.class);
    -                System.out.println("dataSource:"+data.value());
    -                DatabaseContextHolder.putDatabaseType(DatabaseType.getDatabaseType(data.value()));
    +          // 从阻塞队列里获取请求
    +            req = this.requestQueue.take();
    +            AllocateRequest expectedRequest = this.requestTable.get(req.getFilePath());
    +            if (null == expectedRequest) {
    +                log.warn("this mmap request expired, maybe cause timeout " + req.getFilePath() + " "
    +                    + req.getFileSize());
    +                return true;
    +            }
    +            if (expectedRequest != req) {
    +                log.warn("never expected here,  maybe cause timeout " + req.getFilePath() + " "
    +                    + req.getFileSize() + ", req:" + req + ", expectedRequest:" + expectedRequest);
    +                return true;
                 }
     
    -        } catch (Exception e) {
    -            e.printStackTrace();
    +            if (req.getMappedFile() == null) {
    +                long beginTime = System.currentTimeMillis();
    +
    +                MappedFile mappedFile;
    +                if (messageStore.getMessageStoreConfig().isTransientStorePoolEnable()) {
    +                    try {
    +                      // 通过 transientStorePool 创建
    +                        mappedFile = ServiceLoader.load(MappedFile.class).iterator().next();
    +                        mappedFile.init(req.getFilePath(), req.getFileSize(), messageStore.getTransientStorePool());
    +                    } catch (RuntimeException e) {
    +                        log.warn("Use default implementation.");
    +                      // 默认创建
    +                        mappedFile = new MappedFile(req.getFilePath(), req.getFileSize(), messageStore.getTransientStorePool());
    +                    }
    +                } else {
    +                  // 默认创建
    +                    mappedFile = new MappedFile(req.getFilePath(), req.getFileSize());
    +                }
    +
    +                long eclipseTime = UtilAll.computeEclipseTimeMilliseconds(beginTime);
    +                if (eclipseTime > 10) {
    +                    int queueSize = this.requestQueue.size();
    +                    log.warn("create mappedFile spent time(ms) " + eclipseTime + " queue size " + queueSize
    +                        + " " + req.getFilePath() + " " + req.getFileSize());
    +                }
    +
    +                // pre write mappedFile
    +                if (mappedFile.getFileSize() >= this.messageStore.getMessageStoreConfig()
    +                    .getMapedFileSizeCommitLog()
    +                    &&
    +                    this.messageStore.getMessageStoreConfig().isWarmMapedFileEnable()) {
    +                    mappedFile.warmMappedFile(this.messageStore.getMessageStoreConfig().getFlushDiskType(),
    +                        this.messageStore.getMessageStoreConfig().getFlushLeastPagesWhenWarmMapedFile());
    +                }
    +
    +                req.setMappedFile(mappedFile);
    +                this.hasException = false;
    +                isSuccess = true;
    +            }
    +        } catch (InterruptedException e) {
    +            log.warn(this.getServiceName() + " interrupted, possibly by shutdown.");
    +            this.hasException = true;
    +            return false;
    +        } catch (IOException e) {
    +            log.warn(this.getServiceName() + " service has exception. ", e);
    +            this.hasException = true;
    +            if (null != req) {
    +                requestQueue.offer(req);
    +                try {
    +                    Thread.sleep(1);
    +                } catch (InterruptedException ignored) {
    +                }
    +            }
    +        } finally {
    +            if (req != null && isSuccess)
    +              // 通知前面等待的
    +                req.getCountDownLatch().countDown();
             }
    -    }
    +        return true;
    +    }
    - @After("pointCut()") - public void after() { - DatabaseContextHolder.clearDatabaseType(); - } -}
    -

    通过接口判断是否带有注解跟是注解的值,DatabaseType 的配置不太好,不过先忽略了,然后在切点后进行清理

    -

    这是我 master1 的数据,

    -

    -

    master2 的数据

    -

    -

    然后跑一下简单的 demo,

    -
    @Override
    -public void run(String...args) {
    -	LOGGER.info("run here");
    -	System.out.println(studentService.queryOne());
    -	System.out.println(studentService.queryAnother());
     
    -}
    -

    看一下运行结果

    -

    -

    其实这个方法应用场景不止可以用来迁移数据库,还能实现精细化的读写数据源分离之类的,算是做个简单记录和分享。

    -]]>
    - - Java - SpringBoot - - - Java - Spring - SpringBoot - Druid - 数据源动态切换 - -
    - - 聊在东京奥运会闭幕式这天-二 - /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/ - 这届奥运会有可能是我除了 08 年之外关注度最高的一届奥运会,原因可能是因为最近也没什么电影综艺啥的比较好看,前面看跑男倒还行,不是说多好,也就图一乐,最开始看向往的生活觉得也挺不错的,后面变成了统一来了就看黄磊做饭,然后夸黄磊做饭好吃,然后无聊的说这种生活多么多么美好,单调无聊,差不多弃了,这里面还包括大华不在了,大华其实个人还是有点呱噪的,但是挺能搞气氛,并且也有才华,彭彭跟子枫人是不讨厌,但是撑不起来,所以也导致了前面说的结果,都变成了黄磊彩虹屁现场,虽然偶尔怀疑他是否做得好吃,但是整体还是承认的,可对于一个这么多季了的综艺来说,这样也有点单调了。

    -

    还有奥运会像乒乓球,篮球,跳水这几个都是比较喜欢的项目,篮球🏀是从初中开始就也有在自己在玩的,虽然因为身高啊体质基本没什么天赋,但也算是热爱驱动,差不多到了大学因为比较懒才放下了,初中高中还是有很多时间花在上面,不像别人经常打球跑跑跳跳还能长高,我反而一直都没长个子,也因为这个其实蛮遗憾的,后面想想可能是初中的时候远走他乡去住宿读初中,伙食营养跟不上导致的,可能也是自己的一厢情愿吧,总觉得应该还能再长点个,这一点以后我自己的小孩我应该会特别注意这段时间他/她的营养摄入了;然后像乒乓球🏓的话其实小时候是比较讨厌的,因为家里人,父母都没有这类爱好习惯,我也完全不会,但是小学那会班里的“恶霸”就以公平之名要我们男生每个人都排队打几个,我这种不会的反而又要被嘲笑,这个小时候的阴影让我有了比较不好的印象,对它🏓的改观是在工作以后,前司跟一个同样不会的同事经常在饭点会打打,而且那会因为这个其实身体得到了锻炼,感觉是个不错的健身方式,然后又是中国的优势项目,小时候跟着我爸看孔令辉,那时候完全不懂,印象就觉得老瓦很牛,后面其实也没那么关注,上一届好像看了马龙的比赛;跳水也是中国的优势项目,而且也比较简单,不是说真的很简单,就是我们外行观众看着就看看水花大小图一乐。

    -

    这次的观赛过程其实主要还是在乒乓球上面,现在都有点怪我的乌鸦嘴,混双我一直就不太放心(关我什么事,我也不专业),然后一直觉得混双是不是不太稳,结果那天看的时候也是因为央视一套跟五套都没放,我家的有线电视又是没有五加体育,然后用电脑投屏就很卡,看得也很不爽,同时那天因为看的时候已经是 2:0还是再后面点了,一方面是不懂每队只有一次暂停,另一方面不知道已经用过暂停了,所以就特别怀疑马林是不是只会无脑鼓掌,感觉作为教练,并且是前冠军,应该也能在擦汗间隙,或者局间休息调整的时候多给些战略战术的指导,类似于后面男团小胖打奥恰洛夫,像解说都看出来了,其实奥恰那会的反手特别顺,打得特别凶,那就不能让他能特别顺手的上反手位,这当然是外行比较粗浅的看法,在混双过程中其实除了这个,还有让人很不爽的就是我们的许昕跟刘诗雯有种拿不出破釜沉舟的勇气的感觉,在气势上完全被对面两位日本乒乓球最讨厌的两位对手压制着,我都要输了,我就每一颗都要不让你好过,因为真的不是说没有实力,对面水谷隼也不是多么多么强的,可能上一届男团许昕输给他还留着阴影,但是以许昕 19 年男单世界第一的实力,目前也排在世界前三,输一场不应该成为这种阻力,有一些失误也很可惜,后面孙颖莎真的打得很解气,第二局一度以为又要被翻盘了,结果来了个大逆转,女团的时候也是,感觉在心态上孙颖莎还是很值得肯定的,少年老成这个词很适合,看其他的视频也觉得莎莎萌萌哒,陈梦总感觉还欠一点王者霸气,王曼昱还是可以的,反手很凶,我觉得其实这一届日本女乒就是打得非常凶,即使像平野这种看着很弱的妹子,打的球可一点都不弱,也是这种凶狠的打法,有点要压制中国的感觉,这方面我觉得是需要改善的,打这种要不就是实力上的完全碾压,要不就是我实力虽然比较没强多少,但是你狠我打得比你还狠,越保守越要输,我不太成熟的想法是这样的,还有就是面对逆境,这个就要说到男队的了,樊振东跟马龙在半决赛的时候,特别是男团的第二盘,樊振东打奥恰很好地表现了这个心态,当然樊振东我不是特别了解,据说他是比较善于打相持,比较善于焦灼的情况,不过整体看下来樊振东还是有一些欠缺,就是面对情况的快速转变应对,这一点也是马龙特别强的,虽然看起来马龙真的是年纪大了点,没有 16 年那会满头发胶,油光锃亮的大背头和满脸胶原蛋白的意气风发,大范围运动能力也弱了一点,但是经验和能力的全面性也让他最终能再次站上巅峰,还是非常佩服的,这里提一下张继科,虽然可能天赋上是张继科更强点,但是男乒一直都是有强者出现,能为国家队付出这么多并且一直坚持的可不是人人都可以,即使现在同台竞技马龙打不过张继科我还是更喜欢马龙。再来说说我们的对手,主要分三部分,德国男乒,里面有波尔(我刚听到的时候在想怎么又出来个叫波尔的,是不是像举重的石智勇一样,又来一个同名的,结果是同一个,已经四十岁了),这真是个让人敬佩的对手,实力强,经验丰富,虽然男单有点可惜,但是帮助男团获得银牌,真的是起到了定海神针的作用;奥恰洛夫,以前完全不认识,或者说看过也忘了,这次是真的有点意外,竟然有这么个马龙护法,其实他也坦言非常想赢一次马龙,并且在半决赛也非常接近赢得比赛,是个实力非常强的对手,就是男团半决赛输给张本智和有点可惜,有点被打蒙的感觉,佛朗西斯卡的话也是实力不错的选手,就是可能被奥恰跟波尔的光芒掩盖了,跟波尔在男团第一盘男双的比赛中打败日本那对男双也是非常给力的,说实话,最后打国乒的时候的确是国乒实力更胜一筹,但是即使德国赢了我也是充满尊敬,拼的就是硬实力,就像第二盘奥恰打樊振东,反手是真的很强,反过来看奥恰可能也不是很善于快速调整,樊振东打出来自己的节奏,主攻奥恰的中路,他好像没什么好办法解决。再来说我最讨厌的日本,嗯,小日本,张本智和、水谷隼、伊藤美诚,一一评价下(我是外行,绝对主观评价),张本智和,父母也是中国人,原来叫张智和,改日本籍后加了个本,被微博网友笑称日本尖叫鸡,男单输给了斯洛文尼亚选手,男团里是赢了两场,但是在我看来其实实力上可能比不上全力的奥恰,主要是特别能叫,会干扰对手,如果觉得这种也是种能力我也无话可说,要是有那种吼声能直接把对手震聋的,都不需要打比赛了,我简单记了下,赢一颗球,他要叫八声,用 LD 的话来说烦都烦死了,心态是在面对一些困境顺境的应对调整适应能力,而不是对这种噪音的适应能力,至少我是这么看的,所以我很期待樊振东能好好地虐虐他,因为其他像林昀儒真的是非常优秀的新选手,所谓的国乒克星估计也是小日本自己说说的,国乒其实有很多对手,马龙跟樊振东在男单半决赛碰到的这两个几乎都差点把他们掀翻了,所以还是练好自己的实力再来吹吧,免得打脸;水谷隼的话真的是长相就是特别地讨厌,还搞出那套不打比赛的姿态,男团里被波尔干掉就是很好的例子,波尔虽然真的很强,但毕竟 40 岁了,跟伊藤美诚一起说了吧,伊藤实力说实话是有的,混双中很大一部分的赢面来自于她,刘诗雯做了手术状态不好,许昕失误稍多,但是这种赢球了就感觉我赢了你一辈子一场没输的感觉,还有那种不知道怎么形容的笑,实力强的正常打比赛的我都佩服,像女团决赛里,平野跟石川佳纯的打法其实也很凶狠,但是都是正常的比赛,即使中国队两位实力不济输了也很正常,这种就真的需要像孙颖莎这样的小魔王无视各种魔法攻击,无视你各种花里胡哨的打法的人好好教训一下,混双输了以后了解了下她,感觉实力真的不错,是个大威胁,但是其实我们孙颖莎也是经历了九个月的继续成长,像张怡宁也评价了她,可能后面就没什么空间了,当然如果由张怡宁来打她就更适合了,净整这些有的没的,就打得你没脾气。

    -

    乒乓球的说的有点多,就分篇说了,第一篇先到这。

    ]]>
    - 生活 - 运动 + MQ + RocketMQ + 消息队列 - 生活 - 运动 - 东京奥运会 - 乒乓球 - 跳水 + MQ + 消息队列 + RocketMQ
    - 聊一下 RocketMQ 的 DefaultMQPushConsumer 源码 - /2020/06/26/%E8%81%8A%E4%B8%80%E4%B8%8B-RocketMQ-%E7%9A%84-Consumer/ - 首先看下官方的小 demo

    -
    public static void main(String[] args) throws InterruptedException, MQClientException {
    +    聊一下 SpringBoot 中使用的 cglib 作为动态代理中的一个注意点
    +    /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/
    +    这个话题是由一次组内同学分享引出来的,首先在 springboot 2.x 开始默认使用了 cglib 作为 aop 的实现,这里也稍微讲一下,在一个 1.x 的老项目里,可以看到AopAutoConfiguration 是这样的

    +
    @Configuration
    +@ConditionalOnClass({ EnableAspectJAutoProxy.class, Aspect.class, Advice.class })
    +@ConditionalOnProperty(prefix = "spring.aop", name = "auto", havingValue = "true", matchIfMissing = true)
    +public class AopAutoConfiguration {
     
    -        /*
    -         * Instantiate with specified consumer group name.
    -         * 首先是new 一个对象出来,然后指定 Consumer 的 Group
    -         * 同一类Consumer的集合,这类Consumer通常消费同一类消息且消费逻辑一致。消费者组使得在消息消费方面,实现负载均衡和容错的目标变得非常容易。要注意的是,消费者组的消费者实例必须订阅完全相同的Topic。RocketMQ 支持两种消息模式:集群消费(Clustering)和广播消费(Broadcasting)。
    -         */
    -        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("please_rename_unique_group_name_4");
    +	@Configuration
    +	@EnableAspectJAutoProxy(proxyTargetClass = false)
    +	@ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "false", matchIfMissing = true)
    +	public static class JdkDynamicAutoProxyConfiguration {
    +	}
     
    -        /*
    -         * Specify name server addresses.
    -         * <p/>
    -         * 这里可以通知指定环境变量或者设置对象参数的形式指定名字空间服务的地址
    -         *
    -         * Alternatively, you may specify name server addresses via exporting environmental variable: NAMESRV_ADDR
    -         * <pre>
    -         * {@code
    -         * consumer.setNamesrvAddr("name-server1-ip:9876;name-server2-ip:9876");
    -         * }
    -         * </pre>
    -         */
    +	@Configuration
    +	@EnableAspectJAutoProxy(proxyTargetClass = true)
    +	@ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "true", matchIfMissing = false)
    +	public static class CglibAutoProxyConfiguration {
    +	}
     
    -        /*
    -         * Specify where to start in case the specified consumer group is a brand new one.
    -         * 指定消费起始点
    -         */
    -        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
    +}
    - /* - * Subscribe one more more topics to consume. - * 指定订阅的 topic 跟 tag,注意后面的是个表达式,可以以 tag1 || tag2 || tag3 传入 - */ - consumer.subscribe("TopicTest", "*"); +

    而在 2.x 中变成了这样

    +
    @Configuration(proxyBeanMethods = false)
    +@ConditionalOnProperty(prefix = "spring.aop", name = "auto", havingValue = "true", matchIfMissing = true)
    +public class AopAutoConfiguration {
     
    -        /*
    -         *  Register callback to execute on arrival of messages fetched from brokers.
    -         *  注册具体获得消息后的处理方法
    -         */
    -        consumer.registerMessageListener(new MessageListenerConcurrently() {
    +	@Configuration(proxyBeanMethods = false)
    +	@ConditionalOnClass(Advice.class)
    +	static class AspectJAutoProxyingConfiguration {
     
    -            @Override
    -            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
    -                ConsumeConcurrentlyContext context) {
    -                System.out.printf("%s Receive New Messages: %s %n", Thread.currentThread().getName(), msgs);
    -                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    -            }
    -        });
    +		@Configuration(proxyBeanMethods = false)
    +		@EnableAspectJAutoProxy(proxyTargetClass = false)
    +		@ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "false")
    +		static class JdkDynamicAutoProxyConfiguration {
     
    -        /*
    -         *  Launch the consumer instance.
    -         * 启动消费者
    -         */
    -        consumer.start();
    +		}
     
    -        System.out.printf("Consumer Started.%n");
    -    }
    + @Configuration(proxyBeanMethods = false) + @EnableAspectJAutoProxy(proxyTargetClass = true) + @ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "true", + matchIfMissing = true) + static class CglibAutoProxyConfiguration { -

    然后就是看看 start 的过程了

    -
    /**
    -     * This method gets internal infrastructure readily to serve. Instances must call this method after configuration.
    -     *
    -     * @throws MQClientException if there is any client error.
    -     */
    -    @Override
    -    public void start() throws MQClientException {
    -        setConsumerGroup(NamespaceUtil.wrapNamespace(this.getNamespace(), this.consumerGroup));
    -        this.defaultMQPushConsumerImpl.start();
    -        if (null != traceDispatcher) {
    -            try {
    -                traceDispatcher.start(this.getNamesrvAddr(), this.getAccessChannel());
    -            } catch (MQClientException e) {
    -                log.warn("trace dispatcher start failed ", e);
    -            }
    -        }
    -    }
    -

    具体的逻辑在this.defaultMQPushConsumerImpl.start(),这个 defaultMQPushConsumerImpl 就是

    -
    /**
    -     * Internal implementation. Most of the functions herein are delegated to it.
    -     */
    -    protected final transient DefaultMQPushConsumerImpl defaultMQPushConsumerImpl;
    + } -
    public synchronized void start() throws MQClientException {
    -        switch (this.serviceState) {
    -            case CREATE_JUST:
    -                log.info("the consumer [{}] start beginning. messageModel={}, isUnitMode={}", this.defaultMQPushConsumer.getConsumerGroup(),
    -                    this.defaultMQPushConsumer.getMessageModel(), this.defaultMQPushConsumer.isUnitMode());
    -                // 这里比较巧妙,相当于想设立了个屏障,防止并发启动,不过这里并不是悲观锁,也不算个严格的乐观锁
    -                this.serviceState = ServiceState.START_FAILED;
    +	}
    - this.checkConfig(); +

    为何会加载 AopAutoConfiguration 在前面的文章聊聊 SpringBoot 自动装配里已经介绍过,有兴趣的可以看下,可以发现 springboot 在 2.x 版本开始使用 cglib 作为默认的动态代理实现。

    +

    然后就是出现的问题了,代码是这样的,一个简单的基于 springboot 的带有数据库的插入,对插入代码加了事务注解,

    +
    @Mapper
    +public interface StudentMapper {
    +		// 就是插入一条数据
    +    @Insert("insert into student(name, age)" + "values ('nick', '18')")
    +    public Long insert();
    +}
     
    -                this.copySubscription();
    +@Component
    +public class StudentManager {
     
    -                if (this.defaultMQPushConsumer.getMessageModel() == MessageModel.CLUSTERING) {
    -                    this.defaultMQPushConsumer.changeInstanceNameToPID();
    -                }
    +    @Resource
    +    private StudentMapper studentMapper;
    +    
    +    public Long createStudent() {
    +        return studentMapper.insert();
    +    }
    +}
     
    -                // 这个mQClientFactory,负责管理client(consumer、producer),并提供多中功能接口供各个Service(Rebalance、PullMessage等)调用;大部分逻辑均在这个类中完成
    -                this.mQClientFactory = MQClientManager.getInstance().getOrCreateMQClientInstance(this.defaultMQPushConsumer, this.rpcHook);
    +@Component
    +public class StudentServiceImpl implements StudentService {
     
    -                // 这个 rebalanceImpl 主要负责决定,当前的consumer应该从哪些Queue中消费消息;
    -                this.rebalanceImpl.setConsumerGroup(this.defaultMQPushConsumer.getConsumerGroup());
    -                this.rebalanceImpl.setMessageModel(this.defaultMQPushConsumer.getMessageModel());
    -                this.rebalanceImpl.setAllocateMessageQueueStrategy(this.defaultMQPushConsumer.getAllocateMessageQueueStrategy());
    -                this.rebalanceImpl.setmQClientFactory(this.mQClientFactory);
    +    @Resource
    +    private StudentManager studentManager;
     
    -                // 长连接,负责从broker处拉取消息,然后利用ConsumeMessageService回调用户的Listener执行消息消费逻辑
    -                this.pullAPIWrapper = new PullAPIWrapper(
    -                    mQClientFactory,
    -                    this.defaultMQPushConsumer.getConsumerGroup(), isUnitMode());
    -                this.pullAPIWrapper.registerFilterMessageHook(filterMessageHookList);
    +    // 自己引用
    +    @Resource
    +    private StudentServiceImpl studentService;
     
    -                if (this.defaultMQPushConsumer.getOffsetStore() != null) {
    -                    this.offsetStore = this.defaultMQPushConsumer.getOffsetStore();
    -                } else {
    -                    switch (this.defaultMQPushConsumer.getMessageModel()) {
    -                        case BROADCASTING:
    -                            this.offsetStore = new LocalFileOffsetStore(this.mQClientFactory, this.defaultMQPushConsumer.getConsumerGroup());
    -                            break;
    -                        case CLUSTERING:
    -                            this.offsetStore = new RemoteBrokerOffsetStore(this.mQClientFactory, this.defaultMQPushConsumer.getConsumerGroup());
    -                            break;
    -                        default:
    -                            break;
    -                    }
    -                    this.defaultMQPushConsumer.setOffsetStore(this.offsetStore);
    -                }
    -                // offsetStore 维护当前consumer的消费记录(offset);有两种实现,Local和Rmote,Local存储在本地磁盘上,适用于BROADCASTING广播消费模式;而Remote则将消费进度存储在Broker上,适用于CLUSTERING集群消费模式;
    -                this.offsetStore.load();
    +    @Override
    +    @Transactional
    +    public Long createStudent() {
    +        Long id = studentManager.createStudent();
    +        Long id2 = studentService.createStudent2();
    +        return 1L;
    +    }
    +
    +    @Transactional
    +    private Long createStudent2() {
    +//        Integer t = Integer.valueOf("aaa");
    +        return studentManager.createStudent();
    +    }
    +}
    + +

    第一个公有方法 createStudent 首先调用了 manager 层的创建方法,然后再通过引入的 studentService 调用了createStudent2,我们先跑一下看看会出现啥情况,果不其然报错了,正是这个报错让我纠结了很久

    +

    EdR7oB

    +

    报了个空指针,而且是在 createStudent2 已经被调用到了,在它的内部,报的 studentManager 是 null,首先 cglib 作为动态代理它是通过继承的方式来实现的,相当于是会在调用目标对象的代理方法时调用 cglib 生成的子类,具体的代理切面逻辑在子类实现,然后在调用目标对象的目标方法,但是继承的方式对于 final 和私有方法其实是没法进行代理的,因为没法继承,所以我最开始的想法是应该通过 studentService 调用 createStudent2 的时候就报错了,也就是不会进入这个方法内部,后面才发现犯了个特别二的错误,继承的方式去调用父类的私有方法,对于 Java 来说是可以调用到的,父类的私有方法并不由子类的InstanceKlass维护,只能通过子类的InstanceKlass找到Java类对应的_super,这样间接地访问。也就是说子类其实是可以访问的,那为啥访问了会报空指针呢,这里报的是studentManager 是空的,可以往依赖注入方面去想,如果忽略依赖注入,我这个studentManager 的确是 null,那是不是就没有被依赖注入呢,但是为啥前面那个可以呢

    +

    这个问题着实查了很久,不废话来看代码

    +
    @Override
    +		protected Object invokeJoinpoint() throws Throwable {
    +			if (this.methodProxy != null) {
    +        // 这里的 target 就是被代理的 bean
    +				return this.methodProxy.invoke(this.target, this.arguments);
    +			}
    +			else {
    +				return super.invokeJoinpoint();
    +			}
    +		}
    - if (this.getMessageListenerInner() instanceof MessageListenerOrderly) { - this.consumeOrderly = true; - this.consumeMessageService = - new ConsumeMessageOrderlyService(this, (MessageListenerOrderly) this.getMessageListenerInner()); - } else if (this.getMessageListenerInner() instanceof MessageListenerConcurrently) { - this.consumeOrderly = false; - this.consumeMessageService = - new ConsumeMessageConcurrentlyService(this, (MessageListenerConcurrently) this.getMessageListenerInner()); - } - // 实现所谓的"Push-被动"消费机制;从Broker拉取的消息后,封装成ConsumeRequest提交给ConsumeMessageSerivce,此service负责回调用户的Listener消费消息; - this.consumeMessageService.start(); - boolean registerOK = mQClientFactory.registerConsumer(this.defaultMQPushConsumer.getConsumerGroup(), this); - if (!registerOK) { - this.serviceState = ServiceState.CREATE_JUST; - this.consumeMessageService.shutdown(); - throw new MQClientException("The consumer group[" + this.defaultMQPushConsumer.getConsumerGroup() - + "] has been created before, specify another name please." + FAQUrl.suggestTodo(FAQUrl.GROUP_NAME_DUPLICATE_URL), - null); - } +

    这个是org.springframework.aop.framework.CglibAopProxy.CglibMethodInvocation的代码,其实它在这里不是直接调用 super 也就是父类的方法,而是通过 methodProxy 调用 target 目标对象的方法,也就是原始的 studentService bean 的方法,这样子 spring 管理的已经做好依赖注入的 bean 就能正常起作用,否则就会出现上面的问题,因为 cglib 其实是通过继承来实现,通过将调用转移到子类上加入代理逻辑,我们在简单使用的时候会直接 invokeSuper() 调用父类的方法,但是在这里 spring 的场景里需要去支持 spring 的功能逻辑,所以上面的问题就可以开始来解释了,因为 createStudent 是公共方法,cglib 可以对其进行继承代理,但是在执行逻辑的时候其实是通过调用目标对象,也就是 spring 管理的被代理的目标对象的 bean 调用的 createStudent,而对于下面的 createStudent2 方法因为是私有方法,不会走代理逻辑,也就不会有调用回目标对象的逻辑,只是通过继承关系,在子类中没有这个方法,所以会通过子类的InstanceKlass找到这个类对应的_super,然后调用父类的这个私有方法,这里要搞清楚一个点,从这个代理类直接找到其父类然后调用这个私有方法,这个类是由 cglib 生成的,不是被 spring 管理起来经过依赖注入的 bean,所以是没有 studentManager 这个依赖的,也就出现了前面的问题

    +

    而在前面提到的cglib通过methodProxy调用到目标对象,目标对象是在什么时候设置的呢,其实是在bean的生命周期中,org.springframework.beans.factory.config.BeanPostProcessor#postProcessAfterInitialization这个接口的在bean的初始化过程中,会调用实现了这个接口的方法,

    +
    @Override
    +public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
    +	if (bean != null) {
    +		Object cacheKey = getCacheKey(bean.getClass(), beanName);
    +		if (this.earlyProxyReferences.remove(cacheKey) != bean) {
    +			return wrapIfNecessary(bean, beanName, cacheKey);
    +		}
    +	}
    +	return bean;
    +}
    - mQClientFactory.start(); - log.info("the consumer [{}] start OK.", this.defaultMQPushConsumer.getConsumerGroup()); - this.serviceState = ServiceState.RUNNING; - break; - case RUNNING: - case START_FAILED: - case SHUTDOWN_ALREADY: - throw new MQClientException("The PushConsumer service state not OK, maybe started once, " - + this.serviceState - + FAQUrl.suggestTodo(FAQUrl.CLIENT_SERVICE_NOT_OK), - null); - default: - break; - } +

    具体的逻辑在 org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#wrapIfNecessary这个方法里

    +
    protected Object getCacheKey(Class<?> beanClass, @Nullable String beanName) {
    +		if (StringUtils.hasLength(beanName)) {
    +			return (FactoryBean.class.isAssignableFrom(beanClass) ?
    +					BeanFactory.FACTORY_BEAN_PREFIX + beanName : beanName);
    +		}
    +		else {
    +			return beanClass;
    +		}
    +	}
     
    -        this.updateTopicSubscribeInfoWhenSubscriptionChanged();
    -        this.mQClientFactory.checkClientInBroker();
    -        this.mQClientFactory.sendHeartbeatToAllBrokerWithLock();
    -        this.mQClientFactory.rebalanceImmediately();
    -    }
    -

    然后我们往下看主要的目光聚焦mQClientFactory.start()

    -
    public void start() throws MQClientException {
    +	/**
    +	 * Wrap the given bean if necessary, i.e. if it is eligible for being proxied.
    +	 * @param bean the raw bean instance
    +	 * @param beanName the name of the bean
    +	 * @param cacheKey the cache key for metadata access
    +	 * @return a proxy wrapping the bean, or the raw bean instance as-is
    +	 */
    +	protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
    +		if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
    +			return bean;
    +		}
    +		if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
    +			return bean;
    +		}
    +		if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
    +			this.advisedBeans.put(cacheKey, Boolean.FALSE);
    +			return bean;
    +		}
     
    -        synchronized (this) {
    -            switch (this.serviceState) {
    -                case CREATE_JUST:
    -                    this.serviceState = ServiceState.START_FAILED;
    -                    // If not specified,looking address from name server
    -                    if (null == this.clientConfig.getNamesrvAddr()) {
    -                        this.mQClientAPIImpl.fetchNameServerAddr();
    -                    }
    -                    // Start request-response channel
    -                    // 这里主要是初始化了个网络客户端
    -                    this.mQClientAPIImpl.start();
    -                    // Start various schedule tasks
    -                    // 定时任务
    -                    this.startScheduledTask();
    -                    // Start pull service
    -                    // 这里重点说下
    -                    this.pullMessageService.start();
    -                    // Start rebalance service
    -                    this.rebalanceService.start();
    -                    // Start push service
    -                    this.defaultMQProducer.getDefaultMQProducerImpl().start(false);
    -                    log.info("the client factory [{}] start OK", this.clientId);
    -                    this.serviceState = ServiceState.RUNNING;
    -                    break;
    -                case START_FAILED:
    -                    throw new MQClientException("The Factory object[" + this.getClientId() + "] has been created before, and failed.", null);
    -                default:
    -                    break;
    -            }
    -        }
    -    }
    -

    我们来看下这个 pullMessageService,org.apache.rocketmq.client.impl.consumer.PullMessageService,

    实现了 runnable 接口,
    然后可以看到 run 方法

    -
    public void run() {
    -        log.info(this.getServiceName() + " service started");
    +		// 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;
    +		}
     
    -        while (!this.isStopped()) {
    -            try {
    -                PullRequest pullRequest = this.pullRequestQueue.take();
    -                this.pullMessage(pullRequest);
    -            } catch (InterruptedException ignored) {
    -            } catch (Exception e) {
    -                log.error("Pull Message Service Run Method exception", e);
    -            }
    -        }
    +		this.advisedBeans.put(cacheKey, Boolean.FALSE);
    +		return bean;
    +	}
    - log.info(this.getServiceName() + " service end"); - }
    -

    接着在看 pullMessage 方法

    -
    private void pullMessage(final PullRequest pullRequest) {
    -        final MQConsumerInner consumer = this.mQClientFactory.selectConsumer(pullRequest.getConsumerGroup());
    -        if (consumer != null) {
    -            DefaultMQPushConsumerImpl impl = (DefaultMQPushConsumerImpl) consumer;
    -            impl.pullMessage(pullRequest);
    -        } else {
    -            log.warn("No matched consumer for the PullRequest {}, drop it", pullRequest);
    -        }
    -    }
    -

    实际上调用了这个方法,这个方法很长,我在代码里注释下下每一段的功能

    -
    public void pullMessage(final PullRequest pullRequest) {
    -        final ProcessQueue processQueue = pullRequest.getProcessQueue();
    -        // 这里开始就是检查状态,确定是否往下执行
    -        if (processQueue.isDropped()) {
    -            log.info("the pull request[{}] is dropped.", pullRequest.toString());
    -            return;
    -        }
    +

    然后在 org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#createProxy 中创建了代理类

    +]]> + + Java + SpringBoot + + + Java + Spring + SpringBoot + cglib + 事务 + + + + 聊一下 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 {
     
    -        pullRequest.getProcessQueue().setLastPullTimestamp(System.currentTimeMillis());
    +    @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;
    +            }
     
    -        try {
    -            this.makeSureStateOK();
    -        } catch (MQClientException e) {
    -            log.warn("pullMessage exception, consumer state not ok", e);
    -            this.executePullRequestLater(pullRequest, pullTimeDelayMillsWhenException);
    -            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 (this.isPause()) {
    -            log.warn("consumer was paused, execute pull request later. instanceName={}, group={}", this.defaultMQPushConsumer.getInstanceName(), this.defaultMQPushConsumer.getConsumerGroup());
    -            this.executePullRequestLater(pullRequest, PULL_TIME_DELAY_MILLS_WHEN_SUSPEND);
    -            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;
     
    -        // 这块其实是个类似于限流的功能块,对消息数量和消息大小做限制
    -        long cachedMessageCount = processQueue.getMsgCount().get();
    -        long cachedMessageSizeInMiB = processQueue.getMsgSize().get() / (1024 * 1024);
    +            FileLock fileLock = null;
     
    -        if (cachedMessageCount > this.defaultMQPushConsumer.getPullThresholdForQueue()) {
    -            this.executePullRequestLater(pullRequest, PULL_TIME_DELAY_MILLS_WHEN_FLOW_CONTROL);
    -            if ((queueFlowControlTimes++ % 1000) == 0) {
    -                log.warn(
    -                    "the cached message count exceeds the threshold {}, so do flow control, minOffset={}, maxOffset={}, count={}, size={} MiB, pullRequest={}, flowControlTimes={}",
    -                    this.defaultMQPushConsumer.getPullThresholdForQueue(), processQueue.getMsgTreeMap().firstKey(), processQueue.getMsgTreeMap().lastKey(), cachedMessageCount, cachedMessageSizeInMiB, pullRequest, queueFlowControlTimes);
    -            }
    -            return;
    -        }
    +            try {
     
    -        if (cachedMessageSizeInMiB > this.defaultMQPushConsumer.getPullThresholdSizeForQueue()) {
    -            this.executePullRequestLater(pullRequest, PULL_TIME_DELAY_MILLS_WHEN_FLOW_CONTROL);
    -            if ((queueFlowControlTimes++ % 1000) == 0) {
    -                log.warn(
    -                    "the cached message size exceeds the threshold {} MiB, so do flow control, minOffset={}, maxOffset={}, count={}, size={} MiB, pullRequest={}, flowControlTimes={}",
    -                    this.defaultMQPushConsumer.getPullThresholdSizeForQueue(), processQueue.getMsgTreeMap().firstKey(), processQueue.getMsgTreeMap().lastKey(), cachedMessageCount, cachedMessageSizeInMiB, pullRequest, queueFlowControlTimes);
    -            }
    -            return;
    -        }
    +                // fileLock = this.fileChannel.lock(absSlotPos, hashSlotSize,
    +                // false);
    +                int slotValue = this.mappedByteBuffer.getInt(absSlotPos);
    +                if (slotValue <= invalidIndex || slotValue > this.indexHeader.getIndexCount()) {
    +                    slotValue = invalidIndex;
    +                }
     
    -        // 若不是顺序消费(即DefaultMQPushConsumerImpl.consumeOrderly等于false),则检查ProcessQueue对象的msgTreeMap:TreeMap<Long,MessageExt>变量的第一个key值与最后一个key值之间的差额,该key值表示查询的队列偏移量queueoffset;若差额大于阈值(由DefaultMQPushConsumer. consumeConcurrentlyMaxSpan指定,默认是2000),则调用PullMessageService.executePullRequestLater方法,在50毫秒之后重新将该PullRequest请求放入PullMessageService.pullRequestQueue队列中;并跳出该方法;这里的意思主要就是消息有堆积了,等会再来拉取
    -        if (!this.consumeOrderly) {
    -            if (processQueue.getMaxSpan() > this.defaultMQPushConsumer.getConsumeConcurrentlyMaxSpan()) {
    -                this.executePullRequestLater(pullRequest, PULL_TIME_DELAY_MILLS_WHEN_FLOW_CONTROL);
    -                if ((queueMaxSpanFlowControlTimes++ % 1000) == 0) {
    -                    log.warn(
    -                        "the queue's messages, span too long, so do flow control, minOffset={}, maxOffset={}, maxSpan={}, pullRequest={}, flowControlTimes={}",
    -                        processQueue.getMsgTreeMap().firstKey(), processQueue.getMsgTreeMap().lastKey(), processQueue.getMaxSpan(),
    -                        pullRequest, queueMaxSpanFlowControlTimes);
    -                }
    -                return;
    -            }
    -        } else {
    -            if (processQueue.isLocked()) {
    -                if (!pullRequest.isLockedFirst()) {
    -                    final long offset = this.rebalanceImpl.computePullFromWhere(pullRequest.getMessageQueue());
    -                    boolean brokerBusy = offset < pullRequest.getNextOffset();
    -                    log.info("the first time to pull message, so fix offset from broker. pullRequest: {} NewOffset: {} brokerBusy: {}",
    -                        pullRequest, offset, brokerBusy);
    -                    if (brokerBusy) {
    -                        log.info("[NOTIFYME]the first time to pull message, but pull request offset larger than broker consume offset. pullRequest: {} NewOffset: {}",
    -                            pullRequest, offset);
    -                    }
    +                long timeDiff = storeTimestamp - this.indexHeader.getBeginTimestamp();
     
    -                    pullRequest.setLockedFirst(true);
    -                    pullRequest.setNextOffset(offset);
    -                }
    -            } else {
    -                this.executePullRequestLater(pullRequest, pullTimeDelayMillsWhenException);
    -                log.info("pull message later because not locked in broker, {}", pullRequest);
    -                return;
    -            }
    -        }
    +                timeDiff = timeDiff / 1000;
     
    -        // 以PullRequest.messageQueue对象的topic值为参数从RebalanceImpl.subscriptionInner: ConcurrentHashMap, SubscriptionData>中获取对应的SubscriptionData对象,若该对象为null,考虑到并发的关系,调用executePullRequestLater方法,稍后重试;并跳出该方法;
    -        final SubscriptionData subscriptionData = this.rebalanceImpl.getSubscriptionInner().get(pullRequest.getMessageQueue().getTopic());
    -        if (null == subscriptionData) {
    -            this.executePullRequestLater(pullRequest, pullTimeDelayMillsWhenException);
    -            log.warn("find the consumer's subscription failed, {}", pullRequest);
    -            return;
    -        }
    +                if (this.indexHeader.getBeginTimestamp() <= 0) {
    +                    timeDiff = 0;
    +                } else if (timeDiff > Integer.MAX_VALUE) {
    +                    timeDiff = Integer.MAX_VALUE;
    +                } else if (timeDiff < 0) {
    +                    timeDiff = 0;
    +                }
     
    -        final long beginTimestamp = System.currentTimeMillis();
    +              // 计算索引存放位置,头部 + 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);
     
    -        // 异步拉取回调,先不讨论细节
    -        PullCallback pullCallback = new PullCallback() {
    -            @Override
    -            public void onSuccess(PullResult pullResult) {
    -                if (pullResult != null) {
    -                    pullResult = DefaultMQPushConsumerImpl.this.pullAPIWrapper.processPullResult(pullRequest.getMessageQueue(), pullResult,
    -                        subscriptionData);
    +              // 存放的是数量位移,不是绝对位置
    +                this.mappedByteBuffer.putInt(absSlotPos, this.indexHeader.getIndexCount());
     
    -                    switch (pullResult.getPullStatus()) {
    -                        case FOUND:
    -                            long prevRequestOffset = pullRequest.getNextOffset();
    -                            pullRequest.setNextOffset(pullResult.getNextBeginOffset());
    -                            long pullRT = System.currentTimeMillis() - beginTimestamp;
    -                            DefaultMQPushConsumerImpl.this.getConsumerStatsManager().incPullRT(pullRequest.getConsumerGroup(),
    -                                pullRequest.getMessageQueue().getTopic(), pullRT);
    +                if (this.indexHeader.getIndexCount() <= 1) {
    +                    this.indexHeader.setBeginPhyOffset(phyOffset);
    +                    this.indexHeader.setBeginTimestamp(storeTimestamp);
    +                }
     
    -                            long firstMsgOffset = Long.MAX_VALUE;
    -                            if (pullResult.getMsgFoundList() == null || pullResult.getMsgFoundList().isEmpty()) {
    -                                DefaultMQPushConsumerImpl.this.executePullRequestImmediately(pullRequest);
    -                            } else {
    -                                firstMsgOffset = pullResult.getMsgFoundList().get(0).getQueueOffset();
    +                this.indexHeader.incHashSlotCount();
    +                this.indexHeader.incIndexCount();
    +                this.indexHeader.setEndPhyOffset(phyOffset);
    +                this.indexHeader.setEndTimestamp(storeTimestamp);
     
    -                                DefaultMQPushConsumerImpl.this.getConsumerStatsManager().incPullTPS(pullRequest.getConsumerGroup(),
    -                                    pullRequest.getMessageQueue().getTopic(), pullResult.getMsgFoundList().size());
    +                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);
    +        }
     
    -                                boolean dispatchToConsume = processQueue.putMessage(pullResult.getMsgFoundList());
    -                                DefaultMQPushConsumerImpl.this.consumeMessageService.submitConsumeRequest(
    -                                    pullResult.getMsgFoundList(),
    -                                    processQueue,
    -                                    pullRequest.getMessageQueue(),
    -                                    dispatchToConsume);
    +        return false;
    +    }
    - if (DefaultMQPushConsumerImpl.this.defaultMQPushConsumer.getPullInterval() > 0) { - DefaultMQPushConsumerImpl.this.executePullRequestLater(pullRequest, - DefaultMQPushConsumerImpl.this.defaultMQPushConsumer.getPullInterval()); - } else { - DefaultMQPushConsumerImpl.this.executePullRequestImmediately(pullRequest); - } - } +

    具体可以看一下这个简略的示意图

    +]]>
    + + MQ + RocketMQ + 消息队列 + + + MQ + 消息队列 + RocketMQ + +
    + + 聊一下 RocketMQ 的顺序消息 + /2021/08/29/%E8%81%8A%E4%B8%80%E4%B8%8B-RocketMQ-%E7%9A%84%E9%A1%BA%E5%BA%8F%E6%B6%88%E6%81%AF/ + rocketmq 里有一种比较特殊的用法,就是顺序消息,比如订单的生命周期里,在创建,支付,签收等状态轮转中,会发出来对应的消息,这里面就比较需要去保证他们的顺序,当然在处理的业务代码也可以做对应的处理,结合消息重投,但是如果这里消息就能保证顺序性了,那么业务代码就能更好的关注业务代码的处理。

    +

    首先有一种情况是全局的有序,比如对于一个 topic 里就得发送线程保证只有一个,内部的 queue 也只有一个,消费线程也只有一个,这样就能比较容易的保证全局顺序性了,但是这里的问题就是完全限制了性能,不是很现实,在真实场景里很多都是比如对于同一个订单,需要去保证状态的轮转是按照预期的顺序来,而不必要全局的有序性。

    +

    对于这类的有序性,需要在发送和接收方都有对应的处理,在发送消息中,需要去指定 selector,即MessageQueueSelector,能够以固定的方式是分配到对应的 MessageQueue

    +

    比如像 RocketMQ 中的示例

    +
    SendResult sendResult = producer.send(msg, new MessageQueueSelector() {
    +                @Override
    +                public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {
    +                    Long id = (Long) arg;  //message queue is selected by #salesOrderID
    +                    long index = id % mqs.size();
    +                    return mqs.get((int) index);
    +                }
    +            }, orderList.get(i).getOrderId());
    - if (pullResult.getNextBeginOffset() < prevRequestOffset - || firstMsgOffset < prevRequestOffset) { - log.warn( - "[BUG] pull message result maybe data wrong, nextBeginOffset: {} firstMsgOffset: {} prevRequestOffset: {}", - pullResult.getNextBeginOffset(), - firstMsgOffset, - prevRequestOffset); - } +

    而在消费侧有几个点比较重要,首先我们要保证一个 MessageQueue只被一个消费者消费,消费队列存在broker端,要保证 MessageQueue 只被一个消费者消费,那么消费者在进行消息拉取消费时就必须向mq服务器申请队列锁,消费者申请队列锁的代码存在于RebalanceService消息队列负载的实现代码中。

    +
    List<PullRequest> pullRequestList = new ArrayList<PullRequest>();
    +        for (MessageQueue mq : mqSet) {
    +            if (!this.processQueueTable.containsKey(mq)) {
    +              // 判断是否顺序,如果是顺序消费的,则需要加锁
    +                if (isOrder && !this.lock(mq)) {
    +                    log.warn("doRebalance, {}, add a new mq failed, {}, because lock failed", consumerGroup, mq);
    +                    continue;
    +                }
     
    -                            break;
    -                        case NO_NEW_MSG:
    -                            pullRequest.setNextOffset(pullResult.getNextBeginOffset());
    +                this.removeDirtyOffset(mq);
    +                ProcessQueue pq = new ProcessQueue();
    +                long nextOffset = this.computePullFromWhere(mq);
    +                if (nextOffset >= 0) {
    +                    ProcessQueue pre = this.processQueueTable.putIfAbsent(mq, pq);
    +                    if (pre != null) {
    +                        log.info("doRebalance, {}, mq already exists, {}", consumerGroup, mq);
    +                    } else {
    +                        log.info("doRebalance, {}, add a new mq, {}", consumerGroup, mq);
    +                        PullRequest pullRequest = new PullRequest();
    +                        pullRequest.setConsumerGroup(consumerGroup);
    +                        pullRequest.setNextOffset(nextOffset);
    +                        pullRequest.setMessageQueue(mq);
    +                        pullRequest.setProcessQueue(pq);
    +                        pullRequestList.add(pullRequest);
    +                        changed = true;
    +                    }
    +                } else {
    +                    log.warn("doRebalance, {}, add new mq failed, {}", consumerGroup, mq);
    +                }
    +            }
    +        }
    - DefaultMQPushConsumerImpl.this.correctTagsOffset(pullRequest); +

    在申请到锁之后会创建 pullRequest 进行消息拉取,消息拉取部分的代码实现在PullMessageService中,

    +
    @Override
    +    public void run() {
    +        log.info(this.getServiceName() + " service started");
     
    -                            DefaultMQPushConsumerImpl.this.executePullRequestImmediately(pullRequest);
    -                            break;
    -                        case NO_MATCHED_MSG:
    -                            pullRequest.setNextOffset(pullResult.getNextBeginOffset());
    +        while (!this.isStopped()) {
    +            try {
    +                PullRequest pullRequest = this.pullRequestQueue.take();
    +                this.pullMessage(pullRequest);
    +            } catch (InterruptedException ignored) {
    +            } catch (Exception e) {
    +                log.error("Pull Message Service Run Method exception", e);
    +            }
    +        }
     
    -                            DefaultMQPushConsumerImpl.this.correctTagsOffset(pullRequest);
    +        log.info(this.getServiceName() + " service end");
    +    }
    + +

    消息拉取完后,需要提交到ConsumeMessageService中进行消费,顺序消费的实现为ConsumeMessageOrderlyService,提交消息进行消费的方法为ConsumeMessageOrderlyService#submitConsumeRequest,具体实现如下:

    +
    @Override
    +public void submitConsumeRequest(
    +    final List<MessageExt> msgs,
    +    final ProcessQueue processQueue,
    +    final MessageQueue messageQueue,
    +    final boolean dispathToConsume) {
    +    if (dispathToConsume) {
    +        ConsumeRequest consumeRequest = new ConsumeRequest(processQueue, messageQueue);
    +        this.consumeExecutor.submit(consumeRequest);
    +    }
    +}
    - DefaultMQPushConsumerImpl.this.executePullRequestImmediately(pullRequest); - break; - case OFFSET_ILLEGAL: - log.warn("the pull request offset illegal, {} {}", - pullRequest.toString(), pullResult.toString()); - pullRequest.setNextOffset(pullResult.getNextBeginOffset()); +

    构建了一个ConsumeRequest对象,它是个实现了 runnable 接口的类,并提交给了线程池来并行消费,看下顺序消费的ConsumeRequest的run方法实现:

    +
    @Override
    +        public void run() {
    +            if (this.processQueue.isDropped()) {
    +                log.warn("run, the message queue not be able to consume, because it's dropped. {}", this.messageQueue);
    +                return;
    +            }
    +						// 获得 Consumer 消息队列锁,即单个线程独占
    +            final Object objLock = messageQueueLock.fetchLockObject(this.messageQueue);
    +            synchronized (objLock) {
    +              // (广播模式) 或者 (集群模式 && Broker消息队列锁有效)
    +                if (MessageModel.BROADCASTING.equals(ConsumeMessageOrderlyService.this.defaultMQPushConsumerImpl.messageModel())
    +                    || (this.processQueue.isLocked() && !this.processQueue.isLockExpired())) {
    +                    final long beginTime = System.currentTimeMillis();
    +                  // 循环
    +                    for (boolean continueConsume = true; continueConsume; ) {
    +                        if (this.processQueue.isDropped()) {
    +                            log.warn("the message queue not be able to consume, because it's dropped. {}", this.messageQueue);
    +                            break;
    +                        }
     
    -                            pullRequest.getProcessQueue().setDropped(true);
    -                            DefaultMQPushConsumerImpl.this.executeTaskLater(new Runnable() {
    +                      // 消息队列分布式锁未锁定,提交延迟获得锁并消费请求
    +                        if (MessageModel.CLUSTERING.equals(ConsumeMessageOrderlyService.this.defaultMQPushConsumerImpl.messageModel())
    +                            && !this.processQueue.isLocked()) {
    +                            log.warn("the message queue not locked, so consume later, {}", this.messageQueue);
    +                            ConsumeMessageOrderlyService.this.tryLockLaterAndReconsume(this.messageQueue, this.processQueue, 10);
    +                            break;
    +                        }
     
    -                                @Override
    -                                public void run() {
    -                                    try {
    -                                        DefaultMQPushConsumerImpl.this.offsetStore.updateOffset(pullRequest.getMessageQueue(),
    -                                            pullRequest.getNextOffset(), false);
    +                      // 消息队列分布式锁已经过期,提交延迟获得锁并消费请求
    +                        if (MessageModel.CLUSTERING.equals(ConsumeMessageOrderlyService.this.defaultMQPushConsumerImpl.messageModel())
    +                            && this.processQueue.isLockExpired()) {
    +                            log.warn("the message queue lock expired, so consume later, {}", this.messageQueue);
    +                            ConsumeMessageOrderlyService.this.tryLockLaterAndReconsume(this.messageQueue, this.processQueue, 10);
    +                            break;
    +                        }
    +												// 当前周期消费时间超过连续时长,默认:60s,提交延迟消费请求。默认情况下,每消费1分钟休息10ms。
    +                        long interval = System.currentTimeMillis() - beginTime;
    +                        if (interval > MAX_TIME_CONSUME_CONTINUOUSLY) {
    +                            ConsumeMessageOrderlyService.this.submitConsumeRequestLater(processQueue, messageQueue, 10);
    +                            break;
    +                        }
    +												// 获取消费消息。此处和并发消息请求不同,并发消息请求已经带了消费哪些消息。
    +                        final int consumeBatchSize =
    +                            ConsumeMessageOrderlyService.this.defaultMQPushConsumer.getConsumeMessageBatchMaxSize();
     
    -                                        DefaultMQPushConsumerImpl.this.offsetStore.persist(pullRequest.getMessageQueue());
    +                        List<MessageExt> msgs = this.processQueue.takeMessags(consumeBatchSize);
    +                        defaultMQPushConsumerImpl.resetRetryAndNamespace(msgs, defaultMQPushConsumer.getConsumerGroup());
    +                        if (!msgs.isEmpty()) {
    +                            final ConsumeOrderlyContext context = new ConsumeOrderlyContext(this.messageQueue);
     
    -                                        DefaultMQPushConsumerImpl.this.rebalanceImpl.removeProcessQueue(pullRequest.getMessageQueue());
    +                            ConsumeOrderlyStatus status = null;
     
    -                                        log.warn("fix the pull request offset, {}", pullRequest);
    -                                    } catch (Throwable e) {
    -                                        log.error("executeTaskLater Exception", e);
    -                                    }
    -                                }
    -                            }, 10000);
    -                            break;
    -                        default:
    -                            break;
    -                    }
    -                }
    -            }
    +                            ConsumeMessageContext consumeMessageContext = null;
    +                            if (ConsumeMessageOrderlyService.this.defaultMQPushConsumerImpl.hasHook()) {
    +                                consumeMessageContext = new ConsumeMessageContext();
    +                                consumeMessageContext
    +                                    .setConsumerGroup(ConsumeMessageOrderlyService.this.defaultMQPushConsumer.getConsumerGroup());
    +                                consumeMessageContext.setNamespace(defaultMQPushConsumer.getNamespace());
    +                                consumeMessageContext.setMq(messageQueue);
    +                                consumeMessageContext.setMsgList(msgs);
    +                                consumeMessageContext.setSuccess(false);
    +                                // init the consume context type
    +                                consumeMessageContext.setProps(new HashMap<String, String>());
    +                                ConsumeMessageOrderlyService.this.defaultMQPushConsumerImpl.executeHookBefore(consumeMessageContext);
    +                            }
    +														// 执行消费
    +                            long beginTimestamp = System.currentTimeMillis();
    +                            ConsumeReturnType returnType = ConsumeReturnType.SUCCESS;
    +                            boolean hasException = false;
    +                            try {
    +                                this.processQueue.getLockConsume().lock(); // 锁定处理队列
    +                                if (this.processQueue.isDropped()) {
    +                                    log.warn("consumeMessage, the message queue not be able to consume, because it's dropped. {}",
    +                                        this.messageQueue);
    +                                    break;
    +                                }
     
    -            @Override
    -            public void onException(Throwable e) {
    -                if (!pullRequest.getMessageQueue().getTopic().startsWith(MixAll.RETRY_GROUP_TOPIC_PREFIX)) {
    -                    log.warn("execute the pull request exception", e);
    -                }
    +                                status = messageListener.consumeMessage(Collections.unmodifiableList(msgs), context);
    +                            } catch (Throwable e) {
    +                                log.warn("consumeMessage exception: {} Group: {} Msgs: {} MQ: {}",
    +                                    RemotingHelper.exceptionSimpleDesc(e),
    +                                    ConsumeMessageOrderlyService.this.consumerGroup,
    +                                    msgs,
    +                                    messageQueue);
    +                                hasException = true;
    +                            } finally {
    +                                this.processQueue.getLockConsume().unlock();  // 解锁
    +                            }
     
    -                DefaultMQPushConsumerImpl.this.executePullRequestLater(pullRequest, pullTimeDelayMillsWhenException);
    -            }
    -        };
    -        // 如果为集群模式,即可置commitOffsetEnable为 true
    -        boolean commitOffsetEnable = false;
    -        long commitOffsetValue = 0L;
    -        if (MessageModel.CLUSTERING == this.defaultMQPushConsumer.getMessageModel()) {
    -            commitOffsetValue = this.offsetStore.readOffset(pullRequest.getMessageQueue(), ReadOffsetType.READ_FROM_MEMORY);
    -            if (commitOffsetValue > 0) {
    -                commitOffsetEnable = true;
    -            }
    -        }
    +                            if (null == status
    +                                || ConsumeOrderlyStatus.ROLLBACK == status
    +                                || ConsumeOrderlyStatus.SUSPEND_CURRENT_QUEUE_A_MOMENT == status) {
    +                                log.warn("consumeMessage Orderly return not OK, Group: {} Msgs: {} MQ: {}",
    +                                    ConsumeMessageOrderlyService.this.consumerGroup,
    +                                    msgs,
    +                                    messageQueue);
    +                            }
     
    -        // 将上面获得的commitOffsetEnable更新到订阅关系里
    -        String subExpression = null;
    -        boolean classFilter = false;
    -        SubscriptionData sd = this.rebalanceImpl.getSubscriptionInner().get(pullRequest.getMessageQueue().getTopic());
    -        if (sd != null) {
    -            if (this.defaultMQPushConsumer.isPostSubscriptionWhenPull() && !sd.isClassFilterMode()) {
    -                subExpression = sd.getSubString();
    -            }
    +                            long consumeRT = System.currentTimeMillis() - beginTimestamp;
    +                            if (null == status) {
    +                                if (hasException) {
    +                                    returnType = ConsumeReturnType.EXCEPTION;
    +                                } else {
    +                                    returnType = ConsumeReturnType.RETURNNULL;
    +                                }
    +                            } else if (consumeRT >= defaultMQPushConsumer.getConsumeTimeout() * 60 * 1000) {
    +                                returnType = ConsumeReturnType.TIME_OUT;
    +                            } else if (ConsumeOrderlyStatus.SUSPEND_CURRENT_QUEUE_A_MOMENT == status) {
    +                                returnType = ConsumeReturnType.FAILED;
    +                            } else if (ConsumeOrderlyStatus.SUCCESS == status) {
    +                                returnType = ConsumeReturnType.SUCCESS;
    +                            }
     
    -            classFilter = sd.isClassFilterMode();
    -        }
    +                            if (ConsumeMessageOrderlyService.this.defaultMQPushConsumerImpl.hasHook()) {
    +                                consumeMessageContext.getProps().put(MixAll.CONSUME_CONTEXT_TYPE, returnType.name());
    +                            }
     
    -        // 组成 sysFlag
    -        int sysFlag = PullSysFlag.buildSysFlag(
    -            commitOffsetEnable, // commitOffset
    -            true, // suspend
    -            subExpression != null, // subscription
    -            classFilter // class filter
    -        );
    -        // 调用真正的拉取消息接口
    -        try {
    -            this.pullAPIWrapper.pullKernelImpl(
    -                pullRequest.getMessageQueue(),
    -                subExpression,
    -                subscriptionData.getExpressionType(),
    -                subscriptionData.getSubVersion(),
    -                pullRequest.getNextOffset(),
    -                this.defaultMQPushConsumer.getPullBatchSize(),
    -                sysFlag,
    -                commitOffsetValue,
    -                BROKER_SUSPEND_MAX_TIME_MILLIS,
    -                CONSUMER_TIMEOUT_MILLIS_WHEN_SUSPEND,
    -                CommunicationMode.ASYNC,
    -                pullCallback
    -            );
    -        } catch (Exception e) {
    -            log.error("pullKernelImpl exception", e);
    -            this.executePullRequestLater(pullRequest, pullTimeDelayMillsWhenException);
    -        }
    -    }
    -

    以下就是拉取消息的底层 api,不够不是特别复杂,主要是在找 broker,和设置请求参数

    -
    public PullResult pullKernelImpl(
    -    final MessageQueue mq,
    -    final String subExpression,
    -    final String expressionType,
    -    final long subVersion,
    -    final long offset,
    -    final int maxNums,
    -    final int sysFlag,
    -    final long commitOffset,
    -    final long brokerSuspendMaxTimeMillis,
    -    final long timeoutMillis,
    -    final CommunicationMode communicationMode,
    -    final PullCallback pullCallback
    -) throws MQClientException, RemotingException, MQBrokerException, InterruptedException {
    -    FindBrokerResult findBrokerResult =
    -        this.mQClientFactory.findBrokerAddressInSubscribe(mq.getBrokerName(),
    -            this.recalculatePullFromWhichNode(mq), false);
    -    if (null == findBrokerResult) {
    -        this.mQClientFactory.updateTopicRouteInfoFromNameServer(mq.getTopic());
    -        findBrokerResult =
    -            this.mQClientFactory.findBrokerAddressInSubscribe(mq.getBrokerName(),
    -                this.recalculatePullFromWhichNode(mq), false);
    -    }
    +                            if (null == status) {
    +                                status = ConsumeOrderlyStatus.SUSPEND_CURRENT_QUEUE_A_MOMENT;
    +                            }
     
    -    if (findBrokerResult != null) {
    -        {
    -            // check version
    -            if (!ExpressionType.isTagType(expressionType)
    -                && findBrokerResult.getBrokerVersion() < MQVersion.Version.V4_1_0_SNAPSHOT.ordinal()) {
    -                throw new MQClientException("The broker[" + mq.getBrokerName() + ", "
    -                    + findBrokerResult.getBrokerVersion() + "] does not upgrade to support for filter message by " + expressionType, null);
    -            }
    -        }
    -        int sysFlagInner = sysFlag;
    +                            if (ConsumeMessageOrderlyService.this.defaultMQPushConsumerImpl.hasHook()) {
    +                                consumeMessageContext.setStatus(status.toString());
    +                                consumeMessageContext
    +                                    .setSuccess(ConsumeOrderlyStatus.SUCCESS == status || ConsumeOrderlyStatus.COMMIT == status);
    +                                ConsumeMessageOrderlyService.this.defaultMQPushConsumerImpl.executeHookAfter(consumeMessageContext);
    +                            }
     
    -        if (findBrokerResult.isSlave()) {
    -            sysFlagInner = PullSysFlag.clearCommitOffsetFlag(sysFlagInner);
    -        }
    +                            ConsumeMessageOrderlyService.this.getConsumerStatsManager()
    +                                .incConsumeRT(ConsumeMessageOrderlyService.this.consumerGroup, messageQueue.getTopic(), consumeRT);
     
    -        PullMessageRequestHeader requestHeader = new PullMessageRequestHeader();
    -        requestHeader.setConsumerGroup(this.consumerGroup);
    -        requestHeader.setTopic(mq.getTopic());
    -        requestHeader.setQueueId(mq.getQueueId());
    -        requestHeader.setQueueOffset(offset);
    -        requestHeader.setMaxMsgNums(maxNums);
    -        requestHeader.setSysFlag(sysFlagInner);
    -        requestHeader.setCommitOffset(commitOffset);
    -        requestHeader.setSuspendTimeoutMillis(brokerSuspendMaxTimeMillis);
    -        requestHeader.setSubscription(subExpression);
    -        requestHeader.setSubVersion(subVersion);
    -        requestHeader.setExpressionType(expressionType);
    +                            continueConsume = ConsumeMessageOrderlyService.this.processConsumeResult(msgs, status, context, this);
    +                        } else {
    +                            continueConsume = false;
    +                        }
    +                    }
    +                } else {
    +                    if (this.processQueue.isDropped()) {
    +                        log.warn("the message queue not be able to consume, because it's dropped. {}", this.messageQueue);
    +                        return;
    +                    }
     
    -        String brokerAddr = findBrokerResult.getBrokerAddr();
    -        if (PullSysFlag.hasClassFilterFlag(sysFlagInner)) {
    -            brokerAddr = computPullFromWhichFilterServer(mq.getTopic(), brokerAddr);
    -        }
    +                    ConsumeMessageOrderlyService.this.tryLockLaterAndReconsume(this.messageQueue, this.processQueue, 100);
    +                }
    +            }
    +        }
    - PullResult pullResult = this.mQClientFactory.getMQClientAPIImpl().pullMessage( - brokerAddr, - requestHeader, - timeoutMillis, - communicationMode, - pullCallback); +

    获取到锁对象后,使用synchronized尝试申请线程级独占锁。

    +

    如果加锁成功,同一时刻只有一个线程进行消息消费。

    +

    如果加锁失败,会延迟100ms重新尝试向broker端申请锁定messageQueue,锁定成功后重新提交消费请求

    +

    创建消息拉取任务时,消息客户端向broker端申请锁定MessageQueue,使得一个MessageQueue同一个时刻只能被一个消费客户端消费。

    +

    消息消费时,多线程针对同一个消息队列的消费先尝试使用synchronized申请独占锁,加锁成功才能进行消费,使得一个MessageQueue同一个时刻只能被一个消费客户端中一个线程消费。
    这里其实还有很重要的一点是对processQueue的加锁,这里其实是保证了在 rebalance的过程中如果 processQueue 被分配给了另一个 consumer,但是当前已经被我这个 consumer 再消费,但是没提交,就有可能出现被两个消费者消费,所以得进行加锁保证不受 rebalance 影响。

    +]]>
    + + MQ + RocketMQ + 消息队列 + + + MQ + 消息队列 + RocketMQ + +
    + + 聊一下 SpringBoot 中动态切换数据源的方法 + /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/ + 其实这个表示有点不太对,应该是 Druid 动态切换数据源的方法,只是应用在了 springboot 框架中,准备代码准备了半天,之前在一次数据库迁移中使用了,发现 Druid 还是很强大的,用来做动态数据源切换很方便。

    +

    首先这里的场景跟我原来用的有点点区别,在项目中使用的是通过配置中心控制数据源切换,统一切换,而这里的例子多加了个可以根据接口注解配置

    +

    第一部分是最核心的,如何基于 Spring JDBC 和 Druid 来实现数据源切换,是继承了org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource 这个类,他的determineCurrentLookupKey方法会被调用来获得用来决定选择那个数据源的对象,也就是 lookupKey,也可以通过这个类看到就是通过这个 lookupKey 来路由找到数据源。

    +
    public class DynamicDataSource extends AbstractRoutingDataSource {
     
    -        return pullResult;
    -    }
    +    @Override
    +    protected Object determineCurrentLookupKey() {
    +        if (DatabaseContextHolder.getDatabaseType() != null) {
    +            return DatabaseContextHolder.getDatabaseType().getName();
    +        }
    +        return DatabaseType.MASTER1.getName();
    +    }
    +}
    - throw new MQClientException("The broker[" + mq.getBrokerName() + "] not exist", null); -}
    -

    再看下一步的

    -
    public PullResult pullMessage(
    -    final String addr,
    -    final PullMessageRequestHeader requestHeader,
    -    final long timeoutMillis,
    -    final CommunicationMode communicationMode,
    -    final PullCallback pullCallback
    -) throws RemotingException, MQBrokerException, InterruptedException {
    -    RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.PULL_MESSAGE, requestHeader);
    +

    而如何使用这个 lookupKey 呢,就涉及到我们的 DataSource 配置了,原来就是我们可以直接通过spring 的 jdbc 配置数据源,像这样

    +

    +

    现在我们要使用 Druid 作为数据源了,然后配置 DynamicDataSource 的参数,通过 key 来选择对应的 DataSource,也就是下面配的 master1 和 master2

    +
    <bean id="master1" class="com.alibaba.druid.pool.DruidDataSource" init-method="init"
    +          destroy-method="close"
    +          p:driverClassName="com.mysql.cj.jdbc.Driver"
    +          p:url="${master1.demo.datasource.url}"
    +          p:username="${master1.demo.datasource.username}"
    +          p:password="${master1.demo.datasource.password}"
    +          p:initialSize="5"
    +          p:minIdle="1"
    +          p:maxActive="10"
    +          p:maxWait="60000"
    +          p:timeBetweenEvictionRunsMillis="60000"
    +          p:minEvictableIdleTimeMillis="300000"
    +          p:validationQuery="SELECT 'x'"
    +          p:testWhileIdle="true"
    +          p:testOnBorrow="false"
    +          p:testOnReturn="false"
    +          p:poolPreparedStatements="false"
    +          p:maxPoolPreparedStatementPerConnectionSize="20"
    +          p:connectionProperties="config.decrypt=true"
    +          p:filters="stat,config"/>
     
    -    switch (communicationMode) {
    -        case ONEWAY:
    -            assert false;
    -            return null;
    -        case ASYNC:
    -            this.pullMessageAsync(addr, request, timeoutMillis, pullCallback);
    -            return null;
    -        case SYNC:
    -            return this.pullMessageSync(addr, request, timeoutMillis);
    -        default:
    -            assert false;
    -            break;
    -    }
    +    <bean id="master2" class="com.alibaba.druid.pool.DruidDataSource" init-method="init"
    +          destroy-method="close"
    +          p:driverClassName="com.mysql.cj.jdbc.Driver"
    +          p:url="${master2.demo.datasource.url}"
    +          p:username="${master2.demo.datasource.username}"
    +          p:password="${master2.demo.datasource.password}"
    +          p:initialSize="5"
    +          p:minIdle="1"
    +          p:maxActive="10"
    +          p:maxWait="60000"
    +          p:timeBetweenEvictionRunsMillis="60000"
    +          p:minEvictableIdleTimeMillis="300000"
    +          p:validationQuery="SELECT 'x'"
    +          p:testWhileIdle="true"
    +          p:testOnBorrow="false"
    +          p:testOnReturn="false"
    +          p:poolPreparedStatements="false"
    +          p:maxPoolPreparedStatementPerConnectionSize="20"
    +          p:connectionProperties="config.decrypt=true"
    +          p:filters="stat,config"/>
     
    -    return null;
    -}
    -

    通过 communicationMode 判断是同步拉取还是异步拉取,异步就调用

    -
    private void pullMessageAsync(
    -        final String addr,
    -        final RemotingCommand request,
    -        final long timeoutMillis,
    -        final PullCallback pullCallback
    -    ) throws RemotingException, InterruptedException {
    -        this.remotingClient.invokeAsync(addr, request, timeoutMillis, new InvokeCallback() {
    -            @Override
    -            public void operationComplete(ResponseFuture responseFuture) {
    -                异步
    -                RemotingCommand response = responseFuture.getResponseCommand();
    -                if (response != null) {
    -                    try {
    -                        PullResult pullResult = MQClientAPIImpl.this.processPullResponse(response);
    -                        assert pullResult != null;
    -                        pullCallback.onSuccess(pullResult);
    -                    } catch (Exception e) {
    -                        pullCallback.onException(e);
    -                    }
    -                } else {
    -                    if (!responseFuture.isSendRequestOK()) {
    -                        pullCallback.onException(new MQClientException("send request failed to " + addr + ". Request: " + request, responseFuture.getCause()));
    -                    } else if (responseFuture.isTimeout()) {
    -                        pullCallback.onException(new MQClientException("wait response from " + addr + " timeout :" + responseFuture.getTimeoutMillis() + "ms" + ". Request: " + request,
    -                            responseFuture.getCause()));
    -                    } else {
    -                        pullCallback.onException(new MQClientException("unknown reason. addr: " + addr + ", timeoutMillis: " + timeoutMillis + ". Request: " + request, responseFuture.getCause()));
    -                    }
    -                }
    -            }
    -        });
    -    }
    -

    并且会调用前面 pullCallback 的onSuccess和onException方法,同步的就是调用

    -
    private PullResult pullMessageSync(
    -        final String addr,
    -        final RemotingCommand request,
    -        final long timeoutMillis
    -    ) throws RemotingException, InterruptedException, MQBrokerException {
    -        RemotingCommand response = this.remotingClient.invokeSync(addr, request, timeoutMillis);
    -        assert response != null;
    -        return this.processPullResponse(response);
    -    }
    -

    然后就是这个 remotingClient 的 invokeAsync 跟 invokeSync 方法

    -
    @Override
    -    public void invokeAsync(String addr, RemotingCommand request, long timeoutMillis, InvokeCallback invokeCallback)
    -        throws InterruptedException, RemotingConnectException, RemotingTooMuchRequestException, RemotingTimeoutException,
    -        RemotingSendRequestException {
    -        long beginStartTime = System.currentTimeMillis();
    -        final Channel channel = this.getAndCreateChannel(addr);
    -        if (channel != null && channel.isActive()) {
    -            try {
    -                doBeforeRpcHooks(addr, request);
    -                long costTime = System.currentTimeMillis() - beginStartTime;
    -                if (timeoutMillis < costTime) {
    -                    throw new RemotingTooMuchRequestException("invokeAsync call timeout");
    -                }
    -                this.invokeAsyncImpl(channel, request, timeoutMillis - costTime, invokeCallback);
    -            } catch (RemotingSendRequestException e) {
    -                log.warn("invokeAsync: send request exception, so close the channel[{}]", addr);
    -                this.closeChannel(addr, channel);
    -                throw e;
    -            }
    -        } else {
    -            this.closeChannel(addr, channel);
    -            throw new RemotingConnectException(addr);
    -        }
    -    }
    -@Override
    -    public RemotingCommand invokeSync(String addr, final RemotingCommand request, long timeoutMillis)
    -        throws InterruptedException, RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException {
    -        long beginStartTime = System.currentTimeMillis();
    -        final Channel channel = this.getAndCreateChannel(addr);
    -        if (channel != null && channel.isActive()) {
    -            try {
    -                doBeforeRpcHooks(addr, request);
    -                long costTime = System.currentTimeMillis() - beginStartTime;
    -                if (timeoutMillis < costTime) {
    -                    throw new RemotingTimeoutException("invokeSync call timeout");
    -                }
    -                RemotingCommand response = this.invokeSyncImpl(channel, request, timeoutMillis - costTime);
    -                doAfterRpcHooks(RemotingHelper.parseChannelRemoteAddr(channel), request, response);
    -                return response;
    -            } catch (RemotingSendRequestException e) {
    -                log.warn("invokeSync: send request exception, so close the channel[{}]", addr);
    -                this.closeChannel(addr, channel);
    -                throw e;
    -            } catch (RemotingTimeoutException e) {
    -                if (nettyClientConfig.isClientCloseSocketIfTimeout()) {
    -                    this.closeChannel(addr, channel);
    -                    log.warn("invokeSync: close socket because of timeout, {}ms, {}", timeoutMillis, addr);
    -                }
    -                log.warn("invokeSync: wait response timeout exception, the channel[{}]", addr);
    -                throw e;
    -            }
    -        } else {
    -            this.closeChannel(addr, channel);
    -            throw new RemotingConnectException(addr);
    -        }
    -    }
    -

    再往下看

    -
    public RemotingCommand invokeSyncImpl(final Channel channel, final RemotingCommand request,
    -        final long timeoutMillis)
    -        throws InterruptedException, RemotingSendRequestException, RemotingTimeoutException {
    -        final int opaque = request.getOpaque();
    +    <bean id="dataSource" class="com.nicksxs.springdemo.config.DynamicDataSource">
    +        <property name="targetDataSources">
    +            <map key-type="java.lang.String">
    +                <!-- master -->
    +                <entry key="master1" value-ref="master1"/>
    +                <!-- slave -->
    +                <entry key="master2" value-ref="master2"/>
    +            </map>
    +        </property>
    +        <property name="defaultTargetDataSource" ref="master1"/>
    +    </bean>
    - try { - 同步跟异步都是会把结果用ResponseFuture抱起来 - final ResponseFuture responseFuture = new ResponseFuture(channel, opaque, timeoutMillis, null, null); - this.responseTable.put(opaque, responseFuture); - final SocketAddress addr = channel.remoteAddress(); - channel.writeAndFlush(request).addListener(new ChannelFutureListener() { - @Override - public void operationComplete(ChannelFuture f) throws Exception { - if (f.isSuccess()) { - responseFuture.setSendRequestOK(true); - return; - } else { - responseFuture.setSendRequestOK(false); - } +

    现在就要回到头上,介绍下这个DatabaseContextHolder,这里使用了 ThreadLocal 存放这个 DatabaseType,为啥要用这个是因为前面说的我们想要让接口层面去配置不同的数据源,要把持相互隔离不受影响,就使用了 ThreadLocal,关于它也可以看我前面写的一篇文章聊聊传说中的 ThreadLocal,而 DatabaseType 就是个简单的枚举

    +
    public class DatabaseContextHolder {
    +    public static final ThreadLocal<DatabaseType> databaseTypeThreadLocal = new ThreadLocal<>();
    +
    +    public static DatabaseType getDatabaseType() {
    +        return databaseTypeThreadLocal.get();
    +    }
     
    -                    responseTable.remove(opaque);
    -                    responseFuture.setCause(f.cause());
    -                    responseFuture.putResponse(null);
    -                    log.warn("send a request command to channel <" + addr + "> failed.");
    -                }
    -            });
    -            // 区别是同步的是在这等待
    -            RemotingCommand responseCommand = responseFuture.waitResponse(timeoutMillis);
    -            if (null == responseCommand) {
    -                if (responseFuture.isSendRequestOK()) {
    -                    throw new RemotingTimeoutException(RemotingHelper.parseSocketAddressAddr(addr), timeoutMillis,
    -                        responseFuture.getCause());
    -                } else {
    -                    throw new RemotingSendRequestException(RemotingHelper.parseSocketAddressAddr(addr), responseFuture.getCause());
    -                }
    -            }
    +    public static void putDatabaseType(DatabaseType databaseType) {
    +        databaseTypeThreadLocal.set(databaseType);
    +    }
     
    -            return responseCommand;
    -        } finally {
    -            this.responseTable.remove(opaque);
    -        }
    -    }
    +    public static void clearDatabaseType() {
    +        databaseTypeThreadLocal.remove();
    +    }
    +}
    +public enum DatabaseType {
    +    MASTER1("master1", "1"),
    +    MASTER2("master2", "2");
     
    -    public void invokeAsyncImpl(final Channel channel, final RemotingCommand request, final long timeoutMillis,
    -        final InvokeCallback invokeCallback)
    -        throws InterruptedException, RemotingTooMuchRequestException, RemotingTimeoutException, RemotingSendRequestException {
    -        long beginStartTime = System.currentTimeMillis();
    -        final int opaque = request.getOpaque();
    -        boolean acquired = this.semaphoreAsync.tryAcquire(timeoutMillis, TimeUnit.MILLISECONDS);
    -        if (acquired) {
    -            final SemaphoreReleaseOnlyOnce once = new SemaphoreReleaseOnlyOnce(this.semaphoreAsync);
    -            long costTime = System.currentTimeMillis() - beginStartTime;
    -            if (timeoutMillis < costTime) {
    -                once.release();
    -                throw new RemotingTimeoutException("invokeAsyncImpl call timeout");
    -            }
    +    private final String name;
    +    private final String value;
     
    -            final ResponseFuture responseFuture = new ResponseFuture(channel, opaque, timeoutMillis - costTime, invokeCallback, once);
    -            this.responseTable.put(opaque, responseFuture);
    -            try {
    -                channel.writeAndFlush(request).addListener(new ChannelFutureListener() {
    -                    @Override
    -                    public void operationComplete(ChannelFuture f) throws Exception {
    -                        if (f.isSuccess()) {
    -                            responseFuture.setSendRequestOK(true);
    -                            return;
    -                        }
    -                        requestFail(opaque);
    -                        log.warn("send a request command to channel <{}> failed.", RemotingHelper.parseChannelRemoteAddr(channel));
    -                    }
    -                });
    -            } catch (Exception e) {
    -                responseFuture.release();
    -                log.warn("send a request command to channel <" + RemotingHelper.parseChannelRemoteAddr(channel) + "> Exception", e);
    -                throw new RemotingSendRequestException(RemotingHelper.parseChannelRemoteAddr(channel), e);
    -            }
    -        } else {
    -            if (timeoutMillis <= 0) {
    -                throw new RemotingTooMuchRequestException("invokeAsyncImpl invoke too fast");
    -            } else {
    -                String info =
    -                    String.format("invokeAsyncImpl tryAcquire semaphore timeout, %dms, waiting thread nums: %d semaphoreAsyncValue: %d",
    -                        timeoutMillis,
    -                        this.semaphoreAsync.getQueueLength(),
    -                        this.semaphoreAsync.availablePermits()
    -                    );
    -                log.warn(info);
    -                throw new RemotingTimeoutException(info);
    -            }
    -        }
    -    }
    + DatabaseType(String name, String value) { + this.name = name; + this.value = value; + } + public String getName() { + return name; + } + public String getValue() { + return value; + } -]]> - - MQ - RocketMQ - 消息队列 - RocketMQ - 中间件 - RocketMQ - - - MQ - 消息队列 - RocketMQ - 削峰填谷 - 中间件 - 源码解析 - DefaultMQPushConsumer - - - - 聊聊 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);
    +    public static DatabaseType getDatabaseType(String name) {
    +        if (MASTER2.name.equals(name)) {
    +            return MASTER2;
             }
    +        return MASTER1;
    +    }
    +}
    + +

    这边可以看到就是通过动态地通过putDatabaseType设置lookupKey来进行数据源切换,要通过接口注解配置来进行设置的话,我们就需要一个注解

    +
    @Retention(RetentionPolicy.RUNTIME)
    +@Target(ElementType.METHOD)
    +public @interface DataSource {
    +    String value();
    +}
    + +

    这个注解可以配置在我的接口方法上,比如这样

    +
    public interface StudentService {
    +
    +    @DataSource("master1")
    +    public Student queryOne();
    +
    +    @DataSource("master2")
    +    public Student queryAnother();
    +
    +}
    + +

    通过切面来进行数据源的设置

    +
    @Aspect
    +@Component
    +@Order(-1)
    +public class DataSourceAspect {
    +
    +    @Pointcut("execution(* com.nicksxs.springdemo.service..*.*(..))")
    +    public void pointCut() {
    +
    +    }
    +
    +
    +    @Before("pointCut()")
    +    public void before(JoinPoint point)
    +    {
    +        Object target = point.getTarget();
    +        System.out.println(target.toString());
    +        String method = point.getSignature().getName();
    +        System.out.println(method);
    +        Class<?>[] classz = target.getClass().getInterfaces();
    +        Class<?>[] parameterTypes = ((MethodSignature) point.getSignature())
    +                .getMethod().getParameterTypes();
             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));
    -                }
    +            Method m = classz[0].getMethod(method, parameterTypes);
    +            System.out.println("method"+ m.getName());
    +            if (m.isAnnotationPresent(DataSource.class)) {
    +                DataSource data = m.getAnnotation(DataSource.class);
    +                System.out.println("dataSource:"+data.value());
    +                DatabaseContextHolder.putDatabaseType(DatabaseType.getDatabaseType(data.value()));
                 }
    -            return instance;
    -        } catch (Throwable t) {
    -            throw new IllegalStateException("Extension instance(name: " + name + ", class: " +
    -                    type + ")  could not be instantiated: " + t.getMessage(), t);
    +
    +        } catch (Exception e) {
    +            e.printStackTrace();
             }
    -    }
    -

    然后就是创建扩展了,这里如果 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 其实就看构造函数的。

    + } + + @After("pointCut()") + public void after() { + DatabaseContextHolder.clearDatabaseType(); + } +}
    + +

    通过接口判断是否带有注解跟是注解的值,DatabaseType 的配置不太好,不过先忽略了,然后在切点后进行清理

    +

    这是我 master1 的数据,

    +

    +

    master2 的数据

    +

    +

    然后跑一下简单的 demo,

    +
    @Override
    +public void run(String...args) {
    +	LOGGER.info("run here");
    +	System.out.println(studentService.queryOne());
    +	System.out.println(studentService.queryAnother());
    +
    +}
    + +

    看一下运行结果

    +

    +

    其实这个方法应用场景不止可以用来迁移数据库,还能实现精细化的读写数据源分离之类的,算是做个简单记录和分享。

    ]]>
    Java - Dubbo - RPC - SPI - Dubbo - SPI + SpringBoot Java - Dubbo - RPC - SPI + Spring + SpringBoot + Druid + 数据源动态切换 + +
    + + 聊一下 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 岁可能其他项目已经是年龄很大了,不过前面说的举重的吕小军军神也是年纪蛮大了,但是非常强,而且在油管上简直就是个神,相对来说射击是关注比较少,杨倩的也只是看了后面拿到冠军这个结果,有些因为时间或者电视上没放,但是成绩还是不错的,没多少喷点。

    +

    第二篇先到这,纯主观,轻喷。

    +]]>
    + + 生活 + 运动 + + + 生活 + 运动 + 东京奥运会 + 举重 + 射击
    @@ -12038,178 +12103,120 @@ app.setWebAp - 聊聊 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/ - Java并发

    synchronized 的一些学习记录

    -

    jdk1.6 以后对 synchronized 进行了一些优化,包括偏向锁,轻量级锁,重量级锁等

    -

    这些锁的加锁方式大多跟对象头有关,我们可以查看 jdk 代码

    -

    首先对象头的位置注释

    -
    // Bit-format of an object header (most significant first, big endian layout below):
    -//
    -//  32 bits:
    -//  --------
    -//             hash:25 ------------>| age:4    biased_lock:1 lock:2 (normal object)
    -//             JavaThread*:23 epoch:2 age:4    biased_lock:1 lock:2 (biased object)
    -//             size:32 ------------------------------------------>| (CMS free block)
    -//             PromotedObject*:29 ---------->| promo_bits:3 ----->| (CMS promoted object)
    -//
    -//  64 bits:
    -//  --------
    -//  unused:25 hash:31 -->| unused:1   age:4    biased_lock:1 lock:2 (normal object)
    -//  JavaThread*:54 epoch:2 unused:1   age:4    biased_lock:1 lock:2 (biased object)
    -//  PromotedObject*:61 --------------------->| promo_bits:3 ----->| (CMS promoted object)
    -//  size:64 ----------------------------------------------------->| (CMS free block)
    -//
    -//  unused:25 hash:31 -->| cms_free:1 age:4    biased_lock:1 lock:2 (COOPs && normal object)
    -//  JavaThread*:54 epoch:2 cms_free:1 age:4    biased_lock:1 lock:2 (COOPs && biased object)
    -//  narrowOop:32 unused:24 cms_free:1 unused:4 promo_bits:3 ----->| (COOPs && CMS promoted object)
    -//  unused:21 size:35 -->| cms_free:1 unused:7 ------------------>| (COOPs && CMS free block)
    - -
    enum { locked_value             = 0,
    -         unlocked_value           = 1,
    -         monitor_value            = 2,
    -         marked_value             = 3,
    -         biased_lock_pattern      = 5
    -};
    -
    - -

    我们可以用 java jol库来查看对象头,通过一段简单的代码来看下

    -
    public class ObjectHeaderDemo {
    -    public static void main(String[] args) throws InterruptedException {
    -        L l = new L();
    -        System.out.println(ClassLayout.parseInstance(l).toPrintable());
    -		}
    -}
    - -

    Untitled

    -

    然后可以看到打印输出,当然这里因为对齐方式,我们看到的其实顺序是反过来的,按最后三位去看,我们这是 001,好像偏向锁都没开,这里使用的是 jdk1.8,默认开始偏向锁的,其实这里有涉及到了一个配置,jdk1.8 中偏向锁会延迟 4 秒开启,可以通过添加启动参数 -XX:+PrintFlagsFinal,看到

    -

    偏向锁延迟

    -

    因为在初始化的时候防止线程竞争有大量的偏向锁撤销升级,所以会延迟 4s 开启

    -

    我们再来延迟 5s 看看

    -
    public class ObjectHeaderDemo {
    -    public static void main(String[] args) throws InterruptedException {
    -				TimeUnit.SECONDS.sleep(5);
    -        L l = new L();
    -        System.out.println(ClassLayout.parseInstance(l).toPrintable());
    -		}
    -} 
    - -

    https://img.nicksxs.com/uPic/2LBKpX.jpg

    -

    可以看到偏向锁设置已经开启了,我们来是一下加个偏向锁

    -
    public class ObjectHeaderDemo {
    -    public static void main(String[] args) throws InterruptedException {
    -        TimeUnit.SECONDS.sleep(5);
    -        L l = new L();
    -        System.out.println(ClassLayout.parseInstance(l).toPrintable());
    -        synchronized (l) {
    -            System.out.println("1\n" + ClassLayout.parseInstance(l).toPrintable());
    -        }
    -        synchronized (l) {
    -            System.out.println("2\n" + ClassLayout.parseInstance(l).toPrintable());
    -        }
    +    聊在东京奥运会闭幕式这天
    +    /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/
    +    这届奥运会有可能是我除了 08 年之外关注度最高的一届奥运会,原因可能是因为最近也没什么电影综艺啥的比较好看,前面看跑男倒还行,不是说多好,也就图一乐,最开始看向往的生活觉得也挺不错的,后面变成了统一来了就看黄磊做饭,然后夸黄磊做饭好吃,然后无聊的说这种生活多么多么美好,单调无聊,差不多弃了,这里面还包括大华不在了,大华其实个人还是有点呱噪的,但是挺能搞气氛,并且也有才华,彭彭跟子枫人是不讨厌,但是撑不起来,所以也导致了前面说的结果,都变成了黄磊彩虹屁现场,虽然偶尔怀疑他是否做得好吃,但是整体还是承认的,可对于一个这么多季了的综艺来说,这样也有点单调了。

    +

    还有奥运会像乒乓球,篮球,跳水这几个都是比较喜欢的项目,篮球🏀是从初中开始就也有在自己在玩的,虽然因为身高啊体质基本没什么天赋,但也算是热爱驱动,差不多到了大学因为比较懒才放下了,初中高中还是有很多时间花在上面,不像别人经常打球跑跑跳跳还能长高,我反而一直都没长个子,也因为这个其实蛮遗憾的,后面想想可能是初中的时候远走他乡去住宿读初中,伙食营养跟不上导致的,可能也是自己的一厢情愿吧,总觉得应该还能再长点个,这一点以后我自己的小孩我应该会特别注意这段时间他/她的营养摄入了;然后像乒乓球🏓的话其实小时候是比较讨厌的,因为家里人,父母都没有这类爱好习惯,我也完全不会,但是小学那会班里的“恶霸”就以公平之名要我们男生每个人都排队打几个,我这种不会的反而又要被嘲笑,这个小时候的阴影让我有了比较不好的印象,对它🏓的改观是在工作以后,前司跟一个同样不会的同事经常在饭点会打打,而且那会因为这个其实身体得到了锻炼,感觉是个不错的健身方式,然后又是中国的优势项目,小时候跟着我爸看孔令辉,那时候完全不懂,印象就觉得老瓦很牛,后面其实也没那么关注,上一届好像看了马龙的比赛;跳水也是中国的优势项目,而且也比较简单,不是说真的很简单,就是我们外行观众看着就看看水花大小图一乐。

    +

    这次的观赛过程其实主要还是在乒乓球上面,现在都有点怪我的乌鸦嘴,混双我一直就不太放心(关我什么事,我也不专业),然后一直觉得混双是不是不太稳,结果那天看的时候也是因为央视一套跟五套都没放,我家的有线电视又是没有五加体育,然后用电脑投屏就很卡,看得也很不爽,同时那天因为看的时候已经是 2:0还是再后面点了,一方面是不懂每队只有一次暂停,另一方面不知道已经用过暂停了,所以就特别怀疑马林是不是只会无脑鼓掌,感觉作为教练,并且是前冠军,应该也能在擦汗间隙,或者局间休息调整的时候多给些战略战术的指导,类似于后面男团小胖打奥恰洛夫,像解说都看出来了,其实奥恰那会的反手特别顺,打得特别凶,那就不能让他能特别顺手的上反手位,这当然是外行比较粗浅的看法,在混双过程中其实除了这个,还有让人很不爽的就是我们的许昕跟刘诗雯有种拿不出破釜沉舟的勇气的感觉,在气势上完全被对面两位日本乒乓球最讨厌的两位对手压制着,我都要输了,我就每一颗都要不让你好过,因为真的不是说没有实力,对面水谷隼也不是多么多么强的,可能上一届男团许昕输给他还留着阴影,但是以许昕 19 年男单世界第一的实力,目前也排在世界前三,输一场不应该成为这种阻力,有一些失误也很可惜,后面孙颖莎真的打得很解气,第二局一度以为又要被翻盘了,结果来了个大逆转,女团的时候也是,感觉在心态上孙颖莎还是很值得肯定的,少年老成这个词很适合,看其他的视频也觉得莎莎萌萌哒,陈梦总感觉还欠一点王者霸气,王曼昱还是可以的,反手很凶,我觉得其实这一届日本女乒就是打得非常凶,即使像平野这种看着很弱的妹子,打的球可一点都不弱,也是这种凶狠的打法,有点要压制中国的感觉,这方面我觉得是需要改善的,打这种要不就是实力上的完全碾压,要不就是我实力虽然比较没强多少,但是你狠我打得比你还狠,越保守越要输,我不太成熟的想法是这样的,还有就是面对逆境,这个就要说到男队的了,樊振东跟马龙在半决赛的时候,特别是男团的第二盘,樊振东打奥恰很好地表现了这个心态,当然樊振东我不是特别了解,据说他是比较善于打相持,比较善于焦灼的情况,不过整体看下来樊振东还是有一些欠缺,就是面对情况的快速转变应对,这一点也是马龙特别强的,虽然看起来马龙真的是年纪大了点,没有 16 年那会满头发胶,油光锃亮的大背头和满脸胶原蛋白的意气风发,大范围运动能力也弱了一点,但是经验和能力的全面性也让他最终能再次站上巅峰,还是非常佩服的,这里提一下张继科,虽然可能天赋上是张继科更强点,但是男乒一直都是有强者出现,能为国家队付出这么多并且一直坚持的可不是人人都可以,即使现在同台竞技马龙打不过张继科我还是更喜欢马龙。再来说说我们的对手,主要分三部分,德国男乒,里面有波尔(我刚听到的时候在想怎么又出来个叫波尔的,是不是像举重的石智勇一样,又来一个同名的,结果是同一个,已经四十岁了),这真是个让人敬佩的对手,实力强,经验丰富,虽然男单有点可惜,但是帮助男团获得银牌,真的是起到了定海神针的作用;奥恰洛夫,以前完全不认识,或者说看过也忘了,这次是真的有点意外,竟然有这么个马龙护法,其实他也坦言非常想赢一次马龙,并且在半决赛也非常接近赢得比赛,是个实力非常强的对手,就是男团半决赛输给张本智和有点可惜,有点被打蒙的感觉,佛朗西斯卡的话也是实力不错的选手,就是可能被奥恰跟波尔的光芒掩盖了,跟波尔在男团第一盘男双的比赛中打败日本那对男双也是非常给力的,说实话,最后打国乒的时候的确是国乒实力更胜一筹,但是即使德国赢了我也是充满尊敬,拼的就是硬实力,就像第二盘奥恰打樊振东,反手是真的很强,反过来看奥恰可能也不是很善于快速调整,樊振东打出来自己的节奏,主攻奥恰的中路,他好像没什么好办法解决。再来说我最讨厌的日本,嗯,小日本,张本智和、水谷隼、伊藤美诚,一一评价下(我是外行,绝对主观评价),张本智和,父母也是中国人,原来叫张智和,改日本籍后加了个本,被微博网友笑称日本尖叫鸡,男单输给了斯洛文尼亚选手,男团里是赢了两场,但是在我看来其实实力上可能比不上全力的奥恰,主要是特别能叫,会干扰对手,如果觉得这种也是种能力我也无话可说,要是有那种吼声能直接把对手震聋的,都不需要打比赛了,我简单记了下,赢一颗球,他要叫八声,用 LD 的话来说烦都烦死了,心态是在面对一些困境顺境的应对调整适应能力,而不是对这种噪音的适应能力,至少我是这么看的,所以我很期待樊振东能好好地虐虐他,因为其他像林昀儒真的是非常优秀的新选手,所谓的国乒克星估计也是小日本自己说说的,国乒其实有很多对手,马龙跟樊振东在男单半决赛碰到的这两个几乎都差点把他们掀翻了,所以还是练好自己的实力再来吹吧,免得打脸;水谷隼的话真的是长相就是特别地讨厌,还搞出那套不打比赛的姿态,男团里被波尔干掉就是很好的例子,波尔虽然真的很强,但毕竟 40 岁了,跟伊藤美诚一起说了吧,伊藤实力说实话是有的,混双中很大一部分的赢面来自于她,刘诗雯做了手术状态不好,许昕失误稍多,但是这种赢球了就感觉我赢了你一辈子一场没输的感觉,还有那种不知道怎么形容的笑,实力强的正常打比赛的我都佩服,像女团决赛里,平野跟石川佳纯的打法其实也很凶狠,但是都是正常的比赛,即使中国队两位实力不济输了也很正常,这种就真的需要像孙颖莎这样的小魔王无视各种魔法攻击,无视你各种花里胡哨的打法的人好好教训一下,混双输了以后了解了下她,感觉实力真的不错,是个大威胁,但是其实我们孙颖莎也是经历了九个月的继续成长,像张怡宁也评价了她,可能后面就没什么空间了,当然如果由张怡宁来打她就更适合了,净整这些有的没的,就打得你没脾气。

    +

    乒乓球的说的有点多,就分篇说了,第一篇先到这。

    +]]>
    + + 生活 + 运动 + + + 生活 + 运动 + 东京奥运会 + 乒乓球 + 跳水 + + + + 聊聊 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();
     		}
    -}
    - -

    看下运行结果

    -

    https://img.nicksxs.com/uPic/V2l78m.png

    -

    可以看到是加上了 101 = 5 也就是偏向锁,后面是线程 id

    -

    当我再使用一个线程来竞争这个锁的时候

    -
    public class ObjectHeaderDemo {
    -    public static void main(String[] args) throws InterruptedException {
    -        TimeUnit.SECONDS.sleep(5);
    -        L l = new L();
    -        System.out.println(ClassLayout.parseInstance(l).toPrintable());
    -        synchronized (l) {
    -            System.out.println("1\n" + ClassLayout.parseInstance(l).toPrintable());
    -        }
    -				Thread thread1 = new Thread() {
    -            @Override
    -            public void run() {
    -                try {
    -                    TimeUnit.SECONDS.sleep(5L);
    -                } catch (InterruptedException e) {
    -                    e.printStackTrace();
    -                }
    -                synchronized (l) {
    -                    System.out.println("thread1 获取锁成功");
    -                    System.out.println(ClassLayout.parseInstance(l).toPrintable());
    -                    try {
    -                        TimeUnit.SECONDS.sleep(5L);
    -                    } catch (InterruptedException e) {
    -                        e.printStackTrace();
    -                    }
    -                }
    -            }
    -        };
    -				thread1.start();
    +		Holder<Object> holder = cachedInstances.get(name);
    +		if (holder == null) {
    +		    cachedInstances.putIfAbsent(name, new Holder<Object>());
    +		    holder = cachedInstances.get(name);
     		}
    -}
    - -

    https://img.nicksxs.com/uPic/bRMvlR.png

    -

    可以看到变成了轻量级锁,在线程没有争抢,只是进行了切换,就会使用轻量级锁,当两个线程在竞争了,就又会升级成重量级锁

    -
    public class ObjectHeaderDemo {
    -    public static void main(String[] args) throws InterruptedException {
    -        TimeUnit.SECONDS.sleep(5);
    -        L l = new L();
    -        System.out.println(ClassLayout.parseInstance(l).toPrintable());
    -        synchronized (l) {
    -            System.out.println("1\n" + ClassLayout.parseInstance(l).toPrintable());
    +		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);
             }
    -        Thread thread1 = new Thread() {
    -            @Override
    -            public void run() {
    -                try {
    -                    TimeUnit.SECONDS.sleep(5L);
    -                } catch (InterruptedException e) {
    -                    e.printStackTrace();
    -                }
    -                synchronized (l) {
    -                    System.out.println("thread1 获取锁成功");
    -                    System.out.println(ClassLayout.parseInstance(l).toPrintable());
    -                    try {
    -                        TimeUnit.SECONDS.sleep(5L);
    -                    } catch (InterruptedException e) {
    -                        e.printStackTrace();
    -                    }
    -                }
    +        try {
    +            T instance = (T) EXTENSION_INSTANCES.get(clazz);
    +            if (instance == null) {
    +                EXTENSION_INSTANCES.putIfAbsent(clazz, (T) clazz.newInstance());
    +                instance = (T) EXTENSION_INSTANCES.get(clazz);
                 }
    -        };
    -        Thread thread2 = new Thread() {
    -            @Override
    -            public void run() {
    -                try {
    -                    TimeUnit.SECONDS.sleep(5L);
    -                } catch (InterruptedException e) {
    -                    e.printStackTrace();
    -                }
    -                synchronized (l) {
    -                    System.out.println("thread2 获取锁成功");
    -                    System.out.println(ClassLayout.parseInstance(l).toPrintable());
    +            injectExtension(instance);
    +            Set<Class<?>> wrapperClasses = cachedWrapperClasses;
    +            if (wrapperClasses != null && wrapperClasses.size() > 0) {
    +                for (Class<?> wrapperClass : wrapperClasses) {
    +                    instance = injectExtension((T) wrapperClass.getConstructor(type).newInstance(instance));
                     }
                 }
    -        };
    -        thread1.start();
    -        thread2.start();
    -    }
    -}
    -
    -class L {
    -    private boolean myboolean = true;
    -}
    - -

    https://img.nicksxs.com/uPic/LMzMtR.png

    -

    可以看到变成了重量级锁。

    + 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 - Synchronized - 偏向锁 - 轻量级锁 - 重量级锁 - 自旋 + Dubbo + RPC + SPI
    @@ -12285,286 +12292,410 @@ public Result invoke(final Invocation invocation) throws RpcException { // 对 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); - }
    - - -

    Failfast Cluster

    快速失败,只发起一次调用,失败立即报错。通常用于非幂等性的写操作,比如新增记录。

    -

    Failsafe Cluster

    失败安全,出现异常时,直接忽略。通常用于写入审计日志等操作。

    -

    Failback Cluster

    失败自动恢复,后台记录失败请求,定时重发。通常用于消息通知操作。

    -

    Forking Cluster

    并行调用多个服务器,只要一个成功即返回。通常用于实时性要求较高的读操作,但需要浪费更多服务资源。可通过 forks=”2” 来设置最大并行数。

    -

    Broadcast Cluster

    广播调用所有提供者,逐个调用,任意一台报错则报错 2。通常用于通知所有提供者更新缓存或日志等本地资源信息。

    -]]> - - Java - Dubbo - RPC - Dubbo - 容错机制 - - - Java - Dubbo - RPC - 容错机制 - - - - 聊一下 SpringBoot 中使用的 cglib 作为动态代理中的一个注意点 - /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/ - 这个话题是由一次组内同学分享引出来的,首先在 springboot 2.x 开始默认使用了 cglib 作为 aop 的实现,这里也稍微讲一下,在一个 1.x 的老项目里,可以看到AopAutoConfiguration 是这样的

    -
    @Configuration
    -@ConditionalOnClass({ EnableAspectJAutoProxy.class, Aspect.class, Advice.class })
    -@ConditionalOnProperty(prefix = "spring.aop", name = "auto", havingValue = "true", matchIfMissing = true)
    -public class AopAutoConfiguration {
    -
    -	@Configuration
    -	@EnableAspectJAutoProxy(proxyTargetClass = false)
    -	@ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "false", matchIfMissing = true)
    -	public static class JdkDynamicAutoProxyConfiguration {
    -	}
    -
    -	@Configuration
    -	@EnableAspectJAutoProxy(proxyTargetClass = true)
    -	@ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "true", matchIfMissing = false)
    -	public static class CglibAutoProxyConfiguration {
    -	}
    -
    -}
    - -

    而在 2.x 中变成了这样

    -
    @Configuration(proxyBeanMethods = false)
    -@ConditionalOnProperty(prefix = "spring.aop", name = "auto", havingValue = "true", matchIfMissing = true)
    -public class AopAutoConfiguration {
    -
    -	@Configuration(proxyBeanMethods = false)
    -	@ConditionalOnClass(Advice.class)
    -	static class AspectJAutoProxyingConfiguration {
    -
    -		@Configuration(proxyBeanMethods = false)
    -		@EnableAspectJAutoProxy(proxyTargetClass = false)
    -		@ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "false")
    -		static class JdkDynamicAutoProxyConfiguration {
    -
    -		}
    -
    -		@Configuration(proxyBeanMethods = false)
    -		@EnableAspectJAutoProxy(proxyTargetClass = true)
    -		@ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "true",
    -				matchIfMissing = true)
    -		static class CglibAutoProxyConfiguration {
    -
    -		}
    -
    -	}
    - -

    为何会加载 AopAutoConfiguration 在前面的文章聊聊 SpringBoot 自动装配里已经介绍过,有兴趣的可以看下,可以发现 springboot 在 2.x 版本开始使用 cglib 作为默认的动态代理实现。

    -

    然后就是出现的问题了,代码是这样的,一个简单的基于 springboot 的带有数据库的插入,对插入代码加了事务注解,

    -
    @Mapper
    -public interface StudentMapper {
    -		// 就是插入一条数据
    -    @Insert("insert into student(name, age)" + "values ('nick', '18')")
    -    public Long insert();
    -}
    -
    -@Component
    -public class StudentManager {
    -
    -    @Resource
    -    private StudentMapper studentMapper;
    -    
    -    public Long createStudent() {
    -        return studentMapper.insert();
    -    }
    -}
    -
    -@Component
    -public class StudentServiceImpl implements StudentService {
    -
    -    @Resource
    -    private StudentManager studentManager;
    -
    -    // 自己引用
    -    @Resource
    -    private StudentServiceImpl studentService;
    -
    -    @Override
    -    @Transactional
    -    public Long createStudent() {
    -        Long id = studentManager.createStudent();
    -        Long id2 = studentService.createStudent2();
    -        return 1L;
    -    }
    -
    -    @Transactional
    -    private Long createStudent2() {
    -//        Integer t = Integer.valueOf("aaa");
    -        return studentManager.createStudent();
    -    }
    -}
    + // 通过负载均衡来选择 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); + }
    -

    第一个公有方法 createStudent 首先调用了 manager 层的创建方法,然后再通过引入的 studentService 调用了createStudent2,我们先跑一下看看会出现啥情况,果不其然报错了,正是这个报错让我纠结了很久

    -

    EdR7oB

    -

    报了个空指针,而且是在 createStudent2 已经被调用到了,在它的内部,报的 studentManager 是 null,首先 cglib 作为动态代理它是通过继承的方式来实现的,相当于是会在调用目标对象的代理方法时调用 cglib 生成的子类,具体的代理切面逻辑在子类实现,然后在调用目标对象的目标方法,但是继承的方式对于 final 和私有方法其实是没法进行代理的,因为没法继承,所以我最开始的想法是应该通过 studentService 调用 createStudent2 的时候就报错了,也就是不会进入这个方法内部,后面才发现犯了个特别二的错误,继承的方式去调用父类的私有方法,对于 Java 来说是可以调用到的,父类的私有方法并不由子类的InstanceKlass维护,只能通过子类的InstanceKlass找到Java类对应的_super,这样间接地访问。也就是说子类其实是可以访问的,那为啥访问了会报空指针呢,这里报的是studentManager 是空的,可以往依赖注入方面去想,如果忽略依赖注入,我这个studentManager 的确是 null,那是不是就没有被依赖注入呢,但是为啥前面那个可以呢

    -

    这个问题着实查了很久,不废话来看代码

    -
    @Override
    -		protected Object invokeJoinpoint() throws Throwable {
    -			if (this.methodProxy != null) {
    -        // 这里的 target 就是被代理的 bean
    -				return this.methodProxy.invoke(this.target, this.arguments);
    -			}
    -			else {
    -				return super.invokeJoinpoint();
    -			}
    -		}
    +

    Failfast Cluster

    快速失败,只发起一次调用,失败立即报错。通常用于非幂等性的写操作,比如新增记录。

    +

    Failsafe Cluster

    失败安全,出现异常时,直接忽略。通常用于写入审计日志等操作。

    +

    Failback Cluster

    失败自动恢复,后台记录失败请求,定时重发。通常用于消息通知操作。

    +

    Forking Cluster

    并行调用多个服务器,只要一个成功即返回。通常用于实时性要求较高的读操作,但需要浪费更多服务资源。可通过 forks=”2” 来设置最大并行数。

    +

    Broadcast Cluster

    广播调用所有提供者,逐个调用,任意一台报错则报错 2。通常用于通知所有提供者更新缓存或日志等本地资源信息。

    +]]> + + Java + Dubbo - RPC + Dubbo + 容错机制 + + + Java + Dubbo + RPC + 容错机制 + + + + 聊聊 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/ + Java并发

    synchronized 的一些学习记录

    +

    jdk1.6 以后对 synchronized 进行了一些优化,包括偏向锁,轻量级锁,重量级锁等

    +

    这些锁的加锁方式大多跟对象头有关,我们可以查看 jdk 代码

    +

    首先对象头的位置注释

    +
    // Bit-format of an object header (most significant first, big endian layout below):
    +//
    +//  32 bits:
    +//  --------
    +//             hash:25 ------------>| age:4    biased_lock:1 lock:2 (normal object)
    +//             JavaThread*:23 epoch:2 age:4    biased_lock:1 lock:2 (biased object)
    +//             size:32 ------------------------------------------>| (CMS free block)
    +//             PromotedObject*:29 ---------->| promo_bits:3 ----->| (CMS promoted object)
    +//
    +//  64 bits:
    +//  --------
    +//  unused:25 hash:31 -->| unused:1   age:4    biased_lock:1 lock:2 (normal object)
    +//  JavaThread*:54 epoch:2 unused:1   age:4    biased_lock:1 lock:2 (biased object)
    +//  PromotedObject*:61 --------------------->| promo_bits:3 ----->| (CMS promoted object)
    +//  size:64 ----------------------------------------------------->| (CMS free block)
    +//
    +//  unused:25 hash:31 -->| cms_free:1 age:4    biased_lock:1 lock:2 (COOPs && normal object)
    +//  JavaThread*:54 epoch:2 cms_free:1 age:4    biased_lock:1 lock:2 (COOPs && biased object)
    +//  narrowOop:32 unused:24 cms_free:1 unused:4 promo_bits:3 ----->| (COOPs && CMS promoted object)
    +//  unused:21 size:35 -->| cms_free:1 unused:7 ------------------>| (COOPs && CMS free block)
    +
    enum { locked_value             = 0,
    +         unlocked_value           = 1,
    +         monitor_value            = 2,
    +         marked_value             = 3,
    +         biased_lock_pattern      = 5
    +};
    +
    -

    这个是org.springframework.aop.framework.CglibAopProxy.CglibMethodInvocation的代码,其实它在这里不是直接调用 super 也就是父类的方法,而是通过 methodProxy 调用 target 目标对象的方法,也就是原始的 studentService bean 的方法,这样子 spring 管理的已经做好依赖注入的 bean 就能正常起作用,否则就会出现上面的问题,因为 cglib 其实是通过继承来实现,通过将调用转移到子类上加入代理逻辑,我们在简单使用的时候会直接 invokeSuper() 调用父类的方法,但是在这里 spring 的场景里需要去支持 spring 的功能逻辑,所以上面的问题就可以开始来解释了,因为 createStudent 是公共方法,cglib 可以对其进行继承代理,但是在执行逻辑的时候其实是通过调用目标对象,也就是 spring 管理的被代理的目标对象的 bean 调用的 createStudent,而对于下面的 createStudent2 方法因为是私有方法,不会走代理逻辑,也就不会有调用回目标对象的逻辑,只是通过继承关系,在子类中没有这个方法,所以会通过子类的InstanceKlass找到这个类对应的_super,然后调用父类的这个私有方法,这里要搞清楚一个点,从这个代理类直接找到其父类然后调用这个私有方法,这个类是由 cglib 生成的,不是被 spring 管理起来经过依赖注入的 bean,所以是没有 studentManager 这个依赖的,也就出现了前面的问题

    -

    而在前面提到的cglib通过methodProxy调用到目标对象,目标对象是在什么时候设置的呢,其实是在bean的生命周期中,org.springframework.beans.factory.config.BeanPostProcessor#postProcessAfterInitialization这个接口的在bean的初始化过程中,会调用实现了这个接口的方法,

    -
    @Override
    -public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
    -	if (bean != null) {
    -		Object cacheKey = getCacheKey(bean.getClass(), beanName);
    -		if (this.earlyProxyReferences.remove(cacheKey) != bean) {
    -			return wrapIfNecessary(bean, beanName, cacheKey);
    +

    我们可以用 java jol库来查看对象头,通过一段简单的代码来看下

    +
    public class ObjectHeaderDemo {
    +    public static void main(String[] args) throws InterruptedException {
    +        L l = new L();
    +        System.out.println(ClassLayout.parseInstance(l).toPrintable());
     		}
    -	}
    -	return bean;
    -}
    +}
    -

    具体的逻辑在 org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#wrapIfNecessary这个方法里

    -
    protected Object getCacheKey(Class<?> beanClass, @Nullable String beanName) {
    -		if (StringUtils.hasLength(beanName)) {
    -			return (FactoryBean.class.isAssignableFrom(beanClass) ?
    -					BeanFactory.FACTORY_BEAN_PREFIX + beanName : beanName);
    -		}
    -		else {
    -			return beanClass;
    +

    Untitled

    +

    然后可以看到打印输出,当然这里因为对齐方式,我们看到的其实顺序是反过来的,按最后三位去看,我们这是 001,好像偏向锁都没开,这里使用的是 jdk1.8,默认开始偏向锁的,其实这里有涉及到了一个配置,jdk1.8 中偏向锁会延迟 4 秒开启,可以通过添加启动参数 -XX:+PrintFlagsFinal,看到

    +

    偏向锁延迟

    +

    因为在初始化的时候防止线程竞争有大量的偏向锁撤销升级,所以会延迟 4s 开启

    +

    我们再来延迟 5s 看看

    +
    public class ObjectHeaderDemo {
    +    public static void main(String[] args) throws InterruptedException {
    +				TimeUnit.SECONDS.sleep(5);
    +        L l = new L();
    +        System.out.println(ClassLayout.parseInstance(l).toPrintable());
     		}
    -	}
    +} 
    - /** - * Wrap the given bean if necessary, i.e. if it is eligible for being proxied. - * @param bean the raw bean instance - * @param beanName the name of the bean - * @param cacheKey the cache key for metadata access - * @return a proxy wrapping the bean, or the raw bean instance as-is - */ - protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) { - if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) { - return bean; - } - if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) { - return bean; - } - if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) { - this.advisedBeans.put(cacheKey, Boolean.FALSE); - return bean; +

    https://img.nicksxs.com/uPic/2LBKpX.jpg

    +

    可以看到偏向锁设置已经开启了,我们来是一下加个偏向锁

    +
    public class ObjectHeaderDemo {
    +    public static void main(String[] args) throws InterruptedException {
    +        TimeUnit.SECONDS.sleep(5);
    +        L l = new L();
    +        System.out.println(ClassLayout.parseInstance(l).toPrintable());
    +        synchronized (l) {
    +            System.out.println("1\n" + ClassLayout.parseInstance(l).toPrintable());
    +        }
    +        synchronized (l) {
    +            System.out.println("2\n" + ClassLayout.parseInstance(l).toPrintable());
    +        }
     		}
    +}
    - // 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; +

    看下运行结果

    +

    https://img.nicksxs.com/uPic/V2l78m.png

    +

    可以看到是加上了 101 = 5 也就是偏向锁,后面是线程 id

    +

    当我再使用一个线程来竞争这个锁的时候

    +
    public class ObjectHeaderDemo {
    +    public static void main(String[] args) throws InterruptedException {
    +        TimeUnit.SECONDS.sleep(5);
    +        L l = new L();
    +        System.out.println(ClassLayout.parseInstance(l).toPrintable());
    +        synchronized (l) {
    +            System.out.println("1\n" + ClassLayout.parseInstance(l).toPrintable());
    +        }
    +				Thread thread1 = new Thread() {
    +            @Override
    +            public void run() {
    +                try {
    +                    TimeUnit.SECONDS.sleep(5L);
    +                } catch (InterruptedException e) {
    +                    e.printStackTrace();
    +                }
    +                synchronized (l) {
    +                    System.out.println("thread1 获取锁成功");
    +                    System.out.println(ClassLayout.parseInstance(l).toPrintable());
    +                    try {
    +                        TimeUnit.SECONDS.sleep(5L);
    +                    } catch (InterruptedException e) {
    +                        e.printStackTrace();
    +                    }
    +                }
    +            }
    +        };
    +				thread1.start();
     		}
    +}
    + +

    https://img.nicksxs.com/uPic/bRMvlR.png

    +

    可以看到变成了轻量级锁,在线程没有争抢,只是进行了切换,就会使用轻量级锁,当两个线程在竞争了,就又会升级成重量级锁

    +
    public class ObjectHeaderDemo {
    +    public static void main(String[] args) throws InterruptedException {
    +        TimeUnit.SECONDS.sleep(5);
    +        L l = new L();
    +        System.out.println(ClassLayout.parseInstance(l).toPrintable());
    +        synchronized (l) {
    +            System.out.println("1\n" + ClassLayout.parseInstance(l).toPrintable());
    +        }
    +        Thread thread1 = new Thread() {
    +            @Override
    +            public void run() {
    +                try {
    +                    TimeUnit.SECONDS.sleep(5L);
    +                } catch (InterruptedException e) {
    +                    e.printStackTrace();
    +                }
    +                synchronized (l) {
    +                    System.out.println("thread1 获取锁成功");
    +                    System.out.println(ClassLayout.parseInstance(l).toPrintable());
    +                    try {
    +                        TimeUnit.SECONDS.sleep(5L);
    +                    } catch (InterruptedException e) {
    +                        e.printStackTrace();
    +                    }
    +                }
    +            }
    +        };
    +        Thread thread2 = new Thread() {
    +            @Override
    +            public void run() {
    +                try {
    +                    TimeUnit.SECONDS.sleep(5L);
    +                } catch (InterruptedException e) {
    +                    e.printStackTrace();
    +                }
    +                synchronized (l) {
    +                    System.out.println("thread2 获取锁成功");
    +                    System.out.println(ClassLayout.parseInstance(l).toPrintable());
    +                }
    +            }
    +        };
    +        thread1.start();
    +        thread2.start();
    +    }
    +}
     
    -		this.advisedBeans.put(cacheKey, Boolean.FALSE);
    -		return bean;
    -	}
    +class L { + private boolean myboolean = true; +}
    -

    然后在 org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#createProxy 中创建了代理类

    +

    https://img.nicksxs.com/uPic/LMzMtR.png

    +

    可以看到变成了重量级锁。

    ]]>
    Java - SpringBoot Java - Spring - SpringBoot - cglib - 事务 + Synchronized + 偏向锁 + 轻量级锁 + 重量级锁 + 自旋
    - 聊聊 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;
    -            }
    +    聊聊 Java 中绕不开的 Synchronized 关键字
    +    /2021/06/20/%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/
    +    Synchronized 关键字在 Java 的并发体系里也是非常重要的一个内容,首先比较常规的是知道它使用的方式,可以锁对象,可以锁代码块,也可以锁方法,看一个简单的 demo

    +
    public class SynchronizedDemo {
    +
    +    public static void main(String[] args) {
    +        SynchronizedDemo synchronizedDemo = new SynchronizedDemo();
    +        synchronizedDemo.lockMethod();
    +    }
    +
    +    public synchronized void lockMethod() {
    +        System.out.println("here i'm locked");
    +    }
    +
    +    public void lockSynchronizedDemo() {
    +        synchronized (this) {
    +            System.out.println("here lock class");
             }
    -        return false;
    -    }
    -

    然后呢就是为啥一些书或者 effective java 中写了 equalshashCode 要一起重写,这里涉及到当对象作为 HashMapkey 的时候
    首先 HashMap 会使用 hashCode 去判断是否在同一个槽里,然后在通过 equals 去判断是否是同一个 key,是的话就替换,不是的话就链表接下去,如果不重写 hashCode 的话,默认的 objecthashCodenative 方法,根据对象的地址生成的,这样其实对象的值相同的话,因为地址不同,HashMap 也会出现异常,所以需要重写,同时也需要重写 equals 方法,才能确认是同一个 key,而不是落在同一个槽的不同 key.

    + } +}
    + +

    然后来查看反编译结果,其实代码(日光)之下并无新事,即使是完全不懂的也可以通过一些词义看出一些意义

    +
      Last modified 2021620; size 729 bytes
    +  MD5 checksum dd9c529863bd7ff839a95481db578ad9
    +  Compiled from "SynchronizedDemo.java"
    +public class SynchronizedDemo
    +  minor version: 0
    +  major version: 53
    +  flags: (0x0021) ACC_PUBLIC, ACC_SUPER
    +  this_class: #2                          // SynchronizedDemo
    +  super_class: #9                         // java/lang/Object
    +  interfaces: 0, fields: 0, methods: 4, attributes: 1
    +Constant pool:
    +   #1 = Methodref          #9.#22         // java/lang/Object."<init>":()V
    +   #2 = Class              #23            // SynchronizedDemo
    +   #3 = Methodref          #2.#22         // SynchronizedDemo."<init>":()V
    +   #4 = Methodref          #2.#24         // SynchronizedDemo.lockMethod:()V
    +   #5 = Fieldref           #25.#26        // java/lang/System.out:Ljava/io/PrintStream;
    +   #6 = String             #27            // here i\'m locked
    +   #7 = Methodref          #28.#29        // java/io/PrintStream.println:(Ljava/lang/String;)V
    +   #8 = String             #30            // here lock class
    +   #9 = Class              #31            // java/lang/Object
    +  #10 = Utf8               <init>
    +  #11 = Utf8               ()V
    +  #12 = Utf8               Code
    +  #13 = Utf8               LineNumberTable
    +  #14 = Utf8               main
    +  #15 = Utf8               ([Ljava/lang/String;)V
    +  #16 = Utf8               lockMethod
    +  #17 = Utf8               lockSynchronizedDemo
    +  #18 = Utf8               StackMapTable
    +  #19 = Class              #32            // java/lang/Throwable
    +  #20 = Utf8               SourceFile
    +  #21 = Utf8               SynchronizedDemo.java
    +  #22 = NameAndType        #10:#11        // "<init>":()V
    +  #23 = Utf8               SynchronizedDemo
    +  #24 = NameAndType        #16:#11        // lockMethod:()V
    +  #25 = Class              #33            // java/lang/System
    +  #26 = NameAndType        #34:#35        // out:Ljava/io/PrintStream;
    +  #27 = Utf8               here i\'m locked
    +  #28 = Class              #36            // java/io/PrintStream
    +  #29 = NameAndType        #37:#38        // println:(Ljava/lang/String;)V
    +  #30 = Utf8               here lock class
    +  #31 = Utf8               java/lang/Object
    +  #32 = Utf8               java/lang/Throwable
    +  #33 = Utf8               java/lang/System
    +  #34 = Utf8               out
    +  #35 = Utf8               Ljava/io/PrintStream;
    +  #36 = Utf8               java/io/PrintStream
    +  #37 = Utf8               println
    +  #38 = Utf8               (Ljava/lang/String;)V
    +{
    +  public SynchronizedDemo();
    +    descriptor: ()V
    +    flags: (0x0001) ACC_PUBLIC
    +    Code:
    +      stack=1, locals=1, args_size=1
    +         0: aload_0
    +         1: invokespecial #1                  // Method java/lang/Object."<init>":()V
    +         4: return
    +      LineNumberTable:
    +        line 5: 0
    +
    +  public static void main(java.lang.String[]);
    +    descriptor: ([Ljava/lang/String;)V
    +    flags: (0x0009) ACC_PUBLIC, ACC_STATIC
    +    Code:
    +      stack=2, locals=2, args_size=1
    +         0: new           #2                  // class SynchronizedDemo
    +         3: dup
    +         4: invokespecial #3                  // Method "<init>":()V
    +         7: astore_1
    +         8: aload_1
    +         9: invokevirtual #4                  // Method lockMethod:()V
    +        12: return
    +      LineNumberTable:
    +        line 8: 0
    +        line 9: 8
    +        line 10: 12
    +
    +  public synchronized void lockMethod();
    +    descriptor: ()V
    +    flags: (0x0021) ACC_PUBLIC, ACC_SYNCHRONIZED
    +    Code:
    +      stack=2, locals=1, args_size=1
    +         0: getstatic     #5                  // Field java/lang/System.out:Ljava/io/PrintStream;
    +         3: ldc           #6                  // String here i\'m locked
    +         5: invokevirtual #7                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
    +         8: return
    +      LineNumberTable:
    +        line 13: 0
    +        line 14: 8
    +
    +  public void lockSynchronizedDemo();
    +    descriptor: ()V
    +    flags: (0x0001) ACC_PUBLIC
    +    Code:
    +      stack=2, locals=3, args_size=1
    +         0: aload_0
    +         1: dup
    +         2: astore_1
    +         3: monitorenter
    +         4: getstatic     #5                  // Field java/lang/System.out:Ljava/io/PrintStream;
    +         7: ldc           #8                  // String here lock class
    +         9: invokevirtual #7                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
    +        12: aload_1
    +        13: monitorexit
    +        14: goto          22
    +        17: astore_2
    +        18: aload_1
    +        19: monitorexit
    +        20: aload_2
    +        21: athrow
    +        22: return
    +      Exception table:
    +         from    to  target type
    +             4    14    17   any
    +            17    20    17   any
    +      LineNumberTable:
    +        line 17: 0
    +        line 18: 4
    +        line 19: 12
    +        line 20: 22
    +      StackMapTable: number_of_entries = 2
    +        frame_type = 255 /* full_frame */
    +          offset_delta = 17
    +          locals = [ class SynchronizedDemo, class java/lang/Object ]
    +          stack = [ class java/lang/Throwable ]
    +        frame_type = 250 /* chop */
    +          offset_delta = 4
    +}
    +SourceFile: "SynchronizedDemo.java"
    + +

    其中lockMethod中可以看到是通过 ACC_SYNCHRONIZED flag 来标记是被 synchronized 修饰,前面的 ACC 应该是 access 的意思,并且通过 ACC_PUBLIC 也可以看出来他们是同一类访问权限关键字来控制的,而修饰类则是通过3: monitorenter13: monitorexit来控制并发,这个是原来就知道,后来看了下才知道修饰方法是不一样的,但是在前期都比较诟病是 synchronized 的性能,像 monitor 也是通过操作系统的mutex lock互斥锁来实现的,相对是比较重的锁,于是在 JDK 1.6 之后对 synchronized 做了一系列优化,包括偏向锁,轻量级锁,并且包括像 ConcurrentHashMap 这类并发集合都有在使用 synchronized 关键字配合 cas 来做并发保护,

    +

    jdk 对于 synchronized 的优化主要在于多重状态锁的升级,最初会使用偏向锁,当一个线程访问同步块并获取锁时,会在对象头和栈帧中的锁记录里存储锁偏向的线程ID,以后该线程在进入和退出同步块时不需要进行CAS操作来加锁和解锁,只需简单地测试一下对象头的Mark Word里是否存储着指向当前线程的偏向锁。引入偏向锁是为了在无多线程竞争的情况下尽量减少不必要的轻量级锁执行路径,因为轻量级锁的获取及释放依赖多次CAS原子指令,而偏向锁只需要在置换ThreadID的时候依赖一次CAS原子指令(由于一旦出现多线程竞争的情况就必须撤销偏向锁,所以偏向锁的撤销操作的性能损耗必须小于节省下来的CAS原子指令的性能消耗)。
    而当出现线程尝试进入同步块时发现已有偏向锁,并且是其他线程时,会将锁升级成轻量级锁,并且自旋尝试获取锁,如果自旋成功则表示获取轻量级锁成功,否则将会升级成重量级锁进行阻塞,当然这里具体的还很复杂,说的比较浅薄主体还是想将原先的阻塞互斥锁进行轻量化,区分特殊情况进行加锁。

    ]]>
    - java + Java - java + Java + Synchronized + 偏向锁 + 轻量级锁 + 重量级锁 + 自旋
    @@ -12895,196 +13026,113 @@ public Result invoke(final Invocation invocation) throws RpcException { sun.misc.PerfCounter.getFindClasses().increment(); } } - if (resolve) { - resolveClass(c); - } - return c; + if (resolve) { + resolveClass(c); + } + return c; + } + }
    +

    破坏双亲委派

    关于破坏双亲委派模型,第一次是在 JDK1.2 之后引入了双亲委派模型之前,那么在那之前已经有了类加载器,所以java.lang.ClassLoader 中添加了一个 protected 方法 findClass(),并引导用户编写的类加载逻辑时尽可能去重写这个方法,而不是在 loadClass()中编写代码。这个跟上面的逻辑其实类似,当父类加载失败,会调用 findClass()来完成加载;第二次是因为这个模型本身还有一些不足之处,比如 SPI 这种,所以有设计了线程下上下文类加载器(Thread Context ClassLoader)。这个类加载器可以通过 java.lang.Thread 类的 java.lang.Thread#setContextClassLoader() 进行设置,然后第三种是为了追求程序动态性,这里有涉及到了 osgi 等概念,就不展开了

    +]]> + + Java + + + 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;
    +            }
             }
    -    }
    -

    破坏双亲委派

    关于破坏双亲委派模型,第一次是在 JDK1.2 之后引入了双亲委派模型之前,那么在那之前已经有了类加载器,所以java.lang.ClassLoader 中添加了一个 protected 方法 findClass(),并引导用户编写的类加载逻辑时尽可能去重写这个方法,而不是在 loadClass()中编写代码。这个跟上面的逻辑其实类似,当父类加载失败,会调用 findClass()来完成加载;第二次是因为这个模型本身还有一些不足之处,比如 SPI 这种,所以有设计了线程下上下文类加载器(Thread Context ClassLoader)。这个类加载器可以通过 java.lang.Thread 类的 java.lang.Thread#setContextClassLoader() 进行设置,然后第三种是为了追求程序动态性,这里有涉及到了 osgi 等概念,就不展开了

    + return false; + }
    +

    然后呢就是为啥一些书或者 effective java 中写了 equalshashCode 要一起重写,这里涉及到当对象作为 HashMapkey 的时候
    首先 HashMap 会使用 hashCode 去判断是否在同一个槽里,然后在通过 equals 去判断是否是同一个 key,是的话就替换,不是的话就链表接下去,如果不重写 hashCode 的话,默认的 objecthashCodenative 方法,根据对象的地址生成的,这样其实对象的值相同的话,因为地址不同,HashMap 也会出现异常,所以需要重写,同时也需要重写 equals 方法,才能确认是同一个 key,而不是落在同一个槽的不同 key.

    ]]> - Java + java - Java - 类加载 - 加载 - 验证 - 准备 - 解析 - 初始化 - 链接 - 双亲委派 + java - 聊聊 Java 中绕不开的 Synchronized 关键字 - /2021/06/20/%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/ - Synchronized 关键字在 Java 的并发体系里也是非常重要的一个内容,首先比较常规的是知道它使用的方式,可以锁对象,可以锁代码块,也可以锁方法,看一个简单的 demo

    -
    public class SynchronizedDemo {
    -
    -    public static void main(String[] args) {
    -        SynchronizedDemo synchronizedDemo = new SynchronizedDemo();
    -        synchronizedDemo.lockMethod();
    -    }
    -
    -    public synchronized void lockMethod() {
    -        System.out.println("here i'm locked");
    -    }
    -
    -    public void lockSynchronizedDemo() {
    -        synchronized (this) {
    -            System.out.println("here lock class");
    -        }
    -    }
    -}
    + 聊聊 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/ + top 命令在日常的 Linux 使用中,特别是做一些服务器的简单状态查看,排查故障都起了比较大的作用,但是由于这个命令看到的东西比较多,一般只会看部分,或者说像我这样就会比较片面地看一些信息,比如默认是进程维度的,可以在启动命令的时候加-H进入线程模式

    +
    -H  :Threads-mode operation
    +            Instructs top to display individual threads.  Without this command-line option a summation of all threads in each process  is  shown.   Later
    +            this can be changed with the `H' interactive command.
    +

    这样就能用在 Java 中去 jstack 中找到对应的线程
    其实还有比较重要的两个操作,
    一个是在 top 启动状态下,按c键,这样能把比如说是一个 Java 进程,具体的进程命令显示出来
    像这样
    执行前是这样

    执行后是这样

    第二个就是排序了

    +
    SORTING of task window
     
    -

    然后来查看反编译结果,其实代码(日光)之下并无新事,即使是完全不懂的也可以通过一些词义看出一些意义

    -
      Last modified 2021620; size 729 bytes
    -  MD5 checksum dd9c529863bd7ff839a95481db578ad9
    -  Compiled from "SynchronizedDemo.java"
    -public class SynchronizedDemo
    -  minor version: 0
    -  major version: 53
    -  flags: (0x0021) ACC_PUBLIC, ACC_SUPER
    -  this_class: #2                          // SynchronizedDemo
    -  super_class: #9                         // java/lang/Object
    -  interfaces: 0, fields: 0, methods: 4, attributes: 1
    -Constant pool:
    -   #1 = Methodref          #9.#22         // java/lang/Object."<init>":()V
    -   #2 = Class              #23            // SynchronizedDemo
    -   #3 = Methodref          #2.#22         // SynchronizedDemo."<init>":()V
    -   #4 = Methodref          #2.#24         // SynchronizedDemo.lockMethod:()V
    -   #5 = Fieldref           #25.#26        // java/lang/System.out:Ljava/io/PrintStream;
    -   #6 = String             #27            // here i\'m locked
    -   #7 = Methodref          #28.#29        // java/io/PrintStream.println:(Ljava/lang/String;)V
    -   #8 = String             #30            // here lock class
    -   #9 = Class              #31            // java/lang/Object
    -  #10 = Utf8               <init>
    -  #11 = Utf8               ()V
    -  #12 = Utf8               Code
    -  #13 = Utf8               LineNumberTable
    -  #14 = Utf8               main
    -  #15 = Utf8               ([Ljava/lang/String;)V
    -  #16 = Utf8               lockMethod
    -  #17 = Utf8               lockSynchronizedDemo
    -  #18 = Utf8               StackMapTable
    -  #19 = Class              #32            // java/lang/Throwable
    -  #20 = Utf8               SourceFile
    -  #21 = Utf8               SynchronizedDemo.java
    -  #22 = NameAndType        #10:#11        // "<init>":()V
    -  #23 = Utf8               SynchronizedDemo
    -  #24 = NameAndType        #16:#11        // lockMethod:()V
    -  #25 = Class              #33            // java/lang/System
    -  #26 = NameAndType        #34:#35        // out:Ljava/io/PrintStream;
    -  #27 = Utf8               here i\'m locked
    -  #28 = Class              #36            // java/io/PrintStream
    -  #29 = NameAndType        #37:#38        // println:(Ljava/lang/String;)V
    -  #30 = Utf8               here lock class
    -  #31 = Utf8               java/lang/Object
    -  #32 = Utf8               java/lang/Throwable
    -  #33 = Utf8               java/lang/System
    -  #34 = Utf8               out
    -  #35 = Utf8               Ljava/io/PrintStream;
    -  #36 = Utf8               java/io/PrintStream
    -  #37 = Utf8               println
    -  #38 = Utf8               (Ljava/lang/String;)V
    -{
    -  public SynchronizedDemo();
    -    descriptor: ()V
    -    flags: (0x0001) ACC_PUBLIC
    -    Code:
    -      stack=1, locals=1, args_size=1
    -         0: aload_0
    -         1: invokespecial #1                  // Method java/lang/Object."<init>":()V
    -         4: return
    -      LineNumberTable:
    -        line 5: 0
    +          For  compatibility,  this top supports most of the former top sort keys.  Since this is primarily a service to former top users, these commands
    +          do not appear on any help screen.
    +                command   sorted-field                  supported
    +                A         start time (non-display)      No
    +                M         %MEM                          Yes
    +                N         PID                           Yes
    +                P         %CPU                          Yes
    +                T         TIME+                         Yes
     
    -  public static void main(java.lang.String[]);
    -    descriptor: ([Ljava/lang/String;)V
    -    flags: (0x0009) ACC_PUBLIC, ACC_STATIC
    -    Code:
    -      stack=2, locals=2, args_size=1
    -         0: new           #2                  // class SynchronizedDemo
    -         3: dup
    -         4: invokespecial #3                  // Method "<init>":()V
    -         7: astore_1
    -         8: aload_1
    -         9: invokevirtual #4                  // Method lockMethod:()V
    -        12: return
    -      LineNumberTable:
    -        line 8: 0
    -        line 9: 8
    -        line 10: 12
    +          Before using any of the following sort provisions, top suggests that you temporarily turn on column highlighting using the `x' interactive com‐
    +          mand.  That will help ensure that the actual sort environment matches your intent.
     
    -  public synchronized void lockMethod();
    -    descriptor: ()V
    -    flags: (0x0021) ACC_PUBLIC, ACC_SYNCHRONIZED
    -    Code:
    -      stack=2, locals=1, args_size=1
    -         0: getstatic     #5                  // Field java/lang/System.out:Ljava/io/PrintStream;
    -         3: ldc           #6                  // String here i\'m locked
    -         5: invokevirtual #7                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
    -         8: return
    -      LineNumberTable:
    -        line 13: 0
    -        line 14: 8
    +          The following interactive commands will only be honored when the current sort field is visible.  The sort field might not be visible because:
    +                1) there is insufficient Screen Width
    +                2) the `f' interactive command turned it Off
     
    -  public void lockSynchronizedDemo();
    -    descriptor: ()V
    -    flags: (0x0001) ACC_PUBLIC
    -    Code:
    -      stack=2, locals=3, args_size=1
    -         0: aload_0
    -         1: dup
    -         2: astore_1
    -         3: monitorenter
    -         4: getstatic     #5                  // Field java/lang/System.out:Ljava/io/PrintStream;
    -         7: ldc           #8                  // String here lock class
    -         9: invokevirtual #7                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
    -        12: aload_1
    -        13: monitorexit
    -        14: goto          22
    -        17: astore_2
    -        18: aload_1
    -        19: monitorexit
    -        20: aload_2
    -        21: athrow
    -        22: return
    -      Exception table:
    -         from    to  target type
    -             4    14    17   any
    -            17    20    17   any
    -      LineNumberTable:
    -        line 17: 0
    -        line 18: 4
    -        line 19: 12
    -        line 20: 22
    -      StackMapTable: number_of_entries = 2
    -        frame_type = 255 /* full_frame */
    -          offset_delta = 17
    -          locals = [ class SynchronizedDemo, class java/lang/Object ]
    -          stack = [ class java/lang/Throwable ]
    -        frame_type = 250 /* chop */
    -          offset_delta = 4
    -}
    -SourceFile: "SynchronizedDemo.java"
    + < :Move-Sort-Field-Left + Moves the sort column to the left unless the current sort field is the first field being displayed. -

    其中lockMethod中可以看到是通过 ACC_SYNCHRONIZED flag 来标记是被 synchronized 修饰,前面的 ACC 应该是 access 的意思,并且通过 ACC_PUBLIC 也可以看出来他们是同一类访问权限关键字来控制的,而修饰类则是通过3: monitorenter13: monitorexit来控制并发,这个是原来就知道,后来看了下才知道修饰方法是不一样的,但是在前期都比较诟病是 synchronized 的性能,像 monitor 也是通过操作系统的mutex lock互斥锁来实现的,相对是比较重的锁,于是在 JDK 1.6 之后对 synchronized 做了一系列优化,包括偏向锁,轻量级锁,并且包括像 ConcurrentHashMap 这类并发集合都有在使用 synchronized 关键字配合 cas 来做并发保护,

    -

    jdk 对于 synchronized 的优化主要在于多重状态锁的升级,最初会使用偏向锁,当一个线程访问同步块并获取锁时,会在对象头和栈帧中的锁记录里存储锁偏向的线程ID,以后该线程在进入和退出同步块时不需要进行CAS操作来加锁和解锁,只需简单地测试一下对象头的Mark Word里是否存储着指向当前线程的偏向锁。引入偏向锁是为了在无多线程竞争的情况下尽量减少不必要的轻量级锁执行路径,因为轻量级锁的获取及释放依赖多次CAS原子指令,而偏向锁只需要在置换ThreadID的时候依赖一次CAS原子指令(由于一旦出现多线程竞争的情况就必须撤销偏向锁,所以偏向锁的撤销操作的性能损耗必须小于节省下来的CAS原子指令的性能消耗)。
    而当出现线程尝试进入同步块时发现已有偏向锁,并且是其他线程时,会将锁升级成轻量级锁,并且自旋尝试获取锁,如果自旋成功则表示获取轻量级锁成功,否则将会升级成重量级锁进行阻塞,当然这里具体的还很复杂,说的比较浅薄主体还是想将原先的阻塞互斥锁进行轻量化,区分特殊情况进行加锁。

    + > :Move-Sort-Field-Right + Moves the sort column to the right unless the current sort field is the last field being displayed.
    +

    查看 man page 可以找到这一段,其实一般 man page 都是最细致的,只不过因为太多了,有时候懒得看,这里可以通过大写 M 和大写 P 分别按内存和 CPU 排序,下面还有两个小技巧,通过按 x 可以将当前活跃的排序列用不同颜色标出来,然后可以通过<>直接左右移动排序列

    ]]>
    - Java + Linux + 命令 + 小技巧 + top + top + 排序 - Java - Synchronized - 偏向锁 - 轻量级锁 - 重量级锁 - 自旋 + 排序 + linux + 小技巧 + top
    @@ -14135,51 +14183,93 @@ result = result - 聊聊 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/ - top 命令在日常的 Linux 使用中,特别是做一些服务器的简单状态查看,排查故障都起了比较大的作用,但是由于这个命令看到的东西比较多,一般只会看部分,或者说像我这样就会比较片面地看一些信息,比如默认是进程维度的,可以在启动命令的时候加-H进入线程模式

    -
    -H  :Threads-mode operation
    -            Instructs top to display individual threads.  Without this command-line option a summation of all threads in each process  is  shown.   Later
    -            this can be changed with the `H' interactive command.
    -

    这样就能用在 Java 中去 jstack 中找到对应的线程
    其实还有比较重要的两个操作,
    一个是在 top 启动状态下,按c键,这样能把比如说是一个 Java 进程,具体的进程命令显示出来
    像这样
    执行前是这样

    执行后是这样

    第二个就是排序了

    -
    SORTING of task window
    +    聊聊 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());
     
    -          For  compatibility,  this top supports most of the former top sort keys.  Since this is primarily a service to former top users, these commands
    -          do not appear on any help screen.
    -                command   sorted-field                  supported
    -                A         start time (non-display)      No
    -                M         %MEM                          Yes
    -                N         PID                           Yes
    -                P         %CPU                          Yes
    -                T         TIME+                         Yes
     
    -          Before using any of the following sort provisions, top suggests that you temporarily turn on column highlighting using the `x' interactive com‐
    -          mand.  That will help ensure that the actual sort environment matches your intent.
    +        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
     
    -          The following interactive commands will only be honored when the current sort field is visible.  The sort field might not be visible because:
    -                1) there is insufficient Screen Width
    -                2) the `f' interactive command turned it Off
     
    -             <  :Move-Sort-Field-Left
    -                 Moves the sort column to the left unless the current sort field is the first field being displayed.
    +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
     
    -             >  :Move-Sort-Field-Right
    -                 Moves the sort column to the right unless the current sort field is the last field being displayed.
    -

    查看 man page 可以找到这一段,其实一般 man page 都是最细致的,只不过因为太多了,有时候懒得看,这里可以通过大写 M 和大写 P 分别按内存和 CPU 排序,下面还有两个小技巧,通过按 x 可以将当前活跃的排序列用不同颜色标出来,然后可以通过<>直接左右移动排序列

    +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 条数据再进行合并排序就可以获得最终正确的结果。
    这个就是传说中的二次查询法。

    ]]>
    - Linux - 命令 - 小技巧 - top - top - 排序 + Java - 排序 - linux - 小技巧 - top + Java + Sharding-Jdbc
    @@ -14278,6 +14368,35 @@ result = result } }

    看下查询结果

    +]]> + + Java + + + Java + Sharding-Jdbc + + + + 聊聊 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 @@ -14315,174 +14434,60 @@ result = result int alive = url.getParameter("alive", 60000); TaskQueue<Runnable> taskQueue = new TaskQueue(queues <= 0 ? 1 : queues); EagerThreadPoolExecutor executor = new EagerThreadPoolExecutor(cores, threads, (long)alive, TimeUnit.MILLISECONDS, taskQueue, new NamedThreadFactory(name, true), new AbortPolicyWithReport(name, url)); - taskQueue.setExecutor(executor); - return executor; - }
    -这个是改动最多的一个了,因为需要实现这个机制,有兴趣的可以详细看下 -
  • CachedThreadPool: 创建一个自适应线程池,当线程处于空闲1分钟时候,线程会被回收,当有新请求到来时候会创建新线程
    public Executor getExecutor(URL url) {
    -        String name = url.getParameter("threadname", "Dubbo");
    -        int cores = url.getParameter("corethreads", 0);
    -        int threads = url.getParameter("threads", 2147483647);
    -        int queues = url.getParameter("queues", 0);
    -        int alive = url.getParameter("alive", 60000);
    -        return new ThreadPoolExecutor(cores, threads, (long)alive, TimeUnit.MILLISECONDS, (BlockingQueue)(queues == 0 ? new SynchronousQueue() : (queues < 0 ? new LinkedBlockingQueue() : new LinkedBlockingQueue(queues))), new NamedThreadFactory(name, true), new AbortPolicyWithReport(name, url));
    -    }
    -这里可以看到线程池的配置,核心是 0,最大线程数是 2147483647,保活时间是一分钟
    只是非常简略的介绍下,有兴趣可以自行阅读代码。
  • -
-]]>
- - Java - Dubbo - 线程池 - Dubbo - 线程池 - ThreadPool - - - Java - Dubbo - ThreadPool - 线程池 - FixedThreadPool - LimitedThreadPool - EagerThreadPool - CachedThreadPool - -
- - 聊聊 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 - -
- - 聊聊 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 也是基于这样去实现的

+ taskQueue.setExecutor(executor); + return executor; + }
+这个是改动最多的一个了,因为需要实现这个机制,有兴趣的可以详细看下 +
  • CachedThreadPool: 创建一个自适应线程池,当线程处于空闲1分钟时候,线程会被回收,当有新请求到来时候会创建新线程
    public Executor getExecutor(URL url) {
    +        String name = url.getParameter("threadname", "Dubbo");
    +        int cores = url.getParameter("corethreads", 0);
    +        int threads = url.getParameter("threads", 2147483647);
    +        int queues = url.getParameter("queues", 0);
    +        int alive = url.getParameter("alive", 60000);
    +        return new ThreadPoolExecutor(cores, threads, (long)alive, TimeUnit.MILLISECONDS, (BlockingQueue)(queues == 0 ? new SynchronousQueue() : (queues < 0 ? new LinkedBlockingQueue() : new LinkedBlockingQueue(queues))), new NamedThreadFactory(name, true), new AbortPolicyWithReport(name, url));
    +    }
    +这里可以看到线程池的配置,核心是 0,最大线程数是 2147483647,保活时间是一分钟
    只是非常简略的介绍下,有兴趣可以自行阅读代码。
  • + ]]>
    Java + Dubbo - 线程池 + Dubbo + 线程池 + ThreadPool Java - Sharding-Jdbc + Dubbo + ThreadPool + 线程池 + FixedThreadPool + LimitedThreadPool + EagerThreadPool + CachedThreadPool
    - 聊聊 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官方文档

    + 聊聊 mysql 的 MVCC 续篇 + /2020/05/02/%E8%81%8A%E8%81%8A-mysql-%E7%9A%84-MVCC-%E7%BB%AD%E7%AF%87/ + 上一篇聊了mysql 的 innodb 引擎基于 read view 实现的 mvcc 和事务隔离级别,可能有些细心的小伙伴会发现一些问题,第一个是在 RC 级别下的事务提交后的可见性,这里涉及到了三个参数,m_low_limit_id,m_up_limit_id,m_ids,之前看到知乎的一篇写的非常不错的文章,但是就在这一点上似乎有点疑惑,这里基于源码和注释来解释下这个问题

    +
    /**
    +Opens a read view where exactly the transactions serialized before this
    +point in time are seen in the view.
    +@param id		Creator transaction id */
    +
    +void ReadView::prepare(trx_id_t id) {
    +  ut_ad(mutex_own(&trx_sys->mutex));
    +
    +  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 ... 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.

    +

    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.

    -

    纯粹的这种一致性读,实际读取的是快照,也就是基于 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 了

    +

    对于一个 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 @@ -14503,26 +14508,21 @@ t2
    - 聊聊 mysql 的 MVCC 续篇 - /2020/05/02/%E8%81%8A%E8%81%8A-mysql-%E7%9A%84-MVCC-%E7%BB%AD%E7%AF%87/ - 上一篇聊了mysql 的 innodb 引擎基于 read view 实现的 mvcc 和事务隔离级别,可能有些细心的小伙伴会发现一些问题,第一个是在 RC 级别下的事务提交后的可见性,这里涉及到了三个参数,m_low_limit_id,m_up_limit_id,m_ids,之前看到知乎的一篇写的非常不错的文章,但是就在这一点上似乎有点疑惑,这里基于源码和注释来解释下这个问题

    -
    /**
    -Opens a read view where exactly the transactions serialized before this
    -point in time are seen in the view.
    -@param id		Creator transaction id */
    -
    -void ReadView::prepare(trx_id_t id) {
    -  ut_ad(mutex_own(&trx_sys->mutex));
    -
    -  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 的文档

    + 聊聊 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 … 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.

    +

    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.

    -

    对于一个 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 一致性读就够了,如果是有写操作的呢,就需要锁了。

    +

    纯粹的这种一致性读,实际读取的是快照,也就是基于 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 @@ -14557,69 +14557,284 @@ be less than 256 */ /** 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; +/** 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. +
    +]]> + + 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 + 互斥锁 + +
    + + 聊聊传说中的 ThreadLocal + /2021/05/30/%E8%81%8A%E8%81%8A%E4%BC%A0%E8%AF%B4%E4%B8%AD%E7%9A%84-ThreadLocal/ + 说来也惭愧,这个 ThreadLocal 其实一直都是一知半解,而且看了一下之后还发现记错了,所以还是记录下
    原先记忆里的都是反过来,一个 ThreadLocal 是里面按照 thread 作为 key,存储线程内容的,真的是半解都米有,完全是错的,这样就得用 concurrentHashMap 这种去存储并且要锁定线程了,然后内容也只能存一个了,想想简直智障

    +

    究竟是啥结构

    比如我们在代码中 new 一个 ThreadLocal,

    +
    public static void main(String[] args) {
    +        ThreadLocal<Man> tl = new ThreadLocal<>();
    +
    +        new Thread(() -> {
    +            try {
    +                TimeUnit.SECONDS.sleep(2);
    +            } catch (InterruptedException e) {
    +                e.printStackTrace();
    +            }
    +            System.out.println(tl.get());
    +        }).start();
    +        new Thread(() -> {
    +            try {
    +                TimeUnit.SECONDS.sleep(1);
    +            } catch (InterruptedException e) {
    +                e.printStackTrace();
    +            }
    +            tl.set(new Man());
    +        }).start();
    +    }
     
    -/** Rollback data pointer: 7 bytes */
    -constexpr size_t DATA_ROLL_PTR = 2;
    +    static class Man {
    +        String name = "nick";
    +    }
    +

    这里构造了两个线程,一个先往里设值,一个后从里取,运行看下结果,

    知道这个用法的话肯定知道是取不到值的,只是具体的原理原来搞错了,我们来看下设值 set 方法

    +
    public void set(T value) {
    +    Thread t = Thread.currentThread();
    +    ThreadLocalMap map = getMap(t);
    +    if (map != null)
    +        map.set(this, value);
    +    else
    +        createMap(t, value);
    +}
    +

    写博客这会我才明白我原来咋会错得这么离谱,看到第一行代码 t 就是当前线程,然后第二行就是用这个线程去getMap,然后我是把这个当成从 map 里取值了,其实这里是

    +
    ThreadLocalMap getMap(Thread t) {
    +    return t.threadLocals;
    +}
    +

    获取 t 的 threadLocals 成员变量,那这个 threadLocals 又是啥呢

    它其实是线程 Thread 中的一个类型是java.lang.ThreadLocal.ThreadLocalMap的成员变量
    这是 ThreadLocal 的一个静态成员变量

    +
    static class ThreadLocalMap {
     
    -/** Rollback data pointer type size in bytes. */
    -constexpr size_t DATA_ROLL_PTR_LEN = 7;
    + /** + * The entries in this hash map extend WeakReference, using + * its main ref field as the key (which is always a + * ThreadLocal object). Note that null keys (i.e. entry.get() + * == null) mean that the key is no longer referenced, so the + * entry can be expunged from table. Such entries are referred to + * as "stale entries" in the code that follows. + */ + static class Entry extends WeakReference<ThreadLocal<?>> { + /** The value associated with this ThreadLocal. */ + Object value; -

    一个是 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);
      +            Entry(ThreadLocal<?> k, Object v) {
      +                super(k);
      +                value = v;
      +            }
      +        }
      +    }
      +

      全部代码有点长,只截取了一小部分,然后我们再回头来分析前面说的 set 过程,再 copy 下代码

      +
      public void set(T value) {
      +    Thread t = Thread.currentThread();
      +    ThreadLocalMap map = getMap(t);
      +    if (map != null)
      +        map.set(this, value);
      +    else
      +        createMap(t, value);
      +}
      +

      获取到 map 以后呢,如果 map 不为空,就往 map 里 set,这里注意 key 是啥,其实是当前这个 ThreadLocal,这里就比较明白了究竟是啥结构,每个线程都会维护自身的 ThreadLocalMap,它是线程的一个成员变量,当创建 ThreadLocal 的时候,进行设值的时候其实是往这个 map 里以 ThreadLocal 作为 key,往里设 value。

      +

      内存泄漏是什么鬼

      这里又要看下前面的 ThreadLocalMap 结构了,类似 HashMap,它有个 Entry 结构,在设置的时候会先包装成一个 Entry

      +
      private void set(ThreadLocal<?> key, Object value) {
       
      -    if (id < m_up_limit_id || id == m_creator_trx_id) {
      -      return (true);
      -    }
      +        // 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.
       
      -    check_trx_id_sanity(id, name);
      +        Entry[] tab = table;
      +        int len = tab.length;
      +        int i = key.threadLocalHashCode & (len-1);
       
      -    if (id >= m_low_limit_id) {
      -      return (false);
      +        for (Entry e = tab[i];
      +             e != null;
      +             e = tab[i = nextIndex(i, len)]) {
      +            ThreadLocal<?> k = e.get();
       
      -    } else if (m_ids.empty()) {
      -      return (true);
      -    }
      +            if (k == key) {
      +                e.value = value;
      +                return;
      +            }
       
      -    const ids_t::value_type *p = m_ids.data();
      +            if (k == null) {
      +                replaceStaleEntry(key, value, i);
      +                return;
      +            }
      +        }
       
      -    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. -
    + 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 掉

    ]]>
    - Mysql - C - 数据结构 - 源码 - Mysql + Java - mysql - 数据结构 - 源码 - mvcc - read view + Java + ThreadLocal + 弱引用 + 内存泄漏 + WeakReference
    @@ -14698,99 +14913,86 @@ constexpr size_t DATA_ROLL_PTR_LEN - 聊聊 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 - 互斥锁 - -
    - - 聊聊 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 一定会使用,也不是一定不会使用,而是优化器会根据查询成本做个预判,这个预判尽可能会减小查询成本,主要包括回表啥的,但是也不一定完全准确。

    + 聊聊一次 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
    +}
    +

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

    ]]>
    - Mysql - C - 索引 - Mysql + Mac + PHP + Homebrew + PHP + icu4c - mysql - 索引 - is null - is not null - procedure + Mac + PHP + Homebrew + icu4c + zsh + +
    + + 聊聊厦门旅游的好与不好 + /2021/04/11/%E8%81%8A%E8%81%8A%E5%8E%A6%E9%97%A8%E6%97%85%E6%B8%B8%E7%9A%84%E5%A5%BD%E4%B8%8E%E4%B8%8D%E5%A5%BD/ + 这几天去了趟厦门,原来几年前就想去了,本来都请好假了,后面因为一些事情没去成,这次刚好公司组织,就跟 LD 一起去了厦门,也不洋洋洒洒地写游记了,后面可能会有,今天先来总结下好的地方和比较坑的地方。
    这次主要去了中山路、鼓浪屿、曾厝(cuo)垵、植物园、灵玲马戏团,因为住的离环岛路比较近,还有幸现场看了下厦门马拉松,其中

    +

    中山路

    这里看上去是有点民国时期的建筑风格,部分像那种电视里的租界啥的,不过这次去的时候都在翻修,路一大半拦起来了,听导游说这里往里面走有个局口街,然后上次听前同事说厦门比较有名的就是沙茶面和海蛎煎,不出意料的不太爱吃,沙茶面比较普通,可能是没吃到正宗的,海蛎煎吃不惯,倒是有个大叔的沙茶里脊还不错,在局口街那,还有小哥在那拍,应该也算是个网红打卡点了,然后吃了个油条麻糍也还不错,总体如果是看建筑的话可能最近不是个好时间,个人也没这方面爱好,吃的话最好多打听打听沙茶面跟海蛎煎哪里正宗。如果不知道哪家好吃,也不爱看这类建筑的可以排个坑。

    +

    鼓浪屿

    鼓浪屿也是完全没啥概念,需要乘船过去,但是只要二十分钟,岛上没有机动车,基本都靠走,有几个比较有名的地方,菽庄花园,里面有钢琴博物馆,对这个感兴趣的可以去看看,旁边是沙滩还可以逛逛,然后有各种博物馆,风琴啥的,岛上最大的特色是巷子多,道听途说有三百多条小巷,还有几个网红打卡点,周杰伦晴天墙,还有个最美转角,都是挤满了人排队打卡拍照,不过如果不着急,慢慢悠悠逛逛还是不错的,比较推荐,推荐值☆☆

    +

    曾厝垵

    一直读不对这个字,都是叫:那个曾什么垵,愧对语文老师,这里到算是意外之喜,鼓浪屿回来已经挺累了,不过由于比较饿(什么原因后面说),并且离住的地方不远,就过去逛了逛,东西还蛮好吃的,芒果挺便宜,一大杯才十块,无骨鸡爪很贵,不是特别爱,臭豆腐不错的,也不算很贵,这里想起来,那边八婆婆的豆乳烧仙草还不错的,去中山路那会喝了,来曾厝垵也买了,奶茶爱好者可以试试,含糖量应该很高,不爱甜食或者减肥的同学慎重考虑好了再尝试,晚上那边从牌坊出来,沿着环岛路挺多夜宵店什么的,非常推荐,推荐值☆☆☆☆

    +

    植物园

    植物园还是挺名副其实的,有热带植物,沙漠多肉,因为赶时间逛得不多,热带雨林植物那太多人了,都是在那拍照,而且我指的拍照都是拍人照,本身就很小的路,各种十八线网红,或者普通游客在那摆 pose 拍照,挺无语的;沙漠多肉比较惊喜,好多比人高的仙人掌,一大片的仙人球,很可恶的是好多大仙人掌上都有人刻字,越来越体会到,我们社会人多了,什么样的都有,而且不少;还看了下百花厅,但没什么特别的,可能赶时间比较着急,没仔细看,比较推荐,推荐值☆☆☆

    +

    灵玲马戏团

    对这个其实比较排斥,主要是比较晚了,跑的有点远(我太懒了),一开始真的挺拉低体验感受的,上来个什么书法家,现场画马,卖画;不过后面的还算值回票价,主题是花木兰,空中动作应该很考验基本功,然后那些老外的飞轮还跳绳(不知道学名叫啥),动物那块不太忍心看,应该是吃了不少苦头,不过人都这样就往后点再心疼动物吧。

    +

    总结

    厦门是个非常适合干饭人的地方,吃饭的地方大部分是差不多一桌菜十个左右就完了,而且上来就一大碗饭,一瓶雪碧一瓶可乐,对于经常是家里跟亲戚吃饭都得十几二十个菜的乡下人来说,不太吃得惯这样的🤦‍♂️,当然很有可能是我们预算不足,点的差。但是有一点是我回杭州深有感触的,感觉杭州司机的素质真的是跟厦门的司机差了比较多,杭州除非公交车停了,否则人行道很难看到主动让人的,当然这里拿厦门这个旅游城市来对比也不是很公平,不过这也是体现城市现代化文明水平的一个维度吧。

    +]]>
    + + 生活 + 旅游 + + + 生活 + 杭州 + 旅游 + 厦门 + 中山路 + 局口街 + 鼓浪屿 + 曾厝垵 + 植物园 + 马戏团 + 沙茶面 + 海蛎煎
    @@ -15144,205 +15346,44 @@ $ - 聊聊传说中的 ThreadLocal - /2021/05/30/%E8%81%8A%E8%81%8A%E4%BC%A0%E8%AF%B4%E4%B8%AD%E7%9A%84-ThreadLocal/ - 说来也惭愧,这个 ThreadLocal 其实一直都是一知半解,而且看了一下之后还发现记错了,所以还是记录下
    原先记忆里的都是反过来,一个 ThreadLocal 是里面按照 thread 作为 key,存储线程内容的,真的是半解都米有,完全是错的,这样就得用 concurrentHashMap 这种去存储并且要锁定线程了,然后内容也只能存一个了,想想简直智障

    -

    究竟是啥结构

    比如我们在代码中 new 一个 ThreadLocal,

    -
    public static void main(String[] args) {
    -        ThreadLocal<Man> tl = new ThreadLocal<>();
    -
    -        new Thread(() -> {
    -            try {
    -                TimeUnit.SECONDS.sleep(2);
    -            } catch (InterruptedException e) {
    -                e.printStackTrace();
    -            }
    -            System.out.println(tl.get());
    -        }).start();
    -        new Thread(() -> {
    -            try {
    -                TimeUnit.SECONDS.sleep(1);
    -            } catch (InterruptedException e) {
    -                e.printStackTrace();
    -            }
    -            tl.set(new Man());
    -        }).start();
    -    }
    -
    -    static class Man {
    -        String name = "nick";
    -    }
    -

    这里构造了两个线程,一个先往里设值,一个后从里取,运行看下结果,

    知道这个用法的话肯定知道是取不到值的,只是具体的原理原来搞错了,我们来看下设值 set 方法

    -
    public void set(T value) {
    -    Thread t = Thread.currentThread();
    -    ThreadLocalMap map = getMap(t);
    -    if (map != null)
    -        map.set(this, value);
    -    else
    -        createMap(t, value);
    -}
    -

    写博客这会我才明白我原来咋会错得这么离谱,看到第一行代码 t 就是当前线程,然后第二行就是用这个线程去getMap,然后我是把这个当成从 map 里取值了,其实这里是

    -
    ThreadLocalMap getMap(Thread t) {
    -    return t.threadLocals;
    -}
    -

    获取 t 的 threadLocals 成员变量,那这个 threadLocals 又是啥呢

    它其实是线程 Thread 中的一个类型是java.lang.ThreadLocal.ThreadLocalMap的成员变量
    这是 ThreadLocal 的一个静态成员变量

    -
    static class ThreadLocalMap {
    -
    -        /**
    -         * The entries in this hash map extend WeakReference, using
    -         * its main ref field as the key (which is always a
    -         * ThreadLocal object).  Note that null keys (i.e. entry.get()
    -         * == null) mean that the key is no longer referenced, so the
    -         * entry can be expunged from table.  Such entries are referred to
    -         * as "stale entries" in the code that follows.
    -         */
    -        static class Entry extends WeakReference<ThreadLocal<?>> {
    -            /** The value associated with this ThreadLocal. */
    -            Object value;
    -
    -            Entry(ThreadLocal<?> k, Object v) {
    -                super(k);
    -                value = v;
    -            }
    -        }
    -    }
    -

    全部代码有点长,只截取了一小部分,然后我们再回头来分析前面说的 set 过程,再 copy 下代码

    -
    public void set(T value) {
    -    Thread t = Thread.currentThread();
    -    ThreadLocalMap map = getMap(t);
    -    if (map != null)
    -        map.set(this, value);
    -    else
    -        createMap(t, value);
    -}
    -

    获取到 map 以后呢,如果 map 不为空,就往 map 里 set,这里注意 key 是啥,其实是当前这个 ThreadLocal,这里就比较明白了究竟是啥结构,每个线程都会维护自身的 ThreadLocalMap,它是线程的一个成员变量,当创建 ThreadLocal 的时候,进行设值的时候其实是往这个 map 里以 ThreadLocal 作为 key,往里设 value。

    -

    内存泄漏是什么鬼

    这里又要看下前面的 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
    -
    -  cd $last_dir
    -}
    -

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

    + 聊聊如何识别和意识到日常生活中的各类危险 + /2021/06/06/%E8%81%8A%E8%81%8A%E5%A6%82%E4%BD%95%E8%AF%86%E5%88%AB%E5%92%8C%E6%84%8F%E8%AF%86%E5%88%B0%E6%97%A5%E5%B8%B8%E7%94%9F%E6%B4%BB%E4%B8%AD%E7%9A%84%E5%90%84%E7%B1%BB%E5%8D%B1%E9%99%A9/ + 这篇博客的灵感又是来自于我从绍兴来杭州的路上,在我们进站以后上电梯快到的时候,突然前面不动了,右边我能看到的是有个人的行李箱一时拎不起来,另一边后面看到其实是个小孩子在那哭闹,一位妈妈就在那停着安抚或者可能有点手足无措,其实这一点应该是在几年前慢慢意识到是个非常危险的场景,特别是像绍兴北站这样上去站台是非常长的电梯,因为最近扩建改造,车次减少了很多,所以每一班都有很多人,检票上站台的电梯都是满员运转,试想这种情况,如果刚才那位妈妈再多停留一点时间,很可能就会出现后面的人上不来被挤下去,再严重点就是踩踏事件,但是这类情况很少人真的意识到,非常明显的例子就是很多人拿着比较大比较重的行李箱,不走垂梯,并且在快到的时候没有提前准备好,有可能在玩手机啥的,如果提不动,后面又是挤满人了,就很可能出现前面说的这种情况,并且其实这种是非紧急情况,大多数人都没有心理准备,一旦发生后果可能就会很严重,例如火灾地震疏散大部分人或者说负责引导的都是指示要有序撤离,防止踩踏,但是普通坐个扶梯,一般都不会有这个意识,但是如果这个时间比较长,出现了人员站不住往后倒了,真的会很严重。所以如果自己是带娃的或者带了很重的行李箱的,请提前做好准备,看到前面有人带的,最好也保持一定距离。
    还有比如日常走路,旁边有车子停着的情况,比较基本的看车灯有没有亮着,亮着的是否是倒车灯,这种应该特别注意远离,至少保持距离,不能挨着走,很多人特别是一些老年人,在一些人比较多的路上,往往完全无视旁边这些车的状态,我走我的路,谁敢阻拦我,管他车在那动不动,其实真的非常危险,车子本身有视线死角,再加上司机的驾驶习惯和状态,想去送死跟碰瓷的除外,还有就是有一些车会比较特殊,车子发动着,但是没灯,可能是车子灯坏了或者司机通过什么方式关了灯,这种比较难避开,不过如果车子打着了,一般会有比较大的热量散发,车子刚灭了也会有,反正能远离点尽量远离,从轿车的车前面走过挨着走要比从屁股后面挨着走稍微安全一些,但也最好不要挨着车走。
    最后一点其实是我觉得是我自己比较怕死,一般对来向的车或者从侧面出来的车会做更长的预判距离,特别是电瓶车,一般是不让人的,像送外卖的小哥,的确他们不太容易,但是真的很危险啊,基本就生死看刹车,能刹住就赚了,刹不住就看身子骨扛不扛撞了,只是这里要多说点又要谈到资本的趋利性了,总是想法设法的压榨以获取更多的利益,也不扯远了,能远离就远离吧。

    ]]>
    - Mac - PHP - Homebrew - PHP - icu4c + 生活 - Mac - PHP - Homebrew - icu4c - zsh + 生活 + 糟心事 + 扶梯 + 踩踏 + 安全 + 电瓶车
    - 聊聊厦门旅游的好与不好 - /2021/04/11/%E8%81%8A%E8%81%8A%E5%8E%A6%E9%97%A8%E6%97%85%E6%B8%B8%E7%9A%84%E5%A5%BD%E4%B8%8E%E4%B8%8D%E5%A5%BD/ - 这几天去了趟厦门,原来几年前就想去了,本来都请好假了,后面因为一些事情没去成,这次刚好公司组织,就跟 LD 一起去了厦门,也不洋洋洒洒地写游记了,后面可能会有,今天先来总结下好的地方和比较坑的地方。
    这次主要去了中山路、鼓浪屿、曾厝(cuo)垵、植物园、灵玲马戏团,因为住的离环岛路比较近,还有幸现场看了下厦门马拉松,其中

    -

    中山路

    这里看上去是有点民国时期的建筑风格,部分像那种电视里的租界啥的,不过这次去的时候都在翻修,路一大半拦起来了,听导游说这里往里面走有个局口街,然后上次听前同事说厦门比较有名的就是沙茶面和海蛎煎,不出意料的不太爱吃,沙茶面比较普通,可能是没吃到正宗的,海蛎煎吃不惯,倒是有个大叔的沙茶里脊还不错,在局口街那,还有小哥在那拍,应该也算是个网红打卡点了,然后吃了个油条麻糍也还不错,总体如果是看建筑的话可能最近不是个好时间,个人也没这方面爱好,吃的话最好多打听打听沙茶面跟海蛎煎哪里正宗。如果不知道哪家好吃,也不爱看这类建筑的可以排个坑。

    -

    鼓浪屿

    鼓浪屿也是完全没啥概念,需要乘船过去,但是只要二十分钟,岛上没有机动车,基本都靠走,有几个比较有名的地方,菽庄花园,里面有钢琴博物馆,对这个感兴趣的可以去看看,旁边是沙滩还可以逛逛,然后有各种博物馆,风琴啥的,岛上最大的特色是巷子多,道听途说有三百多条小巷,还有几个网红打卡点,周杰伦晴天墙,还有个最美转角,都是挤满了人排队打卡拍照,不过如果不着急,慢慢悠悠逛逛还是不错的,比较推荐,推荐值☆☆

    -

    曾厝垵

    一直读不对这个字,都是叫:那个曾什么垵,愧对语文老师,这里到算是意外之喜,鼓浪屿回来已经挺累了,不过由于比较饿(什么原因后面说),并且离住的地方不远,就过去逛了逛,东西还蛮好吃的,芒果挺便宜,一大杯才十块,无骨鸡爪很贵,不是特别爱,臭豆腐不错的,也不算很贵,这里想起来,那边八婆婆的豆乳烧仙草还不错的,去中山路那会喝了,来曾厝垵也买了,奶茶爱好者可以试试,含糖量应该很高,不爱甜食或者减肥的同学慎重考虑好了再尝试,晚上那边从牌坊出来,沿着环岛路挺多夜宵店什么的,非常推荐,推荐值☆☆☆☆

    -

    植物园

    植物园还是挺名副其实的,有热带植物,沙漠多肉,因为赶时间逛得不多,热带雨林植物那太多人了,都是在那拍照,而且我指的拍照都是拍人照,本身就很小的路,各种十八线网红,或者普通游客在那摆 pose 拍照,挺无语的;沙漠多肉比较惊喜,好多比人高的仙人掌,一大片的仙人球,很可恶的是好多大仙人掌上都有人刻字,越来越体会到,我们社会人多了,什么样的都有,而且不少;还看了下百花厅,但没什么特别的,可能赶时间比较着急,没仔细看,比较推荐,推荐值☆☆☆

    -

    灵玲马戏团

    对这个其实比较排斥,主要是比较晚了,跑的有点远(我太懒了),一开始真的挺拉低体验感受的,上来个什么书法家,现场画马,卖画;不过后面的还算值回票价,主题是花木兰,空中动作应该很考验基本功,然后那些老外的飞轮还跳绳(不知道学名叫啥),动物那块不太忍心看,应该是吃了不少苦头,不过人都这样就往后点再心疼动物吧。

    -

    总结

    厦门是个非常适合干饭人的地方,吃饭的地方大部分是差不多一桌菜十个左右就完了,而且上来就一大碗饭,一瓶雪碧一瓶可乐,对于经常是家里跟亲戚吃饭都得十几二十个菜的乡下人来说,不太吃得惯这样的🤦‍♂️,当然很有可能是我们预算不足,点的差。但是有一点是我回杭州深有感触的,感觉杭州司机的素质真的是跟厦门的司机差了比较多,杭州除非公交车停了,否则人行道很难看到主动让人的,当然这里拿厦门这个旅游城市来对比也不是很公平,不过这也是体现城市现代化文明水平的一个维度吧。

    + 聊聊我刚学会的应用诊断方法 + /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
    @@ -15389,47 +15430,6 @@ $ 3PC - - 聊聊我刚学会的应用诊断方法 - /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 - -
    - - 聊聊如何识别和意识到日常生活中的各类危险 - /2021/06/06/%E8%81%8A%E8%81%8A%E5%A6%82%E4%BD%95%E8%AF%86%E5%88%AB%E5%92%8C%E6%84%8F%E8%AF%86%E5%88%B0%E6%97%A5%E5%B8%B8%E7%94%9F%E6%B4%BB%E4%B8%AD%E7%9A%84%E5%90%84%E7%B1%BB%E5%8D%B1%E9%99%A9/ - 这篇博客的灵感又是来自于我从绍兴来杭州的路上,在我们进站以后上电梯快到的时候,突然前面不动了,右边我能看到的是有个人的行李箱一时拎不起来,另一边后面看到其实是个小孩子在那哭闹,一位妈妈就在那停着安抚或者可能有点手足无措,其实这一点应该是在几年前慢慢意识到是个非常危险的场景,特别是像绍兴北站这样上去站台是非常长的电梯,因为最近扩建改造,车次减少了很多,所以每一班都有很多人,检票上站台的电梯都是满员运转,试想这种情况,如果刚才那位妈妈再多停留一点时间,很可能就会出现后面的人上不来被挤下去,再严重点就是踩踏事件,但是这类情况很少人真的意识到,非常明显的例子就是很多人拿着比较大比较重的行李箱,不走垂梯,并且在快到的时候没有提前准备好,有可能在玩手机啥的,如果提不动,后面又是挤满人了,就很可能出现前面说的这种情况,并且其实这种是非紧急情况,大多数人都没有心理准备,一旦发生后果可能就会很严重,例如火灾地震疏散大部分人或者说负责引导的都是指示要有序撤离,防止踩踏,但是普通坐个扶梯,一般都不会有这个意识,但是如果这个时间比较长,出现了人员站不住往后倒了,真的会很严重。所以如果自己是带娃的或者带了很重的行李箱的,请提前做好准备,看到前面有人带的,最好也保持一定距离。
    还有比如日常走路,旁边有车子停着的情况,比较基本的看车灯有没有亮着,亮着的是否是倒车灯,这种应该特别注意远离,至少保持距离,不能挨着走,很多人特别是一些老年人,在一些人比较多的路上,往往完全无视旁边这些车的状态,我走我的路,谁敢阻拦我,管他车在那动不动,其实真的非常危险,车子本身有视线死角,再加上司机的驾驶习惯和状态,想去送死跟碰瓷的除外,还有就是有一些车会比较特殊,车子发动着,但是没灯,可能是车子灯坏了或者司机通过什么方式关了灯,这种比较难避开,不过如果车子打着了,一般会有比较大的热量散发,车子刚灭了也会有,反正能远离点尽量远离,从轿车的车前面走过挨着走要比从屁股后面挨着走稍微安全一些,但也最好不要挨着车走。
    最后一点其实是我觉得是我自己比较怕死,一般对来向的车或者从侧面出来的车会做更长的预判距离,特别是电瓶车,一般是不让人的,像送外卖的小哥,的确他们不太容易,但是真的很危险啊,基本就生死看刹车,能刹住就赚了,刹不住就看身子骨扛不扛撞了,只是这里要多说点又要谈到资本的趋利性了,总是想法设法的压榨以获取更多的利益,也不扯远了,能远离就远离吧。

    -]]>
    - - 生活 - - - 生活 - 糟心事 - 扶梯 - 踩踏 - 安全 - 电瓶车 - -
    聊聊我的远程工作体验 /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/ @@ -15443,33 +15443,6 @@ $ 远程办公 - - 聊聊最近平淡的生活之看《神探狄仁杰》 - /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/12/31/%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%E3%80%8A%E8%8A%B1%E6%9D%9F%E8%88%AC%E7%9A%84%E6%81%8B%E7%88%B1%E3%80%8B%E8%A7%82%E5%90%8E%E6%84%9F/ - 周末在领导的提议下看了豆瓣的年度榜单,本来感觉没啥心情看的,看到主演有有村架纯就觉得可以看一下,颜值即正义嘛,男主小麦跟女主小娟(后面简称小麦跟小娟)是两个在一次非常偶然的没赶上地铁末班车事件中相识,这里得说下日本这种通宵营业的店好像挺不错的,看着也挺正常,国内估计只有酒吧之类的可以。晚上去的地方是有点暗暗的,好像也有点类似酒吧,旁边有类似于 dj 那种,然后同桌的还有除了男女主的另外一对男女,也是因为没赶上地铁末班车的,但也是陌生人,然后小麦突然看到了有个非常有名的电影人,小娟竟然也认识,然后旁边那对完全不认识,还在那吹自己看过很多电影,比如《肖申克的救赎》,于是男女主都特别鄙夷地看着他们,然后他们又去了另一个有点像泡澡的地方席地而坐,他们发现了自己的鞋子都是一样的,然后在女的去上厕所的时候,小麦暗恋的学姐也来了,然后小麦就去跟学姐他们一起坐了,小娟回来后有点不开心就说去朋友家睡,幸好小麦看出来了(他竟然看出来了,本来以为应该是没填过恋爱很木讷的),就追出去,然后就去了小麦家,到了家小娟发现小麦家的书柜上的书简直就跟她自己家的一模一样,小麦还给小娟吹了头发,一起吃烤饭团,看电影,第二天送小娟上了公交,还约好了一起看木乃伊展,然而并没有交换联系方式,但是他们还是约上了一起看了木乃伊展,在餐馆就出现了片头那一幕的来源,因为餐馆他们想一起听歌,就用有线耳机一人一个耳朵听,但是旁边就有个大叔说“你们是不是不爱音乐,左右耳朵是不一样的,只有一起听才是真正的音乐”这样的话,然后的剧情有点跳,因为是指他们一直在这家餐馆吃饭,中间有他们一起出去玩情节穿插着,也是在这他们确立了关系,可以说主体就是体现了他们非常的合拍和默契,就像一些影评说的,这部电影是说如何跟百分百合拍的人分手,然后就是正常的恋爱开始啪啪啪,一直腻在床上,也没去就业说明会,后面也有讲了一点小麦带着小娟去认识他的朋友,也把小娟介绍给了他们认识,这里算是个小伏笔,后面他们分手也有这里的人的一些关系,接下去的剧情说实话我是不太喜欢的,如果一部八分的电影只是说恋爱被现实打败的话,我觉得在我这是不合格的,但是事实也是这样,小麦其实是有家里的资助,所以后面还是按自己的喜好给一些机构画点插画,小娟则要出去工作,因为小娟家庭观念也是要让她出去有正经工作,用脚指头想也能知道肯定不顺利,然后就是暂时在一家蛋糕店工作,小麦就每天去接小娟,日子过得甜甜蜜蜜,后面小娟在自己的努力下考了个什么资格证,去了一家医院还是什么做前台行政,这中间当然就有父母来见面吃饭了,他们在开始恋爱不久就同居合租了,然后小娟父母就是来说要让她有个正经工作,对男的说的话就是人生就是责任这类的话,而小麦爸爸算是个导火索,因为小麦家里是做烟花生意的,他爸让他就做烟花生意,因为要回老家,并且小麦也不想做,所以就拒绝了,然后他爸就说不给他每个月五万的资助,这也导致了小麦需要去找工作,这个过程也是很辛苦,本来想要年前找好工作,然后事与愿违,后面有一次小娟被同事吐槽怎么从来不去团建,于是她就去了(我以为会拒绝),正在团建的时候小麦给她电话,说找到工作了,是一个创业物流公司这种,这里剧情就是我觉得比较俗套的,小麦各种被虐,累成狗,但是就像小娟爸爸说的话,人生就是责任,所以一直在坚持,但是这样也导致了跟小娟的交流也越来越少,他们原来最爱的漫画,爱玩的游戏,也只剩小娟一个人看,一个人玩,而正是这个时候,小娟说她辞掉了工作,去做一个不是太靠谱的漫画改造的密室逃脱,然后这里其实有一点后面争议很大的,就是这个工作其实是前面小麦介绍给小娟的那些朋友中一个的女朋友介绍的,而在有个剧情就是小娟有一次在这个密室逃脱的老板怀里醒过来,是在 KTV 那样的场景里,这就有很多人觉得小娟是不是出轨了,我觉得其实不那么重要,因为这个离职的事情已经让一切矛盾都摆在眼前,小麦其实是接受这种需要承担责任的生活,也想着要跟小娟结婚,但是小娟似乎还是想要过着那样理想的生活,做自己想做的事情,看自己爱看的漫画,也要小麦能像以前那样一直那么默契的有着相同的爱好,这里的触发点其实还有个是那个小麦的朋友(也就是他女朋友介绍小娟那个不靠谱工作的)的葬礼上,小麦在参加完葬礼后有挺多想倾诉的,而小娟只是想睡了,这个让小麦第二天起来都不想理小娟,只是这里我不太理解,难道这点闹情绪都不能接受吗,所谓的合拍也只是毫无限制的情况下的合拍吧,真正的生活怎么可能如此理想呢,即使没有物质生活的压力,也会有其他的各种压力和限制,在这之后其实小麦想说的是小娟是不是没有想跟自己继续在一起的想法了,而小娟觉得都不说话了,还怎么结婚呢,后面其实导演搞了个小 trick,突然放了异常婚礼,但是不是男女主的,我并不觉得这个桥段很好,在婚礼里男女主都觉得自己想要跟对方说分手了,但是当他们去了最开始一直去的餐馆的时候,一个算是一个现实映照的就是他们一直坐的位子被占了,可能也是导演想通过这个来说明他们已经回不去了,在餐馆交谈的时候,小麦其实是说他们结婚吧,并没有想前面婚礼上预设地要分手,但是小娟放弃了,不想结婚,因为不想过那样的生活了,而小麦觉得可能生活就是那样,不可能一直保持刚恋爱时候的那种感觉,生活就是责任,人生就意味着责任。

    -

    我的一些观点也在前面说了,恋爱到婚姻,即使物质没问题,经济没问题,也会有各种各样的问题,需要一起去解决,因为结婚就意味着需要相互扶持,而不是各取所需,可能我的要求比较高,后面男女主在分手后还一起住了一段时间,我原来还在想会不会通过这个方式让他们继续去磨合同步,只是我失望了,最后给个打分可能是 5 到 6 分吧,勉强及格,好的影视剧应该源于生活高于生活,这一部可能还比不上生活。

    -]]>
    - - 生活 - - - 生活 - 看剧 - -
    聊聊最近平淡的生活之又聊通勤 /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/ @@ -15490,13 +15463,10 @@ $ - 聊聊最近平淡的生活之看看老剧 - /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/12/31/%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%E3%80%8A%E8%8A%B1%E6%9D%9F%E8%88%AC%E7%9A%84%E6%81%8B%E7%88%B1%E3%80%8B%E8%A7%82%E5%90%8E%E6%84%9F/ + 周末在领导的提议下看了豆瓣的年度榜单,本来感觉没啥心情看的,看到主演有有村架纯就觉得可以看一下,颜值即正义嘛,男主小麦跟女主小娟(后面简称小麦跟小娟)是两个在一次非常偶然的没赶上地铁末班车事件中相识,这里得说下日本这种通宵营业的店好像挺不错的,看着也挺正常,国内估计只有酒吧之类的可以。晚上去的地方是有点暗暗的,好像也有点类似酒吧,旁边有类似于 dj 那种,然后同桌的还有除了男女主的另外一对男女,也是因为没赶上地铁末班车的,但也是陌生人,然后小麦突然看到了有个非常有名的电影人,小娟竟然也认识,然后旁边那对完全不认识,还在那吹自己看过很多电影,比如《肖申克的救赎》,于是男女主都特别鄙夷地看着他们,然后他们又去了另一个有点像泡澡的地方席地而坐,他们发现了自己的鞋子都是一样的,然后在女的去上厕所的时候,小麦暗恋的学姐也来了,然后小麦就去跟学姐他们一起坐了,小娟回来后有点不开心就说去朋友家睡,幸好小麦看出来了(他竟然看出来了,本来以为应该是没填过恋爱很木讷的),就追出去,然后就去了小麦家,到了家小娟发现小麦家的书柜上的书简直就跟她自己家的一模一样,小麦还给小娟吹了头发,一起吃烤饭团,看电影,第二天送小娟上了公交,还约好了一起看木乃伊展,然而并没有交换联系方式,但是他们还是约上了一起看了木乃伊展,在餐馆就出现了片头那一幕的来源,因为餐馆他们想一起听歌,就用有线耳机一人一个耳朵听,但是旁边就有个大叔说“你们是不是不爱音乐,左右耳朵是不一样的,只有一起听才是真正的音乐”这样的话,然后的剧情有点跳,因为是指他们一直在这家餐馆吃饭,中间有他们一起出去玩情节穿插着,也是在这他们确立了关系,可以说主体就是体现了他们非常的合拍和默契,就像一些影评说的,这部电影是说如何跟百分百合拍的人分手,然后就是正常的恋爱开始啪啪啪,一直腻在床上,也没去就业说明会,后面也有讲了一点小麦带着小娟去认识他的朋友,也把小娟介绍给了他们认识,这里算是个小伏笔,后面他们分手也有这里的人的一些关系,接下去的剧情说实话我是不太喜欢的,如果一部八分的电影只是说恋爱被现实打败的话,我觉得在我这是不合格的,但是事实也是这样,小麦其实是有家里的资助,所以后面还是按自己的喜好给一些机构画点插画,小娟则要出去工作,因为小娟家庭观念也是要让她出去有正经工作,用脚指头想也能知道肯定不顺利,然后就是暂时在一家蛋糕店工作,小麦就每天去接小娟,日子过得甜甜蜜蜜,后面小娟在自己的努力下考了个什么资格证,去了一家医院还是什么做前台行政,这中间当然就有父母来见面吃饭了,他们在开始恋爱不久就同居合租了,然后小娟父母就是来说要让她有个正经工作,对男的说的话就是人生就是责任这类的话,而小麦爸爸算是个导火索,因为小麦家里是做烟花生意的,他爸让他就做烟花生意,因为要回老家,并且小麦也不想做,所以就拒绝了,然后他爸就说不给他每个月五万的资助,这也导致了小麦需要去找工作,这个过程也是很辛苦,本来想要年前找好工作,然后事与愿违,后面有一次小娟被同事吐槽怎么从来不去团建,于是她就去了(我以为会拒绝),正在团建的时候小麦给她电话,说找到工作了,是一个创业物流公司这种,这里剧情就是我觉得比较俗套的,小麦各种被虐,累成狗,但是就像小娟爸爸说的话,人生就是责任,所以一直在坚持,但是这样也导致了跟小娟的交流也越来越少,他们原来最爱的漫画,爱玩的游戏,也只剩小娟一个人看,一个人玩,而正是这个时候,小娟说她辞掉了工作,去做一个不是太靠谱的漫画改造的密室逃脱,然后这里其实有一点后面争议很大的,就是这个工作其实是前面小麦介绍给小娟的那些朋友中一个的女朋友介绍的,而在有个剧情就是小娟有一次在这个密室逃脱的老板怀里醒过来,是在 KTV 那样的场景里,这就有很多人觉得小娟是不是出轨了,我觉得其实不那么重要,因为这个离职的事情已经让一切矛盾都摆在眼前,小麦其实是接受这种需要承担责任的生活,也想着要跟小娟结婚,但是小娟似乎还是想要过着那样理想的生活,做自己想做的事情,看自己爱看的漫画,也要小麦能像以前那样一直那么默契的有着相同的爱好,这里的触发点其实还有个是那个小麦的朋友(也就是他女朋友介绍小娟那个不靠谱工作的)的葬礼上,小麦在参加完葬礼后有挺多想倾诉的,而小娟只是想睡了,这个让小麦第二天起来都不想理小娟,只是这里我不太理解,难道这点闹情绪都不能接受吗,所谓的合拍也只是毫无限制的情况下的合拍吧,真正的生活怎么可能如此理想呢,即使没有物质生活的压力,也会有其他的各种压力和限制,在这之后其实小麦想说的是小娟是不是没有想跟自己继续在一起的想法了,而小娟觉得都不说话了,还怎么结婚呢,后面其实导演搞了个小 trick,突然放了异常婚礼,但是不是男女主的,我并不觉得这个桥段很好,在婚礼里男女主都觉得自己想要跟对方说分手了,但是当他们去了最开始一直去的餐馆的时候,一个算是一个现实映照的就是他们一直坐的位子被占了,可能也是导演想通过这个来说明他们已经回不去了,在餐馆交谈的时候,小麦其实是说他们结婚吧,并没有想前面婚礼上预设地要分手,但是小娟放弃了,不想结婚,因为不想过那样的生活了,而小麦觉得可能生活就是那样,不可能一直保持刚恋爱时候的那种感觉,生活就是责任,人生就意味着责任。

    +

    我的一些观点也在前面说了,恋爱到婚姻,即使物质没问题,经济没问题,也会有各种各样的问题,需要一起去解决,因为结婚就意味着需要相互扶持,而不是各取所需,可能我的要求比较高,后面男女主在分手后还一起住了一段时间,我原来还在想会不会通过这个方式让他们继续去磨合同步,只是我失望了,最后给个打分可能是 5 到 6 分吧,勉强及格,好的影视剧应该源于生活高于生活,这一部可能还比不上生活。

    ]]>
    生活 @@ -15506,25 +15476,6 @@ $ 看剧
    - - 聊聊给亲戚朋友的老电脑重装系统那些事儿 - /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 全家桶 - 修电脑的 - -
    聊聊那些加塞狗 /2021/01/17/%E8%81%8A%E8%81%8A%E9%82%A3%E4%BA%9B%E5%8A%A0%E5%A1%9E%E7%8B%97/ @@ -15543,153 +15494,39 @@ $ - 聊聊这次换车牌及其他 - /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,估计在交管局那边我就懵逼了,各种插队,而且车子开着车子,也不能随便跑,所以建议办这个的时候有个人一起比较好。

    -]]>
    - - 生活 - - - 生活 - 换车牌 - -
    - - 记一个容器中 dubbo 注册的小知识点 - /2022/10/09/%E8%AE%B0%E4%B8%80%E4%B8%AA%E5%AE%B9%E5%99%A8%E4%B8%AD-dubbo-%E6%B3%A8%E5%86%8C%E7%9A%84%E5%B0%8F%E7%9F%A5%E8%AF%86%E7%82%B9/ - 在目前环境下使用容器部署Java应用还是挺普遍的,但是有一些问题也是随之而来需要解决的,比如容器中应用的dubbo注册,在比较早的版本的dubbo中,就是简单地获取网卡的ip地址。
    具体代码在这个方法里 com.alibaba.dubbo.config.ServiceConfig#doExportUrlsFor1Protocol

    -
    private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List<URL> registryURLs) {
    -        String name = protocolConfig.getName();
    -        if (name == null || name.length() == 0) {
    -            name = "dubbo";
    -        }
    -
    -        String host = protocolConfig.getHost();
    -        if (provider != null && (host == null || host.length() == 0)) {
    -            host = provider.getHost();
    -        }
    -        boolean anyhost = false;
    -        if (NetUtils.isInvalidLocalHost(host)) {
    -            anyhost = true;
    -            try {
    -                host = InetAddress.getLocalHost().getHostAddress();
    -            } catch (UnknownHostException e) {
    -                logger.warn(e.getMessage(), e);
    -            }
    -            if (NetUtils.isInvalidLocalHost(host)) {
    -                if (registryURLs != null && registryURLs.size() > 0) {
    -                    for (URL registryURL : registryURLs) {
    -                        try {
    -                            Socket socket = new Socket();
    -                            try {
    -                                SocketAddress addr = new InetSocketAddress(registryURL.getHost(), registryURL.getPort());
    -                                socket.connect(addr, 1000);
    -                                host = socket.getLocalAddress().getHostAddress();
    -                                break;
    -                            } finally {
    -                                try {
    -                                    socket.close();
    -                                } catch (Throwable e) {}
    -                            }
    -                        } catch (Exception e) {
    -                            logger.warn(e.getMessage(), e);
    -                        }
    -                    }
    -                }
    -                if (NetUtils.isInvalidLocalHost(host)) {
    -                    host = NetUtils.getLocalHost();
    -                }
    -            }
    -        }
    -

    通过jdk自带的方法 java.net.InetAddress#getLocalHost来获取本机地址,这样子对于容器来讲,获取到容器内部ip注册上去其实是没办法被调用到的,
    而在之后的版本中例如dubbo 2.6.5,则可以通过在docker中设置环境变量的形式来注入docker所在的宿主机地址,
    代码同样在com.alibaba.dubbo.config.ServiceConfig#doExportUrlsFor1Protocol这个方法中,但是获取host的方法变成了 com.alibaba.dubbo.config.ServiceConfig#findConfigedHosts

    -
    private String findConfigedHosts(ProtocolConfig protocolConfig, List<URL> registryURLs, Map<String, String> map) {
    -        boolean anyhost = false;
    -
    -        String hostToBind = getValueFromConfig(protocolConfig, Constants.DUBBO_IP_TO_BIND);
    -        if (hostToBind != null && hostToBind.length() > 0 && isInvalidLocalHost(hostToBind)) {
    -            throw new IllegalArgumentException("Specified invalid bind ip from property:" + Constants.DUBBO_IP_TO_BIND + ", value:" + hostToBind);
    -        }
    -
    -        // if bind ip is not found in environment, keep looking up
    -        if (hostToBind == null || hostToBind.length() == 0) {
    -            hostToBind = protocolConfig.getHost();
    -            if (provider != null && (hostToBind == null || hostToBind.length() == 0)) {
    -                hostToBind = provider.getHost();
    -            }
    -            if (isInvalidLocalHost(hostToBind)) {
    -                anyhost = true;
    -                try {
    -                    hostToBind = InetAddress.getLocalHost().getHostAddress();
    -                } catch (UnknownHostException e) {
    -                    logger.warn(e.getMessage(), e);
    -                }
    -                if (isInvalidLocalHost(hostToBind)) {
    -                    if (registryURLs != null && !registryURLs.isEmpty()) {
    -                        for (URL registryURL : registryURLs) {
    -                            if (Constants.MULTICAST.equalsIgnoreCase(registryURL.getParameter("registry"))) {
    -                                // skip multicast registry since we cannot connect to it via Socket
    -                                continue;
    -                            }
    -                            try {
    -                                Socket socket = new Socket();
    -                                try {
    -                                    SocketAddress addr = new InetSocketAddress(registryURL.getHost(), registryURL.getPort());
    -                                    socket.connect(addr, 1000);
    -                                    hostToBind = socket.getLocalAddress().getHostAddress();
    -                                    break;
    -                                } finally {
    -                                    try {
    -                                        socket.close();
    -                                    } catch (Throwable e) {
    -                                    }
    -                                }
    -                            } catch (Exception e) {
    -                                logger.warn(e.getMessage(), e);
    -                            }
    -                        }
    -                    }
    -                    if (isInvalidLocalHost(hostToBind)) {
    -                        hostToBind = getLocalHost();
    -                    }
    -                }
    -            }
    -        }
    -
    -        map.put(Constants.BIND_IP_KEY, hostToBind);
    -
    -        // registry ip is not used for bind ip by default
    -        String hostToRegistry = getValueFromConfig(protocolConfig, Constants.DUBBO_IP_TO_REGISTRY);
    -        if (hostToRegistry != null && hostToRegistry.length() > 0 && isInvalidLocalHost(hostToRegistry)) {
    -            throw new IllegalArgumentException("Specified invalid registry ip from property:" + Constants.DUBBO_IP_TO_REGISTRY + ", value:" + hostToRegistry);
    -        } else if (hostToRegistry == null || hostToRegistry.length() == 0) {
    -            // bind ip is used as registry ip by default
    -            hostToRegistry = hostToBind;
    -        }
    -
    -        map.put(Constants.ANYHOST_KEY, String.valueOf(anyhost));
    -
    -        return hostToRegistry;
    -    }
    -

    String hostToRegistry = getValueFromConfig(protocolConfig, Constants.DUBBO_IP_TO_REGISTRY);
    就是这一行,

    -
    private String getValueFromConfig(ProtocolConfig protocolConfig, String key) {
    -    String protocolPrefix = protocolConfig.getName().toUpperCase() + "_";
    -    String port = ConfigUtils.getSystemProperty(protocolPrefix + key);
    -    if (port == null || port.length() == 0) {
    -        port = ConfigUtils.getSystemProperty(key);
    -    }
    -    return port;
    -}
    -

    也就是配置了DUBBO_IP_TO_REGISTRY这个环境变量

    + 聊聊最近平淡的生活之看看老剧 + /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)一篇了

    ]]>
    - java + 生活 - dubbo + 生活 + 看剧 + +
    + + 聊聊给亲戚朋友的老电脑重装系统那些事儿 + /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 全家桶 + 修电脑的
    @@ -15706,6 +15543,22 @@ $ 杭州 + + 聊聊这次换车牌及其他 + /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,估计在交管局那边我就懵逼了,各种插队,而且车子开着车子,也不能随便跑,所以建议办这个的时候有个人一起比较好。

    +]]>
    + + 生活 + + + 生活 + 换车牌 + +
    记录下 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/ @@ -15775,6 +15628,19 @@ $ stream + + 聊聊最近平淡的生活之看《神探狄仁杰》 + /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 版之后的各种乱七八糟的翻牌和乱拍已经让这个真正的王者神话故事有点力不从心,这里边有部西游记后传是个人还比较喜欢的,虽然武打动作比较鬼畜,但是剧情基本是无敌的,在西游的架构上衍生出来这么完整丰富的故事,人物角色也都有各自的出彩点。
    说回狄仁杰,在这之前也看过徐克拍的几部狄仁杰的电影版,第一部刘德华拍得相对完成度更高,故事性也可圈可点,后面几部就是剧情拉胯,靠特效拉回来一点分,虽说这个也是所谓的狄仁杰宇宙的构思在里面但是现在来看基本是跟西游那些差不多,完全没有整体性可言,打一枪换一个地方,演员也没有延续性,剧情也是前后跳脱,没什么关联跟承上启下,导致质量层次不一,更不用谈什么狄仁杰宇宙了,不过这个事情也是难说,原因很多,现在资本都是更加趋利的,一些需要更长久时间才能有回报的投资是很难获得资本青睐,所以只能将重心投给选择一些流量明星,而本来应该将资源投给剧本打磨的基本就没了,再深入说也没意义了,社会现状就是这样。
    还有一点感想是,以前的剧里的拍摄环境还是比较惨的,看着一些房子,甚至皇宫都是比较破旧的,地面还是石板这种,想想以前的演员的环境再想想现在的,比如成龙说的,以前他拍剧就是啪摔了,问这条有没有过,过了就直接送医院,而不是现在可能手蹭破点皮就大叫,甚至还有饭圈这些破事。

    +]]>
    + + 生活 + + + 生活 + 看剧 + +
    记录下 zookeeper 集群迁移和易错点 /2022/05/29/%E8%AE%B0%E5%BD%95%E4%B8%8B-zookeeper-%E9%9B%86%E7%BE%A4%E8%BF%81%E7%A7%BB/ @@ -15824,22 +15690,25 @@ zk3 192.168.2.3 - 这周末我又在老丈人家打了天小工 - /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/ + 新年开工开车来杭州,因为没有车位加限行今天来就没开车来了,从东站做公交回住的地方,这班神奇的车我之前也吐槽过了,有神奇的乘客和神奇的司机,因为基本上这班车是从我毕业就开始乘了,所以也算是比较熟悉了,以前总体感觉不太好的是乘坐时间太长了,不过这个也不能怪车,是我自己住得远(离东站),后来住到了现在的地方,也算是直达,并且 LD 比较喜欢直达的,不爱更快却要换乘的地铁,所以坐的频率比较高,也说过前面那些比较气人的乘客,自己不好好戴口罩,反而联合一起上车的乘客诽谤司机,说他要吃人了要打人了,也正是这个司机比较有意思,上车就让戴好口罩,还给大家讲,哪里哪里又有疫情了,我觉得其实这个司机还是不错的,特殊时期,对于这种公共交通,这样的确是比较负责任的做法,只是说话方式,语气这个因人而异,他也不是来伺候人的,而且这么一大车人,说了一遍不行,再说一遍,三遍以上了,嗓门大一点也属于正常的人的行为。
    还是说回今天要说的,今天这位司机我看着跟前面说的那位有点像,因为上车的时候比较暗没看清脸,主要原因是这位司机开车比较猛,比较急,然后车上因为这个时间点,比较多大学开学来的学生,拎着个行李箱,一开始是前面已经都站满了人,后面还有很多空位,因为后面没地方放行李箱,就因为这样前面站着的有几个就在说司机开慢点,结果司机貌似也没听进去,还是我行我素,过了会又有人说司机开稳一点,就在这个人说完没一会,停在红绿灯路口的车里,就有人问有没有垃圾桶,接着又让司机开门,说晕车太严重了,要下车,司机开了门,我望出去两个妹子下了车,好像在路边草丛吐了,前面开门下车的时候就有人说她们第一次来杭州,可能有点责怪司机开的不稳,也影响了杭州交通给新来杭州的人的感受,说完了事情经过,其实我有蛮多感触,对于杭州公交司机,我大概是大一来了没多久,陪室友去文三路买电脑就晕车,下车的时候在公交车站吐了,可能是从大学开始缺乏锻炼,又饮食不规律,更加容易晕车,大部分晕车我觉得都是我自己的原因,有时候是上车前吃太多了,或者早上起太早,没睡好,没吃东西,反正自己也是挺多原因的,说到司机的原因的话,我觉得可能这班车还算好的,最让我难受的还是上下班高峰的时候,因为经过的那条路是比较重要的主干道,路比较老比较窄,并且还有很多人行道,所以经常一脚油门连带着一脚刹车,真的很难受,这种算是我觉得真的是公交体验比较差的一点,但是这一点呢也不能完全怪公交司机,杭州的路政规划是很垃圾,没看错,是垃圾,所以总体结论是公交还行,主要是路政规划就是垃圾,包括这条主干道这么多人行道,并且两边都是老小区,老年人在上班高峰可能要买菜送娃或者其他事情,在通畅的情况下可能只需要六分钟的路程,有时候因为各种原因,半小时都开不完,扯开去一点,杭州的路,核心的高速说封就封,本来是高架可以直接通到城西,结果没造,到了路本已经很拥挤的时候开始来造隧道,各种破坏,隧道接高架的地方,无尽的加塞,对于我这样的小白司机来说真的是太恶心了,所以我一直想说的就是杭州这个地方房价领先基础设施十年,地铁,高架,高速通通不行,地面道路就更不行了。
    总结下,其实杭州的真正的公交体验差,应该还是路造成的,对于前面的那两位妹子来说,有可能是她们来自于公交司机都是开的特别稳,并且路况也很好的地方,也或者是我被虐习惯了🤦‍♂️

    ]]>
    生活 - 运动 - 跑步 - 干活 + 公交 生活 - 运动 - 减肥 - 跑步 - 干活 + 开车 + 加塞 + 糟心事 + 规则 + 公交 + 路政规划 + 基础设施 + 杭州 + 高速
    @@ -15858,28 +15727,6 @@ zk3 192.168.2.3 - - 闲聊下乘公交的用户体验 - /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/ - 新年开工开车来杭州,因为没有车位加限行今天来就没开车来了,从东站做公交回住的地方,这班神奇的车我之前也吐槽过了,有神奇的乘客和神奇的司机,因为基本上这班车是从我毕业就开始乘了,所以也算是比较熟悉了,以前总体感觉不太好的是乘坐时间太长了,不过这个也不能怪车,是我自己住得远(离东站),后来住到了现在的地方,也算是直达,并且 LD 比较喜欢直达的,不爱更快却要换乘的地铁,所以坐的频率比较高,也说过前面那些比较气人的乘客,自己不好好戴口罩,反而联合一起上车的乘客诽谤司机,说他要吃人了要打人了,也正是这个司机比较有意思,上车就让戴好口罩,还给大家讲,哪里哪里又有疫情了,我觉得其实这个司机还是不错的,特殊时期,对于这种公共交通,这样的确是比较负责任的做法,只是说话方式,语气这个因人而异,他也不是来伺候人的,而且这么一大车人,说了一遍不行,再说一遍,三遍以上了,嗓门大一点也属于正常的人的行为。
    还是说回今天要说的,今天这位司机我看着跟前面说的那位有点像,因为上车的时候比较暗没看清脸,主要原因是这位司机开车比较猛,比较急,然后车上因为这个时间点,比较多大学开学来的学生,拎着个行李箱,一开始是前面已经都站满了人,后面还有很多空位,因为后面没地方放行李箱,就因为这样前面站着的有几个就在说司机开慢点,结果司机貌似也没听进去,还是我行我素,过了会又有人说司机开稳一点,就在这个人说完没一会,停在红绿灯路口的车里,就有人问有没有垃圾桶,接着又让司机开门,说晕车太严重了,要下车,司机开了门,我望出去两个妹子下了车,好像在路边草丛吐了,前面开门下车的时候就有人说她们第一次来杭州,可能有点责怪司机开的不稳,也影响了杭州交通给新来杭州的人的感受,说完了事情经过,其实我有蛮多感触,对于杭州公交司机,我大概是大一来了没多久,陪室友去文三路买电脑就晕车,下车的时候在公交车站吐了,可能是从大学开始缺乏锻炼,又饮食不规律,更加容易晕车,大部分晕车我觉得都是我自己的原因,有时候是上车前吃太多了,或者早上起太早,没睡好,没吃东西,反正自己也是挺多原因的,说到司机的原因的话,我觉得可能这班车还算好的,最让我难受的还是上下班高峰的时候,因为经过的那条路是比较重要的主干道,路比较老比较窄,并且还有很多人行道,所以经常一脚油门连带着一脚刹车,真的很难受,这种算是我觉得真的是公交体验比较差的一点,但是这一点呢也不能完全怪公交司机,杭州的路政规划是很垃圾,没看错,是垃圾,所以总体结论是公交还行,主要是路政规划就是垃圾,包括这条主干道这么多人行道,并且两边都是老小区,老年人在上班高峰可能要买菜送娃或者其他事情,在通畅的情况下可能只需要六分钟的路程,有时候因为各种原因,半小时都开不完,扯开去一点,杭州的路,核心的高速说封就封,本来是高架可以直接通到城西,结果没造,到了路本已经很拥挤的时候开始来造隧道,各种破坏,隧道接高架的地方,无尽的加塞,对于我这样的小白司机来说真的是太恶心了,所以我一直想说的就是杭州这个地方房价领先基础设施十年,地铁,高架,高速通通不行,地面道路就更不行了。
    总结下,其实杭州的真正的公交体验差,应该还是路造成的,对于前面的那两位妹子来说,有可能是她们来自于公交司机都是开的特别稳,并且路况也很好的地方,也或者是我被虐习惯了🤦‍♂️

    -]]>
    - - 生活 - 公交 - - - 生活 - 开车 - 加塞 - 糟心事 - 规则 - 公交 - 路政规划 - 基础设施 - 杭州 - 高速 - -
    闲话篇-也算碰到了为老不尊和坏人变老了的典型案例 /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/ @@ -15922,4 +15769,157 @@ zk3 192.168.2.3 + + 记一个容器中 dubbo 注册的小知识点 + /2022/10/09/%E8%AE%B0%E4%B8%80%E4%B8%AA%E5%AE%B9%E5%99%A8%E4%B8%AD-dubbo-%E6%B3%A8%E5%86%8C%E7%9A%84%E5%B0%8F%E7%9F%A5%E8%AF%86%E7%82%B9/ + 在目前环境下使用容器部署Java应用还是挺普遍的,但是有一些问题也是随之而来需要解决的,比如容器中应用的dubbo注册,在比较早的版本的dubbo中,就是简单地获取网卡的ip地址。
    具体代码在这个方法里 com.alibaba.dubbo.config.ServiceConfig#doExportUrlsFor1Protocol

    +
    private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List<URL> registryURLs) {
    +        String name = protocolConfig.getName();
    +        if (name == null || name.length() == 0) {
    +            name = "dubbo";
    +        }
    +
    +        String host = protocolConfig.getHost();
    +        if (provider != null && (host == null || host.length() == 0)) {
    +            host = provider.getHost();
    +        }
    +        boolean anyhost = false;
    +        if (NetUtils.isInvalidLocalHost(host)) {
    +            anyhost = true;
    +            try {
    +                host = InetAddress.getLocalHost().getHostAddress();
    +            } catch (UnknownHostException e) {
    +                logger.warn(e.getMessage(), e);
    +            }
    +            if (NetUtils.isInvalidLocalHost(host)) {
    +                if (registryURLs != null && registryURLs.size() > 0) {
    +                    for (URL registryURL : registryURLs) {
    +                        try {
    +                            Socket socket = new Socket();
    +                            try {
    +                                SocketAddress addr = new InetSocketAddress(registryURL.getHost(), registryURL.getPort());
    +                                socket.connect(addr, 1000);
    +                                host = socket.getLocalAddress().getHostAddress();
    +                                break;
    +                            } finally {
    +                                try {
    +                                    socket.close();
    +                                } catch (Throwable e) {}
    +                            }
    +                        } catch (Exception e) {
    +                            logger.warn(e.getMessage(), e);
    +                        }
    +                    }
    +                }
    +                if (NetUtils.isInvalidLocalHost(host)) {
    +                    host = NetUtils.getLocalHost();
    +                }
    +            }
    +        }
    +

    通过jdk自带的方法 java.net.InetAddress#getLocalHost来获取本机地址,这样子对于容器来讲,获取到容器内部ip注册上去其实是没办法被调用到的,
    而在之后的版本中例如dubbo 2.6.5,则可以通过在docker中设置环境变量的形式来注入docker所在的宿主机地址,
    代码同样在com.alibaba.dubbo.config.ServiceConfig#doExportUrlsFor1Protocol这个方法中,但是获取host的方法变成了 com.alibaba.dubbo.config.ServiceConfig#findConfigedHosts

    +
    private String findConfigedHosts(ProtocolConfig protocolConfig, List<URL> registryURLs, Map<String, String> map) {
    +        boolean anyhost = false;
    +
    +        String hostToBind = getValueFromConfig(protocolConfig, Constants.DUBBO_IP_TO_BIND);
    +        if (hostToBind != null && hostToBind.length() > 0 && isInvalidLocalHost(hostToBind)) {
    +            throw new IllegalArgumentException("Specified invalid bind ip from property:" + Constants.DUBBO_IP_TO_BIND + ", value:" + hostToBind);
    +        }
    +
    +        // if bind ip is not found in environment, keep looking up
    +        if (hostToBind == null || hostToBind.length() == 0) {
    +            hostToBind = protocolConfig.getHost();
    +            if (provider != null && (hostToBind == null || hostToBind.length() == 0)) {
    +                hostToBind = provider.getHost();
    +            }
    +            if (isInvalidLocalHost(hostToBind)) {
    +                anyhost = true;
    +                try {
    +                    hostToBind = InetAddress.getLocalHost().getHostAddress();
    +                } catch (UnknownHostException e) {
    +                    logger.warn(e.getMessage(), e);
    +                }
    +                if (isInvalidLocalHost(hostToBind)) {
    +                    if (registryURLs != null && !registryURLs.isEmpty()) {
    +                        for (URL registryURL : registryURLs) {
    +                            if (Constants.MULTICAST.equalsIgnoreCase(registryURL.getParameter("registry"))) {
    +                                // skip multicast registry since we cannot connect to it via Socket
    +                                continue;
    +                            }
    +                            try {
    +                                Socket socket = new Socket();
    +                                try {
    +                                    SocketAddress addr = new InetSocketAddress(registryURL.getHost(), registryURL.getPort());
    +                                    socket.connect(addr, 1000);
    +                                    hostToBind = socket.getLocalAddress().getHostAddress();
    +                                    break;
    +                                } finally {
    +                                    try {
    +                                        socket.close();
    +                                    } catch (Throwable e) {
    +                                    }
    +                                }
    +                            } catch (Exception e) {
    +                                logger.warn(e.getMessage(), e);
    +                            }
    +                        }
    +                    }
    +                    if (isInvalidLocalHost(hostToBind)) {
    +                        hostToBind = getLocalHost();
    +                    }
    +                }
    +            }
    +        }
    +
    +        map.put(Constants.BIND_IP_KEY, hostToBind);
    +
    +        // registry ip is not used for bind ip by default
    +        String hostToRegistry = getValueFromConfig(protocolConfig, Constants.DUBBO_IP_TO_REGISTRY);
    +        if (hostToRegistry != null && hostToRegistry.length() > 0 && isInvalidLocalHost(hostToRegistry)) {
    +            throw new IllegalArgumentException("Specified invalid registry ip from property:" + Constants.DUBBO_IP_TO_REGISTRY + ", value:" + hostToRegistry);
    +        } else if (hostToRegistry == null || hostToRegistry.length() == 0) {
    +            // bind ip is used as registry ip by default
    +            hostToRegistry = hostToBind;
    +        }
    +
    +        map.put(Constants.ANYHOST_KEY, String.valueOf(anyhost));
    +
    +        return hostToRegistry;
    +    }
    +

    String hostToRegistry = getValueFromConfig(protocolConfig, Constants.DUBBO_IP_TO_REGISTRY);
    就是这一行,

    +
    private String getValueFromConfig(ProtocolConfig protocolConfig, String key) {
    +    String protocolPrefix = protocolConfig.getName().toUpperCase() + "_";
    +    String port = ConfigUtils.getSystemProperty(protocolPrefix + key);
    +    if (port == null || port.length() == 0) {
    +        port = ConfigUtils.getSystemProperty(key);
    +    }
    +    return port;
    +}
    +

    也就是配置了DUBBO_IP_TO_REGISTRY这个环境变量

    +]]>
    + + java + + + dubbo + +
    + + 这周末我又在老丈人家打了天小工 + /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 毫升左右的矿泉水。

    +]]>
    + + 生活 + 运动 + 跑步 + 干活 + + + 生活 + 运动 + 减肥 + 跑步 + 干活 + +
    diff --git a/sitemap.xml b/sitemap.xml index 85e4d6ce51..ce343baa0e 100644 --- a/sitemap.xml +++ b/sitemap.xml @@ -200,7 +200,7 @@ - https://nicksxs.me/2022/02/27/Disruptor-%E7%B3%BB%E5%88%97%E4%BA%8C/ + https://nicksxs.me/2022/02/13/Disruptor-%E7%B3%BB%E5%88%97%E4%B8%80/ 2022-06-11 @@ -209,7 +209,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 @@ -245,7 +245,7 @@ - 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 @@ -254,7 +254,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/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 @@ -290,7 +290,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 @@ -299,7 +299,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 @@ -308,7 +308,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/2022/01/30/spring-event-%E4%BB%8B%E7%BB%8D/ 2022-06-11 @@ -317,7 +317,7 @@ - https://nicksxs.me/2022/01/30/spring-event-%E4%BB%8B%E7%BB%8D/ + 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 @@ -371,7 +371,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/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 @@ -380,7 +380,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/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 @@ -389,7 +389,7 @@ - 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/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 @@ -398,7 +398,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 @@ -407,7 +407,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/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 @@ -425,7 +425,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/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 @@ -443,7 +443,7 @@ - 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/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 @@ -452,7 +452,7 @@ - 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 @@ -461,7 +461,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/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 @@ -470,7 +470,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/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 @@ -479,7 +479,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/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 @@ -488,7 +488,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/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 @@ -1397,7 +1397,7 @@ - https://nicksxs.me/2019/12/10/Redis-Part-1/ + https://nicksxs.me/2015/03/13/Reverse-Integer/ 2020-01-12 @@ -1406,7 +1406,7 @@ - https://nicksxs.me/2017/05/09/ambari-summary/ + https://nicksxs.me/2015/03/11/Reverse-Bits/ 2020-01-12 @@ -1415,7 +1415,7 @@ - https://nicksxs.me/2015/03/13/Reverse-Integer/ + https://nicksxs.me/2015/01/14/Two-Sum/ 2020-01-12 @@ -1424,7 +1424,7 @@ - https://nicksxs.me/2015/01/14/Two-Sum/ + https://nicksxs.me/2016/09/29/binary-watch/ 2020-01-12 @@ -1433,7 +1433,7 @@ - https://nicksxs.me/2016/08/14/docker-mysql-cluster/ + https://nicksxs.me/2019/12/10/Redis-Part-1/ 2020-01-12 @@ -1442,7 +1442,7 @@ - https://nicksxs.me/2016/09/29/binary-watch/ + https://nicksxs.me/2017/05/09/ambari-summary/ 2020-01-12 @@ -1451,7 +1451,7 @@ - https://nicksxs.me/2015/03/11/Reverse-Bits/ + https://nicksxs.me/2016/08/14/docker-mysql-cluster/ 2020-01-12 @@ -1478,7 +1478,7 @@ - https://nicksxs.me/2019/12/26/redis%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%BB%8B%E7%BB%8D/ + https://nicksxs.me/2016/11/10/php-abstract-class-and-interface/ 2020-01-12 @@ -1496,7 +1496,7 @@ - https://nicksxs.me/2016/11/10/php-abstract-class-and-interface/ + https://nicksxs.me/2019/12/26/redis%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%BB%8B%E7%BB%8D/ 2020-01-12 @@ -1523,7 +1523,7 @@ - https://nicksxs.me/categories/index.html + https://nicksxs.me/tags/index.html 2020-01-12 @@ -1532,7 +1532,7 @@ - https://nicksxs.me/tags/index.html + https://nicksxs.me/categories/index.html 2020-01-12 @@ -1541,7 +1541,7 @@ - https://nicksxs.me/2014/12/30/Clone-Graph-Part-I/ + https://nicksxs.me/2019/09/23/AbstractQueuedSynchronizer/ 2020-01-12 @@ -1550,7 +1550,7 @@ - https://nicksxs.me/2019/09/23/AbstractQueuedSynchronizer/ + https://nicksxs.me/2014/12/30/Clone-Graph-Part-I/ 2020-01-12 @@ -1568,7 +1568,7 @@ - https://nicksxs.me/2015/01/04/Path-Sum/ + https://nicksxs.me/2015/03/11/Number-Of-1-Bits/ 2020-01-12 @@ -1577,7 +1577,7 @@ - https://nicksxs.me/2015/03/11/Number-Of-1-Bits/ + https://nicksxs.me/2015/01/04/Path-Sum/ 2020-01-12 @@ -1622,7 +1622,7 @@ - https://nicksxs.me/2017/03/28/spark-little-tips/ + https://nicksxs.me/2016/07/13/swoole-websocket-test/ 2020-01-12 @@ -1631,7 +1631,7 @@ - https://nicksxs.me/2016/07/13/swoole-websocket-test/ + https://nicksxs.me/2017/03/28/spark-little-tips/ 2020-01-12 @@ -1687,7 +1687,7 @@ https://nicksxs.me/ - 2022-10-11 + 2022-10-12 daily 1.0 @@ -1695,1988 +1695,1988 @@ https://nicksxs.me/tags/%E7%94%9F%E6%B4%BB/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E5%B9%B4%E7%BB%88%E6%80%BB%E7%BB%93/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/2020/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/2021/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E6%8B%96%E6%9B%B4/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/leetcode/ - 2022-10-11 + https://nicksxs.me/tags/Java/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/java/ - 2022-10-11 + https://nicksxs.me/tags/JVM/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/Binary-Tree/ - 2022-10-11 + https://nicksxs.me/tags/C/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/DFS/ - 2022-10-11 + https://nicksxs.me/tags/leetcode/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E4%BA%8C%E5%8F%89%E6%A0%91/ - 2022-10-11 + https://nicksxs.me/tags/java/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E9%A2%98%E8%A7%A3/ - 2022-10-11 + https://nicksxs.me/tags/Binary-Tree/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/Java/ - 2022-10-11 + https://nicksxs.me/tags/DFS/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/JVM/ - 2022-10-11 + https://nicksxs.me/tags/%E4%BA%8C%E5%8F%89%E6%A0%91/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/C/ - 2022-10-11 + https://nicksxs.me/tags/%E9%A2%98%E8%A7%A3/ + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/Linked-List/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E8%AF%BB%E5%90%8E%E6%84%9F/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E5%B9%B4%E4%B8%AD%E6%80%BB%E7%BB%93/ - 2022-10-11 + https://nicksxs.me/tags/2019/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E6%8A%80%E6%9C%AF/ - 2022-10-11 + https://nicksxs.me/tags/%E5%B9%B4%E4%B8%AD%E6%80%BB%E7%BB%93/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E8%AF%BB%E4%B9%A6/ - 2022-10-11 + https://nicksxs.me/tags/%E6%8A%80%E6%9C%AF/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E5%B9%B6%E5%8F%91/ - 2022-10-11 + https://nicksxs.me/tags/%E8%AF%BB%E4%B9%A6/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/j-u-c/ - 2022-10-11 + https://nicksxs.me/tags/c/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/aqs/ - 2022-10-11 + https://nicksxs.me/tags/%E5%B9%B6%E5%8F%91/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/c/ - 2022-10-11 + https://nicksxs.me/tags/j-u-c/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/2019/ - 2022-10-11 + https://nicksxs.me/tags/aqs/ + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/condition/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/await/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/signal/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/lock/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/unlock/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/Apollo/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/Stream/ - 2022-10-11 + https://nicksxs.me/tags/environment/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/Comparator/ - 2022-10-11 + https://nicksxs.me/tags/value/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E6%8E%92%E5%BA%8F/ - 2022-10-11 + https://nicksxs.me/tags/%E6%B3%A8%E8%A7%A3/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/sort/ - 2022-10-11 + https://nicksxs.me/tags/Disruptor/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/nullsfirst/ - 2022-10-11 + https://nicksxs.me/tags/Stream/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/environment/ - 2022-10-11 + https://nicksxs.me/tags/Comparator/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/value/ - 2022-10-11 + https://nicksxs.me/tags/%E6%8E%92%E5%BA%8F/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E6%B3%A8%E8%A7%A3/ - 2022-10-11 + https://nicksxs.me/tags/sort/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/Disruptor/ - 2022-10-11 + https://nicksxs.me/tags/nullsfirst/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/G1/ - 2022-10-11 + https://nicksxs.me/tags/Dubbo/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/GC/ - 2022-10-11 + https://nicksxs.me/tags/RPC/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/Garbage-First-Collector/ - 2022-10-11 + https://nicksxs.me/tags/%E8%B4%9F%E8%BD%BD%E5%9D%87%E8%A1%A1/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/Filter/ - 2022-10-11 + https://nicksxs.me/tags/G1/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/Interceptor/ - 2022-10-11 + https://nicksxs.me/tags/GC/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/AOP/ - 2022-10-11 + https://nicksxs.me/tags/Garbage-First-Collector/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/Spring/ - 2022-10-11 + https://nicksxs.me/tags/Filter/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/Tomcat/ - 2022-10-11 + https://nicksxs.me/tags/Interceptor/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/Servlet/ - 2022-10-11 + https://nicksxs.me/tags/AOP/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/Web/ - 2022-10-11 + https://nicksxs.me/tags/Spring/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/Dubbo/ - 2022-10-11 + https://nicksxs.me/tags/Tomcat/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/RPC/ - 2022-10-11 + https://nicksxs.me/tags/Servlet/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E8%B4%9F%E8%BD%BD%E5%9D%87%E8%A1%A1/ - 2022-10-11 + https://nicksxs.me/tags/Web/ + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/Print-FooBar-Alternately/ - 2022-10-11 - weekly - 0.2 - - - - https://nicksxs.me/tags/DP/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E9%80%92%E5%BD%92/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/Preorder-Traversal/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/Inorder-Traversal/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E5%89%8D%E5%BA%8F/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E4%B8%AD%E5%BA%8F/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/stack/ - 2022-10-11 + https://nicksxs.me/tags/DP/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/min-stack/ - 2022-10-11 + https://nicksxs.me/tags/3Sum-Closest/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E6%9C%80%E5%B0%8F%E6%A0%88/ - 2022-10-11 + https://nicksxs.me/tags/Shift-2D-Grid/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/leetcode-155/ - 2022-10-11 + https://nicksxs.me/tags/stack/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/3Sum-Closest/ - 2022-10-11 + https://nicksxs.me/tags/min-stack/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/linked-list/ - 2022-10-11 + https://nicksxs.me/tags/%E6%9C%80%E5%B0%8F%E6%A0%88/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/Shift-2D-Grid/ - 2022-10-11 + https://nicksxs.me/tags/leetcode-155/ + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/Lowest-Common-Ancestor-of-a-Binary-Tree/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/First-Bad-Version/ - 2022-10-11 + https://nicksxs.me/tags/linked-list/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/Intersection-of-Two-Arrays/ - 2022-10-11 + https://nicksxs.me/tags/First-Bad-Version/ + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/string/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/Median-of-Two-Sorted-Arrays/ - 2022-10-11 + https://nicksxs.me/tags/Intersection-of-Two-Arrays/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/Rotate-Image/ - 2022-10-11 + https://nicksxs.me/tags/dp/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E7%9F%A9%E9%98%B5/ - 2022-10-11 + https://nicksxs.me/tags/%E4%BB%A3%E7%A0%81%E9%A2%98%E8%A7%A3/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/dp/ - 2022-10-11 + https://nicksxs.me/tags/Trapping-Rain-Water/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E4%BB%A3%E7%A0%81%E9%A2%98%E8%A7%A3/ - 2022-10-11 + https://nicksxs.me/tags/%E6%8E%A5%E9%9B%A8%E6%B0%B4/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/Trapping-Rain-Water/ - 2022-10-11 + https://nicksxs.me/tags/Leetcode-42/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E6%8E%A5%E9%9B%A8%E6%B0%B4/ - 2022-10-11 + https://nicksxs.me/tags/Median-of-Two-Sorted-Arrays/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/Leetcode-42/ - 2022-10-11 + https://nicksxs.me/tags/Rotate-Image/ + 2022-10-12 + weekly + 0.2 + + + + https://nicksxs.me/tags/%E7%9F%A9%E9%98%B5/ + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/Remove-Duplicates-from-Sorted-List/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/mfc/ - 2022-10-11 + https://nicksxs.me/tags/linux/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/Maven/ - 2022-10-11 + https://nicksxs.me/tags/grep/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/linux/ - 2022-10-11 + https://nicksxs.me/tags/%E8%BD%AC%E4%B9%89/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/grep/ - 2022-10-11 + https://nicksxs.me/tags/mfc/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E8%BD%AC%E4%B9%89/ - 2022-10-11 + https://nicksxs.me/tags/Maven/ + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/C/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/Redis/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/Distributed-Lock/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/hadoop/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/cluster/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/docker/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/mysql/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/Docker/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/namespace/ - 2022-10-11 + 2022-10-12 + weekly + 0.2 + + + + https://nicksxs.me/tags/Dockerfile/ + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/cgroup/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/echo/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/uname/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E5%8F%91%E8%A1%8C%E7%89%88/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/Gogs/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/Webhook/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/Dockerfile/ - 2022-10-11 + https://nicksxs.me/tags/%E5%8D%9A%E5%AE%A2%EF%BC%8C%E6%96%87%E7%AB%A0/ + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/Mysql/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/Mybatis/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/Sql%E6%B3%A8%E5%85%A5/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/nginx/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E6%97%A5%E5%BF%97/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E7%BC%93%E5%AD%98/ - 2022-10-11 - weekly - 0.2 - - - - https://nicksxs.me/tags/%E5%8D%9A%E5%AE%A2%EF%BC%8C%E6%96%87%E7%AB%A0/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/openresty/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/redis/ - 2022-10-11 + https://nicksxs.me/tags/php/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/mq/ - 2022-10-11 + https://nicksxs.me/tags/redis/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/php/ - 2022-10-11 + https://nicksxs.me/tags/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/im/ - 2022-10-11 + https://nicksxs.me/tags/%E6%BA%90%E7%A0%81/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/ - 2022-10-11 + https://nicksxs.me/tags/mq/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E6%BA%90%E7%A0%81/ - 2022-10-11 + https://nicksxs.me/tags/im/ + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E6%B7%98%E6%B1%B0%E7%AD%96%E7%95%A5/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E5%BA%94%E7%94%A8/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/Evict/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E8%BF%87%E6%9C%9F%E7%AD%96%E7%95%A5/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/Rust/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E6%89%80%E6%9C%89%E6%9D%83/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E5%86%85%E5%AD%98%E5%88%86%E5%B8%83/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E6%96%B0%E8%AF%AD%E8%A8%80/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E5%8F%AF%E5%8F%98%E5%BC%95%E7%94%A8/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E4%B8%8D%E5%8F%AF%E5%8F%98%E5%BC%95%E7%94%A8/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E5%88%87%E7%89%87/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/spark/ - 2022-10-11 + https://nicksxs.me/tags/Spring-Event/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/python/ - 2022-10-11 + https://nicksxs.me/tags/websocket/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/websocket/ - 2022-10-11 + https://nicksxs.me/tags/swoole/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/swoole/ - 2022-10-11 + https://nicksxs.me/tags/spark/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/WordPress/ - 2022-10-11 + https://nicksxs.me/tags/python/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E5%B0%8F%E6%8A%80%E5%B7%A7/ - 2022-10-11 + https://nicksxs.me/tags/WordPress/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/Spring-Event/ - 2022-10-11 + https://nicksxs.me/tags/%E5%B0%8F%E6%8A%80%E5%B7%A7/ + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/gc/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E6%A0%87%E8%AE%B0%E6%95%B4%E7%90%86/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/jvm/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/ssh/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E7%AB%AF%E5%8F%A3%E8%BD%AC%E5%8F%91/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E5%90%90%E6%A7%BD/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E7%96%AB%E6%83%85/ - 2022-10-11 - weekly - 0.2 - - - - https://nicksxs.me/tags/%E7%BE%8E%E5%9B%BD/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E5%85%AC%E4%BA%A4%E8%BD%A6/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E5%8F%A3%E7%BD%A9/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E6%9D%80%E4%BA%BA%E8%AF%9B%E5%BF%83/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/MQ/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E6%B6%88%E6%81%AF%E9%98%9F%E5%88%97/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/RocketMQ/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E5%89%8A%E5%B3%B0%E5%A1%AB%E8%B0%B7/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E4%B8%AD%E9%97%B4%E4%BB%B6/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E5%BC%80%E8%BD%A6/ - 2022-10-11 + https://nicksxs.me/tags/%E7%BE%8E%E5%9B%BD/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E5%8A%A0%E5%A1%9E/ - 2022-10-11 + https://nicksxs.me/tags/%E6%89%93%E5%8D%A1/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E7%B3%9F%E5%BF%83%E4%BA%8B/ - 2022-10-11 + https://nicksxs.me/tags/%E5%B9%B8%E7%A6%8F%E4%BA%86%E5%90%97/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E8%A7%84%E5%88%99/ - 2022-10-11 + https://nicksxs.me/tags/%E8%B6%B3%E7%90%83/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E5%85%AC%E4%BA%A4/ - 2022-10-11 + https://nicksxs.me/tags/git/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E8%B7%AF%E6%94%BF%E8%A7%84%E5%88%92/ - 2022-10-11 + https://nicksxs.me/tags/scp/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E5%9F%BA%E7%A1%80%E8%AE%BE%E6%96%BD/ - 2022-10-11 + https://nicksxs.me/tags/%E5%BC%80%E8%BD%A6/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E6%9D%AD%E5%B7%9E/ - 2022-10-11 + https://nicksxs.me/tags/%E5%8A%A0%E5%A1%9E/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E5%81%A5%E5%BA%B7%E7%A0%81/ - 2022-10-11 + https://nicksxs.me/tags/%E7%B3%9F%E5%BF%83%E4%BA%8B/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/git/ - 2022-10-11 + https://nicksxs.me/tags/%E8%A7%84%E5%88%99/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/scp/ - 2022-10-11 + https://nicksxs.me/tags/%E5%85%AC%E4%BA%A4/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E8%BF%90%E5%8A%A8/ - 2022-10-11 + https://nicksxs.me/tags/%E8%B7%AF%E6%94%BF%E8%A7%84%E5%88%92/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E5%87%8F%E8%82%A5/ - 2022-10-11 + https://nicksxs.me/tags/%E5%9F%BA%E7%A1%80%E8%AE%BE%E6%96%BD/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E8%B7%91%E6%AD%A5/ - 2022-10-11 + https://nicksxs.me/tags/%E6%9D%AD%E5%B7%9E/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E5%B9%B2%E6%B4%BB/ - 2022-10-11 + https://nicksxs.me/tags/%E5%81%A5%E5%BA%B7%E7%A0%81/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E6%89%93%E5%8D%A1/ - 2022-10-11 + https://nicksxs.me/tags/%E8%BF%90%E5%8A%A8/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E5%B9%B8%E7%A6%8F%E4%BA%86%E5%90%97/ - 2022-10-11 + https://nicksxs.me/tags/%E5%87%8F%E8%82%A5/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E8%B6%B3%E7%90%83/ - 2022-10-11 + https://nicksxs.me/tags/%E8%B7%91%E6%AD%A5/ + 2022-10-12 + weekly + 0.2 + + + + https://nicksxs.me/tags/%E5%B9%B2%E6%B4%BB/ + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E5%9B%A4%E7%89%A9%E8%B5%84/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E5%BD%B1%E8%AF%84/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E5%AF%84%E7%94%9F%E8%99%AB/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E5%AD%97%E7%AC%A6%E9%9B%86/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E7%BC%96%E7%A0%81/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/utf8/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/utf8mb4/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/utf8mb4-0900-ai-ci/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/utf8mb4-unicode-ci/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/utf8mb4-general-ci/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/NameServer/ - 2022-10-11 + https://nicksxs.me/tags/DefaultMQPushConsumer/ + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/SpringBoot/ - 2022-10-11 + https://nicksxs.me/tags/NameServer/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E8%87%AA%E5%8A%A8%E8%A3%85%E9%85%8D/ - 2022-10-11 + https://nicksxs.me/tags/SpringBoot/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/AutoConfiguration/ - 2022-10-11 + https://nicksxs.me/tags/cglib/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/Druid/ - 2022-10-11 + https://nicksxs.me/tags/%E4%BA%8B%E5%8A%A1/ + 2022-10-12 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/ - 2022-10-11 + https://nicksxs.me/tags/Druid/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E4%B8%9C%E4%BA%AC%E5%A5%A5%E8%BF%90%E4%BC%9A/ - 2022-10-11 + 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/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E4%B8%BE%E9%87%8D/ - 2022-10-11 + https://nicksxs.me/tags/%E8%87%AA%E5%8A%A8%E8%A3%85%E9%85%8D/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E5%B0%84%E5%87%BB/ - 2022-10-11 + https://nicksxs.me/tags/AutoConfiguration/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E4%B9%92%E4%B9%93%E7%90%83/ - 2022-10-11 + https://nicksxs.me/tags/%E4%B8%9C%E4%BA%AC%E5%A5%A5%E8%BF%90%E4%BC%9A/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E8%B7%B3%E6%B0%B4/ - 2022-10-11 + https://nicksxs.me/tags/%E4%B8%BE%E9%87%8D/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/DefaultMQPushConsumer/ - 2022-10-11 + https://nicksxs.me/tags/%E5%B0%84%E5%87%BB/ + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/SPI/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/Adaptive/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E8%87%AA%E9%80%82%E5%BA%94%E6%8B%93%E5%B1%95/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/Synchronized/ - 2022-10-11 + https://nicksxs.me/tags/%E4%B9%92%E4%B9%93%E7%90%83/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E5%81%8F%E5%90%91%E9%94%81/ - 2022-10-11 + https://nicksxs.me/tags/%E8%B7%B3%E6%B0%B4/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E8%BD%BB%E9%87%8F%E7%BA%A7%E9%94%81/ - 2022-10-11 + https://nicksxs.me/tags/%E5%AE%B9%E9%94%99%E6%9C%BA%E5%88%B6/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E9%87%8D%E9%87%8F%E7%BA%A7%E9%94%81/ - 2022-10-11 + https://nicksxs.me/tags/Synchronized/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E8%87%AA%E6%97%8B/ - 2022-10-11 + https://nicksxs.me/tags/%E5%81%8F%E5%90%91%E9%94%81/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E5%AE%B9%E9%94%99%E6%9C%BA%E5%88%B6/ - 2022-10-11 + https://nicksxs.me/tags/%E8%BD%BB%E9%87%8F%E7%BA%A7%E9%94%81/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/cglib/ - 2022-10-11 + https://nicksxs.me/tags/%E9%87%8D%E9%87%8F%E7%BA%A7%E9%94%81/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E4%BA%8B%E5%8A%A1/ - 2022-10-11 + https://nicksxs.me/tags/%E8%87%AA%E6%97%8B/ + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E7%B1%BB%E5%8A%A0%E8%BD%BD/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E5%8A%A0%E8%BD%BD/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E9%AA%8C%E8%AF%81/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E5%87%86%E5%A4%87/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E8%A7%A3%E6%9E%90/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E5%88%9D%E5%A7%8B%E5%8C%96/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E9%93%BE%E6%8E%A5/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E5%8F%8C%E4%BA%B2%E5%A7%94%E6%B4%BE/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/JPS/ - 2022-10-11 + https://nicksxs.me/tags/top/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/JStack/ - 2022-10-11 + https://nicksxs.me/tags/JPS/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/JMap/ - 2022-10-11 + https://nicksxs.me/tags/JStack/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/Broker/ - 2022-10-11 + https://nicksxs.me/tags/JMap/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/top/ - 2022-10-11 + https://nicksxs.me/tags/Broker/ + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/Sharding-Jdbc/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/ThreadPool/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E7%BA%BF%E7%A8%8B%E6%B1%A0/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/FixedThreadPool/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/LimitedThreadPool/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/EagerThreadPool/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/CachedThreadPool/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/mvcc/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/read-view/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/gap-lock/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/next-key-lock/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E5%B9%BB%E8%AF%BB/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/ - 2022-10-11 + https://nicksxs.me/tags/%E7%B4%A2%E5%BC%95/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/Design-Patterns/ - 2022-10-11 + https://nicksxs.me/tags/is-null/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E5%8D%95%E4%BE%8B/ - 2022-10-11 + https://nicksxs.me/tags/is-not-null/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/Singleton/ - 2022-10-11 + https://nicksxs.me/tags/procedure/ + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E7%BC%93%E5%AD%98%E7%A9%BF%E9%80%8F/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E7%BC%93%E5%AD%98%E5%87%BB%E7%A9%BF/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E7%BC%93%E5%AD%98%E9%9B%AA%E5%B4%A9/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E5%B8%83%E9%9A%86%E8%BF%87%E6%BB%A4%E5%99%A8/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/bloom-filter/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E4%BA%92%E6%96%A5%E9%94%81/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E7%B4%A2%E5%BC%95/ - 2022-10-11 + https://nicksxs.me/tags/ThreadLocal/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/is-null/ - 2022-10-11 + https://nicksxs.me/tags/%E5%BC%B1%E5%BC%95%E7%94%A8/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/is-not-null/ - 2022-10-11 + https://nicksxs.me/tags/%E5%86%85%E5%AD%98%E6%B3%84%E6%BC%8F/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/procedure/ - 2022-10-11 + https://nicksxs.me/tags/WeakReference/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/ThreadLocal/ - 2022-10-11 + https://nicksxs.me/tags/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E5%BC%B1%E5%BC%95%E7%94%A8/ - 2022-10-11 + https://nicksxs.me/tags/Design-Patterns/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E5%86%85%E5%AD%98%E6%B3%84%E6%BC%8F/ - 2022-10-11 + https://nicksxs.me/tags/%E5%8D%95%E4%BE%8B/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/WeakReference/ - 2022-10-11 + https://nicksxs.me/tags/Singleton/ + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/Mac/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/PHP/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/Homebrew/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/icu4c/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/zsh/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E6%97%85%E6%B8%B8/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E5%8E%A6%E9%97%A8/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E4%B8%AD%E5%B1%B1%E8%B7%AF/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E5%B1%80%E5%8F%A3%E8%A1%97/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E9%BC%93%E6%B5%AA%E5%B1%BF/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E6%9B%BE%E5%8E%9D%E5%9E%B5/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E6%A4%8D%E7%89%A9%E5%9B%AD/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E9%A9%AC%E6%88%8F%E5%9B%A2/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E6%B2%99%E8%8C%B6%E9%9D%A2/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E6%B5%B7%E8%9B%8E%E7%85%8E/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E5%88%86%E5%B8%83%E5%BC%8F%E4%BA%8B%E5%8A%A1/ - 2022-10-11 + https://nicksxs.me/tags/%E6%89%B6%E6%A2%AF/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E4%B8%A4%E9%98%B6%E6%AE%B5%E6%8F%90%E4%BA%A4/ - 2022-10-11 + https://nicksxs.me/tags/%E8%B8%A9%E8%B8%8F/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E4%B8%89%E9%98%B6%E6%AE%B5%E6%8F%90%E4%BA%A4/ - 2022-10-11 + https://nicksxs.me/tags/%E5%AE%89%E5%85%A8/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/2PC/ - 2022-10-11 + https://nicksxs.me/tags/%E7%94%B5%E7%93%B6%E8%BD%A6/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/3PC/ - 2022-10-11 + https://nicksxs.me/tags/Thread-dump/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/Thread-dump/ - 2022-10-11 + https://nicksxs.me/tags/%E5%88%86%E5%B8%83%E5%BC%8F%E4%BA%8B%E5%8A%A1/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E6%89%B6%E6%A2%AF/ - 2022-10-11 + https://nicksxs.me/tags/%E4%B8%A4%E9%98%B6%E6%AE%B5%E6%8F%90%E4%BA%A4/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E8%B8%A9%E8%B8%8F/ - 2022-10-11 + https://nicksxs.me/tags/%E4%B8%89%E9%98%B6%E6%AE%B5%E6%8F%90%E4%BA%A4/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E5%AE%89%E5%85%A8/ - 2022-10-11 + https://nicksxs.me/tags/2PC/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E7%94%B5%E7%93%B6%E8%BD%A6/ - 2022-10-11 + https://nicksxs.me/tags/3PC/ + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E8%BF%9C%E7%A8%8B%E5%8A%9E%E5%85%AC/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E7%9C%8B%E5%89%A7/ - 2022-10-11 + https://nicksxs.me/tags/%E9%AA%91%E8%BD%A6/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E9%AA%91%E8%BD%A6/ - 2022-10-11 + https://nicksxs.me/tags/%E7%9C%8B%E5%89%A7/ + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E8%A3%85%E7%94%B5%E8%84%91/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E8%80%81%E7%94%B5%E8%84%91/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/360-%E5%85%A8%E5%AE%B6%E6%A1%B6/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E4%BF%AE%E7%94%B5%E8%84%91%E7%9A%84/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E6%8D%A2%E8%BD%A6%E7%89%8C/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/dubbo/ - 2022-10-11 + https://nicksxs.me/tags/stream/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/stream/ - 2022-10-11 + https://nicksxs.me/tags/zookeeper/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/zookeeper/ - 2022-10-11 + https://nicksxs.me/tags/%E9%AB%98%E9%80%9F/ + 2022-10-12 weekly 0.2 https://nicksxs.me/tags/%E7%9C%8B%E4%B9%A6/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E9%AB%98%E9%80%9F/ - 2022-10-11 + https://nicksxs.me/tags/%E5%A4%A7%E6%89%AB%E9%99%A4/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/tags/%E5%A4%A7%E6%89%AB%E9%99%A4/ - 2022-10-11 + https://nicksxs.me/tags/dubbo/ + 2022-10-12 weekly 0.2 @@ -3685,1036 +3685,1036 @@ https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/Java/ - 2022-10-11 + 2022-10-12 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/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/leetcode/ - 2022-10-11 + https://nicksxs.me/categories/Java/leetcode/ + 2022-10-12 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/ - 2022-10-11 + https://nicksxs.me/categories/Java/JVM/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/Java/leetcode/ - 2022-10-11 + https://nicksxs.me/categories/leetcode/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/Java/JVM/ - 2022-10-11 + https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E5%B9%B4%E7%BB%88%E6%80%BB%E7%BB%93/2020/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/Binary-Tree/ - 2022-10-11 + https://nicksxs.me/categories/Java/GC/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/%E5%B9%B4%E7%BB%88%E6%80%BB%E7%BB%93/ - 2022-10-11 + https://nicksxs.me/categories/Linked-List/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/Linked-List/ - 2022-10-11 + https://nicksxs.me/categories/Binary-Tree/ + 2022-10-12 + weekly + 0.2 + + + + https://nicksxs.me/categories/%E5%B9%B4%E7%BB%88%E6%80%BB%E7%BB%93/ + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/%E8%AF%BB%E5%90%8E%E6%84%9F/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/Java/GC/ - 2022-10-11 + https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E5%B9%B4%E7%BB%88%E6%80%BB%E7%BB%93/2019/ + 2022-10-12 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/ - 2022-10-11 + https://nicksxs.me/categories/C/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/leetcode/java/ - 2022-10-11 + https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E5%B9%B4%E4%B8%AD%E6%80%BB%E7%BB%93/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/%E5%B9%B4%E7%BB%88%E6%80%BB%E7%BB%93/2020/ - 2022-10-11 + https://nicksxs.me/categories/leetcode/java/ + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/Java/%E5%B9%B6%E5%8F%91/ - 2022-10-11 + 2022-10-12 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/ - 2022-10-11 + https://nicksxs.me/categories/%E5%B9%B4%E7%BB%88%E6%80%BB%E7%BB%93/2020/ + 2022-10-12 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/ - 2022-10-11 + https://nicksxs.me/categories/java/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/Java/%E9%9B%86%E5%90%88/ - 2022-10-11 + 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/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/C/ - 2022-10-11 + https://nicksxs.me/categories/Java/Apollo/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/java/ - 2022-10-11 + https://nicksxs.me/categories/Java/%E9%9B%86%E5%90%88/ + 2022-10-12 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/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/Java/Apollo/ - 2022-10-11 + https://nicksxs.me/categories/Java/Dubbo/ + 2022-10-12 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/ - 2022-10-11 + https://nicksxs.me/categories/leetcode/java/Linked-List/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/leetcode/java/Binary-Tree/ - 2022-10-11 + https://nicksxs.me/categories/Filter/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/Java/Dubbo/ - 2022-10-11 + https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E5%B9%B4%E4%B8%AD%E6%80%BB%E7%BB%93/2021/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/Filter/ - 2022-10-11 + https://nicksxs.me/categories/leetcode/java/Binary-Tree/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/leetcode/java/Linked-List/ - 2022-10-11 + https://nicksxs.me/categories/DP/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/DP/ - 2022-10-11 + https://nicksxs.me/categories/stack/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/stack/ - 2022-10-11 + https://nicksxs.me/categories/Java/leetcode/Lowest-Common-Ancestor-of-a-Binary-Tree/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/linked-list/ - 2022-10-11 + https://nicksxs.me/categories/Java/Apollo/value/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/Java/leetcode/Lowest-Common-Ancestor-of-a-Binary-Tree/ - 2022-10-11 + https://nicksxs.me/categories/linked-list/ + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/%E5%AD%97%E7%AC%A6%E4%B8%B2-online/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/Java/leetcode/Rotate-Image/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/Java/Apollo/value/ - 2022-10-11 + https://nicksxs.me/categories/Linux/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/leetcode/java/Binary-Tree/DFS/ - 2022-10-11 + https://nicksxs.me/categories/Interceptor-AOP/ + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/Java/Maven/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/Linux/ - 2022-10-11 + https://nicksxs.me/categories/leetcode/java/Binary-Tree/DFS/ + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/Redis/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/Interceptor-AOP/ - 2022-10-11 + https://nicksxs.me/categories/data-analysis/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/data-analysis/ - 2022-10-11 + https://nicksxs.me/categories/docker/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/docker/ - 2022-10-11 + https://nicksxs.me/categories/leetcode/java/DP/ + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/Docker/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/%E6%8C%81%E7%BB%AD%E9%9B%86%E6%88%90/ - 2022-10-11 + https://nicksxs.me/categories/leetcode/java/stack/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/leetcode/java/DP/ - 2022-10-11 + https://nicksxs.me/categories/%E6%8C%81%E7%BB%AD%E9%9B%86%E6%88%90/ + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/Java/Mybatis/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/nginx/ - 2022-10-11 - weekly - 0.2 - - - - https://nicksxs.me/categories/leetcode/java/stack/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/leetcode/java/linked-list/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/redis/ - 2022-10-11 + https://nicksxs.me/categories/php/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/php/ - 2022-10-11 + https://nicksxs.me/categories/redis/ + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/leetcode/java/string/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/%E8%AF%AD%E8%A8%80/ - 2022-10-11 + https://nicksxs.me/categories/Linux/%E5%91%BD%E4%BB%A4/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/Linux/%E5%91%BD%E4%BB%A4/ - 2022-10-11 + https://nicksxs.me/categories/Spring/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/Redis/Distributed-Lock/ - 2022-10-11 + https://nicksxs.me/categories/%E8%AF%AD%E8%A8%80/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/%E5%B0%8F%E6%8A%80%E5%B7%A7/ - 2022-10-11 + https://nicksxs.me/categories/Java/Spring/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/Java/Spring/ - 2022-10-11 + https://nicksxs.me/categories/Redis/Distributed-Lock/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/Spring/ - 2022-10-11 + https://nicksxs.me/categories/%E8%AF%BB%E5%90%8E%E6%84%9F/%E7%94%9F%E6%B4%BB/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/Java/gc/ - 2022-10-11 + https://nicksxs.me/categories/%E5%B0%8F%E6%8A%80%E5%B7%A7/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/%E8%AF%BB%E5%90%8E%E6%84%9F/%E7%94%9F%E6%B4%BB/ - 2022-10-11 + https://nicksxs.me/categories/Java/gc/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E8%BF%90%E5%8A%A8/ - 2022-10-11 + https://nicksxs.me/categories/ssh/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/ssh/ - 2022-10-11 + https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E5%90%90%E6%A7%BD/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E5%90%90%E6%A7%BD/ - 2022-10-11 + https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E8%BF%90%E5%8A%A8/ + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/MQ/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/Docker/%E4%BB%8B%E7%BB%8D/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E5%85%AC%E4%BA%A4/ - 2022-10-11 + https://nicksxs.me/categories/%E8%AF%BB%E5%90%8E%E6%84%9F/%E7%99%BD%E5%B2%A9%E6%9D%BE/ + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/git/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/shell/ - 2022-10-11 + 2022-10-12 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/ - 2022-10-11 + https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E5%85%AC%E4%BA%A4/ + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E5%BD%B1%E8%AF%84/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/Mysql/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/Java/Mybatis/Mysql/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/Java/SpringBoot/ - 2022-10-11 + https://nicksxs.me/categories/Mybatis/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/Mybatis/ - 2022-10-11 + https://nicksxs.me/categories/Java/SpringBoot/ + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/Java/Dubbo/RPC/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/Dubbo-RPC/ - 2022-10-11 + https://nicksxs.me/categories/Redis/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/Java/%E7%B1%BB%E5%8A%A0%E8%BD%BD/ - 2022-10-11 + https://nicksxs.me/categories/Dubbo-RPC/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/Redis/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/ - 2022-10-11 + https://nicksxs.me/categories/Java/%E7%B1%BB%E5%8A%A0%E8%BD%BD/ + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/Thread-dump/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/Dubbo-%E7%BA%BF%E7%A8%8B%E6%B1%A0/ - 2022-10-11 + https://nicksxs.me/categories/Linux/%E5%91%BD%E4%BB%A4/grep/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/Java/Design-Patterns/ - 2022-10-11 + https://nicksxs.me/categories/Dubbo-%E7%BA%BF%E7%A8%8B%E6%B1%A0/ + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/Redis/%E5%BA%94%E7%94%A8/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/SpringBoot/ - 2022-10-11 + https://nicksxs.me/categories/Java/Design-Patterns/ + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/Mac/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E6%97%85%E6%B8%B8/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/%E5%88%86%E5%B8%83%E5%BC%8F%E4%BA%8B%E5%8A%A1/ - 2022-10-11 + https://nicksxs.me/categories/Spring/Servlet/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/%E8%AF%AD%E8%A8%80/Rust/ - 2022-10-11 + https://nicksxs.me/categories/SpringBoot/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E5%BC%80%E8%BD%A6/ - 2022-10-11 + https://nicksxs.me/categories/%E5%88%86%E5%B8%83%E5%BC%8F%E4%BA%8B%E5%8A%A1/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/Linux/%E5%91%BD%E4%BB%A4/grep/ - 2022-10-11 + https://nicksxs.me/categories/%E8%AF%AD%E8%A8%80/Rust/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/Rust/ - 2022-10-11 + https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E5%BC%80%E8%BD%A6/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/C/ - 2022-10-11 + https://nicksxs.me/categories/Rust/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/Spring/Servlet/ - 2022-10-11 + https://nicksxs.me/categories/C/ + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/Java/gc/jvm/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/ssh/%E6%8A%80%E5%B7%A7/ - 2022-10-11 + 2022-10-12 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/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/MQ/RocketMQ/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/git/%E5%B0%8F%E6%8A%80%E5%B7%A7/ - 2022-10-11 + 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/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/Linux/%E5%91%BD%E4%BB%A4/echo/ - 2022-10-11 + https://nicksxs.me/categories/git/%E5%B0%8F%E6%8A%80%E5%B7%A7/ + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/shell/%E5%B0%8F%E6%8A%80%E5%B7%A7/ - 2022-10-11 + 2022-10-12 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/ - 2022-10-11 + 2022-10-12 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/ - 2022-10-11 + https://nicksxs.me/categories/Linux/%E5%91%BD%E4%BB%A4/echo/ + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/%E7%94%9F%E6%B4%BB/%E5%BD%B1%E8%AF%84/2020/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/Mysql/Sql%E6%B3%A8%E5%85%A5/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/Mybatis/%E7%BC%93%E5%AD%98/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/Java/Dubbo/RPC/SPI/ - 2022-10-11 - weekly - 0.2 - - - - https://nicksxs.me/categories/Dubbo/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/Redis/%E6%BA%90%E7%A0%81/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/%E9%97%AE%E9%A2%98%E6%8E%92%E6%9F%A5/ - 2022-10-11 + https://nicksxs.me/categories/Dubbo/ + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/Linux/%E5%91%BD%E4%BB%A4/top/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/Mysql/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/ - 2022-10-11 + https://nicksxs.me/categories/%E9%97%AE%E9%A2%98%E6%8E%92%E6%9F%A5/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/Java/Singleton/ - 2022-10-11 + https://nicksxs.me/categories/%E5%B0%8F%E6%8A%80%E5%B7%A7/grep/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/Redis/%E7%BC%93%E5%AD%98/ - 2022-10-11 + https://nicksxs.me/categories/Mysql/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/ + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/Mysql/%E7%B4%A2%E5%BC%95/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/Mac/PHP/ - 2022-10-11 + https://nicksxs.me/categories/Redis/%E7%BC%93%E5%AD%98/ + 2022-10-12 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/ - 2022-10-11 + https://nicksxs.me/categories/Java/Singleton/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/%E5%B0%8F%E6%8A%80%E5%B7%A7/grep/ - 2022-10-11 + https://nicksxs.me/categories/Mac/PHP/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/C/Redis/ - 2022-10-11 + https://nicksxs.me/categories/Spring/Servlet/Interceptor/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/Spring/Servlet/Interceptor/ - 2022-10-11 + 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/ + 2022-10-12 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/ - 2022-10-11 + https://nicksxs.me/categories/C/Redis/ + 2022-10-12 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/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/%E6%B6%88%E6%81%AF%E9%98%9F%E5%88%97/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/Docker/%E5%8F%91%E8%A1%8C%E7%89%88%E6%9C%AC/ - 2022-10-11 + 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/ + 2022-10-12 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/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/Spring/Mybatis/ - 2022-10-11 + https://nicksxs.me/categories/Docker/%E5%8F%91%E8%A1%8C%E7%89%88%E6%9C%AC/ + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/MQ/RocketMQ/%E6%B6%88%E6%81%AF%E9%98%9F%E5%88%97/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/Dubbo/SPI/ - 2022-10-11 + https://nicksxs.me/categories/Spring/Mybatis/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/Dubbo/%E5%AE%B9%E9%94%99%E6%9C%BA%E5%88%B6/ - 2022-10-11 + https://nicksxs.me/categories/Dubbo/SPI/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/%E5%B7%A5%E5%85%B7/ - 2022-10-11 + https://nicksxs.me/categories/Dubbo/%E5%AE%B9%E9%94%99%E6%9C%BA%E5%88%B6/ + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/%E5%B0%8F%E6%8A%80%E5%B7%A7/top/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/Dubbo/%E7%BA%BF%E7%A8%8B%E6%B1%A0/ - 2022-10-11 + https://nicksxs.me/categories/%E5%B7%A5%E5%85%B7/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/Mysql/%E6%BA%90%E7%A0%81/ - 2022-10-11 + https://nicksxs.me/categories/%E5%B0%8F%E6%8A%80%E5%B7%A7/grep/%E6%9F%A5%E6%97%A5%E5%BF%97/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/%E7%BC%93%E5%AD%98/ - 2022-10-11 + https://nicksxs.me/categories/Mysql/%E6%BA%90%E7%A0%81/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/C/Mysql/ - 2022-10-11 + https://nicksxs.me/categories/Dubbo/%E7%BA%BF%E7%A8%8B%E6%B1%A0/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/Mac/Homebrew/ - 2022-10-11 + https://nicksxs.me/categories/C/Mysql/ + 2022-10-12 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/ - 2022-10-11 + https://nicksxs.me/categories/%E7%BC%93%E5%AD%98/ + 2022-10-12 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/ - 2022-10-11 + https://nicksxs.me/categories/Mac/Homebrew/ + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/Spring/Servlet/Interceptor/AOP/ - 2022-10-11 + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/%E6%B6%88%E6%81%AF%E9%98%9F%E5%88%97/RocketMQ/ - 2022-10-11 + 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/ + 2022-10-12 weekly 0.2 - https://nicksxs.me/categories/Dubbo/SPI/Adaptive/ - 2022-10-11 + https://nicksxs.me/categories/%E6%B6%88%E6%81%AF%E9%98%9F%E5%88%97/RocketMQ/ + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/%E5%B0%8F%E6%8A%80%E5%B7%A7/top/%E6%8E%92%E5%BA%8F/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/Dubbo/%E7%BA%BF%E7%A8%8B%E6%B1%A0/ThreadPool/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/%E7%BC%93%E5%AD%98/%E7%A9%BF%E9%80%8F/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/PHP/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/%E4%B8%AD%E9%97%B4%E4%BB%B6/ - 2022-10-11 + 2022-10-12 + weekly + 0.2 + + + + https://nicksxs.me/categories/Dubbo/SPI/Adaptive/ + 2022-10-12 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/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/PHP/icu4c/ - 2022-10-11 + 2022-10-12 weekly 0.2 https://nicksxs.me/categories/%E4%B8%AD%E9%97%B4%E4%BB%B6/RocketMQ/ - 2022-10-11 + 2022-10-12 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/ - 2022-10-11 + 2022-10-12 weekly 0.2 diff --git a/tags/docker/index.html b/tags/docker/index.html index 6ccb4a605b..50caa9219d 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?

    0%

    docker 标签

    2016
    ymous"> \ 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 7cd8178c61..fc0d76579b 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%
    uicklink.umd.js" integrity="sha256-4kQf9z5ntdQrzsBC3YSHnEz02Z9C1UeW/E9OgnvlzSY=" crossorigin="anonymous"> \ 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 d6aaaedb25..f10748b100 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 49b947eacc..8b720592cf 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 1a0eb5f99f..6597407d34 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 8c05f3750a..7847c42413 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 80462dc99c..74a6bbc2c3 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