1. 程式人生 > 其它 >Sentinel教程進階一Sentinel-API

Sentinel教程進階一Sentinel-API

sentinel功能強大,但是開源出來的sentinel可以說是一個半成品,bug多,並且很多功能沒有實現,可能是因為它有收費的版本吧。因此我們如果想在生產上應用就要戒驕戒躁,瞭解它的原始碼,對它進行優化改造。在改造過程中不可避免的要呼叫sentinel的api介面進行一些規則的同步等操作。

監聽埠

服務整合sentinel的方式

        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
        </dependency>

啟動服務後,一旦訪問了介面,sentinel會通過websocket或netty的方式監聽8719(預設)埠,提供一些介面方便我們以http的方式呼叫取獲取、修改sentinel的限流規則,叢集配置等。

監聽的埠預設是8719,但是如果埠被佔用,就會換自動換埠,具體換埠邏輯是8719+重試次數/3,這個沒什麼意思,不比深究。

程式碼實現

具體啟動埠監聽的邏輯在com.alibaba.csp.sentinel.transport.init.CommandCenterInitFunc中,該類在sentinel-transport-common模組中,具體依賴如下

@InitOrder(-1)
public class CommandCenterInitFunc implements InitFunc {

    @Override
    public void init() throws Exception {
        //commandCenter預設是SimpleHttpCommandCenter
        CommandCenter commandCenter = CommandCenterProvider.getCommandCenter();

        if (commandCenter == null) {
            RecordLog.warn("[CommandCenterInitFunc] Cannot resolve CommandCenter");
            return;
        }

        commandCenter.beforeStart();
        //啟動監聽
        commandCenter.start();
        RecordLog.info("[CommandCenterInit] Starting command center: "
                + commandCenter.getClass().getCanonicalName());
    }
}

上述程式碼中commandCenter預設是SimpleHttpCommandCenter,如果引入sentinel-transport-netty-http,則它就會變成NettyHttpCommandCenter,具體原因是sentinel為spi類定義了一個order屬性,NettyHttpCommandCenter的order屬性更高

具體模組之間的關係如下如

埠可通過引數:csp.sentinel.api.port指定。

具體啟動邏輯可以自己跟一下,比較簡單。

api介面

具體有哪些介面呢?

com.alibaba.csp.sentinel.command.CommandHandler介面的所有實現類

我們可以通過呼叫localhost:port/api獲取到所有的api

這些handler基本上分佈在三個模組中

  • sentinel-transport-common:提供一些規則相關的,基本的介面

  • sentinel-cluster-client-default:叢集客戶端相關介面

  • sentinel-cluster-server-default:叢集服務端相關介面

sentinel-transport-common

ApiCommandHandler /api 獲取所有介面
FetchClusterModeCommandHandler /getClusterMode 獲取叢集模式資訊
ModifyClusterModeCommandHandler /setClusterMode 修改叢集模式
BasicInfoCommandHandler /basicInfo 獲取服務基本資訊 { "machine": "localhost", "ip": "172.18.208.214"}
FetchActiveRuleCommandHandler /getRules 獲取規則,引數type flow|degrade|authority|system
FetchClusterNodeByIdCommandHandler /clusterNodeById 根據id查詢clustNode資訊
FetchClusterNodeHumanCommandHandler /cnode get clusterNode metrics by id, request param: id={resourceName}
FetchJsonTreeCommandHandler /jsonTree 簇點鏈路
FetchOriginCommandHandler /origin get origin clusterNode by id, request param: id={resourceName}
FetchSimpleClusterNodeCommandHandler /clusterNode get all clusterNode VO, use type=notZero to ignore those nodes with totalRequest <=0
FetchSystemStatusCommandHandler /systemStatus get system status {"b":0.0,"r":0.0,"t":0,"qps":0.0,"rqps":0.0}
FetchTreeCommandHandler /tree get metrics in tree mode, use id to specify detailed tree root 統計資訊
ModifyRulesCommandHandler /setRules 更新規則
OnOffGetCommandHandler /getSwitch get sentinel switch status
OnOffSetCommandHandler /setSwitch set sentinel switch, accept param: value={true|false}
SendMetricCommandHandler /metric get and aggregate metrics, accept param:startTime={startTime}&endTime={endTime}&maxLines={maxLines}&identify={resourceName}
VersionCommandHandler /version sentinel版本 1.8.1

sentinel-cluster-client-default

FetchClusterClientConfigHandler /cluster/client/fetchConfig 獲取叢集-客戶端配置
ModifyClusterClientConfigHandler /cluster/client/modifyConfig 修改叢集-客戶端配置

sentinel-cluster-server-default

FetchClusterFlowRulesCommandHandler /cluster/server/flowRules 獲取叢集限流規則
FetchClusterParamFlowRulesCommandHandler /cluster/server/paramRules 獲取叢集熱點引數規則
FetchClusterServerConfigHandler /cluster/server/fetchConfig 獲取叢集server配置
FetchClusterServerInfoCommandHandler /cluster/server/info 獲取叢集server資訊
FetchClusterMetricCommandHandler /cluster/server/metricList 獲取叢集統計資訊
ModifyClusterFlowRulesCommandHandler /cluster/server/modifyFlowRules 修改叢集限流規則
ModifyClusterParamFlowRulesCommandHandler /cluster/server/modifyParamRules 修改叢集熱點引數規則
ModifyClusterServerFlowConfigHandler /cluster/server/modifyFlowConfig 待檢視
ModifyClusterServerTransportConfigHandler /cluster/server/modifyTransportConfig 修改叢集server配置
ModifyServerNamespaceSetHandler /cluster/server/modifyNamespaceSet 修改namespace資訊
public class SimpleHttpCommandCenter implements CommandCenter {

       public void run() {
                boolean success = false;
                ServerSocket serverSocket = SimpleHttpCommandCenter.getServerSocketFromBasePort(this.port);
                if (serverSocket != null) {
                    CommandCenterLog.info("[CommandCenter] Begin listening at port " + serverSocket.getLocalPort(), new Object[0]);
                    SimpleHttpCommandCenter.this.socketReference = serverSocket;
                    SimpleHttpCommandCenter.this.executor.submit(SimpleHttpCommandCenter.this.new ServerThread(serverSocket));
                    success = true;
                    this.port = serverSocket.getLocalPort();
                } else {
                    CommandCenterLog.info("[CommandCenter] chooses port fail, http command center will not work", new Object[0]);
                }

                if (!success) {
                    this.port = -1;
                }

                TransportConfig.setRuntimePort(this.port);
                SimpleHttpCommandCenter.this.executor.shutdown();
            }
}

專案整合sentinel啟動後,api服務並不會啟動,而是等到專案被訪問的時候才會被啟動,具體的方式是啟動一個netty服務監聽8719埠(預設)

SphU.entry("testRule1", EntryType.IN, 1, id);