CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-redis-clients--jedis

Jedis is a blazingly small and sane Redis java client.

Overview
Eval results
Files

clustering.mddocs/

Clustering and High Availability

This document covers Redis Cluster support, high availability through Redis Sentinel, multi-cluster failover scenarios, and advanced deployment patterns for fault tolerance.

Redis Cluster

ClusterCommands

Interface for Redis Cluster management and administration commands.

public interface ClusterCommands {
    /**
     * Get cluster nodes information
     * @return Cluster nodes configuration and status
     */
    String clusterNodes();
    
    /**
     * Get cluster information and statistics
     * @return Cluster info including state, slots, and metrics
     */
    String clusterInfo();
    
    /**
     * Get cluster slots mapping
     * @return List of slot ranges and responsible nodes
     */
    List<Object> clusterSlots();
    
    /**
     * Get keys in specific cluster slot
     * @param slot Cluster slot number (0-16383)
     * @param count Maximum number of keys to return
     * @return List of keys in the slot
     */
    List<String> clusterGetKeysInSlot(int slot, int count);
    
    /**
     * Count keys in cluster slot
     * @param slot Cluster slot number
     * @return Number of keys in the slot
     */
    Long clusterCountKeysInSlot(int slot);
    
    /**
     * Get slot for key
     * @param key Redis key
     * @return Cluster slot number for the key
     */
    Long clusterKeySlot(String key);
    
    /**
     * Initiate cluster failover
     * @return Status code reply
     */
    String clusterFailover();
    
    /**
     * Initiate cluster failover with options
     * @param failoverOption Failover type (FORCE or TAKEOVER)
     * @return Status code reply
     */
    String clusterFailover(ClusterFailoverOption failoverOption);
    
    /**
     * Forget cluster node
     * @param nodeId Node ID to forget
     * @return Status code reply
     */
    String clusterForget(String nodeId);
    
    /**
     * Meet new cluster node
     * @param ip Node IP address
     * @param port Node port
     * @return Status code reply
     */
    String clusterMeet(String ip, int port);
    
    /**
     * Reset cluster node
     * @param resetType Reset type (HARD or SOFT)
     * @return Status code reply
     */
    String clusterReset(ClusterResetType resetType);
    
    /**
     * Save cluster configuration
     * @return Status code reply
     */
    String clusterSaveConfig();
    
    /**
     * Set cluster slot state
     * @param slot Slot number
     * @param nodeId Node ID to assign slot
     * @return Status code reply
     */
    String clusterSetSlotNode(int slot, String nodeId);
    
    /**
     * Set slot as migrating
     * @param slot Slot number
     * @param nodeId Target node ID
     * @return Status code reply
     */
    String clusterSetSlotMigrating(int slot, String nodeId);
    
    /**
     * Set slot as importing
     * @param slot Slot number
     * @param nodeId Source node ID
     * @return Status code reply
     */
    String clusterSetSlotImporting(int slot, String nodeId);
    
    /**
     * Clear slot state
     * @param slot Slot number
     * @return Status code reply
     */
    String clusterSetSlotStable(int slot);
    
    /**
     * Replicate from master node
     * @param nodeId Master node ID
     * @return Status code reply
     */
    String clusterReplicate(String nodeId);
    
    /**
     * Get cluster node ID
     * @return Current node ID
     */
    String clusterMyId();
}

JedisCluster Usage

Redis Cluster client with automatic key routing and failover.

public class JedisCluster extends UnifiedJedis {
    /**
     * Creates cluster client with single node discovery
     * @param jedisClusterNode Any cluster node endpoint
     */
    public JedisCluster(HostAndPort jedisClusterNode);
    
    /**
     * Creates cluster client with multiple discovery nodes
     * @param clusterNodes Set of cluster node endpoints for discovery
     */
    public JedisCluster(Set<HostAndPort> clusterNodes);
    
    /**
     * Creates cluster client with configuration
     * @param clusterNodes Cluster discovery nodes
     * @param config Client configuration
     */
    public JedisCluster(Set<HostAndPort> clusterNodes, JedisClientConfig config);
    
    /**
     * Creates cluster client with pool configuration
     * @param clusterNodes Cluster discovery nodes
     * @param config Client configuration
     * @param poolConfig Pool configuration for node connections
     */
    public JedisCluster(Set<HostAndPort> clusterNodes, JedisClientConfig config,
                       JedisPoolConfig poolConfig);
    
    /**
     * Creates cluster client with timeout settings
     * @param clusterNodes Cluster discovery nodes
     * @param connectionTimeout Connection timeout in milliseconds
     * @param soTimeout Socket timeout in milliseconds
     */
    public JedisCluster(Set<HostAndPort> clusterNodes, int connectionTimeout, int soTimeout);
    
    /**
     * Creates cluster client with retry settings
     * @param clusterNodes Cluster discovery nodes
     * @param connectionTimeout Connection timeout
     * @param soTimeout Socket timeout
     * @param maxAttempts Maximum retry attempts for commands
     */
    public JedisCluster(Set<HostAndPort> clusterNodes, int connectionTimeout, 
                       int soTimeout, int maxAttempts);
    
    /**
     * Gets connection pool for specific cluster node
     * @param node Cluster node endpoint
     * @return Connection pool for the node
     */
    public JedisPool getConnectionPoolFromSlot(int slot);
    
    /**
     * Gets all cluster node pools
     * @return Map of node endpoints to connection pools
     */
    public Map<String, JedisPool> getClusterNodes();
    
    /**
     * Refreshes cluster topology information
     */
    public void refreshClusterSlots();
    
    /**
     * Gets cluster slot cache
     * @return Current slot-to-node mapping
     */
    public Map<Integer, JedisPool> getSlotPoolMap();
    
    /**
     * Closes cluster client and all node connections
     */
    public void close();
}

Usage Example

Set<HostAndPort> clusterNodes = new HashSet<>();
clusterNodes.add(new HostAndPort("redis-node1.example.com", 7000));
clusterNodes.add(new HostAndPort("redis-node2.example.com", 7001));
clusterNodes.add(new HostAndPort("redis-node3.example.com", 7002));

JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(20);
poolConfig.setMaxIdle(10);
poolConfig.setTestOnBorrow(true);

JedisClientConfig clientConfig = DefaultJedisClientConfig.builder()
    .connectionTimeoutMillis(2000)
    .socketTimeoutMillis(2000)
    .password("cluster-password")
    .build();

JedisCluster cluster = new JedisCluster(clusterNodes, clientConfig, poolConfig);

try {
    // Use like regular Redis client - clustering is transparent
    cluster.set("user:1000", "John Doe");
    cluster.hset("user:1000:profile", "email", "john@example.com");
    
    // Keys are automatically routed to correct cluster nodes
    String user = cluster.get("user:1000");
    Map<String, String> profile = cluster.hgetAll("user:1000:profile");
    
    // Cluster-specific operations
    String clusterInfo = cluster.clusterInfo();
    String nodes = cluster.clusterNodes();
    
    // Get slot information
    Long slot = cluster.clusterKeySlot("user:1000");
    List<String> keysInSlot = cluster.clusterGetKeysInSlot(slot.intValue(), 10);
    
} finally {
    cluster.close();
}

Cluster Pipeline

Pipeline operations for Redis Cluster with automatic node routing.

public class ClusterPipeline implements AutoCloseable {
    /**
     * Creates cluster pipeline
     * @param clusterNodes Cluster node endpoints
     * @param clientConfig Client configuration
     */
    public ClusterPipeline(Set<HostAndPort> clusterNodes, JedisClientConfig clientConfig);
    
    /**
     * Queues SET command
     * @param key Redis key
     * @param value String value
     * @return Response object for the command
     */
    public Response<String> set(String key, String value);
    
    /**
     * Queues GET command
     * @param key Redis key
     * @return Response object for the command
     */
    public Response<String> get(String key);
    
    /**
     * Queues hash operations
     * @param key Hash key
     * @param field Hash field
     * @param value Field value
     * @return Response object for the command
     */
    public Response<Long> hset(String key, String field, String value);
    
    /**
     * Synchronizes all queued commands
     * Sends commands to appropriate cluster nodes and retrieves responses
     */
    public void sync();
    
    /**
     * Synchronizes and returns all responses
     * @return List of command responses
     */
    public List<Object> syncAndReturnAll();
    
    /**
     * Closes the cluster pipeline
     */
    public void close();
}

Usage Example

Set<HostAndPort> clusterNodes = Set.of(
    new HostAndPort("node1", 7000),
    new HostAndPort("node2", 7001),
    new HostAndPort("node3", 7002)
);

try (ClusterPipeline pipeline = new ClusterPipeline(clusterNodes, clientConfig)) {
    // Queue multiple commands - they'll be routed to appropriate nodes
    Response<String> r1 = pipeline.set("key1", "value1");
    Response<String> r2 = pipeline.set("key2", "value2");
    Response<Long> r3 = pipeline.hset("hash1", "field1", "value1");
    
    // Execute all commands
    pipeline.sync();
    
    // Get results
    String result1 = r1.get();  // "OK"
    String result2 = r2.get();  // "OK"
    Long result3 = r3.get();    // 1
}

Redis Sentinel (High Availability)

JedisSentinelPool

Connection pool with Redis Sentinel integration for automatic failover.

public class JedisSentinelPool extends Pool<Jedis> {
    /**
     * Creates sentinel pool with default configuration
     * @param masterName Master name in Sentinel configuration
     * @param sentinels Set of Sentinel endpoints ("host:port")
     */
    public JedisSentinelPool(String masterName, Set<String> sentinels);
    
    /**
     * Creates sentinel pool with pool configuration
     * @param masterName Master name in Sentinel configuration
     * @param sentinels Set of Sentinel endpoints
     * @param poolConfig Pool configuration
     */
    public JedisSentinelPool(String masterName, Set<String> sentinels, 
                           JedisPoolConfig poolConfig);
    
    /**
     * Creates sentinel pool with client configuration
     * @param masterName Master name
     * @param sentinels Sentinel endpoints
     * @param clientConfig Client configuration
     */
    public JedisSentinelPool(String masterName, Set<String> sentinels,
                           JedisClientConfig clientConfig);
    
    /**
     * Creates sentinel pool with full configuration
     * @param masterName Master name
     * @param sentinels Sentinel endpoints
     * @param poolConfig Pool configuration
     * @param clientConfig Client configuration
     */
    public JedisSentinelPool(String masterName, Set<String> sentinels,
                           JedisPoolConfig poolConfig, JedisClientConfig clientConfig);
    
    /**
     * Creates sentinel pool with sentinel authentication
     * @param masterName Master name
     * @param sentinels Sentinel endpoints
     * @param poolConfig Pool configuration
     * @param clientConfig Master client configuration  
     * @param sentinelClientConfig Sentinel client configuration
     */
    public JedisSentinelPool(String masterName, Set<String> sentinels,
                           JedisPoolConfig poolConfig, JedisClientConfig clientConfig,
                           JedisClientConfig sentinelClientConfig);
    
    /**
     * Gets current master endpoint
     * @return Current Redis master host and port
     */
    public HostAndPort getCurrentHostMaster();
    
    /**
     * Gets Jedis connection from pool
     * @return Jedis instance connected to current master
     */
    public Jedis getResource();
    
    /**
     * Destroys the sentinel pool
     */
    public void destroy();
}

SentinelCommands

Commands for interacting with Redis Sentinel.

public interface SentinelCommands {
    /**
     * Get master address by name
     * @param masterName Master name
     * @return Master host and port
     */
    List<String> sentinelGetMasterAddrByName(String masterName);
    
    /**
     * Get master information
     * @param masterName Master name
     * @return Master configuration and status
     */
    List<Map<String, String>> sentinelMasters();
    
    /**
     * Get specific master information
     * @param masterName Master name
     * @return Master details
     */
    Map<String, String> sentinelMaster(String masterName);
    
    /**
     * Get sentinel information about slaves
     * @param masterName Master name
     * @return List of slave configurations
     */
    List<Map<String, String>> sentinelSlaves(String masterName);
    
    /**
     * Get sentinel information about other sentinels
     * @param masterName Master name
     * @return List of sentinel configurations
     */
    List<Map<String, String>> sentinelSentinels(String masterName);
    
    /**
     * Force failover of master
     * @param masterName Master name
     * @return Status code reply
     */
    String sentinelFailover(String masterName);
    
    /**
     * Monitor new master
     * @param masterName Master name
     * @param ip Master IP address
     * @param port Master port
     * @param quorum Quorum for failover decisions
     * @return Status code reply
     */
    String sentinelMonitor(String masterName, String ip, int port, int quorum);
    
    /**
     * Remove master from monitoring
     * @param masterName Master name
     * @return Status code reply
     */
    String sentinelRemove(String masterName);
    
    /**
     * Set master configuration
     * @param masterName Master name
     * @param parameterName Parameter name
     * @param parameterValue Parameter value
     * @return Status code reply
     */
    String sentinelSet(String masterName, String parameterName, String parameterValue);
}

Usage Example

String masterName = "mymaster";
Set<String> sentinels = new HashSet<>();
sentinels.add("sentinel1.example.com:26379");
sentinels.add("sentinel2.example.com:26379");
sentinels.add("sentinel3.example.com:26379");

JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(20);
poolConfig.setTestOnBorrow(true);

JedisClientConfig masterConfig = DefaultJedisClientConfig.builder()
    .password("redis-password")
    .database(0)
    .build();

JedisClientConfig sentinelConfig = DefaultJedisClientConfig.builder()
    .password("sentinel-password")
    .build();

JedisSentinelPool sentinelPool = new JedisSentinelPool(
    masterName, sentinels, poolConfig, masterConfig, sentinelConfig
);

try {
    // Use pool normally - failover is automatic
    try (Jedis jedis = sentinelPool.getResource()) {
        jedis.set("key", "value");
        String value = jedis.get("key");
    }
    
    // Monitor current master
    HostAndPort currentMaster = sentinelPool.getCurrentHostMaster();
    System.out.println("Current master: " + currentMaster);
    
} finally {
    sentinelPool.destroy();
}

Multi-Cluster Failover

Multi-Cluster Configuration

Configuration for multi-cluster failover scenarios with circuit breaker patterns.

public class MultiClusterClientConfig {
    public static class Builder {
        /**
         * Sets exceptions that trigger fallback to next cluster
         * @param fallbackExceptionList List of exception classes
         * @return Builder instance
         */
        public Builder fallbackExceptionList(List<Class<? extends Exception>> fallbackExceptionList);
        
        /**
         * Sets circuit breaker sliding window size
         * @param circuitBreakerSlidingWindowSize Window size for failure tracking
         * @return Builder instance
         */
        public Builder circuitBreakerSlidingWindowSize(int circuitBreakerSlidingWindowSize);
        
        /**
         * Sets circuit breaker failure rate threshold
         * @param circuitBreakerFailureRateThreshold Failure rate (0.0-1.0) to open circuit
         * @return Builder instance
         */
        public Builder circuitBreakerFailureRateThreshold(float circuitBreakerFailureRateThreshold);
        
        /**
         * Sets minimum calls before circuit breaker evaluation
         * @param circuitBreakerMinimumNumberOfCalls Minimum calls in window
         * @return Builder instance
         */
        public Builder circuitBreakerMinimumNumberOfCalls(int circuitBreakerMinimumNumberOfCalls);
        
        /**
         * Sets circuit breaker wait duration in open state
         * @param circuitBreakerWaitDurationInOpenState Wait duration in milliseconds
         * @return Builder instance
         */
        public Builder circuitBreakerWaitDurationInOpenState(long circuitBreakerWaitDurationInOpenState);
        
        /**
         * Builds multi-cluster configuration
         * @return Configuration instance
         */
        public MultiClusterClientConfig build();
    }
    
    public List<Class<? extends Exception>> getFallbackExceptionList();
    public int getCircuitBreakerSlidingWindowSize();
    public float getCircuitBreakerFailureRateThreshold();
    public int getCircuitBreakerMinimumNumberOfCalls();
    public long getCircuitBreakerWaitDurationInOpenState();
}

Multi-Cluster Connection Provider

Connection provider supporting multiple Redis clusters with automatic failover.

public class MultiClusterPooledConnectionProvider implements ConnectionProvider {
    /**
     * Creates multi-cluster connection provider
     * @param clusters List of cluster connection providers in priority order
     * @param multiClusterClientConfig Multi-cluster configuration
     */
    public MultiClusterPooledConnectionProvider(List<ClusterConnectionProvider> clusters,
                                              MultiClusterClientConfig multiClusterClientConfig);
    
    @Override
    public Connection getConnection();
    
    @Override
    public Connection getConnection(CommandArguments commandArguments);
    
    /**
     * Gets active cluster index
     * @return Index of currently active cluster
     */
    public int getActiveMultiClusterIndex();
    
    /**
     * Gets cluster providers
     * @return List of cluster connection providers
     */
    public List<ClusterConnectionProvider> getClusterConnectionProviders();
    
    /**
     * Manually trigger failover to next cluster
     */
    public void incrementActiveMultiClusterIndex();
    
    @Override
    public void close();
}

Circuit Breaker Failover

Circuit breaker implementation for multi-cluster failover.

public class CircuitBreakerFailoverBase {
    /**
     * Creates circuit breaker failover
     * @param connectionProvider Primary connection provider
     * @param config Multi-cluster configuration
     */
    public CircuitBreakerFailoverBase(ConnectionProvider connectionProvider,
                                    MultiClusterClientConfig config);
    
    /**
     * Executes command with circuit breaker protection
     * @param commandObject Command to execute
     * @return Command result
     */
    public <T> T execute(CommandObject<T> commandObject);
    
    /**
     * Gets circuit breaker state
     * @return Current circuit breaker state (CLOSED, OPEN, HALF_OPEN)
     */
    public String getCircuitBreakerState();
    
    /**
     * Gets failure rate
     * @return Current failure rate (0.0-1.0)
     */
    public float getFailureRate();
    
    /**
     * Resets circuit breaker statistics
     */
    public void resetCircuitBreakerStats();
}

Usage Example

// Configure multiple clusters
List<ClusterConnectionProvider> clusters = Arrays.asList(
    // Primary cluster
    new ClusterConnectionProvider(
        Set.of(new HostAndPort("primary-node1", 7000),
               new HostAndPort("primary-node2", 7001)),
        primaryConfig, poolConfig
    ),
    // Fallback cluster
    new ClusterConnectionProvider(
        Set.of(new HostAndPort("fallback-node1", 7000),
               new HostAndPort("fallback-node2", 7001)),
        fallbackConfig, poolConfig
    )
);

// Configure circuit breaker
MultiClusterClientConfig multiConfig = MultiClusterClientConfig.builder()
    .fallbackExceptionList(Arrays.asList(
        JedisConnectionException.class,
        JedisClusterException.class
    ))
    .circuitBreakerFailureRateThreshold(0.5f)  // 50% failure rate
    .circuitBreakerSlidingWindowSize(100)      // 100 call window
    .circuitBreakerMinimumNumberOfCalls(10)    // Min 10 calls
    .circuitBreakerWaitDurationInOpenState(60000)  // 1 minute wait
    .build();

MultiClusterPooledConnectionProvider mcProvider = 
    new MultiClusterPooledConnectionProvider(clusters, multiConfig);

UnifiedJedis multiClusterJedis = new UnifiedJedis(mcProvider);

try {
    // Operations automatically failover if primary cluster fails
    multiClusterJedis.set("key", "value");
    String value = multiClusterJedis.get("key");
    
    // Monitor cluster state
    int activeCluster = mcProvider.getActiveMultiClusterIndex();
    System.out.println("Active cluster: " + activeCluster);
    
} finally {
    multiClusterJedis.close();
}

Sharded Deployments

JedisSharding

Client for consistent hashing across multiple Redis instances.

public class JedisSharding implements JedisCommands, AutoCloseable {
    /**
     * Creates sharding client with default hashing
     * @param shards List of Redis shard information
     */
    public JedisSharding(List<JedisShardInfo> shards);
    
    /**
     * Creates sharding client with custom hashing algorithm
     * @param shards List of Redis shard information
     * @param algo Hashing algorithm implementation
     */
    public JedisSharding(List<JedisShardInfo> shards, Hashing algo);
    
    /**
     * Creates sharding client with key tag pattern
     * @param shards List of Redis shard information  
     * @param keyTagPattern Pattern for extracting hash tags from keys
     */
    public JedisSharding(List<JedisShardInfo> shards, Pattern keyTagPattern);
    
    /**
     * Gets shard information for a key
     * @param key Redis key
     * @return Shard info for the key
     */
    public JedisShardInfo getShardInfo(String key);
    
    /**
     * Gets all shard information
     * @return Collection of all shards
     */
    public Collection<JedisShardInfo> getAllShardInfo();
    
    /**
     * Gets Jedis connection for specific key
     * @param key Redis key
     * @return Jedis instance for the shard containing the key
     */
    public Jedis getShard(String key);
    
    /**
     * Gets Jedis connection for specific shard info
     * @param shardInfo Shard information
     * @return Jedis instance for the shard
     */
    public Jedis getShard(JedisShardInfo shardInfo);
    
    /**
     * Closes all shard connections
     */
    public void close();
}

JedisShardInfo

Information about individual Redis shards in a sharded deployment.

public class JedisShardInfo {
    /**
     * Creates shard info with equal weight
     * @param host Redis host
     * @param port Redis port
     */
    public JedisShardInfo(String host, int port);
    
    /**
     * Creates shard info with custom weight
     * @param host Redis host
     * @param port Redis port
     * @param weight Shard weight for consistent hashing
     */
    public JedisShardInfo(String host, int port, int weight);
    
    /**
     * Creates shard info with name and weight
     * @param host Redis host
     * @param port Redis port  
     * @param name Shard name
     * @param weight Shard weight
     */
    public JedisShardInfo(String host, int port, String name, int weight);
    
    /**
     * Creates shard info from URI
     * @param uri Redis connection URI
     */
    public JedisShardInfo(URI uri);
    
    public String getHost();
    public int getPort();
    public String getName();
    public int getWeight();
    public int getTimeout();
    public String getPassword();
    
    /**
     * Sets connection timeout
     * @param timeout Timeout in milliseconds
     */
    public void setTimeout(int timeout);
    
    /**
     * Sets authentication password
     * @param auth Redis password
     */
    public void setPassword(String auth);
}

Usage Example

// Create shards with different weights
List<JedisShardInfo> shards = Arrays.asList(
    new JedisShardInfo("redis1.example.com", 6379, "shard1", 1),
    new JedisShardInfo("redis2.example.com", 6379, "shard2", 1), 
    new JedisShardInfo("redis3.example.com", 6379, "shard3", 2)  // Double weight
);

JedisSharding sharding = new JedisSharding(shards);

try {
    // Keys automatically distributed based on consistent hashing
    sharding.set("user:1000", "John");     // Routed to appropriate shard
    sharding.set("user:2000", "Jane");     // May go to different shard
    
    // Retrieve data - client finds correct shard automatically
    String user1 = sharding.get("user:1000");
    String user2 = sharding.get("user:2000");
    
    // Get shard information
    JedisShardInfo shardInfo = sharding.getShardInfo("user:1000");
    System.out.println("Key user:1000 on shard: " + shardInfo.getName());
    
} finally {
    sharding.close();
}

Connection Routing and Load Balancing

Broadcast and Round Robin

Configuration for operations that need to run on multiple Redis instances.

public class JedisBroadcastAndRoundRobinConfig {
    /**
     * Creates broadcast and round robin configuration
     * @param pools List of connection pools for different Redis instances
     */
    public JedisBroadcastAndRoundRobinConfig(List<Pool<Connection>> pools);
    
    /**
     * Gets connection for broadcast operation (all pools)
     * @return List of connections from all pools
     */
    public List<Connection> getBroadcastConnections();
    
    /**
     * Gets connection for round-robin operation (next pool in rotation)
     * @return Connection from next pool in round-robin
     */
    public Connection getRoundRobinConnection();
    
    /**
     * Gets all connection pools
     * @return List of connection pools
     */
    public List<Pool<Connection>> getPools();
}

This documentation covers Redis clustering, high availability, and advanced deployment patterns available in Jedis. The library provides comprehensive support for production Redis deployments with automatic failover, load balancing, and fault tolerance.

Install with Tessl CLI

npx tessl i tessl/maven-redis-clients--jedis

docs

authentication.md

client-side-caching.md

clustering.md

commands-operations.md

connection-management.md

core-clients.md

exceptions.md

index.md

modules.md

parameters.md

pubsub.md

transactions-pipelining.md

tile.json