or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

api-definitions.mdcommand-handlers.mdconstants-configuration.mdgateway-flow-rules.mdindex.mdparameter-processing.mdsentinel-integration.md

sentinel-integration.mddocs/

0

# Sentinel Integration

1

2

The Sentinel Integration system provides components for embedding gateway flow control into Sentinel's processing chain using the slot-based architecture. This enables seamless integration with Sentinel's core flow control, circuit breaking, and monitoring capabilities.

3

4

## Capabilities

5

6

### GatewayFlowSlot

7

8

Core Sentinel slot for gateway parameter flow checking, integrated into Sentinel's processing chain with high priority.

9

10

```java { .api }

11

/**

12

* Sentinel slot for gateway parameter flow checking

13

* Integrated with Sentinel's slot chain at order -4000 (high priority)

14

*/

15

@Spi(order = -4000)

16

class GatewayFlowSlot extends AbstractLinkedProcessorSlot<DefaultNode> {

17

/**

18

* Main entry point for flow control checking

19

* @param context Sentinel context containing request information

20

* @param resource Resource wrapper identifying the protected resource

21

* @param node Default node for metrics collection

22

* @param count Request count (usually 1)

23

* @param prioritized Whether this is a prioritized request

24

* @param args Additional arguments including parsed parameters

25

* @throws Throwable When flow control blocks the request

26

*/

27

void entry(Context context, ResourceWrapper resource, DefaultNode node, int count,

28

boolean prioritized, Object... args) throws Throwable;

29

30

/**

31

* Exit point called after request processing

32

* @param context Sentinel context

33

* @param resourceWrapper Resource wrapper

34

* @param count Request count

35

* @param args Additional arguments

36

*/

37

void exit(Context context, ResourceWrapper resourceWrapper, int count, Object... args);

38

}

39

```

40

41

**Usage Examples:**

42

43

The `GatewayFlowSlot` is automatically integrated into Sentinel's slot chain through the SPI mechanism. It doesn't require direct instantiation but is configured through the slot chain builder:

44

45

```java

46

// GatewayFlowSlot is automatically loaded and positioned in the slot chain

47

// when Sentinel initializes due to the @Spi annotation

48

49

// The slot processes gateway-specific flow control rules and converts them

50

// to standard Sentinel parameter flow rules for processing

51

52

// Example of how it's used internally:

53

public class GatewayEntryExample {

54

public void processRequest(String resource, HttpServletRequest request) {

55

Entry entry = null;

56

try {

57

// Parse parameters for gateway flow control

58

Object[] params = extractParameters(request);

59

60

// Create Sentinel entry - GatewayFlowSlot will be invoked automatically

61

entry = SphU.entry(resource, EntryType.IN, 1, params);

62

63

// Process the request

64

handleRequest(request);

65

66

} catch (BlockException e) {

67

// Handle flow control blocking

68

handleBlockedException(e);

69

} finally {

70

if (entry != null) {

71

entry.exit();

72

}

73

}

74

}

75

}

76

```

77

78

### GatewaySlotChainBuilder (Deprecated)

79

80

Legacy slot chain builder for gateway-specific slot chain construction.

81

82

```java { .api }

83

/**

84

* Legacy slot chain builder (deprecated since 1.7.2)

85

* Use Sentinel's default slot chain builder instead

86

*/

87

@Deprecated

88

class GatewaySlotChainBuilder extends DefaultSlotChainBuilder {

89

// Implementation details omitted as this class is deprecated

90

}

91

```

92

93

**Migration Note:**

94

95

The `GatewaySlotChainBuilder` is deprecated since version 1.7.2. Instead of using a custom slot chain builder, the `GatewayFlowSlot` is now automatically integrated into the default slot chain through the SPI mechanism.

96

97

```java

98

// OLD (deprecated) approach:

99

// SlotChainProvider.setSlotChainBuilder(new GatewaySlotChainBuilder());

100

101

// NEW approach:

102

// No explicit configuration needed - GatewayFlowSlot is automatically loaded

103

// through @Spi annotation when Sentinel initializes

104

```

105

106

## Integration with Sentinel's Processing Chain

107

108

The gateway integration follows Sentinel's standard slot-based processing model:

109

110

### Slot Chain Order

111

112

The `GatewayFlowSlot` is positioned with order `-4000`, meaning it executes early in the slot chain:

113

114

1. **GatewayFlowSlot (-4000)** - Gateway-specific parameter flow control

115

2. **NodeSelectorSlot (-10000)** - Resource node selection

116

3. **ClusterBuilderSlot (-9000)** - Cluster node building

117

4. **LogSlot (-8000)** - Request logging

118

5. **StatisticSlot (-7000)** - Metrics collection

119

6. **ParamFlowSlot (-6000)** - Parameter flow control

120

7. **SystemSlot (-5000)** - System protection

121

8. **AuthoritySlot (-4000)** - Authority control

122

9. **FlowSlot (-2000)** - Standard flow control

123

10. **DegradeSlot (-1000)** - Circuit breaker

124

125

### Context and Resource Handling

126

127

The gateway integration uses Sentinel's context system for resource identification:

128

129

```java

130

// Context names follow gateway-specific patterns

131

public static final String GATEWAY_CONTEXT_DEFAULT = "sentinel_gateway_context_default";

132

public static final String GATEWAY_CONTEXT_PREFIX = "sentinel_gateway_context$$";

133

public static final String GATEWAY_CONTEXT_ROUTE_PREFIX = "sentinel_gateway_context$$route$$";

134

```

135

136

**Usage Examples:**

137

138

```java

139

// Gateway contexts are typically created automatically, but can be customized:

140

141

// Default gateway context

142

ContextUtil.enter(SentinelGatewayConstants.GATEWAY_CONTEXT_DEFAULT);

143

144

// Route-specific context

145

String routeContext = SentinelGatewayConstants.GATEWAY_CONTEXT_ROUTE_PREFIX + "user-service";

146

ContextUtil.enter(routeContext);

147

148

// Custom API context

149

String apiContext = SentinelGatewayConstants.GATEWAY_CONTEXT_PREFIX + "user-api";

150

ContextUtil.enter(apiContext);

151

```

152

153

## Parameter Processing Integration

154

155

The gateway integration automatically handles parameter extraction and processing:

156

157

### Parameter Extraction Flow

158

159

1. **Rule Matching**: Gateway flow rules are matched against the current resource

160

2. **Parameter Extraction**: Parameters are extracted based on rule configuration

161

3. **Rule Conversion**: Gateway rules are converted to standard Sentinel parameter rules

162

4. **Flow Control**: Standard Sentinel parameter flow control is applied

163

164

```java

165

// Example of parameter processing integration

166

public class GatewayParameterIntegration {

167

private final GatewayParamParser<HttpServletRequest> paramParser;

168

169

public void processGatewayRequest(String resource, HttpServletRequest request) {

170

// Extract parameters based on gateway rules

171

Object[] params = paramParser.parseParameterFor(resource, request, rule -> true);

172

173

Entry entry = null;

174

try {

175

// Pass parameters to Sentinel - GatewayFlowSlot will process them

176

entry = SphU.entry(resource, EntryType.IN, 1, params);

177

178

// Process request

179

processRequest(request);

180

181

} catch (ParamFlowException e) {

182

// Handle parameter-based flow control

183

handleParameterFlowControl(e);

184

} catch (FlowException e) {

185

// Handle general flow control

186

handleFlowControl(e);

187

} finally {

188

if (entry != null) {

189

entry.exit();

190

}

191

}

192

}

193

}

194

```

195

196

## Rule Conversion and Management

197

198

Gateway rules are automatically converted to standard Sentinel rules for processing:

199

200

### Conversion Process

201

202

1. **Gateway Rules**: Defined using `GatewayFlowRule` with gateway-specific parameters

203

2. **Parameter Rules**: Converted to `ParamFlowRule` for parameter-based control

204

3. **Flow Rules**: Simple rules converted to standard `FlowRule` objects

205

4. **Metrics Storage**: Parameter metrics stored using Sentinel's parameter metric system

206

207

```java

208

// Example of rule conversion (handled automatically)

209

public class RuleConversionExample {

210

public void demonstrateConversion() {

211

// Gateway rule with parameter control

212

GatewayFlowRule gatewayRule = new GatewayFlowRule("user-api")

213

.setGrade(RuleConstant.FLOW_GRADE_QPS)

214

.setCount(100)

215

.setParamItem(new GatewayParamFlowItem()

216

.setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_CLIENT_IP));

217

218

// Load gateway rule - conversion happens automatically

219

GatewayRuleManager.loadRules(Set.of(gatewayRule));

220

221

// Retrieve converted parameter rules (for monitoring/debugging)

222

List<ParamFlowRule> convertedRules = GatewayRuleManager.getConvertedParamRules("user-api");

223

224

// The converted rules are automatically used by Sentinel's parameter flow control

225

}

226

}

227

```

228

229

## Error Handling and Exceptions

230

231

Gateway integration handles various Sentinel exceptions:

232

233

### Exception Types

234

235

```java

236

// Parameter-based flow control exceptions

237

catch (ParamFlowException e) {

238

// Triggered when parameter flow rules are violated

239

// e.g., too many requests from same IP, user, etc.

240

return buildRateLimitResponse("Parameter limit exceeded", 429);

241

}

242

243

// General flow control exceptions

244

catch (FlowException e) {

245

// Triggered when general flow rules are violated

246

// e.g., QPS limit exceeded

247

return buildRateLimitResponse("Rate limit exceeded", 429);

248

}

249

250

// System protection exceptions

251

catch (SystemBlockException e) {

252

// Triggered when system protection rules are violated

253

return buildRateLimitResponse("System overloaded", 503);

254

}

255

256

// Authority control exceptions

257

catch (AuthorityException e) {

258

// Triggered when authority rules are violated

259

return buildRateLimitResponse("Access denied", 403);

260

}

261

262

// Circuit breaker exceptions

263

catch (DegradeException e) {

264

// Triggered when circuit breaker is open

265

return buildRateLimitResponse("Service unavailable", 503);

266

}

267

```

268

269

## Monitoring and Metrics

270

271

Gateway integration supports comprehensive monitoring through Sentinel's metrics system:

272

273

### Metrics Collection

274

275

```java

276

// Metrics are automatically collected for gateway resources

277

public class GatewayMonitoring {

278

public void displayMetrics(String resource) {

279

// Get parameter metrics for gateway resource

280

ParameterMetric paramMetric = ParameterMetricStorage.getParamMetricForResource(resource);

281

if (paramMetric != null) {

282

// Access parameter-specific metrics

283

// e.g., QPS per IP, per user, etc.

284

}

285

286

// Get standard resource metrics

287

ClusterNode clusterNode = ClusterBuilderSlot.getClusterNode(resource);

288

if (clusterNode != null) {

289

long totalQps = clusterNode.totalQps();

290

long passQps = clusterNode.passQps();

291

long blockQps = clusterNode.blockQps();

292

293

System.out.printf("Resource: %s, Total: %d, Pass: %d, Block: %d%n",

294

resource, totalQps, passQps, blockQps);

295

}

296

}

297

}

298

```

299

300

## Best Practices

301

302

1. **Use appropriate context names** for different gateway resources

303

2. **Monitor converted parameter rules** to understand actual flow control behavior

304

3. **Handle all Sentinel exception types** appropriately in gateway responses

305

4. **Configure slot chain properly** - avoid using deprecated `GatewaySlotChainBuilder`

306

5. **Monitor parameter metrics** for insights into parameter-based flow patterns

307

6. **Use consistent resource naming** across gateway rules and API definitions

308

7. **Test exception handling** to ensure proper rate limit responses

309

8. **Consider performance impact** of parameter extraction in high-traffic scenarios

310

9. **Use resource hierarchies** effectively for better monitoring and control granularity

311

10. **Integrate with Sentinel dashboard** for real-time monitoring and rule management