Jedis Java Client for Redis

repository·master·Indexed 11 days ago

https://github.com/redis/jedis

A 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.

Tokens
121K
Snippets
342
Records
526
Agent score
91%

What's inside Jedis

  1. What is Jedis?

    master
    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.
  2. Understand ClusterCommandExecutor routing and policies

    master

    The ClusterCommandExecutor is used by RedisClusterClient to provide cluster-aware routing. It uses CRC16 hashing to determine the target shard for a given key and handles cluster topology changes via MOVED and ASK redirections.

    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 like SCAN or FT.CURSOR.
  3. Use Token-Based Authentication (TBA)

    master
    Starting 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.
  4. Choose the appropriate CommandExecutor implementation

    master

    The CommandExecutor interface defines how commands are executed. Depending on your Redis deployment, you will use different implementations:

    ImplementationUse CaseKey Characteristics
    SimpleCommandExecutorDeprecated UnifiedJedis(Connection)Single fixed connection; no retry; no pooling.
    DefaultCommandExecutorRedisClient (Standalone)Uses ConnectionProvider and connection pooling; no retry logic.
    RetryableCommandExecutorCustom UnifiedJedis setupsImplements deadline-proportional backoff and configurable maxAttempts.
    ClusterCommandExecutorRedisClusterClientCluster-aware routing (hash slots), handles MOVED/ASK redirections, and supports broadcast commands.
    MultiDbCommandExecutorMultiDbClient (Experimental)Uses circuit breakers (Resilience4j) and exponential backoff for multi-database failover.
  5. Manage transaction completion and cleanup

    master

    A transaction can be finalized in two ways:

    • exec(): Executes all queued commands atomically and returns a List<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 MULTI state, Jedis automatically sends DISCARD.
    • If the transaction is in a WATCH state, Jedis automatically sends UNWATCH. This ensures the connection is returned to the pool in a clean state.
  6. Optimize performance by using byte[] for binary data

    master

    While Redis/Jedis provides String-based APIs, Redis internally treats data as 8-bit blocks (binary safe). In Java, String is 16-bit, meaning Jedis must encode/decode strings using a SafeEncoder.

    To avoid the performance overhead of encoding/decoding, use the binary versions of commands (accepting byte[]) when working with non-textual or binary data.

  7. Perform automatic failback using health checks

    master

    When 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:

    1. Continuous Monitoring: Health checks must be enabled so Jedis can monitor all configured databases (including inactive ones).
    2. Recovery Detection: The database must pass the required number of consecutive health checks to be marked as healthy.
    3. Weight-Based Selection: The recovered database must have a higher weight than the currently active database.
    4. Grace Period: The configured grace period must have elapsed since the database was last marked as unhealthy.
  8. Configure Failover and Retry

    master
    Jedis 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.
  9. Define and name Integration vs Unit tests

    master

    The 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 *IT suffix. Do not use *IntegrationTest or the @Tag("integration") marker for new code.

    Test TypeNaming ConventionJUnit TagRunner
    Unit*Test or *TestsNoneSurefire
    Integration*ITNoneFailsafe
    ScenarioAny@Tag("scenario")Failsafe (skipped by default)
  10. Understand the Jedis execution flow

    master

    Jedis follows a layered execution model to process commands. When you call a method on a client (like RedisClient or RedisClusterClient), the request flows through several components:

    1. UnifiedJedis: The high-level API entry point that translates method calls into CommandObjects.
    2. CommandExecutor: An abstraction that handles the logic of how a command is executed (e.g., simple execution, retries, or cluster-aware routing).
    3. ConnectionProvider: Responsible for obtaining a connection, which might involve looking up a slot in a cluster or retrieving a connection from a pool.
    4. 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.