4. SOFAJRaftソースコード解析 - RheaKVの初期化が何をしましたか?

序文

RheaKVので懸念しているいくつかの章にので、ここでは分割され、その長い長さについて話す、RheaKVの初期化については、この章の話は何をしましたか?

のはの点では例から、例えば見てみましょう:

public static void main(final String[] args) throws Exception {
    final PlacementDriverOptions pdOpts = PlacementDriverOptionsConfigured.newConfigured()
            .withFake(true) // use a fake pd
            .config();
    final StoreEngineOptions storeOpts = StoreEngineOptionsConfigured.newConfigured() //
            .withStorageType(StorageType.RocksDB)
            .withRocksDBOptions(RocksDBOptionsConfigured.newConfigured().withDbPath(Configs.DB_PATH).config())
            .withRaftDataPath(Configs.RAFT_DATA_PATH)
            .withServerAddress(new Endpoint("127.0.0.1", 8181))
            .config();

    final RheaKVStoreOptions opts = RheaKVStoreOptionsConfigured.newConfigured() //
            .withClusterName(Configs.CLUSTER_NAME) //
            .withInitialServerList(Configs.ALL_NODE_ADDRESSES)
            .withStoreEngineOptions(storeOpts) //
            .withPlacementDriverOptions(pdOpts) //
            .config();
    System.out.println(opts);
    final Node node = new Node(opts);
    node.start();
    Runtime.getRuntime().addShutdownHook(new Thread(node::stop));
    System.out.println("server1 start OK");
}

ここにPDを用いることなく、ロジックを簡単にするために設けられました

ノードの実装:

public class Node {

    private final RheaKVStoreOptions options;

    private RheaKVStore              rheaKVStore;

    public Node(RheaKVStoreOptions options) {
        this.options = options;
    }

    public void start() {
        this.rheaKVStore = new DefaultRheaKVStore();
        this.rheaKVStore.init(this.options);
    }

    public void stop() {
        this.rheaKVStore.shutdown();
    }

    public RheaKVStore getRheaKVStore() {
        return rheaKVStore;
    }
}

だからここではDefaultRheaKVStoreを初期化し、そのinitメソッドを呼び出すことです

RheaKVデフォルトのストレージDefaultRheaKVStore

DefaultRheaKVStore初期化方法は、初期化処理が完了しているため、ダイレクトルックのinitメソッドDefaultRheaKVStore本明細書。

public synchronized boolean init(final RheaKVStoreOptions opts) {
    //1. 如果已经启动了,那么直接返回
    if (this.started) {
        LOG.info("[DefaultRheaKVStore] already started.");
        return true;
    }
    this.opts = opts;
    // init placement driver
    // 2.根据PDoptions设置PD
    final PlacementDriverOptions pdOpts = opts.getPlacementDriverOptions();
    final String clusterName = opts.getClusterName();
    Requires.requireNonNull(pdOpts, "opts.placementDriverOptions");
    Requires.requireNonNull(clusterName, "opts.clusterName");
    //设置集群
    if (Strings.isBlank(pdOpts.getInitialServerList())) {
        // if blank, extends parent's value
        pdOpts.setInitialServerList(opts.getInitialServerList());
    }
    //如果是无 PD 场景, RheaKV 提供 Fake PD Client
    if (pdOpts.isFake()) {
        this.pdClient = new FakePlacementDriverClient(opts.getClusterId(), clusterName);
    } else {
        this.pdClient = new RemotePlacementDriverClient(opts.getClusterId(), clusterName);
    }
    //初始化PD
    if (!this.pdClient.init(pdOpts)) {
        LOG.error("Fail to init [PlacementDriverClient].");
        return false;
    }
    // init store engine
    //3. 初始化存储引擎
    final StoreEngineOptions stOpts = opts.getStoreEngineOptions();
    if (stOpts != null) {
        stOpts.setInitialServerList(opts.getInitialServerList());
        this.storeEngine = new StoreEngine(this.pdClient);
        //初始化存储引擎
        if (!this.storeEngine.init(stOpts)) {
            LOG.error("Fail to init [StoreEngine].");
            return false;
        }
    }
    //获取当前节点的ip和端口号
    final Endpoint selfEndpoint = this.storeEngine == null ? null : this.storeEngine.getSelfEndpoint();
    final RpcOptions rpcOpts = opts.getRpcOptions();
    Requires.requireNonNull(rpcOpts, "opts.rpcOptions");
    //4. 初始化一个RpcService,并重写getLeader方法
    this.rheaKVRpcService = new DefaultRheaKVRpcService(this.pdClient, selfEndpoint) {

        @Override
        public Endpoint getLeader(final long regionId, final boolean forceRefresh, final long timeoutMillis) {
            final Endpoint leader = getLeaderByRegionEngine(regionId);
            if (leader != null) {
                return leader;
            }
            return super.getLeader(regionId, forceRefresh, timeoutMillis);
        }
    };
    if (!this.rheaKVRpcService.init(rpcOpts)) {
        LOG.error("Fail to init [RheaKVRpcService].");
        return false;
    }
    //获取重试次数,默认重试两次
    this.failoverRetries = opts.getFailoverRetries();
    //默认5000
    this.futureTimeoutMillis = opts.getFutureTimeoutMillis();
    //是否只从leader读取数据,默认为true
    this.onlyLeaderRead = opts.isOnlyLeaderRead();
    //5.初始化kvDispatcher, 这里默认为true
    if (opts.isUseParallelKVExecutor()) {
        //获取当前cpu
        final int numWorkers = Utils.cpus();
        //向左移动4位,相当于乘以16
        final int bufSize = numWorkers << 4;
        final String name = "parallel-kv-executor";
        final ThreadFactory threadFactory = Constants.THREAD_AFFINITY_ENABLED
                //这里选择是否启用线程亲和性ThreadFactory
                ? new AffinityNamedThreadFactory(name, true) : new NamedThreadFactory(name, true);
        //初始化Dispatcher
        this.kvDispatcher = new TaskDispatcher(bufSize, numWorkers, WaitStrategyType.LITE_BLOCKING_WAIT,
                threadFactory);
    }
    this.batchingOpts = opts.getBatchingOptions();
    //默认是true
    if (this.batchingOpts.isAllowBatching()) {
        //这几个batching暂时不知道是用来做什么的,等用到再分析
        this.getBatching = new GetBatching(KeyEvent::new, "get_batching",
                new GetBatchingHandler("get", false));
        this.getBatchingOnlySafe = new GetBatching(KeyEvent::new, "get_batching_only_safe",
                new GetBatchingHandler("get_only_safe", true));
        this.putBatching = new PutBatching(KVEvent::new, "put_batching",
                new PutBatchingHandler("put"));
    }
    LOG.info("[DefaultRheaKVStore] start successfully, options: {}.", opts);
    return this.started = true;
}
  1. すでに始まっている場合、開始するかどうかをチェックし、その後、直接のリターン
  2. 係るPDoptionsがPDを設定し、PDは、グローバルセンタマスタ制御ノードであり、クラスタ全体のスケジュール、メンテナンスRegionRouteTableルーティングテーブルを管理する責任があります。ここでは、PDを有効にしていない、それはFakePlacementDriverClientをインスタンス化し、初期化
  3. 初期化ストレージエンジン、現在StoreEngineストレージエンジンはMemoryDBとRocksDB 2つの実装をサポートし、私たちはここにいるRocksDBで、initメソッド補完説明します
  4. ストレージサービスクライアントRPCクライアントエンドパッケージのrheaKVRpcService、KVの初期化、フェイルオーバー・ロジックを実現。そして、タイムアウトは、デフォルトのリーダーからデータを読み取るために、5000ミリ秒です待っfutureTimeoutMillis二回の再試行を設定します
  5. 初期kvDispatcher

初期化ストレージエンジン

StoreEngine内のinitメソッドで初期化が動作しているとき、私たちは直接このメソッドを実装見える達成し、この方法は、コアオブジェクトの初期化ロジックは忍耐が読むには少しの希望、より複雑です。

StoreEngine熱#

public synchronized boolean init(final StoreEngineOptions opts) {
    if (this.started) {
        LOG.info("[StoreEngine] already started.");
        return true;
    }
    this.storeOpts = Requires.requireNonNull(opts, "opts");
    Endpoint serverAddress = Requires.requireNonNull(opts.getServerAddress(), "opts.serverAddress");
    //获取ip和端口
    final int port = serverAddress.getPort();
    final String ip = serverAddress.getIp();
    //如果传入的IP为空,那么就设置启动机器ip作为serverAddress的ip
    if (ip == null || Utils.IP_ANY.equals(ip)) {
        serverAddress = new Endpoint(NetUtil.getLocalCanonicalHostName(), port);
        opts.setServerAddress(serverAddress);
    }
    //获取度量上报时间
    final long metricsReportPeriod = opts.getMetricsReportPeriod();
    // init region options
    List<RegionEngineOptions> rOptsList = opts.getRegionEngineOptionsList();
    //1. 如果RegionEngineOptions为空,则默认初始化一个
    if (rOptsList == null || rOptsList.isEmpty()) {
        // -1 region
        final RegionEngineOptions rOpts = new RegionEngineOptions();
        rOpts.setRegionId(Constants.DEFAULT_REGION_ID);
        rOptsList = Lists.newArrayList();
        rOptsList.add(rOpts);
        opts.setRegionEngineOptionsList(rOptsList);
    }
    //获取集群名
    final String clusterName = this.pdClient.getClusterName();
    //2. 遍历rOptsList集合,为其中的RegionEngineOptions对象设置参数
    for (final RegionEngineOptions rOpts : rOptsList) {
        //用集群名+“-”+RegionId 拼接设置为RaftGroupId
        rOpts.setRaftGroupId(JRaftHelper.getJRaftGroupId(clusterName, rOpts.getRegionId()));
        rOpts.setServerAddress(serverAddress);
        rOpts.setInitialServerList(opts.getInitialServerList());
        if (rOpts.getNodeOptions() == null) {
            // copy common node options
            rOpts.setNodeOptions(opts.getCommonNodeOptions() == null ? new NodeOptions() : opts
                .getCommonNodeOptions().copy());
        }
        //如果原本没有设置度量上报时间,那么就重置一下
        if (rOpts.getMetricsReportPeriod() <= 0 && metricsReportPeriod > 0) {
            // extends store opts 300
            rOpts.setMetricsReportPeriod(metricsReportPeriod);
        }
    }
    // init store
    // 3. 初始化Store和Store里面的region
    final Store store = this.pdClient.getStoreMetadata(opts);
    if (store == null || store.getRegions() == null || store.getRegions().isEmpty()) {
        LOG.error("Empty store metadata: {}.", store);
        return false;
    }
    this.storeId = store.getId();
    // init executors
    //4. 初始化执行器
    if (this.readIndexExecutor == null) {
        this.readIndexExecutor = StoreEngineHelper.createReadIndexExecutor(opts.getReadIndexCoreThreads());
    }
    if (this.raftStateTrigger == null) {
        this.raftStateTrigger = StoreEngineHelper.createRaftStateTrigger(opts.getLeaderStateTriggerCoreThreads());
    }
    if (this.snapshotExecutor == null) {
        this.snapshotExecutor = StoreEngineHelper.createSnapshotExecutor(opts.getSnapshotCoreThreads());
    }
    // init rpc executors 默认false
    final boolean useSharedRpcExecutor = opts.isUseSharedRpcExecutor();
    //5. 初始化rpc远程执行器,用来执行RPCServer的Processors
    if (!useSharedRpcExecutor) {
        if (this.cliRpcExecutor == null) {
            this.cliRpcExecutor = StoreEngineHelper.createCliRpcExecutor(opts.getCliRpcCoreThreads());
        }
        if (this.raftRpcExecutor == null) {
            this.raftRpcExecutor = StoreEngineHelper.createRaftRpcExecutor(opts.getRaftRpcCoreThreads());
        }
        if (this.kvRpcExecutor == null) {
            this.kvRpcExecutor = StoreEngineHelper.createKvRpcExecutor(opts.getKvRpcCoreThreads());
        }
    }
    // init metrics
    //做指标度量
    startMetricReporters(metricsReportPeriod);
    // init rpc server
    //6. 初始化rpcServer,供其他服务调用
    this.rpcServer = new RpcServer(port, true, true);
    //为server加入各种processor
    RaftRpcServerFactory.addRaftRequestProcessors(this.rpcServer, this.raftRpcExecutor, this.cliRpcExecutor);
    StoreEngineHelper.addKvStoreRequestProcessor(this.rpcServer, this);
    if (!this.rpcServer.start()) {
        LOG.error("Fail to init [RpcServer].");
        return false;
    }
    // init db store
    //7. 根据不同的类型选择db
    if (!initRawKVStore(opts)) {
        return false;
    }
    // init all region engine
    // 8. 为每个region初始化RegionEngine
    if (!initAllRegionEngine(opts, store)) {
        LOG.error("Fail to init all [RegionEngine].");
        return false;
    }
    // heartbeat sender
    //如果开启了自管理的集群,那么需要初始化心跳发送器
    if (this.pdClient instanceof RemotePlacementDriverClient) {
        HeartbeatOptions heartbeatOpts = opts.getHeartbeatOptions();
        if (heartbeatOpts == null) {
            heartbeatOpts = new HeartbeatOptions();
        }
        this.heartbeatSender = new HeartbeatSender(this);
        if (!this.heartbeatSender.init(heartbeatOpts)) {
            LOG.error("Fail to init [HeartbeatSender].");
            return false;
        }
    }
    this.startTime = System.currentTimeMillis();
    LOG.info("[StoreEngine] start successfully: {}.", this);
    return this.started = true;
}

私たちは、ダウン見て上からコード番号をマーク:

  1. ここでは、空の場合、デフォルトの初期化は、その後、regionEngineOptionsListのStoreEngineOptionsが空であることを確認した後、回収rOptsListに追加しました
  2. トラバーサルrOptsListコレクション、およびオブジェクトの設定におけるクラスタ情報RegionEngineOptions
  3. ストアはその後RegionEngineOptionsに応じてインスタンス化し、領域内部を初期化
  4. 初期化アクチュエータ
  5. RPCServerの実行プロセッサの初期化RPC遠隔アクチュエータ
  6. 初期rpcServerは、他のサービスを求めて
  7. タイプ選択されたDBに応じて、現在StoreEngineストレージエンジンはMemoryDBとRocksDB 2つの実装をサポートしています。MemoryDB ConcurrentSkipListMapのは、達成に基づきます。
  8. 各地域のRegionEngineを初期化

ストア初期設定を保存し、地域内の

ここでgetStoreMetadata法pdClientは、我々が実現FakePlacementDriverClientを参照してくださいここでは、初期化を呼び出します:
FakePlacementDriverClient#getStoreMetadata

public Store getStoreMetadata(final StoreEngineOptions opts) {
    //实例化store
    final Store store = new Store();
    final List<RegionEngineOptions> rOptsList = opts.getRegionEngineOptionsList();
    final List<Region> regionList = Lists.newArrayListWithCapacity(rOptsList.size());
    store.setId(-1);
    store.setEndpoint(opts.getServerAddress());
    for (final RegionEngineOptions rOpts : rOptsList) {
        //根据rOpts初始化Region实例加入到regionList中
        regionList.add(getLocalRegionMetadata(rOpts));
    }
    store.setRegions(regionList);
    return store;
}

この方法の内側に設定rOptsList領域をインスタンス化するためにループgetLocalRegionMetadata法内部rOptsList RegionEngineOptionsと呼ばれる店舗を、インスタンス化横断後、regionListは次に、コレクションに加えます。
あなたは、メインrOptsListとregionListインデックスは1対1の関係のリストで、次のコードは、この対応に使用されるリストする必要があります。

ここでは、少し理解することができるはずです。

この絵の意義は、各店舗には、以下の地域の多くを持っています。

その後、我々はどのように初期化する地域を見て:
ここで初期化するgetLocalRegionMetadataのコールFakePlacementDriverClient親AbstractPlacementDriverClientある
AbstractPlacementDriverClient#getLocalRegionMetadataは、

protected Region getLocalRegionMetadata(final RegionEngineOptions opts) {
    final long regionId = Requires.requireNonNull(opts.getRegionId(), "opts.regionId");
    Requires.requireTrue(regionId >= Region.MIN_ID_WITH_MANUAL_CONF, "opts.regionId must >= "
                                                                     + Region.MIN_ID_WITH_MANUAL_CONF);
    Requires.requireTrue(regionId < Region.MAX_ID_WITH_MANUAL_CONF, "opts.regionId must < "
                                                                    + Region.MAX_ID_WITH_MANUAL_CONF);
    final byte[] startKey = opts.getStartKeyBytes();
    final byte[] endKey = opts.getEndKeyBytes();
    final String initialServerList = opts.getInitialServerList();
    //实例化region
    final Region region = new Region();
    final Configuration conf = new Configuration();
    // region
    region.setId(regionId);
    region.setStartKey(startKey);
    region.setEndKey(endKey);
    region.setRegionEpoch(new RegionEpoch(-1, -1));
    // peers
    Requires.requireTrue(Strings.isNotBlank(initialServerList), "opts.initialServerList is blank");
    //将集群ip和端口解析到peer中
    conf.parse(initialServerList);
    //每个region都会存有集群的信息
    region.setPeers(JRaftHelper.toPeerList(conf.listPeers()));
    this.regionRouteTable.addOrUpdateRegion(region);
    return region;
}

初期化がヌルである領域KVは最小のデータ単位であり、データ・パーティションまたはスライスとして理解、各領域が閉左右開区間[startKey、endKey)を有し、それは要求に応じて可能/ロード/トラフィック・データでありますボリュームサイズと他の指標は自動的に分割し、自動的に再配置をコピーします。レプリケーション地域の建設は、ラフトストアグループは、異なるノードに格納された複数のコピーは、データの複製は、同じグループ筏プロトコルログにより、すべてのノードを同期させることがあります。

最後は、地域にregionRouteTableに格納されます。

public void addOrUpdateRegion(final Region region) {
    Requires.requireNonNull(region, "region");
    Requires.requireNonNull(region.getRegionEpoch(), "regionEpoch");
    final long regionId = region.getId();
    final byte[] startKey = BytesUtil.nullToEmpty(region.getStartKey());
    final StampedLock stampedLock = this.stampedLock;
    final long stamp = stampedLock.writeLock();
    try {
        this.regionTable.put(regionId, region.copy());
        this.rangeTable.put(startKey, regionId);
    } finally {
        stampedLock.unlockWrite(stamp);
    }
}

この方法は、startKeyとしてキー範囲テーブルに従って格納次いでregionTableに従ってregionId領域に格納されています。

各地域のRegionEngineを初期化

initAllRegionEngineでは初期化されますRegionEngine:
StoreEngine#initAllRegionEngine

private boolean initAllRegionEngine(final StoreEngineOptions opts, final Store store) {
    Requires.requireNonNull(opts, "opts");
    Requires.requireNonNull(store, "store");
    //获取主目录
    String baseRaftDataPath = opts.getRaftDataPath();
    if (Strings.isNotBlank(baseRaftDataPath)) {
        try {
            FileUtils.forceMkdir(new File(baseRaftDataPath));
        } catch (final Throwable t) {
            LOG.error("Fail to make dir for raftDataPath: {}.", baseRaftDataPath);
            return false;
        }
    } else {
        baseRaftDataPath = "";
    }
    final Endpoint serverAddress = opts.getServerAddress();
    final List<RegionEngineOptions> rOptsList = opts.getRegionEngineOptionsList();
    final List<Region> regionList = store.getRegions();
    //因为regionList是根据rOptsList来初始化的,所以这里校验一样数量是不是一样的
    Requires.requireTrue(rOptsList.size() == regionList.size());
    for (int i = 0; i < rOptsList.size(); i++) {
        //一一对应的获取相应的RegionEngineOptions和region
        final RegionEngineOptions rOpts = rOptsList.get(i);
        final Region region = regionList.get(i);
        //如果region路径是空的,那么就重新设值
        if (Strings.isBlank(rOpts.getRaftDataPath())) {
            final String childPath = "raft_data_region_" + region.getId() + "_" + serverAddress.getPort();
            rOpts.setRaftDataPath(Paths.get(baseRaftDataPath, childPath).toString());
        }
        Requires.requireNonNull(region.getRegionEpoch(), "regionEpoch");
        //根据Region初始化RegionEngine
        final RegionEngine engine = new RegionEngine(region, this);
        if (engine.init(rOpts)) {
            //KV Server 服务端的请求处理服务
            // 每个 RegionKVService 对应一个 Region,只处理本身 Region 范畴内的请求
            final RegionKVService regionKVService = new DefaultRegionKVService(engine);
            //放入到regionKVServiceTable中
            registerRegionKVService(regionKVService);
            //设置region与engine映射表
            this.regionEngineTable.put(region.getId(), engine);
        } else {
            LOG.error("Fail to init [RegionEngine: {}].", region);
            return false;
        }
    }
    return true;
}

この方法は、最初のホームディレクトリとしてbaseRaftDataPathを初期化
した後rOptsList regionListと、トラバースrOptsList取り出され、そしてRegionEngineOptionsは、対応する領域を見つける
、各領域のために本明細書RegionEngineをインスタンス化し、エンジンパッケージ化RegionKVService
最後RegionKVService regionKVServiceTableは、領域マッピングテーブルregionEngineTableに配置され、マッピングテーブルに入れ

RegionKVServicがここKV Serverサービス要求処理サーバで、StoreEngineはそれぞれが唯一の処理要求自体地域のカテゴリに、地域RegionKVServiceに対応し、多くのRegionKVServiceが含まれています。

初期RegionEngine#のinit

public synchronized boolean init(final RegionEngineOptions opts) {
    if (this.started) {
        LOG.info("[RegionEngine: {}] already started.", this.region);
        return true;
    }
    this.regionOpts = Requires.requireNonNull(opts, "opts");
    //实例化状态机
    this.fsm = new KVStoreStateMachine(this.region, this.storeEngine);

    // node options
    NodeOptions nodeOpts = opts.getNodeOptions();
    if (nodeOpts == null) {
        nodeOpts = new NodeOptions();
    }
    //如果度量间隔时间大于零,那么开启度量
    final long metricsReportPeriod = opts.getMetricsReportPeriod();
    if (metricsReportPeriod > 0) {
        // metricsReportPeriod > 0 means enable metrics
        nodeOpts.setEnableMetrics(true);
    }
    //初始化集群配置
    nodeOpts.setInitialConf(new Configuration(JRaftHelper.toJRaftPeerIdList(this.region.getPeers())));
    nodeOpts.setFsm(this.fsm);
    //初始化各种日志的路径
    final String raftDataPath = opts.getRaftDataPath();
    try {
        FileUtils.forceMkdir(new File(raftDataPath));
    } catch (final Throwable t) {
        LOG.error("Fail to make dir for raftDataPath {}.", raftDataPath);
        return false;
    }
    if (Strings.isBlank(nodeOpts.getLogUri())) {
        final Path logUri = Paths.get(raftDataPath, "log");
        nodeOpts.setLogUri(logUri.toString());
    }
    if (Strings.isBlank(nodeOpts.getRaftMetaUri())) {
        final Path meteUri = Paths.get(raftDataPath, "meta");
        nodeOpts.setRaftMetaUri(meteUri.toString());
    }
    if (Strings.isBlank(nodeOpts.getSnapshotUri())) {
        final Path snapshotUri = Paths.get(raftDataPath, "snapshot");
        nodeOpts.setSnapshotUri(snapshotUri.toString());
    }
    LOG.info("[RegionEngine: {}], log uri: {}, raft meta uri: {}, snapshot uri: {}.", this.region,
        nodeOpts.getLogUri(), nodeOpts.getRaftMetaUri(), nodeOpts.getSnapshotUri());
    final Endpoint serverAddress = opts.getServerAddress();
    final PeerId serverId = new PeerId(serverAddress, 0);
    final RpcServer rpcServer = this.storeEngine.getRpcServer();
    this.raftGroupService = new RaftGroupService(opts.getRaftGroupId(), serverId, nodeOpts, rpcServer, true);
    //初始化node节点
    this.node = this.raftGroupService.start(false);
    RouteTable.getInstance().updateConfiguration(this.raftGroupService.getGroupId(), nodeOpts.getInitialConf());
    if (this.node != null) {
        final RawKVStore rawKVStore = this.storeEngine.getRawKVStore();
        final Executor readIndexExecutor = this.storeEngine.getReadIndexExecutor();
        //RaftRawKVStore 是 RheaKV 基于 Raft 复制状态机 KVStoreStateMachine 的 RawKVStore 接口 KV 存储实现
        //RheaKV 的 Raft 入口,从这里开始 Raft 流程
        this.raftRawKVStore = new RaftRawKVStore(this.node, rawKVStore, readIndexExecutor);
        //拦截请求做指标度量
        this.metricsRawKVStore = new MetricsRawKVStore(this.region.getId(), this.raftRawKVStore);
        // metrics config
        if (this.regionMetricsReporter == null && metricsReportPeriod > 0) {
            final MetricRegistry metricRegistry = this.node.getNodeMetrics().getMetricRegistry();
            if (metricRegistry != null) {
                final ScheduledExecutorService scheduler = this.storeEngine.getMetricsScheduler();
                // start raft node metrics reporter
                this.regionMetricsReporter = Slf4jReporter.forRegistry(metricRegistry) //
                    .prefixedWith("region_" + this.region.getId()) //
                    .withLoggingLevel(Slf4jReporter.LoggingLevel.INFO) //
                    .outputTo(LOG) //
                    .scheduleOn(scheduler) //
                    .shutdownExecutorOnStop(scheduler != null) //
                    .build();
                this.regionMetricsReporter.start(metricsReportPeriod, TimeUnit.SECONDS);
            }
        }
        this.started = true;
        LOG.info("[RegionEngine] start successfully: {}.", this);
    }
    return this.started;
}

いくつかの例について話しましたおなじみの話をするときに最初に私を見つけることができ、ここに来ます。あなたはケースに慣れていない場合、あなたは私の最初の記事を読むことを望むことができる:1。SOFAJRaftソースコード解析を-開始SOFAJRaftたときにどうしますか?
;ここでインスタンス化された状態機械は、KVStoreStateMachineの一例である
LogUri、RaftMetaUri、SnapshotUri割り当ての動きを閉じ、storeEngineレーンrpcServerを取得し、
バック初期化ノードを介しraftGroupServiceを起動し、
次raftRawKVStoreこの例では、インスタンス化されRheaKVラフトは、入口ここから筏を流し、全てのRheaKVデータは、それによって処理されています。

概要

RheaKVの初期化は、コンテンツの多くについても、この1つはコンポーネントは、ストアを初期化する必要があり、地域の関係のようなもので、起動時にRheaKVを話し、すでにJRaftはどこステートマシンがように設定している場合、開始します内容も非常に豊富です。ここからは感じることができる、あなたは良いアーキテクチャは喜びである参照してください。

おすすめ

転載: www.cnblogs.com/luozhiyun/p/11768860.html