Jedis Java Client for Redis
repository·master·Indexed 11 days ago
https://github.com/redis/jedisA high-performance Java client for Redis supporting standard commands, Redis Clusters, failover, and Token-Based Authentication (TBA). Features include pipelining, transactions via Response objects, Pub/Sub with JedisPubSub, and support for Microsoft EntraID. Version 8.0.0 supports Redis 7.2+ and JDK 8 through 25.
What's inside Jedis
- Jedis is a popular, lightweight, and easy-to-use Java client for Redis. It provides a simple API to interact with Redis, supporting various Redis data types and features like clustering, failover, and token-based authentication.
Understand ClusterCommandExecutor routing and policies
masterThe
ClusterCommandExecutoris used byRedisClusterClientto provide cluster-aware routing. It uses CRC16 hashing to determine the target shard for a given key and handles cluster topology changes viaMOVEDandASKredirections.Request Policies:
DEFAULT: Single-shard routing based on the key's hash slot. For keyless commands, it uses round-robin distribution.ALL_SHARDS: Broadcasts the command to all primary nodes.ALL_NODES: Broadcasts the command to all nodes, including replicas.MULTI_SHARD: Used for multi-key commands that span multiple shards.SPECIAL: Special handling for commands likeSCANorFT.CURSOR.
Use Token-Based Authentication (TBA)
masterStarting from the 5.3.0 GA release, Jedis supports Token-Based Authentication (TBA). This is often used with Microsoft EntraID. An extension library is available to enhance the developer experience and provide necessary components for TBA functionality.Choose the appropriate CommandExecutor implementation
masterThe
CommandExecutorinterface defines how commands are executed. Depending on your Redis deployment, you will use different implementations:Implementation Use Case Key Characteristics SimpleCommandExecutorDeprecated UnifiedJedis(Connection)Single fixed connection; no retry; no pooling. DefaultCommandExecutorRedisClient(Standalone)Uses ConnectionProviderand connection pooling; no retry logic.RetryableCommandExecutorCustom UnifiedJedissetupsImplements deadline-proportional backoff and configurable maxAttempts.ClusterCommandExecutorRedisClusterClientCluster-aware routing (hash slots), handles MOVED/ASKredirections, and supports broadcast commands.MultiDbCommandExecutorMultiDbClient(Experimental)Uses circuit breakers (Resilience4j) and exponential backoff for multi-database failover. Manage transaction completion and cleanup
masterA transaction can be finalized in two ways:
exec(): Executes all queued commands atomically and returns aList<Object>of results.discard(): Discards all queued commands without executing them.
Connection Lifecycle & Cleanup: Transactions acquire a dedicated connection. To prevent connection leaks, always use try-with-resources. When a transaction is closed via
close()(automatically at the end of a try-with-resources block):- If the transaction is in a
MULTIstate, Jedis automatically sendsDISCARD. - If the transaction is in a
WATCHstate, Jedis automatically sendsUNWATCH. This ensures the connection is returned to the pool in a clean state.
Optimize performance by using byte[] for binary data
masterWhile Redis/Jedis provides String-based APIs, Redis internally treats data as 8-bit blocks (binary safe). In Java,
Stringis 16-bit, meaning Jedis must encode/decode strings using aSafeEncoder.To avoid the performance overhead of encoding/decoding, use the binary versions of commands (accepting
byte[]) when working with non-textual or binary data.Perform automatic failback using health checks
masterWhen a previously failed Redis database becomes available again, Jedis can automatically switch traffic back to it if automatic failback is enabled.
For automatic failback to occur, the following conditions must be met:
- Continuous Monitoring: Health checks must be enabled so Jedis can monitor all configured databases (including inactive ones).
- Recovery Detection: The database must pass the required number of consecutive health checks to be marked as healthy.
- Weight-Based Selection: The recovered database must have a higher weight than the currently active database.
- Grace Period: The configured grace period must have elapsed since the database was last marked as unhealthy.
TLS Hostname Verification Enforced by Default
masterJedis 8.0.0 enforces TLS hostname verification by default to improve security. If you are using TLS and your server's certificate does not match the hostname, connections will fail unless configured otherwise.Configure Failover and Retry
masterJedis supports retry and failover mechanisms. This is useful for connecting to multiple independent Redis deployments or replicating across active-active Redis Enterprise clusters. If the primary deployment becomes unavailable, Jedis can fail over to the next available deployment.Define and name Integration vs Unit tests
masterThe test runner (Surefire for unit, Failsafe for integration) selects tests based on their naming convention and JUnit tags.
Crucial Rule for New Tests: New integration tests MUST use the
*ITsuffix. Do not use*IntegrationTestor the@Tag("integration")marker for new code.Test Type Naming Convention JUnit Tag Runner Unit *Testor*TestsNone Surefire Integration *ITNone Failsafe Scenario Any @Tag("scenario")Failsafe (skipped by default) Understand the Jedis execution flow
masterJedis follows a layered execution model to process commands. When you call a method on a client (like
RedisClientorRedisClusterClient), the request flows through several components:- UnifiedJedis: The high-level API entry point that translates method calls into
CommandObjects. - CommandExecutor: An abstraction that handles the logic of how a command is executed (e.g., simple execution, retries, or cluster-aware routing).
- ConnectionProvider: Responsible for obtaining a connection, which might involve looking up a slot in a cluster or retrieving a connection from a pool.
- Connection: The low-level object that performs the actual network I/O with the Redis server.
Depending on the client type and configuration, the flow varies to support features like retries, cluster slot mapping, or database failover.
- UnifiedJedis: The high-level API entry point that translates method calls into
RESP3 Negotiated by Default
masterIn Jedis 8.0.0, allUnifiedJedis-based clients now attempt to negotiate the RESP3 protocol by default. If the Redis server does not support RESP3, the client will gracefully fall back to RESP2.