CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-com-alibaba-csp--sentinel-cluster-client-default

Default cluster client implementation for Sentinel cluster flow control

Pending
Overview
Eval results
Files

cluster-token-client.mddocs/

Cluster Token Client

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.

Capabilities

DefaultClusterTokenClient

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

/**
 * Default implementation of ClusterTokenClient for distributed flow control
 */
public class DefaultClusterTokenClient implements ClusterTokenClient {
    /**
     * Create a new cluster token client with automatic server change monitoring
     */
    public DefaultClusterTokenClient();
    
    /**
     * Start the token client connection to the cluster server
     * @throws Exception if connection setup fails
     */
    public void start() throws Exception;
    
    /**
     * Stop the token client and close connections
     * @throws Exception if shutdown fails
     */
    public void stop() throws Exception;
    
    /**
     * Get the current state of the token client
     * @return client state constant (CLIENT_STATUS_OFF, CLIENT_STATUS_PENDING, CLIENT_STATUS_STARTED)
     */
    public int getState();
    
    /**
     * Get descriptor of the currently connected token server
     * @return server descriptor with host and port, or null if not connected
     */
    public TokenServerDescriptor currentServer();
}

Usage Examples:

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

// Configure server assignment
ClusterClientAssignConfig assignConfig = new ClusterClientAssignConfig("cluster-server", 8719);
ClusterClientConfigManager.applyNewAssignConfig(assignConfig);

// Create and start client
DefaultClusterTokenClient client = new DefaultClusterTokenClient();
try {
    client.start();
    
    // Check connection status
    if (client.getState() == ClientConstants.CLIENT_STATUS_STARTED) {
        System.out.println("Connected to: " + client.currentServer());
    }
} finally {
    client.stop();
}

Flow Control Token Requests

Request tokens for basic flow control rules without additional parameters.

/**
 * Request tokens from the cluster server for flow control
 * @param flowId the unique flow rule ID
 * @param acquireCount number of tokens to acquire (must be > 0)
 * @param prioritized whether this request should be prioritized
 * @return result containing status and remaining token information
 */
public TokenResult requestToken(Long flowId, int acquireCount, boolean prioritized);

Usage Examples:

// Request single token for a flow rule
TokenResult result = client.requestToken(12345L, 1, false);

switch (result.getStatus()) {
    case TokenResultStatus.OK:
        System.out.println("Token acquired, remaining: " + result.getRemaining());
        break;
    case TokenResultStatus.BLOCKED:
        System.out.println("Request blocked, wait: " + result.getWaitInMs() + "ms");
        break;
    case TokenResultStatus.NO_RULE_EXISTS:
        System.out.println("No flow rule exists for ID: 12345");
        break;
    case TokenResultStatus.BAD_REQUEST:
        System.out.println("Invalid request parameters");
        break;
    case TokenResultStatus.FAIL:
        System.out.println("Request failed due to client error");
        break;
}

// Request multiple tokens with priority
TokenResult priorityResult = client.requestToken(67890L, 5, true);

Parameterized Flow Control

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

/**
 * Request tokens for parameterized flow control with specific parameters
 * @param flowId the unique flow rule ID
 * @param acquireCount number of tokens to acquire (must be > 0)
 * @param params collection of parameters for the flow rule (must not be null or empty)
 * @return result containing status and remaining token information
 */
public TokenResult requestParamToken(Long flowId, int acquireCount, Collection<Object> params);

Usage Examples:

import java.util.Arrays;
import java.util.List;

// Request tokens for parameterized flow control
List<Object> params = Arrays.asList("user123", "premium");
TokenResult result = client.requestParamToken(54321L, 1, params);

if (result.getStatus() == TokenResultStatus.OK) {
    System.out.println("Parameterized token acquired");
} else if (result.getStatus() == TokenResultStatus.BLOCKED) {
    System.out.println("Blocked for these parameters: " + params);
}

// Multiple parameters example
List<Object> complexParams = Arrays.asList(
    "serviceA", 
    "endpoint/users", 
    "GET",
    Map.of("region", "us-east", "tier", "premium")
);
TokenResult complexResult = client.requestParamToken(98765L, 3, complexParams);

Concurrent Token Management

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

/**
 * Request concurrent tokens from cluster server
 * Note: This method is not implemented and returns null
 * @param clientAddress the address of the requesting client
 * @param ruleId the unique rule ID
 * @param acquireCount number of tokens to acquire
 * @return null (not implemented)
 */
public TokenResult requestConcurrentToken(String clientAddress, Long ruleId, int acquireCount);

/**
 * Release concurrent tokens  
 * Note: This method is not implemented and does nothing
 * @param tokenId the unique token ID to release
 */
public void releaseConcurrentToken(Long tokenId);

Error Handling

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

  • TokenResultStatus.OK: Token successfully acquired
  • TokenResultStatus.BLOCKED: Request blocked by flow control rules
  • TokenResultStatus.NO_RULE_EXISTS: No matching flow rule found on server
  • TokenResultStatus.TOO_MANY_REQUEST: Server overloaded with requests
  • TokenResultStatus.BAD_REQUEST: Invalid request parameters (null flowId, count <= 0, etc.)
  • TokenResultStatus.FAIL: Client-side error (no connection, network failure, etc.)

Exception Handling:

try {
    TokenResult result = client.requestToken(ruleId, count, false);
    // Handle result
} catch (Exception ex) {
    // Network or client errors result in FAIL status, not exceptions
    // Exceptions typically indicate configuration or initialization issues
    System.err.println("Client error: " + ex.getMessage());
}

Thread Safety

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

  1. Create one client instance per application
  2. Start the client once during application initialization
  3. Reuse the client instance across multiple threads
  4. Stop the client during application shutdown

Connection Management

The client automatically handles:

  • Reconnection: Automatic reconnection with exponential backoff on connection failures
  • Server Changes: Dynamic server assignment through configuration updates
  • Connection State: Proper connection lifecycle management
  • Resource Cleanup: Automatic cleanup of network resources on shutdown

Install with Tessl CLI

npx tessl i tessl/maven-com-alibaba-csp--sentinel-cluster-client-default

docs

cluster-token-client.md

codec-system.md

command-interface.md

configuration.md

index.md

network-transport.md

tile.json