動的に構成されたクラスター フロー制御を実装する Sentinel の方法
導入
06-クラスター埋め込み-8081
クラスター フロー制御を使用する理由は何ですか?
単一マシンのフロー制御と比較して、各マシンに単一マシンの電流制限しきい値を設定します。理想的な状況では、クラスター全体の電流制限しきい値はマシン数 ✖️単一マシンのしきい値になります。ただし、実際の状況では、各マシンへの流量が不均一になる可能性があり、そのため、一部のマシンは総量に達しない場合に流量制限を開始する可能性があります。したがって、単一マシンの次元のみで制限される場合、全体のトラフィックを正確に制限することは不可能になります。クラスタのフロー制御は、クラスタ全体の総コール数を正確に制御でき、単一マシンの電流制限と組み合わせることで、フロー制御の効果をより発揮できます。
単一マシンのトラフィックの偏りの問題と、クラスタ全体の QPS をどのように設定するかという問題に基づいて、クラスタの電流制限モードを作成する必要がありますが、このとき、総数を具体的にカウントするサーバーを見つけることができると当然考えました。すべてのインスタンスはこのサーバーと通信して、このサーバーを呼び出すことができるかどうかを判断します。これは、クラスター フロー制御の最も基本的な方法です。
原理
クラスター電流制限の原理は非常にシンプルです。スタンドアロン電流制限と同様に、qps などの統計が必要です。違いは、スタンドアロン バージョンは各インスタンスで統計を実行するのに対し、クラスター バージョンには統計専用のインスタンスがあることです。 。
この特別なトークン サーバーは、統計データ用に Sentinel と呼ばれます。Sentinel トークン クライアントとしての他のインスタンスは、トークン サーバーからトークンを要求します。トークンを取得できた場合は、現在の QPS が合計しきい値に達していないことを意味し、そうでない場合は、次の図に示すように、クラスターの合計しきい値に達したため、現在のインスタンスをブロックする必要があります。
スタンドアロン フロー制御と比較して、クラスター フロー制御には 2 つのアイデンティティがあります。
- トークン クライアント: クラスター フロー制御クライアント。トークン サーバーと通信してトークンを要求するために使用されます。クラスター電流制限サーバーは、結果をクライアントに返し、電流フローを制限するかどうかを決定します。
- トークン サーバー: クラスター フロー制御サーバーは、トークン クライアントからのリクエストを処理し、構成されたクラスター ルールに基づいてトークンを発行するかどうか (トークンの通過を許可するかどうか) を決定します。
スタンドアロン フロー制御には ID が 1 つだけあり、各センチネルはトークン サーバーです。
クラスタ電流制限のトークン サーバーは単一ポイントであることに注意してください。トークン サーバーが停止すると、クラスタ電流制限は単一マシン電流制限モードに縮退します。
Sentinel クラスターのフロー制御は、電流制限ルールとホットスポット ルールの 2 種類のルールをサポートし、2 つの形式のしきい値計算方法をサポートします。
- クラスター全体モード: つまり、クラスター全体のリソースの全体的な qps がこのしきい値を超えないように制限します。
- 単一マシン償却モード: 単一マシン償却モードで設定されたしきい値は、単一マシンが耐えられる制限と同じです。トークン サーバーは、接続数に基づいて合計しきい値を計算します (たとえば、クライアントが 3 つある場合)独立モードでトークン サーバーに接続している場合、構成された単一マシンの償却しきい値は 10、計算されたクラスターの合計数は 30)、制限は計算された合計しきい値に基づきます。この方法は、現在の接続数に基づいて合計しきい値をリアルタイムで計算します。これは、マシンが頻繁に変更される環境に非常に適しています。
導入方法
トークン サーバーには 2 つの展開方法があります。
1 つは独立したデプロイメントで、次の図に示すように、トークン サーバー サービスを個別に開始してトークン クライアント リクエストを処理します。
個別にデプロイされたトークン サーバー サービスが失敗すると、他のトークン クライアントはローカル フロー制御モード、つまりフロー制御のスタンドアロン バージョンに低下します。そのため、このクラスター フロー制限方法では、トークンの高可用性を確保する必要があります。サーバ。
1 つは組み込みのデプロイメントで、同じプロセス内の組み込みのトークン サーバーとサービスとして開始されます。このモードでは、クラスター内の各インスタンスはピアであり、次の図に示すように、トークン サーバーとクライアントがいつでも変更できます。
組み込みデプロイメント モードでは、トークン サーバー サービスがハングアップした場合、別のトークン クライアントをトークン サーバーにアップグレードできます。もちろん、現在のトークン サーバーを使用したくない場合は、別のトークン クライアントを選択して引き継ぐこともできます。この責任を負い、現在のトークン サーバーをトークン クライアントに切り替えます。Sentinel は、トークン サーバーとトークン クライアントを切り替えるための API を提供します。
http://192.168.175.1:8721/setClusterMode?mode=1
このうちモードは0
クライアント、1
サーバー、-1
シャットダウンを表します。
埋め込みモード
依存関係をインポートする
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-cluster-server-default</artifactId>
<version>2.0.0-alpha</version>
</dependency>
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-cluster-client-default</artifactId>
<version>2.0.0-alpha</version>
</dependency>
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
<version>2.0.0-alpha</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10</version>
</dependency>
アプリケーション.yml
server:
port: 8081
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
username: root
password: gj001212
type: com.alibaba.druid.pool.DruidDataSource
cloud:
nacos:
discovery:
server-addr: 192.168.146.1:8839
sentinel:
transport:
dashboard: localhost:7777
port: 8719
eager: true
web-context-unify: false
application:
name: cloudalibaba-sentinel-clusterServer
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #开启sql日志
VM オプション構成を変更し、異なるポートで 3 つのインスタンスを起動します。
-Dserver.port=9091 -Dproject.name=cloudalibaba-sentinel-clusterServer -Dcsp.sentinel.log.use.pid=true
-Dserver.port=9092 -Dproject.name=cloudalibaba-sentinel-clusterServer -Dcsp.sentinel.log.use.pid=true
-Dserver.port=9093 -Dproject.name=cloudalibaba-sentinel-clusterServer -Dcsp.sentinel.log.use.pid=true
コンソール構成
Sentinel コンソールにログインしてアクセスを取得すると、Sentinel 上のクラスター フロー制御が表示されます。
クリックしてトークンサーバーを追加します。
[外部リンク画像の転送に失敗しました。ソース サイトにはリーチ防止メカニズムがある可能性があります。画像を保存して直接アップロードすることをお勧めします (img-MNDP51sm-1683617959600) (C:\Users\86151\AppData\Roaming\Typora\) typora-user-images\ image-20230509103407298.png)]
Sentinel は nacos を組み合わせてクラスター電流制限を実装します
ClusterGroupEntity 解析クラス
package com.liang.springcloud.alibaba.entity;
import java.util.Set;
/**
* @author Eric Zhao
* @since 1.4.1
*/
public class ClusterGroupEntity {
private String machineId;
private String ip;
private Integer port;
private Set<String> clientSet;
public String getMachineId() {
return machineId;
}
public ClusterGroupEntity setMachineId(String machineId) {
this.machineId = machineId;
return this;
}
public String getIp() {
return ip;
}
public ClusterGroupEntity setIp(String ip) {
this.ip = ip;
return this;
}
public Integer getPort() {
return port;
}
public ClusterGroupEntity setPort(Integer port) {
this.port = port;
return this;
}
public Set<String> getClientSet() {
return clientSet;
}
public ClusterGroupEntity setClientSet(Set<String> clientSet) {
this.clientSet = clientSet;
return this;
}
@Override
public String toString() {
return "ClusterGroupEntity{" +
"machineId='" + machineId + '\'' +
", ip='" + ip + '\'' +
", port=" + port +
", clientSet=" + clientSet +
'}';
}
}
定数
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.liang.springcloud.alibaba;
/**
* @author Eric Zhao
*/
public final class Constants {
public static final String FLOW_POSTFIX = "-flow-rules";
public static final String PARAM_FLOW_POSTFIX = "-param-rules";
public static final String SERVER_NAMESPACE_SET_POSTFIX = "-cs-namespace-set";
public static final String CLIENT_CONFIG_POSTFIX = "-cluster-client-config";
public static final String CLUSTER_MAP_POSTFIX = "-cluster-map";
private Constants() {
}
}
リソースフォルダーにMETA-INF/serviceを作成し、com.alibaba.csp.sentinel.init.InitFuncというファイルを作成し、そのファイル内にInitFuncインターフェイスを実装するクラスのフルパスを記述します。 :
com.liang.springcloud.alibaba.init.ClusterInitFunc
ClusterInitFunc
package com.liang.springcloud.alibaba.init;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import com.alibaba.csp.sentinel.cluster.ClusterStateManager;
import com.alibaba.csp.sentinel.cluster.client.config.ClusterClientAssignConfig;
import com.alibaba.csp.sentinel.cluster.client.config.ClusterClientConfig;
import com.alibaba.csp.sentinel.cluster.client.config.ClusterClientConfigManager;
import com.alibaba.csp.sentinel.cluster.flow.rule.ClusterFlowRuleManager;
import com.alibaba.csp.sentinel.cluster.flow.rule.ClusterParamFlowRuleManager;
import com.alibaba.csp.sentinel.cluster.server.config.ClusterServerConfigManager;
import com.alibaba.csp.sentinel.cluster.server.config.ServerTransportConfig;
import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.datasource.nacos.NacosDataSource;
import com.liang.springcloud.alibaba.Constants;
import com.liang.springcloud.alibaba.entity.ClusterGroupEntity;
import com.alibaba.csp.sentinel.init.InitFunc;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRuleManager;
import com.alibaba.csp.sentinel.transport.config.TransportConfig;
import com.alibaba.csp.sentinel.util.AppNameUtil;
import com.alibaba.csp.sentinel.util.HostNameUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
/**
* @author Eric Zhao
*/
public class ClusterInitFunc implements InitFunc {
private static final String APP_NAME = AppNameUtil.getAppName();
private final String remoteAddress = "localhost:8839";
private final String groupId = "SENTINEL_GROUP";
private final String flowDataId = APP_NAME + Constants.FLOW_POSTFIX;
private final String paramDataId = APP_NAME + Constants.PARAM_FLOW_POSTFIX;
private final String configDataId = APP_NAME + "-cluster-client-config";
private final String clusterMapDataId = APP_NAME + Constants.CLUSTER_MAP_POSTFIX;
@Override
public void init() throws Exception {
// Register client dynamic rule data source.
initDynamicRuleProperty();
// Register token client related data source.
// Token client common config:
initClientConfigProperty();
// Token client assign config (e.g. target token server) retrieved from assign map:
initClientServerAssignProperty();
// Register token server related data source.
// Register dynamic rule data source supplier for token server:
registerClusterRuleSupplier();
// Token server transport config extracted from assign map:
initServerTransportConfigProperty();
// Init cluster state property for extracting mode from cluster map data source.
initStateProperty();
}
private void initDynamicRuleProperty() {
ReadableDataSource<String, List<FlowRule>> ruleSource = new NacosDataSource<>(remoteAddress, groupId,
flowDataId, source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {
}));
FlowRuleManager.register2Property(ruleSource.getProperty());
ReadableDataSource<String, List<ParamFlowRule>> paramRuleSource = new NacosDataSource<>(remoteAddress, groupId,
paramDataId, source -> JSON.parseObject(source, new TypeReference<List<ParamFlowRule>>() {
}));
ParamFlowRuleManager.register2Property(paramRuleSource.getProperty());
}
private void initClientConfigProperty() {
ReadableDataSource<String, ClusterClientConfig> clientConfigDs = new NacosDataSource<>(remoteAddress, groupId,
configDataId, source -> JSON.parseObject(source, new TypeReference<ClusterClientConfig>() {
}));
ClusterClientConfigManager.registerClientConfigProperty(clientConfigDs.getProperty());
}
private void initServerTransportConfigProperty() {
ReadableDataSource<String, ServerTransportConfig> serverTransportDs = new NacosDataSource<>(remoteAddress, groupId,
clusterMapDataId, source -> {
List<ClusterGroupEntity> groupList = JSON.parseObject(source, new TypeReference<List<ClusterGroupEntity>>() {
});
return Optional.ofNullable(groupList)
.flatMap(this::extractServerTransportConfig)
.orElse(null);
});
ClusterServerConfigManager.registerServerTransportProperty(serverTransportDs.getProperty());
}
private void registerClusterRuleSupplier() {
// Register cluster flow rule property supplier which creates data source by namespace.
// Flow rule dataId format: ${namespace}-flow-rules
ClusterFlowRuleManager.setPropertySupplier(namespace -> {
ReadableDataSource<String, List<FlowRule>> ds = new NacosDataSource<>(remoteAddress, groupId,
namespace + Constants.FLOW_POSTFIX, source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {
}));
return ds.getProperty();
});
// Register cluster parameter flow rule property supplier which creates data source by namespace.
ClusterParamFlowRuleManager.setPropertySupplier(namespace -> {
ReadableDataSource<String, List<ParamFlowRule>> ds = new NacosDataSource<>(remoteAddress, groupId,
namespace + Constants.PARAM_FLOW_POSTFIX, source -> JSON.parseObject(source, new TypeReference<List<ParamFlowRule>>() {
}));
return ds.getProperty();
});
}
private void initClientServerAssignProperty() {
// Cluster map format:
// [{"clientSet":["112.12.88.66@8729","112.12.88.67@8727"],"ip":"112.12.88.68","machineId":"112.12.88.68@8728","port":11111}]
// machineId: <ip@commandPort>, commandPort for port exposed to Sentinel dashboard (transport module)
ReadableDataSource<String, ClusterClientAssignConfig> clientAssignDs = new NacosDataSource<>(remoteAddress, groupId,
clusterMapDataId, source -> {
List<ClusterGroupEntity> groupList = JSON.parseObject(source, new TypeReference<List<ClusterGroupEntity>>() {
});
return Optional.ofNullable(groupList)
.flatMap(this::extractClientAssignment)
.orElse(null);
});
ClusterClientConfigManager.registerServerAssignProperty(clientAssignDs.getProperty());
}
private void initStateProperty() {
// Cluster map format:
// [{"clientSet":["112.12.88.66@8729","112.12.88.67@8727"],"ip":"112.12.88.68","machineId":"112.12.88.68@8728","port":11111}]
// machineId: <ip@commandPort>, commandPort for port exposed to Sentinel dashboard (transport module)
ReadableDataSource<String, Integer> clusterModeDs = new NacosDataSource<>(remoteAddress, groupId,
clusterMapDataId, source -> {
List<ClusterGroupEntity> groupList = JSON.parseObject(source, new TypeReference<List<ClusterGroupEntity>>() {
});
return Optional.ofNullable(groupList)
.map(this::extractMode)
.orElse(ClusterStateManager.CLUSTER_NOT_STARTED);
});
ClusterStateManager.registerProperty(clusterModeDs.getProperty());
}
private int extractMode(List<ClusterGroupEntity> groupList) {
// If any server group machineId matches current, then it's token server.
if (groupList.stream().anyMatch(this::machineEqual)) {
return ClusterStateManager.CLUSTER_SERVER;
}
// If current machine belongs to any of the token server group, then it's token client.
// Otherwise it's unassigned, should be set to NOT_STARTED.
boolean canBeClient = groupList.stream()
.flatMap(e -> e.getClientSet().stream())
.filter(Objects::nonNull)
.anyMatch(e -> e.equals(getCurrentMachineId()));
return canBeClient ? ClusterStateManager.CLUSTER_CLIENT : ClusterStateManager.CLUSTER_NOT_STARTED;
}
private Optional<ServerTransportConfig> extractServerTransportConfig(List<ClusterGroupEntity> groupList) {
return groupList.stream()
.filter(this::machineEqual)
.findAny()
.map(e -> new ServerTransportConfig().setPort(e.getPort()).setIdleSeconds(600));
}
private Optional<ClusterClientAssignConfig> extractClientAssignment(List<ClusterGroupEntity> groupList) {
if (groupList.stream().anyMatch(this::machineEqual)) {
return Optional.empty();
}
// Build client assign config from the client set of target server group.
for (ClusterGroupEntity group : groupList) {
if (group.getClientSet().contains(getCurrentMachineId())) {
String ip = group.getIp();
Integer port = group.getPort();
return Optional.of(new ClusterClientAssignConfig(ip, port));
}
}
return Optional.empty();
}
private boolean machineEqual(/*@Valid*/ ClusterGroupEntity group) {
return getCurrentMachineId().equals(group.getMachineId());
}
private String getCurrentMachineId() {
// Note: this may not work well for container-based env.
return HostNameUtil.getIp() + SEPARATOR + TransportConfig.getRuntimePort();
}
private static final String SEPARATOR = "@";
}