SOFABolt 源碼分析13 - Connection 事件處理機制的設計

image.png

Connection 事件處理相關類

  • ConnectionEventType:定義了三種 Connection 相關事件
  • ConnectionEventHandler:Connection 事件處理器,處理兩類事件
  • Netty 定義的事件:例如 connect弥奸,channelActive 等
  • SOFABolt 定義的事件:事件類型 ConnectionEventType
  • RpcConnectionEventHandler:ConnectionEventHandler 實現(xiàn)類榨惠,重寫了其 channelInactive 方法
  • ConnectionEventListener:Connection 事件監(jiān)聽器,存儲處理對應 ConnectionEventType 的 ConnectionEventProcessor 列表
  • ConnectionEventProcessor:真正的 Connection 事件處理器接口

基本原理

  1. 繼承 ConnectionEventProcessor盛霎,編寫自定義的事件處理類
  2. 將自定義的事件處理類添加到 ConnectionEventListener 中
  3. 當觸發(fā) ConnectionEventType 相關事件時赠橙,ConnectionEventHandler 通知監(jiān)聽器 ConnectionEventListener,ConnectionEventListener 取出 ConnectionEventType 的自定義事件處理器列表愤炸,執(zhí)行其 onEvent 方法

一期揪、使用姿勢

事件處理器

=========================== 連接處理器 ===========================
public class MyCONNECTEventProcessor implements ConnectionEventProcessor {
    @Override
    public void onEvent(String remoteAddr, Connection conn) {
        System.out.println("hello, " + remoteAddr);
    }
}

=========================== 斷開處理器 ===========================
public class MyCLOSEEventProcessor implements ConnectionEventProcessor {
    @Override
    public void onEvent(String remoteAddr, Connection conn) {
        System.out.println("bye, " + remoteAddr);
    }
}

服務端

RpcServer server = new RpcServer(8888);
server.registerUserProcessor(new MyServerUserProcessor());
server.addConnectionEventProcessor(ConnectionEventType.CONNECT, new MyCONNECTEventProcessor());
server.addConnectionEventProcessor(ConnectionEventType.CLOSE, new MyCLOSEEventProcessor());
server.start();

客戶端

RpcClient client = new RpcClient();
client.addConnectionEventProcessor(ConnectionEventType.CONNECT, new MyCONNECTEventProcessor());
client.addConnectionEventProcessor(ConnectionEventType.CLOSE, new MyCLOSEEventProcessor());
client.init();

二、源碼分析

2.1 服務端

public class RpcServer extends AbstractRemotingServer implements RemotingServer {
    ...
    /** connection event handler */
    private ConnectionEventHandler connectionEventHandler;
    /** connection event listener */
    private ConnectionEventListener connectionEventListener = new ConnectionEventListener();
    /** connection manager */
    private DefaultConnectionManager connectionManager;

    protected void doInit() {
        ...
        // 服務端打開了 連接管理器 開關
        if (this.switches().isOn(GlobalSwitch.SERVER_MANAGE_CONNECTION_SWITCH)) {
            // 創(chuàng)建 ConnectionEventHandler 處理器
            this.connectionEventHandler = new RpcConnectionEventHandler(switches());
            // 創(chuàng)建 連接管理器
            this.connectionManager = new DefaultConnectionManager(new RandomSelectStrategy());
            // 設置 connectionManager 到 ConnectionEventHandler 中
            this.connectionEventHandler.setConnectionManager(this.connectionManager);
            // 設置 connectionEventListener 到 ConnectionEventHandler 中
            this.connectionEventHandler.setConnectionEventListener(this.connectionEventListener);
        } else {
            // 創(chuàng)建 ConnectionEventHandler 處理器
            this.connectionEventHandler = new ConnectionEventHandler(switches());
            // 設置 connectionEventListener 到 ConnectionEventHandler 中
            this.connectionEventHandler.setConnectionEventListener(this.connectionEventListener);
        }
        ...
        
        this.bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel channel) {
                ...
                // 添加 connectionEventHandler 到 netty 的 pipeline
                pipeline.addLast("connectionEventHandler", connectionEventHandler);
                ...
                createConnection(channel);
            }

            private void createConnection(SocketChannel channel) {
                Url url = addressParser.parse(RemotingUtil.parseRemoteAddress(channel));
                if (switches().isOn(GlobalSwitch.SERVER_MANAGE_CONNECTION_SWITCH)) {
                    connectionManager.add(new Connection(channel, url), url.getUniqueKey());
                } else {
                    new Connection(channel, url);
                }
                // 發(fā)布 ConnectionEventType.CONNECT 事件
                channel.pipeline().fireUserEventTriggered(ConnectionEventType.CONNECT);
            }
        });
    }

    public void addConnectionEventProcessor(ConnectionEventType type, ConnectionEventProcessor processor) {
        this.connectionEventListener.addConnectionEventProcessor(type, processor);
    }
}

2.2 客戶端

public class RpcClient extends AbstractConfigurableInstance {
    /** connection event handler */
    private ConnectionEventHandler connectionEventHandler = new RpcConnectionEventHandler(switches());
    /** reconnect manager */
    private ReconnectManager reconnectManager;
    /** connection event listener */
    private ConnectionEventListener connectionEventListener = new ConnectionEventListener();
    /** connection manager */
    private DefaultConnectionManager connectionManager = new DefaultConnectionManager(connectionSelectStrategy, connectionFactory, connectionEventHandler, connectionEventListener, switches());

    public void init() {
        ...
        this.connectionManager.init();
        ...
        // 重連開關
        if (switches().isOn(GlobalSwitch.CONN_RECONNECT_SWITCH)) {
            // 創(chuàng)建 ReconnectManager
            reconnectManager = new ReconnectManager(connectionManager);
            // 設置 ReconnectManager 到 connectionEventHandler 中规个,當 channelInactive 時凤薛,進行重連操作
            connectionEventHandler.setReconnectManager(reconnectManager);
        }
    }

    public void addConnectionEventProcessor(ConnectionEventType type,
                                            ConnectionEventProcessor processor) {
        this.connectionEventListener.addConnectionEventProcessor(type, processor);
    }
}

======================== DefaultConnectionManager ==========================
    public void init() {
        // 將當前的 DefaultConnectionManager 設置到 connectionEventHandler 中,用于 channelInactive 時诞仓,從 DefaultConnectionManager 中移除指定 Connection
        this.connectionEventHandler.setConnectionManager(this);
        // 將 connectionEventListener 設置到 connectionEventHandler 中
        this.connectionEventHandler.setConnectionEventListener(connectionEventListener);
        this.connectionFactory.init(connectionEventHandler);
    }

======================== AbstractConnectionFactory ==========================
    public void init(final ConnectionEventHandler connectionEventHandler) {
        ...
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel channel) {
                ...
                pipeline.addLast("connectionEventHandler", connectionEventHandler);
                ...
            }
        });
    }

不論是服務端還是客戶端缤苫,其實本質(zhì)都在做一件事情:創(chuàng)建 ConnectionEventHandler 實例并添加到 Netty 的 pipeline 中。
之后當有 ConnectionEvent 觸發(fā)時(無論是 Netty 定義的事件被觸發(fā)墅拭,還是 SOFABolt 定義的事件被觸發(fā))活玲,ConnectionEventHandler 會通過異步線程執(zhí)行器通知 ConnectionEventListener,ConnectionEventListener 將消息派發(fā)給具體的 ConnectionEventProcessor 實現(xiàn)類。具體源碼如下:

2.3 事件處理機制核心部分

======================== ConnectionEventListener ==========================
/**
 * Listen and dispatch connection events.
 */
public class ConnectionEventListener {
    private ConcurrentHashMap<ConnectionEventType, List<ConnectionEventProcessor>> processors = new ConcurrentHashMap<ConnectionEventType, List<ConnectionEventProcessor>>(3);

    /**
     * Dispatch events.
     */
    public void onEvent(ConnectionEventType type, String remoteAddr, Connection conn) {
        List<ConnectionEventProcessor> processorList = this.processors.get(type);
        if (processorList != null) {
            for (ConnectionEventProcessor processor : processorList) {
                processor.onEvent(remoteAddr, conn);
            }
        }
    }

    /**
     * Add event processor.
     */
    public void addConnectionEventProcessor(ConnectionEventType type,
                                            ConnectionEventProcessor processor) {
        List<ConnectionEventProcessor> processorList = this.processors.get(type);
        if (processorList == null) {
            this.processors.putIfAbsent(type, new ArrayList<ConnectionEventProcessor>(1));
            processorList = this.processors.get(type);
        }
        processorList.add(processor);
    }
}

======================== ConnectionEventProcessor ==========================
/**
 * Process connection events.
 */
public interface ConnectionEventProcessor {
    /**
     * Process event.
     */
    public void onEvent(String remoteAddr, Connection conn);
}

======================== ConnectionEventHandler ==========================
/**
 * Log the channel status event.
 */
@Sharable
public class ConnectionEventHandler extends ChannelDuplexHandler {
    private ConnectionManager       connectionManager;
    private ConnectionEventListener eventListener;
    private ConnectionEventExecutor eventExecutor;
    private ReconnectManager        reconnectManager;
    private GlobalSwitch            globalSwitch;

    @Override
    public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress,
                        SocketAddress localAddress, ChannelPromise promise) throws Exception {
        if (logger.isInfoEnabled()) {
            ...
        }
        super.connect(ctx, remoteAddress, localAddress, promise);
    }
    ...
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        ...
        super.channelInactive(ctx);
        Attribute attr = ctx.channel().attr(Connection.CONNECTION);
        
        if (null != attr) {
            // 進行重連操作舒憾,這也是 ConnectionEventHandler 持有 reconnectManager 引用的原因
            if (this.globalSwitch != null
                && this.globalSwitch.isOn(GlobalSwitch.CONN_RECONNECT_SWITCH)) {
                Connection conn = (Connection) attr.get();
                if (reconnectManager != null) {
                    reconnectManager.addReconnectTask(conn.getUrl());
                }
            }
            // 調(diào)用 ConnectionEventType.CLOSE 事件
            onEvent((Connection) attr.get(), remoteAddress, ConnectionEventType.CLOSE);
        }
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object event) throws Exception {
        if (event instanceof ConnectionEventType) {
            switch ((ConnectionEventType) event) {
                case CONNECT:
                    Channel channel = ctx.channel();
                    if (null != channel) {
                        Connection connection = channel.attr(Connection.CONNECTION).get();
                        // 調(diào)用 ConnectionEventType.CONNECT 事件
                        this.onEvent(connection, connection.getUrl().getOriginUrl(), ConnectionEventType.CONNECT);
                    } 
                    break;
                default:
                    return;
            }
        } else {
            super.userEventTriggered(ctx, event);
        }
    }

    private void onEvent(Connection conn, String remoteAddress, ConnectionEventType type) {
        if (this.eventListener != null) {
            // 1. 創(chuàng)建任務:該任務執(zhí)行調(diào)用 ConnectionEventListener 的 onEvent
            // 2. 使用 ConnectionEventExecutor 執(zhí)行該任務
            this.eventExecutor.onEvent(new Runnable() {
                @Override
                public void run() {
                    ConnectionEventHandler.this.eventListener.onEvent(type, remoteAddress, conn);
                }
            });
        }
    }

    public void setConnectionEventListener(ConnectionEventListener listener) {
        if (listener != null) {
            // 設置 ConnectionEventListener
            this.eventListener = listener;
            // 創(chuàng)建 ConnectionEventExecutor镀钓,事件的異步執(zhí)行器
            if (this.eventExecutor == null) {
                this.eventExecutor = new ConnectionEventExecutor();
            }
        }
    }

    public class ConnectionEventExecutor {
        ExecutorService executor = new ThreadPoolExecutor(1, 1, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(10000), new NamedThreadFactory("Bolt-conn-event-executor", true));

        public void onEvent(Runnable event) {
            executor.execute(event);
        }
    }
}

======================== RpcConnectionEventHandler ==========================
public class RpcConnectionEventHandler extends ConnectionEventHandler {
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Connection conn = ctx.channel().attr(Connection.CONNECTION).get();
        if (conn != null) {
            // 這就是 ConnectionEventHandler 持有 ConnectionManager 引用的原因
            this.getConnectionManager().remove(conn);
        }
        super.channelInactive(ctx);
    }
}

事件的處理流程

事件觸發(fā) -> RpcConnectionEventHandler -> [ ConnectionEventListener -> ConnectionEventProcessor ]
方括號內(nèi)的操作由 ConnectionEventExecutor 異步執(zhí)行
事件的觸發(fā)有兩種:Netty定義的事件(例如 channelInactive)和 SOFABolt 定義的事件,前者直接在 Netty 定義的事件觸發(fā)方法中進行(例如 channelInactive)镀迂,后者在 userEventTriggered 方法中進行觸發(fā)掸宛。

事件的觸發(fā)時機

  • ConnectionEventType.CONNECT
  • AbstractConnectionFactory # createConnection(客戶端)
  • RpcServer # doInit # childHandler # initChannel # createConnection(服務端)
  • ConnectionEventType.CLOSE
  • ConnectionEventHandler # channelInactive
======================== 客戶端創(chuàng)建連接 ==========================
@Override
    public Connection createConnection(Url url) throws Exception {
        Channel channel = doCreateConnection(url.getIp(), url.getPort(), url.getConnectTimeout());
        Connection conn = new Connection(channel, ProtocolCode.fromBytes(url.getProtocol()),
            url.getVersion(), url);
        // 發(fā)布 ConnectionEventType.CONNECT 事件
        channel.pipeline().fireUserEventTriggered(ConnectionEventType.CONNECT);
        return conn;
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市招拙,隨后出現(xiàn)的幾起案子唧瘾,更是在濱河造成了極大的恐慌,老刑警劉巖别凤,帶你破解...
    沈念sama閱讀 216,496評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件饰序,死亡現(xiàn)場離奇詭異,居然都是意外死亡规哪,警方通過查閱死者的電腦和手機求豫,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,407評論 3 392
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來诉稍,“玉大人蝠嘉,你說我怎么就攤上這事”蓿” “怎么了蚤告?”我有些...
    開封第一講書人閱讀 162,632評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長服爷。 經(jīng)常有香客問我杜恰,道長,這世上最難降的妖魔是什么仍源? 我笑而不...
    開封第一講書人閱讀 58,180評論 1 292
  • 正文 為了忘掉前任心褐,我火速辦了婚禮,結(jié)果婚禮上笼踩,老公的妹妹穿的比我還像新娘逗爹。我一直安慰自己,他們只是感情好嚎于,可當我...
    茶點故事閱讀 67,198評論 6 388
  • 文/花漫 我一把揭開白布掘而。 她就那樣靜靜地躺著,像睡著了一般匾旭。 火紅的嫁衣襯著肌膚如雪镣屹。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,165評論 1 299
  • 那天价涝,我揣著相機與錄音女蜈,去河邊找鬼。 笑死,一個胖子當著我的面吹牛伪窖,可吹牛的內(nèi)容都是我干的逸寓。 我是一名探鬼主播,決...
    沈念sama閱讀 40,052評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼覆山,長吁一口氣:“原來是場噩夢啊……” “哼竹伸!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起簇宽,我...
    開封第一講書人閱讀 38,910評論 0 274
  • 序言:老撾萬榮一對情侶失蹤勋篓,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后魏割,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體譬嚣,經(jīng)...
    沈念sama閱讀 45,324評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,542評論 2 332
  • 正文 我和宋清朗相戀三年钞它,在試婚紗的時候發(fā)現(xiàn)自己被綠了拜银。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,711評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡遭垛,死狀恐怖尼桶,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情锯仪,我是刑警寧澤泵督,帶...
    沈念sama閱讀 35,424評論 5 343
  • 正文 年R本政府宣布,位于F島的核電站卵酪,受9級特大地震影響幌蚊,放射性物質(zhì)發(fā)生泄漏谤碳。R本人自食惡果不足惜溃卡,卻給世界環(huán)境...
    茶點故事閱讀 41,017評論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望蜒简。 院中可真熱鬧瘸羡,春花似錦、人聲如沸搓茬。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,668評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽卷仑。三九已至峻村,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間锡凝,已是汗流浹背粘昨。 一陣腳步聲響...
    開封第一講書人閱讀 32,823評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人张肾。 一個月前我還...
    沈念sama閱讀 47,722評論 2 368
  • 正文 我出身青樓芭析,卻偏偏與公主長得像,于是被迫代替她去往敵國和親吞瞪。 傳聞我的和親對象是個殘疾皇子馁启,可洞房花燭夜當晚...
    茶點故事閱讀 44,611評論 2 353

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現(xiàn)芍秆,斷路器惯疙,智...
    卡卡羅2017閱讀 134,651評論 18 139
  • 1、通過CocoaPods安裝項目名稱項目信息 AFNetworking網(wǎng)絡請求組件 FMDB本地數(shù)據(jù)庫組件 SD...
    陽明先生_X自主閱讀 15,979評論 3 119
  • 國家電網(wǎng)公司企業(yè)標準(Q/GDW)- 面向?qū)ο蟮挠秒娦畔?shù)據(jù)交換協(xié)議 - 報批稿:20170802 前言: 排版 ...
    庭說閱讀 10,958評論 6 13
  • 上午九點四十妖啥,去市場二樓螟碎。幫陶瓷店倪同學拆射燈。她換店鋪了迹栓。原來的玻璃門店鋪并不免租掉分,所以又換回到胡同里去了。 而...
    果然越來越好閱讀 214評論 0 0
  • 愛情是一件奢侈品克伊! 哀怨情仇中酥郭,或大多數(shù)都會鬼終于平凡,平凡的愛情愿吹,平淡的生活不从。 學時追究純粹的愛情,青春時荷爾蒙...
    我是一只小小鳥閱讀 387評論 0 1