or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cluster-token-client.mdcodec-system.mdcommand-interface.mdconfiguration.mdindex.mdnetwork-transport.md

cluster-token-client.mddocs/

0

# Cluster Token Client

1

2

The cluster token client provides the main interface for requesting flow control tokens from Sentinel cluster servers. It supports regular flow control, parameterized flow control, and connection lifecycle management.

3

4

## Capabilities

5

6

### DefaultClusterTokenClient

7

8

Main implementation of the cluster token client that handles server connections, configuration changes, and token requests.

9

10

```java { .api }

11

/**

12

* Default implementation of ClusterTokenClient for distributed flow control

13

*/

14

public class DefaultClusterTokenClient implements ClusterTokenClient {

15

/**

16

* Create a new cluster token client with automatic server change monitoring

17

*/

18

public DefaultClusterTokenClient();

19

20

/**

21

* Start the token client connection to the cluster server

22

* @throws Exception if connection setup fails

23

*/

24

public void start() throws Exception;

25

26

/**

27

* Stop the token client and close connections

28

* @throws Exception if shutdown fails

29

*/

30

public void stop() throws Exception;

31

32

/**

33

* Get the current state of the token client

34

* @return client state constant (CLIENT_STATUS_OFF, CLIENT_STATUS_PENDING, CLIENT_STATUS_STARTED)

35

*/

36

public int getState();

37

38

/**

39

* Get descriptor of the currently connected token server

40

* @return server descriptor with host and port, or null if not connected

41

*/

42

public TokenServerDescriptor currentServer();

43

}

44

```

45

46

**Usage Examples:**

47

48

```java

49

import com.alibaba.csp.sentinel.cluster.client.DefaultClusterTokenClient;

50

import com.alibaba.csp.sentinel.cluster.client.config.ClusterClientConfigManager;

51

import com.alibaba.csp.sentinel.cluster.client.config.ClusterClientAssignConfig;

52

53

// Configure server assignment

54

ClusterClientAssignConfig assignConfig = new ClusterClientAssignConfig("cluster-server", 8719);

55

ClusterClientConfigManager.applyNewAssignConfig(assignConfig);

56

57

// Create and start client

58

DefaultClusterTokenClient client = new DefaultClusterTokenClient();

59

try {

60

client.start();

61

62

// Check connection status

63

if (client.getState() == ClientConstants.CLIENT_STATUS_STARTED) {

64

System.out.println("Connected to: " + client.currentServer());

65

}

66

} finally {

67

client.stop();

68

}

69

```

70

71

### Flow Control Token Requests

72

73

Request tokens for basic flow control rules without additional parameters.

74

75

```java { .api }

76

/**

77

* Request tokens from the cluster server for flow control

78

* @param flowId the unique flow rule ID

79

* @param acquireCount number of tokens to acquire (must be > 0)

80

* @param prioritized whether this request should be prioritized

81

* @return result containing status and remaining token information

82

*/

83

public TokenResult requestToken(Long flowId, int acquireCount, boolean prioritized);

84

```

85

86

**Usage Examples:**

87

88

```java

89

// Request single token for a flow rule

90

TokenResult result = client.requestToken(12345L, 1, false);

91

92

switch (result.getStatus()) {

93

case TokenResultStatus.OK:

94

System.out.println("Token acquired, remaining: " + result.getRemaining());

95

break;

96

case TokenResultStatus.BLOCKED:

97

System.out.println("Request blocked, wait: " + result.getWaitInMs() + "ms");

98

break;

99

case TokenResultStatus.NO_RULE_EXISTS:

100

System.out.println("No flow rule exists for ID: 12345");

101

break;

102

case TokenResultStatus.BAD_REQUEST:

103

System.out.println("Invalid request parameters");

104

break;

105

case TokenResultStatus.FAIL:

106

System.out.println("Request failed due to client error");

107

break;

108

}

109

110

// Request multiple tokens with priority

111

TokenResult priorityResult = client.requestToken(67890L, 5, true);

112

```

113

114

### Parameterized Flow Control

115

116

Request tokens for parameterized flow control rules that consider specific parameter values.

117

118

```java { .api }

119

/**

120

* Request tokens for parameterized flow control with specific parameters

121

* @param flowId the unique flow rule ID

122

* @param acquireCount number of tokens to acquire (must be > 0)

123

* @param params collection of parameters for the flow rule (must not be null or empty)

124

* @return result containing status and remaining token information

125

*/

126

public TokenResult requestParamToken(Long flowId, int acquireCount, Collection<Object> params);

127

```

128

129

**Usage Examples:**

130

131

```java

132

import java.util.Arrays;

133

import java.util.List;

134

135

// Request tokens for parameterized flow control

136

List<Object> params = Arrays.asList("user123", "premium");

137

TokenResult result = client.requestParamToken(54321L, 1, params);

138

139

if (result.getStatus() == TokenResultStatus.OK) {

140

System.out.println("Parameterized token acquired");

141

} else if (result.getStatus() == TokenResultStatus.BLOCKED) {

142

System.out.println("Blocked for these parameters: " + params);

143

}

144

145

// Multiple parameters example

146

List<Object> complexParams = Arrays.asList(

147

"serviceA",

148

"endpoint/users",

149

"GET",

150

Map.of("region", "us-east", "tier", "premium")

151

);

152

TokenResult complexResult = client.requestParamToken(98765L, 3, complexParams);

153

```

154

155

### Concurrent Token Management

156

157

Methods for concurrent token management are declared in the interface but not implemented in this version.

158

159

```java { .api }

160

/**

161

* Request concurrent tokens from cluster server

162

* Note: This method is not implemented and returns null

163

* @param clientAddress the address of the requesting client

164

* @param ruleId the unique rule ID

165

* @param acquireCount number of tokens to acquire

166

* @return null (not implemented)

167

*/

168

public TokenResult requestConcurrentToken(String clientAddress, Long ruleId, int acquireCount);

169

170

/**

171

* Release concurrent tokens

172

* Note: This method is not implemented and does nothing

173

* @param tokenId the unique token ID to release

174

*/

175

public void releaseConcurrentToken(Long tokenId);

176

```

177

178

## Error Handling

179

180

The token client handles various error conditions and returns appropriate status codes:

181

182

- **TokenResultStatus.OK**: Token successfully acquired

183

- **TokenResultStatus.BLOCKED**: Request blocked by flow control rules

184

- **TokenResultStatus.NO_RULE_EXISTS**: No matching flow rule found on server

185

- **TokenResultStatus.TOO_MANY_REQUEST**: Server overloaded with requests

186

- **TokenResultStatus.BAD_REQUEST**: Invalid request parameters (null flowId, count <= 0, etc.)

187

- **TokenResultStatus.FAIL**: Client-side error (no connection, network failure, etc.)

188

189

**Exception Handling:**

190

191

```java

192

try {

193

TokenResult result = client.requestToken(ruleId, count, false);

194

// Handle result

195

} catch (Exception ex) {

196

// Network or client errors result in FAIL status, not exceptions

197

// Exceptions typically indicate configuration or initialization issues

198

System.err.println("Client error: " + ex.getMessage());

199

}

200

```

201

202

## Thread Safety

203

204

The `DefaultClusterTokenClient` is thread-safe and can be safely used from multiple threads simultaneously. However, it's recommended to:

205

206

1. Create one client instance per application

207

2. Start the client once during application initialization

208

3. Reuse the client instance across multiple threads

209

4. Stop the client during application shutdown

210

211

## Connection Management

212

213

The client automatically handles:

214

215

- **Reconnection**: Automatic reconnection with exponential backoff on connection failures

216

- **Server Changes**: Dynamic server assignment through configuration updates

217

- **Connection State**: Proper connection lifecycle management

218

- **Resource Cleanup**: Automatic cleanup of network resources on shutdown