查看Curator框架 为实现对 连接状态ConnectionState的管理与监听是怎么构造的。后面我们也可以应用到业务的各种监听中。

Curator2.13实现

接口 Listener

Listener接口,给用户实现stateChange()传入新的状态,用户实现对这新的状态要做什么逻辑处理。

public interface ConnectionStateListener
{
/**
* Called when there is a state change in the connection
* @param client the client
* @param newState the new state
*/
public void stateChanged(CuratorFramework client, ConnectionState newState);
}

接口 Listenable

提供一个监听对象容器的接口

// Abstracts a listenable object
public interface Listenable<T>
{
/**
* Add the given listener. The listener will be executed in the containing instance's thread.
*
* @param listener listener to add
*/
public void addListener(T listener); public void addListener(T listener, Executor executor); public void removeListener(T listener);
}

ListenerContainer<T> implements Listenable<T>

/**
* Abstracts an object that has listeners 装Listener的容器
* <T> Listener类型
*/
public class ListenerContainer<T> implements Listenable<T>
{
private final Map<T, ListenerEntry<T>> listeners = Maps.newConcurrentMap(); @Override
public void addListener(T listener)
{
addListener(listener, MoreExecutors.sameThreadExecutor());
} @Override
public void addListener(T listener, Executor executor)
{
listeners.put(listener, new ListenerEntry<T>(listener, executor));
} /**
* 对 Listener 列表的遍历进行封装
* Utility - apply the given function to each listener.
* @param function function to call for each listener
*/
public void forEach(final Function<T, Void> function)
{
for ( final ListenerEntry<T> entry : listeners.values() )
{
entry.executor.execute
(
new Runnable()
{
@Override
public void run()
{
try
{
function.apply(entry.listener);
}
catch ( Throwable e )
{
ThreadUtils.checkInterrupted(e);
log.error(String.format("Listener (%s) threw an exception", entry.listener), e);
}
}
}
);
}
} public void clear()
{
listeners.clear();
} public int size()
{
return listeners.size();
} }

ConnectionStateManager

// to manage connection state
public class ConnectionStateManager {
// 又是队列? 玩消息什么的都是用队列。现在是存放 ConnectionState
BlockingQueue<ConnectionState> eventQueue = new ArrayBlockingQueue<ConnectionState>(QUEUE_SIZE);
// 持有 ListenerContainer
private final ListenerContainer<ConnectionStateListener> listeners = new ListenerContainer<ConnectionStateListener>(); /**
* Start the manager,起一个线程去执行 processEvents(),要是这线程挂了怎么办?异常怎么处理的?框架怎么处理的。。
*/
public void start()
{
service.submit
(
new Callable<Object>()
{
@Override
public Object call() throws Exception
{
processEvents();
return null;
}
}
);
} @Override
public void close()
{
if ( state.compareAndSet(State.STARTED, State.CLOSED) )
{
service.shutdownNow();
listeners.clear();
}
} // 对不断产生的 ConnectionState 进行处理,生产者?
private void processEvents(){
// 当 ConnectionStateManager 启动完成
while ( state.get() == State.STARTED )
{
// 不断从队列拿 Conection 状态
final ConnectionState newState = eventQueue.take();
// 对每个 状态监听接口 应用 Function, 状态监听接口作为 主语
// forEach 是 listeners封装的 遍历所有 listener 的方法而已。。。
listeners.forEach(
new Function<ConnectionStateListener, Void>() {
// ConnectionStateListener是我们自己要实现的接口,stateChanged是要实现的方法
@Override
public Void apply(ConnectionStateListener listener)
{
listener.stateChanged(client, newState);
return null;
}
}
);
/**
上面这段
如果没有封装 Listener 到 ListenerContainer 的话, 所有 Listener 就是个 List列表,就直接调 Listener 的 stateChanged 方法了吧。
for Listener {
listener.stateChanged(client, newState);
} 因为 封装 Listener 到 ListenerContainer了, 上面的 forEach 方法内部就可以有些内部实现,比如 对每个 Listener 都是用对应的 executor 来执行。
**/
}
} // 上面的方法是处理 ConnectionState 的,那 ConnectionState 是怎么传进来的呢? 生产者?
/**
* Post a state change. If the manager is already in that state the change
* is ignored. Otherwise the change is queued for listeners.
*
* @param newConnectionState new state
* @return true if the state actually changed, false if it was already at that state
*/
public synchronized boolean addStateChange(ConnectionState newConnectionState)
{
// 先判断 ConnectionStateManager 是否已经启动好, state 是内部 Enum
if ( state.get() != State.STARTED )
{
return false;
} ConnectionState previousState = currentConnectionState;
if ( previousState == newConnectionState )
{
return false;
}
ConnectionState localState = newConnectionState;
// !!!
notifyAll(); while ( !eventQueue.offer(state) )
{
eventQueue.poll();
log.warn("ConnectionStateManager queue full - dropping events to make room");
}
return true;
} }

调用

启动

// 启动 connectionStateManager,不断检测 connectionState 变化
connectionStateManager.start(); // must be called before client.start()
// 来个匿名默认的 ConnectionStateListener
final ConnectionStateListener listener = new ConnectionStateListener()
{
@Override
public void stateChanged(CuratorFramework client, ConnectionState newState)
{
if ( ConnectionState.CONNECTED == newState || ConnectionState.RECONNECTED == newState )
{
logAsErrorConnectionErrors.set(true);
}
}
};
this.getConnectionStateListenable().addListener(listener);

生产 ConnectionState,把zk那里拿到的state转一下,然后addStateChange

void validateConnection(Watcher.Event.KeeperState state)
{
if ( state == Watcher.Event.KeeperState.Disconnected )
{
suspendConnection();
}
else if ( state == Watcher.Event.KeeperState.Expired )
{
connectionStateManager.addStateChange(ConnectionState.LOST);
}
else if ( state == Watcher.Event.KeeperState.SyncConnected )
{
connectionStateManager.addStateChange(ConnectionState.RECONNECTED);
}
else if ( state == Watcher.Event.KeeperState.ConnectedReadOnly )
{
connectionStateManager.addStateChange(ConnectionState.READ_ONLY);
}
}

复用?

还有其他各种Listener,都可以放到 ListenerContainer

private final ListenerContainer<CuratorListener> listeners;
private final ListenerContainer<UnhandledErrorListener> unhandledErrorListeners; /**
* Receives notifications about errors and background events
*/
public interface CuratorListener {
/**
* Called when a background task has completed or a watch has triggered
* @param event the event
* @throws Exception any errors
*/
public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception;
} public interface UnhandledErrorListener
{
/**
* Called when an exception is caught in a background thread, handler, etc. Before this
* listener is called, the error will have been logged and a {@link ConnectionState#LOST}
* event will have been queued for any {@link ConnectionStateListener}s.
* @param message Source message
* @param e exception
*/
public void unhandledError(String message, Throwable e);
}

总结一下源码技巧

  1. ConnectionState的监听和管理在类ConnectionStateManager中, 就是个 生产者消费者模式的代码,特点就是: public addStateChange() 暴露给外部用户生产 ConnectionState,通过队列eventQueue传递,private processEvents()在内部对ConnectionState进行消费。
  2. 直接new匿名类,对接口进行默认实现。
  3. 对Listener列表对象进行Container封装,然后 封装foreach方法,传入Function接口 就是foreach每个元素要执行的业务逻辑,方法体就可以加一些其他福利。

Curator4.2.0实现

curator4.2.0对ConnectionStateListener进行了一些改进,如下:

1. 装饰ConnectionStateListener,Ccurator-505

当网络断开时,zk会传送很多 connection/disconnection event,为防止 Curator因此而不断reseting state,该issue提供了 一种对监听回路进行切断或者连接的ConnectionStateListener, 它会对ConnectionStateListeners 进行装饰代理。当它接受到 ConnectionState.SUSPENDED,监听回路会切断变成open状态,这段时间会组织发送state给所有Listener,就忽略了对connection state的改变。时间到期后监听回路会变成close状态,并且发送当前的connection state。简而言之,当不断出现up/down/up/down/up/down的中间状态,使用者将只看到first down,然后N ms之后连接能够修复的话将只看到重连状态。

Create a circuit breaker style ConnectionStateListener. It would proxy any ConnectionStateListeners used by Curator recipe/classes such that when the connection is lost the circuit would open for a period of time and, while open, ignore any changes in state. After the time period expires the circuit would close and send whatever the current connection state is. This way, if the connection is going up/down/up/down/up/down, the application would only see the first down and then N ms later hopefully the connection is repaired and the application would only see the reconnection.

curator-505,结合源码中的testcase更易于理解。

接口ConnectionStateListenerDecorator

该接口用来统一返回是否装饰的ConnectionStateListener

public interface ConnectionStateListenerDecorator
{
ConnectionStateListener decorateListener(CuratorFramework client, ConnectionStateListener actual); // 不对 ConnectionStateListener 进行装饰
ConnectionStateListenerDecorator standard = (__, actual) -> actual; /**
* Decorates the listener with circuit breaking behavior
* @param retryPolicy the circuit breaking policy to use
* @return new decorator
*/
static ConnectionStateListenerDecorator circuitBreaking(RetryPolicy retryPolicy) {
return (client, actual) -> new CircuitBreakingConnectionStateListener(client, actual, retryPolicy);
} /**
* Decorates the listener with circuit breaking behavior
* @param retryPolicy the circuit breaking policy to use
* @param service the scheduler to use
* @return new decorator
*/
static ConnectionStateListenerDecorator circuitBreaking(RetryPolicy retryPolicy, ScheduledExecutorService service)
{
return (client, actual) -> new CircuitBreakingConnectionStateListener(client, actual, retryPolicy, service);
}
}

CircuitBreakingConnectionStateListener

对ConnectionStateListener进行装饰:正常情况下,decorator为close为连接状态,会将state传给所有Listener。当decorator接收到第一个disconnected state,监听回路变为open即断开状态,不再将state传给各Listener(第一个disconnected state状态会传),而是decorator起线程来通过RetryPolicy进行重试,当重试次数达到一定程度会将close断路 。

public class CircuitBreakingConnectionStateListener implements ConnectionStateListener
{
// 对该 Listener 进行装饰
private final ConnectionStateListener listener;
private final CircuitBreaker circuitBreaker;
// guarded by sync
private boolean circuitLostHasBeenSent;
private ConnectionState circuitLastState;
private ConnectionState circuitInitialState; // 同步方法?
@Override
public synchronized void stateChanged(CuratorFramework client, ConnectionState newState)
{
// 断路器被打开了,newState 将不传给 Listener 处理
if ( circuitBreaker.isOpen() ) {
handleOpenStateChange(newState);
} else {
handleClosedStateChange(newState);
}
} private synchronized void handleOpenStateChange(ConnectionState newState)
{
if ( circuitLostHasBeenSent || (newState != ConnectionState.LOST) )
{
// Circuit is open. Ignoring state change !!状态变化都自己收了。。
circuitLastState = newState;
}
else
{
// Circuit is open. State changed to LOST. Sending to listener (第一次 Lost 信息还是会传给 Listener,也就是用个boolean来判断)
circuitLostHasBeenSent = true;
circuitLastState = circuitInitialState = ConnectionState.LOST;
callListener(ConnectionState.LOST);
}
} // 正常状态下走这里,将state传给Listener
private synchronized void handleClosedStateChange(ConnectionState newState)
{
// 接收到不是connection状态的就尝试打开断路器
if ( !newState.isConnected() ) {
// checkCloseCircuit 作为 调Runnable的匿名函数
if ( circuitBreaker.tryToOpen(this::checkCloseCircuit) )
{
circuitLastState = circuitInitialState = newState;
circuitLostHasBeenSent = (newState == ConnectionState.LOST);
}
else{
log.debug("Could not open circuit breaker. State: {}", newState);
}
}
callListener(newState);
}
// 通过线程池执行该方法,作为Runnable 匿名函数传入
private synchronized void checkCloseCircuit() {
// 连接上了就关闭断路
if ( (circuitLastState == null) || circuitLastState.isConnected() ) {
closeCircuit();
}
// 没连接上,还在 retry 的时候就 保持断路
else if ( circuitBreaker.tryToRetry(this::checkCloseCircuit) ) {
// Circuit open is continuing due to retry
}
// 经过 retryPolicy 的 不断 retry后还没连上,累了,就关闭断路
else {
// Circuit is closing due to retries exhausted
closeCircuit();
}
}
}

2. 重构 ListenerContainer

ListenerManager

这个ListenerManager就是从ListenerContainer演进而来的,PR上是说为了不再依赖Guava并且支持mappingmapping。和原来一样也封装了对Listener列表遍历的forEach(Consumer<V> function)

/**
* Upgraded version of {@link org.apache.curator.framework.listen.ListenerContainer} that
* doesn't leak Guava's internals and also supports mapping/wrapping of listeners
*/
public class MappingListenerManager<K, V> implements ListenerManager<K, V> {
@Override
public void forEach(Consumer<V> function)
{
for ( ListenerEntry<V> entry : listeners.values() )
{
entry.executor.execute(() -> {
try {
function.accept(entry.listener);
}
catch ( Throwable e ) {
ThreadUtils.checkInterrupted(e);
log.error(String.format("Listener (%s) threw an exception", entry.listener), e);
}
});
}
}
}

源码技巧

  • 断路器?就是装饰器模式,增加了一些额外的if-else逻辑。
  • 将原来Guava的Function换成了原生的Consumer,实现传入function进行处理的逻辑。

Curator源码阅读 - ConnectionState的管理与监听的更多相关文章

  1. 简单读!tomcat源码(一)启动与监听

    tomcat 作为知名的web容器,很棒! 本文简单了从其应用命令开始拆解,让我们对他有清晰的了解,揭开神秘的面纱!(冗长的代码流水线,给你一目了然) 话分两头: 1. tomcat是如何启动的? 2 ...

  2. Linux 0.11源码阅读笔记-内存管理

    内存管理 Linux内核使用段页式内存管理方式. 内存池 物理页:物理空闲内存被划分为固定大小(4k)的页 内存池:所有空闲物理页组成内存池,以页为单位进行分配回收.并通过位图记录了每个物理页是否空闲 ...

  3. tomcat源码阅读之session管理器(Manager)

    一.UML图分析: (一) Session: Session保存了一个客户端访问服务器时,服务器专门为这个客户端建立一个session用来保存相关的会话信息,session有一个有效时间,这个时间默认 ...

  4. Linux 源码阅读 进程管理

    Linux 源码阅读 进程管理 版本:2.6.24 1.准备知识 1.1 Linux系统中,进程是最小的调度单位: 1.2 PCB数据结构:task_struct (Location:linux-2. ...

  5. 【面试】足够“忽悠”面试官的『Spring事务管理器』源码阅读梳理(建议珍藏)

    PS:文章内容涉及源码,请耐心阅读. 理论实践,相辅相成 伟大领袖毛主席告诉我们实践出真知.这是无比正确的.但是也会很辛苦. 就像淘金一样,从大量沙子中淘出金子一定是一个无比艰辛的过程.但如果真能淘出 ...

  6. LevelDB(v1.3) 源码阅读之 Arena(内存管理器)

    LevelDB(v1.3) 源码阅读系列使用 LevelDB v1.3 版本的代码,可以通过如下方式下载并切换到 v1.3 版本的代码: $ git clone https://github.com/ ...

  7. 【原】AFNetworking源码阅读(四)

    [原]AFNetworking源码阅读(四) 本文转载请注明出处 —— polobymulberry-博客园 1. 前言 上一篇还遗留了很多问题,包括AFURLSessionManagerTaskDe ...

  8. 【原】AFNetworking源码阅读(三)

    [原]AFNetworking源码阅读(三) 本文转载请注明出处 —— polobymulberry-博客园 1. 前言 上一篇的话,主要是讲了如何通过构建一个request来生成一个data tas ...

  9. 【原】SDWebImage源码阅读(三)

    [原]SDWebImage源码阅读(三) 本文转载请注明出处 —— polobymulberry-博客园 1.SDWebImageDownloader中的downloadImageWithURL 我们 ...

随机推荐

  1. ActivityManagerService

    先上类图: 基本类说明和运行框架图中蓝色表示AMS进程,黄色表示app进程.1. 全局调度者在android中,AMS是activity和进程的全局调度者,也就是说系统中载入和准备载入的activit ...

  2. Ubuntu里node命令无效解决方法

    在ubuntu里用sudo apt-get install nodejs安装Node.js后, 会发现terminals里运行node命令(比如node –-version)时候会有No such f ...

  3. app被Rejected 的各种原因翻译。这个绝对有用

    1. Terms and conditions(法律与条款) 1.1  As a developer of applications for the App Store you are bound b ...

  4. sql —— 自动增长列

    1.设置自动增长列 设置完毕添加数据这个字段就不用再手动添加了,会从10001开始,每条数据自动加1.

  5. time,datetime模块

    time模块 时间戳 返回1970年1月1日 00:00:00开始按秒计算时间偏移量 time_stamp = time.time() print(time_stamp,type(time_stamp ...

  6. mysql 语句的查询过程解析

    select * from tb where ID = 1 下面解析的查询过程都是基于上面的简单查询,该系列的所有素材都来自于丁奇的mysql的45讲 1.建立连接 a.客户端发出请求,请求首先到达连 ...

  7. iOS 通知观察者的被调函数不一定运行在主线程

    Tony in iOS | 08/08/2013 iOS 通知观察者的被调函数不一定运行在主线程 今天修复Bug时候发现的一个小细节,记录下. 问题描述 事情是这样的:我在A视图(UITableVie ...

  8. BZOJ 4551树题解

    好吧,洛谷的数据比较水暴力就可以过....(而且跑到飞快) 不过(BZ水不过去)还是讲讲正规的做法. 其实一眼可以看出可以树剖,但是,码起来有点麻烦. 其实有一种更简单的离线做法. 我们很容易联想到并 ...

  9. 在laravel框架中使用ajax请求报错419

    laravel框架中报419 419 unknown status 这个时候你需要将这个接口放到api路由上,这样可以跳过CSRF的检查

  10. UVa 10323 【数学】

    UVa 10323 题目:计算阶乘在10000~6227020800之间的值,不在范围对应输出Under或者Over. 分析:简单题.数论.因为13!=6227020800,7!<10000&l ...