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

connection-management.mddocs/

Connection Management

This document covers Jedis connection management including connection pools, factories, configuration, and lifecycle management for optimal performance and resource utilization.

Core Connection Classes

Connection

Low-level Redis connection handling network I/O and protocol communication.

public class Connection implements Closeable {
    /**
     * Creates connection to Redis server
     * @param host Redis server host
     * @param port Redis server port
     */
    public Connection(String host, int port);
    
    /**
     * Creates connection with timeout configuration
     * @param host Redis server host
     * @param port Redis server port
     * @param connectionTimeout Connection timeout in milliseconds
     * @param soTimeout Socket timeout in milliseconds
     */
    public Connection(String host, int port, int connectionTimeout, int soTimeout);
    
    /**
     * Creates connection with client configuration
     * @param hostAndPort Server endpoint
     * @param clientConfig Client configuration
     */
    public Connection(HostAndPort hostAndPort, JedisClientConfig clientConfig);
    
    /**
     * Establishes connection to Redis server
     */
    public void connect();
    
    /**
     * Disconnects from Redis server
     */
    public void disconnect();
    
    /**
     * Checks if connection is established
     * @return true if connected
     */
    public boolean isConnected();
    
    /**
     * Gets connection timeout
     * @return Connection timeout in milliseconds
     */
    public int getConnectionTimeout();
    
    /**
     * Gets socket timeout
     * @return Socket timeout in milliseconds
     */
    public int getSoTimeout();
    
    /**
     * Sends Redis command over connection
     * @param cmd Protocol command
     * @param args Command arguments
     */
    public void sendCommand(ProtocolCommand cmd, String... args);
    
    /**
     * Sends Redis command with byte arguments
     * @param cmd Protocol command
     * @param args Binary command arguments
     */
    public void sendCommand(ProtocolCommand cmd, byte[]... args);
    
    /**
     * Gets Redis server host
     * @return Server host
     */
    public String getHost();
    
    /**
     * Gets Redis server port
     * @return Server port
     */
    public int getPort();
    
    /**
     * Closes the connection
     */
    public void close();
}

HostAndPort

Represents a Redis server endpoint with host and port information.

public class HostAndPort implements Serializable {
    /**
     * Creates host and port endpoint
     * @param host Server hostname or IP address
     * @param port Server port number
     */
    public HostAndPort(String host, int port);
    
    /**
     * Gets the host
     * @return Server host
     */
    public String getHost();
    
    /**
     * Gets the port
     * @return Server port
     */
    public int getPort();
    
    /**
     * Parses host:port string into HostAndPort
     * @param hostAndPortStr String in format "host:port"
     * @return HostAndPort instance
     */
    public static HostAndPort parseString(String hostAndPortStr);
    
    /**
     * Converts multiple host:port strings to HostAndPort set
     * @param hostAndPortStrings Array of "host:port" strings
     * @return Set of HostAndPort instances
     */
    public static Set<HostAndPort> parseStrings(String... hostAndPortStrings);
    
    @Override
    public boolean equals(Object obj);
    
    @Override
    public int hashCode();
    
    @Override
    public String toString();
}

Connection Pooling

JedisPoolConfig

Configuration for Jedis connection pools, extending Apache Commons Pool configuration.

public class JedisPoolConfig extends GenericObjectPoolConfig<Jedis> {
    /**
     * Creates pool configuration with default settings
     */
    public JedisPoolConfig();
    
    /**
     * Sets maximum number of connections in pool
     * @param maxTotal Maximum total connections
     */
    public void setMaxTotal(int maxTotal);
    
    /**
     * Gets maximum number of connections in pool
     * @return Maximum total connections
     */
    public int getMaxTotal();
    
    /**
     * Sets maximum number of idle connections
     * @param maxIdle Maximum idle connections
     */
    public void setMaxIdle(int maxIdle);
    
    /**
     * Gets maximum number of idle connections
     * @return Maximum idle connections
     */
    public int getMaxIdle();
    
    /**
     * Sets minimum number of idle connections
     * @param minIdle Minimum idle connections
     */
    public void setMinIdle(int minIdle);
    
    /**
     * Gets minimum number of idle connections
     * @return Minimum idle connections
     */
    public int getMinIdle();
    
    /**
     * Sets whether to test connections when borrowing from pool
     * @param testOnBorrow true to test connections
     */
    public void setTestOnBorrow(boolean testOnBorrow);
    
    /**
     * Gets whether connections are tested when borrowed
     * @return true if testing on borrow
     */
    public boolean getTestOnBorrow();
    
    /**
     * Sets whether to test connections when returning to pool
     * @param testOnReturn true to test connections
     */
    public void setTestOnReturn(boolean testOnReturn);
    
    /**
     * Sets whether to test idle connections
     * @param testWhileIdle true to test idle connections
     */
    public void setTestWhileIdle(boolean testWhileIdle);
    
    /**
     * Sets time between eviction runs
     * @param timeBetweenEvictionRunsMillis Time in milliseconds
     */
    public void setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis);
    
    /**
     * Sets minimum idle time before eviction
     * @param minEvictableIdleTimeMillis Time in milliseconds
     */
    public void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis);
    
    /**
     * Sets maximum wait time for connection
     * @param maxWaitMillis Maximum wait time in milliseconds
     */
    public void setMaxWaitMillis(long maxWaitMillis);
    
    /**
     * Sets number of tests per eviction run
     * @param numTestsPerEvictionRun Number of tests
     */
    public void setNumTestsPerEvictionRun(int numTestsPerEvictionRun);
    
    /**
     * Sets action when pool is exhausted
     * @param whenExhaustedAction Action to take (WHEN_EXHAUSTED_BLOCK, WHEN_EXHAUSTED_FAIL, WHEN_EXHAUSTED_GROW)
     */
    public void setBlockWhenExhausted(boolean blockWhenExhausted);
    
    /**
     * Sets LIFO behavior for pool
     * @param lifo true for LIFO, false for FIFO
     */
    public void setLifo(boolean lifo);
}

Usage Example

JedisPoolConfig poolConfig = new JedisPoolConfig();

// Connection limits
poolConfig.setMaxTotal(128);              // Maximum connections
poolConfig.setMaxIdle(128);               // Maximum idle connections
poolConfig.setMinIdle(16);                // Minimum idle connections

// Connection testing
poolConfig.setTestOnBorrow(true);         // Test before lending
poolConfig.setTestOnReturn(false);        // Don't test on return
poolConfig.setTestWhileIdle(true);        // Test idle connections

// Eviction policy
poolConfig.setMinEvictableIdleTimeMillis(60000);  // 1 minute
poolConfig.setTimeBetweenEvictionRunsMillis(30000); // 30 seconds
poolConfig.setNumTestsPerEvictionRun(3);

// Blocking behavior
poolConfig.setBlockWhenExhausted(true);   // Block when no connections available
poolConfig.setMaxWaitMillis(10000);       // Wait up to 10 seconds

JedisPool pool = new JedisPool(poolConfig, "localhost", 6379);

ConnectionPool

Generic connection pool for managing Connection instances.

public class ConnectionPool implements Closeable {
    /**
     * Creates connection pool
     * @param poolConfig Pool configuration
     * @param factory Connection factory
     */
    public ConnectionPool(GenericObjectPoolConfig<Connection> poolConfig,
                         ConnectionFactory factory);
    
    /**
     * Gets connection from pool
     * @return Connection instance
     */
    public Connection getResource();
    
    /**
     * Returns connection to pool
     * @param connection Connection to return
     */
    public void returnResource(Connection connection);
    
    /**
     * Returns broken connection to pool
     * @param connection Broken connection
     */
    public void returnBrokenResource(Connection connection);
    
    /**
     * Gets number of active connections
     * @return Active connection count
     */
    public int getNumActive();
    
    /**
     * Gets number of idle connections
     * @return Idle connection count
     */
    public int getNumIdle();
    
    /**
     * Closes the pool
     */
    public void close();
    
    /**
     * Destroys the pool
     */
    public void destroy();
}

ConnectionFactory

Factory for creating Connection instances with specific configuration.

public class ConnectionFactory implements PooledObjectFactory<Connection> {
    /**
     * Creates connection factory
     * @param hostAndPort Server endpoint
     * @param clientConfig Client configuration
     */
    public ConnectionFactory(HostAndPort hostAndPort, JedisClientConfig clientConfig);
    
    /**
     * Creates a new connection instance
     * @return PooledObject wrapping connection
     */
    @Override
    public PooledObject<Connection> makeObject();
    
    /**
     * Destroys a connection
     * @param pooledConnection Connection to destroy
     */
    @Override
    public void destroyObject(PooledObject<Connection> pooledConnection);
    
    /**
     * Validates a connection
     * @param pooledConnection Connection to validate
     * @return true if connection is valid
     */
    @Override
    public boolean validateObject(PooledObject<Connection> pooledConnection);
    
    /**
     * Activates a connection when borrowed from pool
     * @param pooledConnection Connection to activate
     */
    @Override
    public void activateObject(PooledObject<Connection> pooledConnection);
    
    /**
     * Passivates connection when returned to pool
     * @param pooledConnection Connection to passivate
     */
    @Override
    public void passivateObject(PooledObject<Connection> pooledConnection);
}

Connection Providers

ConnectionProvider

Interface for providing Redis connections in different deployment scenarios.

public interface ConnectionProvider extends Closeable {
    /**
     * Gets connection for executing commands
     * @return Connection instance
     */
    Connection getConnection();
    
    /**
     * Gets connection for specified command arguments
     * @param commandArguments Command arguments that may determine routing
     * @return Connection instance  
     */
    Connection getConnection(CommandArguments commandArguments);
    
    /**
     * Closes the connection provider
     */
    void close();
}

PooledConnectionProvider

Connection provider using connection pooling for single Redis instances.

public class PooledConnectionProvider implements ConnectionProvider {
    /**
     * Creates pooled connection provider
     * @param pool Connection pool
     */
    public PooledConnectionProvider(Pool<Connection> pool);
    
    /**
     * Creates pooled connection provider from Jedis pool
     * @param jedisPool Jedis pool
     */
    public PooledConnectionProvider(JedisPool jedisPool);
    
    /**
     * Creates pooled connection provider with configuration
     * @param hostAndPort Server endpoint
     * @param clientConfig Client configuration
     * @param poolConfig Pool configuration
     */
    public PooledConnectionProvider(HostAndPort hostAndPort, 
                                  JedisClientConfig clientConfig,
                                  GenericObjectPoolConfig<Connection> poolConfig);
    
    @Override
    public Connection getConnection();
    
    @Override
    public Connection getConnection(CommandArguments commandArguments);
    
    /**
     * Gets the underlying connection pool
     * @return Connection pool
     */
    public Pool<Connection> getPool();
    
    @Override
    public void close();
}

ClusterConnectionProvider

Connection provider for Redis Cluster deployments.

public class ClusterConnectionProvider implements ConnectionProvider {
    /**
     * Creates cluster connection provider
     * @param clusterNodes Set of cluster nodes
     * @param clientConfig Client configuration
     */
    public ClusterConnectionProvider(Set<HostAndPort> clusterNodes, 
                                   JedisClientConfig clientConfig);
    
    /**
     * Creates cluster connection provider with pool configuration
     * @param clusterNodes Set of cluster nodes
     * @param clientConfig Client configuration
     * @param poolConfig Pool configuration
     */
    public ClusterConnectionProvider(Set<HostAndPort> clusterNodes,
                                   JedisClientConfig clientConfig,
                                   GenericObjectPoolConfig<Connection> poolConfig);
    
    @Override
    public Connection getConnection();
    
    @Override
    public Connection getConnection(CommandArguments commandArguments);
    
    /**
     * Gets connection for specific slot
     * @param slot Cluster slot number
     * @return Connection to node handling the slot
     */
    public Connection getConnectionFromSlot(int slot);
    
    /**
     * Gets connection for specific node
     * @param node Cluster node endpoint
     * @return Connection to the specified node
     */
    public Connection getConnectionFromNode(HostAndPort node);
    
    /**
     * Refreshes cluster topology
     */
    public void renewSlotCache();
    
    /**
     * Gets all cluster nodes
     * @return Map of node endpoints to connection pools
     */
    public Map<String, Pool<Connection>> getNodes();
    
    @Override
    public void close();
}

SentineledConnectionProvider

Connection provider with Redis Sentinel integration for high availability.

public class SentineledConnectionProvider implements ConnectionProvider {
    /**
     * Creates sentineled connection provider
     * @param masterName Redis master name in Sentinel configuration
     * @param sentinels Set of Sentinel endpoints
     * @param clientConfig Client configuration
     * @param poolConfig Pool configuration
     */
    public SentineledConnectionProvider(String masterName, 
                                      Set<HostAndPort> sentinels,
                                      JedisClientConfig clientConfig,
                                      GenericObjectPoolConfig<Connection> poolConfig);
    
    @Override
    public Connection getConnection();
    
    @Override 
    public Connection getConnection(CommandArguments commandArguments);
    
    /**
     * Gets current master endpoint
     * @return Current master host and port
     */
    public HostAndPort getCurrentMaster();
    
    /**
     * Gets connection pool for current master
     * @return Master connection pool
     */
    public Pool<Connection> getMasterPool();
    
    @Override
    public void close();
}

Connection Configuration

JedisClientConfig

Comprehensive client configuration interface.

public interface JedisClientConfig {
    /**
     * Gets connection timeout
     * @return Connection timeout in milliseconds
     */
    int getConnectionTimeoutMillis();
    
    /**
     * Gets socket timeout for Redis operations
     * @return Socket timeout in milliseconds
     */
    int getSoTimeoutMillis();
    
    /**
     * Gets blocking socket timeout for blocking operations
     * @return Blocking socket timeout in milliseconds
     */
    int getBlockingSocketTimeoutMillis();
    
    /**
     * Gets Redis username for authentication
     * @return Username or null if not set
     */
    String getUser();
    
    /**
     * Gets Redis password for authentication
     * @return Password or null if not set
     */
    String getPassword();
    
    /**
     * Gets Redis database number
     * @return Database index (0-15)
     */
    int getDatabase();
    
    /**
     * Gets client name for Redis CLIENT SETNAME
     * @return Client name or null if not set
     */
    String getClientName();
    
    /**
     * Checks if SSL/TLS is enabled
     * @return true if SSL enabled
     */
    boolean isSsl();
    
    /**
     * Gets SSL socket factory
     * @return SSL socket factory or null if not set
     */
    SSLSocketFactory getSslSocketFactory();
    
    /**
     * Gets SSL parameters
     * @return SSL parameters or null if not set
     */
    SSLParameters getSslParameters();
    
    /**
     * Gets hostname verifier for SSL
     * @return Hostname verifier or null if not set
     */
    HostnameVerifier getHostnameVerifier();
    
    /**
     * Gets Redis protocol version
     * @return Redis protocol (RESP2 or RESP3)
     */
    RedisProtocol getRedisProtocol();
    
    /**
     * Gets credentials provider
     * @return Credentials provider or null if not set
     */
    RedisCredentialsProvider getCredentialsProvider();
    
    /**
     * Gets socket factory
     * @return Socket factory or null for default
     */
    JedisSocketFactory getSocketFactory();
}

DefaultJedisClientConfig

Default implementation of JedisClientConfig with builder pattern.

public class DefaultJedisClientConfig implements JedisClientConfig {
    /**
     * Creates builder for client configuration
     * @return Configuration builder
     */
    public static Builder builder() {
        return new Builder();
    }
    
    /**
     * Creates default configuration
     * @return Default client configuration
     */
    public static JedisClientConfig create() {
        return new DefaultJedisClientConfig();
    }
    
    public static class Builder {
        /**
         * Sets connection timeout
         * @param connectionTimeoutMillis Timeout in milliseconds
         * @return Builder instance
         */
        public Builder connectionTimeoutMillis(int connectionTimeoutMillis);
        
        /**
         * Sets socket timeout
         * @param socketTimeoutMillis Timeout in milliseconds
         * @return Builder instance
         */
        public Builder socketTimeoutMillis(int socketTimeoutMillis);
        
        /**
         * Sets blocking socket timeout
         * @param blockingSocketTimeoutMillis Timeout in milliseconds
         * @return Builder instance
         */
        public Builder blockingSocketTimeoutMillis(int blockingSocketTimeoutMillis);
        
        /**
         * Sets Redis username
         * @param user Username
         * @return Builder instance
         */
        public Builder user(String user);
        
        /**
         * Sets Redis password
         * @param password Password
         * @return Builder instance
         */
        public Builder password(String password);
        
        /**
         * Sets Redis database
         * @param database Database index
         * @return Builder instance
         */
        public Builder database(int database);
        
        /**
         * Sets client name
         * @param clientName Client identifier
         * @return Builder instance
         */
        public Builder clientName(String clientName);
        
        /**
         * Enables SSL/TLS
         * @param ssl true to enable SSL
         * @return Builder instance
         */
        public Builder ssl(boolean ssl);
        
        /**
         * Sets SSL socket factory
         * @param sslSocketFactory SSL socket factory
         * @return Builder instance
         */
        public Builder sslSocketFactory(SSLSocketFactory sslSocketFactory);
        
        /**
         * Sets SSL parameters
         * @param sslParameters SSL parameters
         * @return Builder instance
         */
        public Builder sslParameters(SSLParameters sslParameters);
        
        /**
         * Sets hostname verifier
         * @param hostnameVerifier Hostname verifier
         * @return Builder instance
         */
        public Builder hostnameVerifier(HostnameVerifier hostnameVerifier);
        
        /**
         * Sets Redis protocol version
         * @param protocol Protocol version
         * @return Builder instance
         */
        public Builder protocol(RedisProtocol protocol);
        
        /**
         * Sets credentials provider
         * @param credentialsProvider Credentials provider
         * @return Builder instance
         */
        public Builder credentialsProvider(RedisCredentialsProvider credentialsProvider);
        
        /**
         * Sets socket factory
         * @param socketFactory Socket factory
         * @return Builder instance
         */
        public Builder socketFactory(JedisSocketFactory socketFactory);
        
        /**
         * Builds the configuration
         * @return Client configuration instance
         */
        public DefaultJedisClientConfig build();
    }
}

Socket Factories

JedisSocketFactory

Interface for custom socket creation.

public interface JedisSocketFactory {
    /**
     * Creates socket for Redis connection
     * @param host Redis server host
     * @param port Redis server port
     * @return Socket instance
     * @throws IOException If socket creation fails
     */
    Socket createSocket(String host, int port) throws IOException;
    
    /**
     * Updates socket after creation
     * @param socket Socket to update
     * @throws IOException If socket update fails
     */
    void updateSocket(Socket socket) throws IOException;
}

DefaultJedisSocketFactory

Default socket factory implementation.

public class DefaultJedisSocketFactory implements JedisSocketFactory {
    /**
     * Creates default socket factory
     */
    public DefaultJedisSocketFactory();
    
    /**
     * Creates socket factory with SSL configuration
     * @param sslSocketFactory SSL socket factory
     * @param sslParameters SSL parameters
     * @param hostnameVerifier Hostname verifier
     */
    public DefaultJedisSocketFactory(SSLSocketFactory sslSocketFactory,
                                   SSLParameters sslParameters,
                                   HostnameVerifier hostnameVerifier);
    
    @Override
    public Socket createSocket(String host, int port) throws IOException;
    
    @Override
    public void updateSocket(Socket socket) throws IOException;
}

Connection Utilities

HostAndPortMapper

Interface for mapping server endpoints, useful for network address translation.

public interface HostAndPortMapper {
    /**
     * Maps a host and port to different endpoint
     * @param hostAndPort Original endpoint
     * @return Mapped endpoint
     */
    HostAndPort getHostAndPort(HostAndPort hostAndPort);
}

Usage Examples

Basic Pool Configuration

// Create optimized pool configuration
JedisPoolConfig poolConfig = new JedisPoolConfig();

// Size configuration
poolConfig.setMaxTotal(200);          // Max connections
poolConfig.setMaxIdle(50);            // Max idle connections  
poolConfig.setMinIdle(10);            // Min idle connections

// Health checking
poolConfig.setTestOnBorrow(true);     // Test before use
poolConfig.setTestWhileIdle(true);    // Test idle connections
poolConfig.setMinEvictableIdleTimeMillis(60000);  // Evict after 1 minute idle

// Timeout configuration
poolConfig.setMaxWaitMillis(5000);    // Wait up to 5 seconds for connection

// Client configuration
JedisClientConfig clientConfig = DefaultJedisClientConfig.builder()
    .connectionTimeoutMillis(2000)
    .socketTimeoutMillis(2000)
    .user("myuser")
    .password("mypassword")
    .database(0)
    .clientName("myapp")
    .build();

// Create pool
JedisPool pool = new JedisPool(poolConfig, "localhost", 6379, clientConfig);

SSL Configuration

// SSL configuration
JedisClientConfig sslConfig = DefaultJedisClientConfig.builder()
    .ssl(true)
    .sslSocketFactory(createTrustedSslSocketFactory())
    .hostnameVerifier((hostname, session) -> hostname.equals("redis.example.com"))
    .build();

JedisPool sslPool = new JedisPool(poolConfig, "redis.example.com", 6380, sslConfig);

Connection Provider Pattern

// Single instance with pooling
ConnectionProvider provider = new PooledConnectionProvider(
    new HostAndPort("localhost", 6379),
    clientConfig,
    poolConfig
);

// Use with UnifiedJedis
UnifiedJedis jedis = new UnifiedJedis(provider);

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

ConnectionProvider clusterProvider = new ClusterConnectionProvider(
    clusterNodes, clientConfig, poolConfig
);

UnifiedJedis clusterJedis = new UnifiedJedis(clusterProvider);

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