{
  "schema_version": 2,
  "id": "develop/clients/jedis/connect",
  "title": "Connect to the server",
  "url": "https://redis.io/docs/latest/develop/clients/jedis/connect/",
  "summary": "Connect your Java application to a Redis database",
  "tags": [
    "docs",
    "develop",
    "stack",
    "oss",
    "rs",
    "rc",
    "oss",
    "kubernetes",
    "clients"
  ],
  "last_updated": "2026-10-12T14:48:04+01:00",
  "page_type": "content",
  "content_hash": "8ecfd2d1ad131aad2e36e52f1dc89e3859281ebd510c85b47d905f7a922a495b",
  "sections": [
    {
      "id": "overview",
      "title": "Overview",
      "role": "overview",
      "text": "> [!NOTE]\n> Jedis 7.2.0 introduced a new client connection API:\n>\n> | New API class | Replaces | Use case |\n> | :-- | :-- | :-- |\n> | `RedisClient` | `UnifiedJedis`, `JedisPool`, `JedisPooled` | Single connection (with connection pooling) |\n> | `RedisClusterClient` | `JedisCluster` | Redis Cluster connections |\n> | `RedisSentinelClient` | `JedisSentinelPool` | Redis Sentinel connections |\n>\n> The old client classes are now considered deprecated."
    },
    {
      "id": "basic-connection",
      "title": "Basic connection",
      "role": "content",
      "text": "The following code opens a basic connection to a local Redis server:\n\n[code example]\n\n> [!NOTE]\n> Jedis supports [connection URLs](https://redis.io/docs/latest/develop/clients/connection-urls#jedis-java) through `RedisClient.create()`.\n> A URL can set the host, port, credentials, database, and whether to use TLS,\n> so you can use one instead of passing those options separately.\n\nAfter you have connected, you can check the connection by storing and\nretrieving a simple string value:\n\n[code example]"
    },
    {
      "id": "connect-to-a-redis-cluster",
      "title": "Connect to a Redis cluster",
      "role": "content",
      "text": "To connect to a Redis cluster, use `RedisClusterClient`. \n\n[code example]"
    },
    {
      "id": "connect-to-redis-sentinel",
      "title": "Connect to Redis Sentinel",
      "role": "content",
      "text": "To connect through [Redis Sentinel](https://redis.io/docs/latest/operate/oss_and_stack/management/sentinel),\nuse `RedisSentinelClient`. Pass the name of the primary that the Sentinels monitor to\n`masterName()`, and the Sentinel addresses to `sentinels()`. The client asks the Sentinels\nfor the current primary and switches to the new one after a failover.\n\n[code example]\n\nThe Sentinels and the data nodes have separate credentials. Pass a client configuration for\nthe primary to `clientConfig()`, and one for the Sentinels to `sentinelClientConfig()`:\n\n[code example]\n\n`RedisSentinelClient` always sends commands to the primary. It doesn't support reading\nfrom replicas."
    },
    {
      "id": "connect-to-your-production-redis-with-tls",
      "title": "Connect to your production Redis with TLS",
      "role": "content",
      "text": "When you deploy your application, use TLS and follow the [Redis security](https://redis.io/docs/latest/operate/oss_and_stack/management/security) guidelines.\n\nBefore connecting your application to the TLS-enabled Redis server, ensure that your certificates and private keys are in the correct format.\n\nTo convert user certificate and private key from the PEM format to `pkcs12`, use this command:\n\n[code example]\n\nEnter password to protect your `pkcs12` file.\n\nConvert the server (CA) certificate to the JKS format using the [keytool](https://docs.oracle.com/en/java/javase/12/tools/keytool.html) shipped with JDK.\n\n[code example]\n\nEstablish a secure connection with your Redis database using this snippet.\n\n[code example]"
    },
    {
      "id": "connect-using-client-side-caching",
      "title": "Connect using client-side caching",
      "role": "content",
      "text": "Client-side caching is a technique to reduce network traffic between\nthe client and server, resulting in better performance. See\n[Client-side caching introduction](https://redis.io/docs/latest/develop/clients/client-side-caching)\nfor more information about how client-side caching works and how to use it effectively.\n\nTo enable client-side caching, specify the\n[RESP3](https://redis.io/docs/latest/develop/reference/protocol-spec#resp-versions)\nprotocol and pass a cache configuration object during the connection.\n\nThe example below shows the simplest client-side caching connection to the default host and port,\n`localhost:6379`.\nAll of the connection variants described above accept these parameters, so you can\nuse client-side caching with a connection pool or a cluster connection in exactly the same way.\n\n> [!NOTE]\n> Client-side caching requires Jedis v5.2.0 or later.\n> To maximize compatibility with all Redis products, client-side caching\n> is supported by Redis v7.4 or later.\n>\n> The [Redis server products](https://redis.io/docs/latest/operate) support\n> [opt-in/opt-out](https://redis.io/docs/latest/develop/reference/client-side-caching#opt-in-and-opt-out-caching) mode\n> and [broadcasting mode](https://redis.io/docs/latest/develop/reference/client-side-caching#broadcasting-mode)\n> for CSC, but these modes are not currently implemented by Jedis.\n\n[code example]\n\nOnce you have connected, the usual Redis commands will work transparently\nwith the cache:\n\n[code example]\n\nYou can see the cache working if you connect to the same Redis database\nwith [`redis-cli`](https://redis.io/docs/latest/develop/tools/cli) and run the\n[`MONITOR`](https://redis.io/docs/latest/commands/monitor) command. If you run the\ncode above but without passing `cacheConfig` during the connection,\nyou should see the following in the CLI among the output from `MONITOR`:\n\n[code example]\n\nThe server responds to both `get(\"city\")` calls.\nIf you run the code with `cacheConfig` added in again, you will see\n\n[code example]\n\nThe first `get(\"city\")` call contacted the server, but the second\ncall was satisfied by the cache."
    },
    {
      "id": "removing-items-from-the-cache",
      "title": "Removing items from the cache",
      "role": "content",
      "text": "You can remove individual keys from the cache with the\n`deleteByRedisKey()` method of the cache object. This removes all cached items associated\nwith each specified key, so all results from multi-key commands (such as\n[`MGET`](https://redis.io/docs/latest/commands/mget)) and composite data structures\n(such as [hashes](https://redis.io/docs/latest/develop/data-types/hashes)) will be\ncleared at once. The example below shows the effect of removing a single\nkey from the cache:\n\n[code example]\n\nYou can also clear all cached items using the `flush()`\nmethod:\n\n[code example]\n\nThe client will also flush the cache automatically\nif any connection (including one from a connection pool)\nis disconnected."
    },
    {
      "id": "configure-a-connection-pool",
      "title": "Configure a connection pool",
      "role": "configuration",
      "text": "A connection pool maintains several open connections and reuses them\nefficiently. When you open a connection from a pool, the pool allocates\none of its open connections. When you subsequently close the same connection,\nit is not actually closed but simply returned to the pool for reuse.\nThis avoids the overhead of repeated connecting and disconnecting.\nSee\n[Connection pools and multiplexing](https://redis.io/docs/latest/develop/clients/pools-and-muxing)\nfor more information.\n\nFrom Jedis 7.2.0, the `RedisClient` class provides connection pooling automatically,\nbut it's important to configure the connection pool correctly to get the best performance. \nEach pool holds a specified number of connections, creates more connections when necessary, and terminates them when they are no longer needed.\n\nHere is a simplified connection lifecycle in a pool:\n\n1. A connection is requested from the pool.\n2. A connection is served:\n   - An idle connection is served when non-active connections are available, or \n   - A new connection is created when the number of connections is under `maxTotal`. \n3. The connection becomes active.\n4. The connection is released back to the pool.\n5. The connection is marked as stale. \n6. The connection is kept idle for `minEvictableIdleTime`. \n7. The connection becomes evictable if the number of connections is greater than `minIdle`. \n8. The connection is ready to be closed.\n\nPass a `ConnectionPoolConfig` object to the `RedisClient` builder to configure the pool. \n(`ConnectionPoolConfig` is a wrapper around `GenericObjectPoolConfig` from [Apache Commons Pool2](https://commons.apache.org/proper/commons-pool/apidocs/org/apache/commons/pool2/impl/GenericObjectPoolConfig.html)).\n\n[code example]"
    },
    {
      "id": "retrying-a-command-after-a-connection-failure",
      "title": "Retrying a command after a connection failure",
      "role": "content",
      "text": "If a connection is lost before a command is completed, the command will fail with a `JedisConnectionException`. Although the connection pool manages the connections\nfor you, you must request a new connection from the pool to retry the command.\nYou would typically do this in a loop that makes several attempts to reconnect\nbefore aborting and reporting that the error isn't transient. The example below\nshows a retry loop that uses a simple\n[exponential backoff](https://en.wikipedia.org/wiki/Exponential_backoff)\nstrategy:\n\n[code example]"
    }
  ],
  "examples": [
    {
      "id": "basic-connection-ex0",
      "language": "java",
      "code": "package org.example;\nimport redis.clients.jedis.RedisClient;\n\npublic class Main {\n    public static void main(String[] args) {\n        RedisClient jedis = RedisClient.create(\"redis://localhost:6379\");\n\n        // Code that interacts with Redis...\n\n        jedis.close();\n    }\n}",
      "section_id": "basic-connection"
    },
    {
      "id": "basic-connection-ex1",
      "language": "java",
      "code": "...\n\nString res1 = jedis.set(\"bike:1\", \"Deimos\");\nSystem.out.println(res1); // OK\n\nString res2 = jedis.get(\"bike:1\");\nSystem.out.println(res2); // Deimos\n\n...",
      "section_id": "basic-connection"
    },
    {
      "id": "connect-to-a-redis-cluster-ex0",
      "language": "java",
      "code": "import redis.clients.jedis.RedisClusterClient;\nimport redis.clients.jedis.HostAndPort;\n\n//...\n\nSet<HostAndPort> jedisClusterNodes = new HashSet<HostAndPort>();\njedisClusterNodes.add(new HostAndPort(\"127.0.0.1\", 7379));\njedisClusterNodes.add(new HostAndPort(\"127.0.0.1\", 7380));\nRedisClusterClient jedis = RedisClusterClient.create(jedisClusterNodes);",
      "section_id": "connect-to-a-redis-cluster"
    },
    {
      "id": "connect-to-redis-sentinel-ex0",
      "language": "java",
      "code": "import redis.clients.jedis.HostAndPort;\nimport redis.clients.jedis.RedisSentinelClient;\n\nimport java.util.HashSet;\nimport java.util.Set;\n\n//...\n\nSet<HostAndPort> sentinels = new HashSet<>();\nsentinels.add(new HostAndPort(\"localhost\", 26379));\nsentinels.add(new HostAndPort(\"localhost\", 26380));\nsentinels.add(new HostAndPort(\"localhost\", 26381));\n\nRedisSentinelClient jedis = RedisSentinelClient.builder()\n        .masterName(\"mymaster\")\n        .sentinels(sentinels)\n        .build();\n\njedis.set(\"foo\", \"bar\");\nSystem.out.println(jedis.get(\"foo\")); // bar\n\njedis.close();",
      "section_id": "connect-to-redis-sentinel"
    },
    {
      "id": "connect-to-redis-sentinel-ex1",
      "language": "java",
      "code": "import redis.clients.jedis.DefaultJedisClientConfig;\nimport redis.clients.jedis.JedisClientConfig;\n\n//...\n\n// Credentials for the primary and replica nodes.\nJedisClientConfig masterConfig = DefaultJedisClientConfig.builder()\n        .password(\"secret!\") // use your Redis password\n        .build();\n\n// Credentials for the Sentinel nodes.\nJedisClientConfig sentinelConfig = DefaultJedisClientConfig.builder()\n        .password(\"sentinelSecret!\") // use your Sentinel password\n        .build();\n\nRedisSentinelClient jedis = RedisSentinelClient.builder()\n        .masterName(\"mymaster\")\n        .sentinels(sentinels)\n        .clientConfig(masterConfig)\n        .sentinelClientConfig(sentinelConfig)\n        .build();",
      "section_id": "connect-to-redis-sentinel"
    },
    {
      "id": "connect-to-your-production-redis-with-tls-ex0",
      "language": "plaintext",
      "code": "openssl pkcs12 -export -in ./redis_user.crt -inkey ./redis_user_private.key -out redis-user-keystore.p12 -name \"redis\"",
      "section_id": "connect-to-your-production-redis-with-tls"
    },
    {
      "id": "connect-to-your-production-redis-with-tls-ex1",
      "language": "plaintext",
      "code": "keytool -importcert -keystore truststore.jks \\ \n  -storepass REPLACE_WITH_YOUR_PASSWORD \\\n  -file redis_ca.pem",
      "section_id": "connect-to-your-production-redis-with-tls"
    },
    {
      "id": "connect-to-your-production-redis-with-tls-ex2",
      "language": "java",
      "code": "package org.example;\n\nimport redis.clients.jedis.*;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.security.GeneralSecurityException;\n\npublic class Main {\n\n    public static void main(String[] args) throws GeneralSecurityException, IOException {\n        HostAndPort address = new HostAndPort(\"my-redis-instance.cloud.redislabs.com\", 6379);\n\n        SslOptions sslOptions = SslOptions.builder()\n                .truststore(new File(\"./truststore.jks\"), \"secret!\".toCharArray())\n                .trustStoreType(\"jks\")\n                // optional: use if Redis requires client certificate\n                .keystore(new File(\"./redis-user-keystore.p12\"), \"secret!\".toCharArray())\n                .keyStoreType(\"pkcs12\")\n                .build();\n\n        JedisClientConfig config = DefaultJedisClientConfig.builder()\n                .sslOptions(sslOptions)\n                .user(\"default\") // use your Redis user. More info https://redis.io/docs/latest/operate/oss_and_stack/management/security/acl/\n                .password(\"secret!\") // use your Redis password\n                .build();\n\n        RedisClient jedis = RedisClient.builder()\n              .hostAndPort(address)\n              .clientConfig(config)\n              .build();\n        jedis.set(\"foo\", \"bar\");\n        System.out.println(jedis.get(\"foo\")); // prints bar\n    }\n}",
      "section_id": "connect-to-your-production-redis-with-tls"
    },
    {
      "id": "connect-using-client-side-caching-ex0",
      "language": "java",
      "code": "HostAndPort endpoint = new HostAndPort(\"localhost\", 6379);\n\nDefaultJedisClientConfig config = DefaultJedisClientConfig\n    .builder()\n    .password(\"secretPassword\")\n    .protocol(RedisProtocol.RESP3)\n    .build();\n\nCacheConfig cacheConfig = CacheConfig.builder().maxSize(1000).build();\n\nRedisClient client = RedisClient.builder()\n        .hostAndPort(endpoint)\n        .clientConfig(config)\n        .cacheConfig(cacheConfig)\n        .build();",
      "section_id": "connect-using-client-side-caching"
    },
    {
      "id": "connect-using-client-side-caching-ex1",
      "language": "java",
      "code": "client.set(\"city\", \"New York\");\nclient.get(\"city\");     // Retrieved from Redis server and cached\nclient.get(\"city\");     // Retrieved from cache",
      "section_id": "connect-using-client-side-caching"
    },
    {
      "id": "connect-using-client-side-caching-ex2",
      "language": "plaintext",
      "code": "1723109720.268903 [...] \"SET\" \"city\" \"New York\"\n1723109720.269681 [...] \"GET\" \"city\"\n1723109720.270205 [...] \"GET\" \"city\"",
      "section_id": "connect-using-client-side-caching"
    },
    {
      "id": "connect-using-client-side-caching-ex3",
      "language": "plaintext",
      "code": "1723110248.712663 [...] \"SET\" \"city\" \"New York\"\n1723110248.713607 [...] \"GET\" \"city\"",
      "section_id": "connect-using-client-side-caching"
    },
    {
      "id": "removing-items-from-the-cache-ex0",
      "language": "java",
      "code": "client.hget(\"person:1\", \"name\");    // Read from the server\nclient.hget(\"person:1\", \"name\");    // Read from the cache\n\nclient.hget(\"person:2\", \"name\");    // Read from the server\nclient.hget(\"person:2\", \"name\");    // Read from the cache\n\nCache myCache = client.getCache();\nmyCache.deleteByRedisKey(\"person:1\");\n\nclient.hget(\"person:1\", \"name\");    // Read from the server\nclient.hget(\"person:1\", \"name\");    // Read from the cache\n\nclient.hget(\"person:2\", \"name\");    // Still read from the cache",
      "section_id": "removing-items-from-the-cache"
    },
    {
      "id": "removing-items-from-the-cache-ex1",
      "language": "java",
      "code": "client.hget(\"person:1\", \"name\");    // Read from the server\nclient.hget(\"person:1\", \"name\");    // Read from the cache\n\nclient.hget(\"person:2\", \"name\");    // Read from the server\nclient.hget(\"person:2\", \"name\");    // Read from the cache\n\nCache myCache = client.getCache();\nmyCache.flush();\n\nclient.hget(\"person:1\", \"name\");    // Read from the server\nclient.hget(\"person:1\", \"name\");    // Read from the cache\n\nclient.hget(\"person:2\", \"name\");    // Read from the server\nclient.hget(\"person:2\", \"name\");    // Read from the cache",
      "section_id": "removing-items-from-the-cache"
    },
    {
      "id": "configure-a-connection-pool-ex0",
      "language": "java",
      "code": "ConnectionPoolConfig poolConfig = new ConnectionPoolConfig();\n// maximum active connections in the pool,\n// tune this according to your needs and application type\n// default is 8\npoolConfig.setMaxTotal(8);\n\n// maximum idle connections in the pool, default is 8\npoolConfig.setMaxIdle(8);\n// minimum idle connections in the pool, default 0\npoolConfig.setMinIdle(0);\n\n// Enables waiting for a connection to become available.\npoolConfig.setBlockWhenExhausted(true);\n// The maximum number of seconds to wait for a connection to become available\npoolConfig.setMaxWait(Duration.ofSeconds(1));\n\n// Enables sending a PING command periodically while the connection is idle.\npoolConfig.setTestWhileIdle(true);\n// controls the period between checks for idle connections in the pool\npoolConfig.setTimeBetweenEvictionRuns(Duration.ofSeconds(1));\n\nRedisClient jedis = RedisClient.builder()\n        .hostAndPort(\"localhost\", 6379)\n        .poolConfig(poolConfig)\n        .build();",
      "section_id": "configure-a-connection-pool"
    },
    {
      "id": "retrying-a-command-after-a-connection-failure-ex0",
      "language": "java",
      "code": "RedisClient jedis = RedisClient.builder()\n        .hostAndPort(\"localhost\", 6379)\n        .poolConfig(poolConfig)\n        .clientConfig(config)\n        .build();\n\n// Set max retry attempts\nfinal int MAX_RETRIES = 5;\n\n// Example of retrying a command\nString key = \"retry-example\";\nString value = \"success\";\n\nint attempts = 0;\nboolean success = false;\n\nwhile (!success && attempts < MAX_RETRIES) {\n    try {\n        attempts++;\n        String result = jedis.set(key, value);\n        System.out.println(\"Command succeeded on attempt \" + attempts + \": \" + result);\n        success = true;\n    } catch (JedisConnectionException e) {\n        System.out.println(\"Connection failed on attempt \" + attempts + \": \" + e.getMessage());\n        if (attempts >= MAX_RETRIES) {\n            System.out.println(\"Max retries reached. Giving up.\");\n            throw e;\n        }\n\n        // Wait before retrying\n        try {\n            Thread.sleep(500 * attempts); // Exponential backoff\n        } catch (InterruptedException ie) {\n            Thread.currentThread().interrupt();\n        }\n    }\n}",
      "section_id": "retrying-a-command-after-a-connection-failure"
    }
  ]
}
