### Immediate Transaction Start and Execution Source: https://github.com/redis/jedis/blob/master/docs/transactions-multi.md This snippet demonstrates how to start a transaction immediately using `jedis.multi()`, queue commands, and then execute them with `tx.exec()`. It shows how to access results both through `Response` objects and the list returned by `exec()`. ```java import redis.clients.jedis.RedisClient; import redis.clients.jedis.AbstractTransaction; import redis.clients.jedis.Response; import java.util.List; RedisClient jedis = RedisClient.create("redis://localhost:6379"); // Create a transaction that immediately sends MULTI try (AbstractTransaction tx = jedis.multi()) { // Commands are queued Response set1 = tx.set("counter:1", "0"); Response incr1 = tx.incrBy("counter:1", 1); Response incr2 = tx.incrBy("counter:1", 2); // Execute the transaction List results = tx.exec(); // Access results via Response objects System.out.println(incr1.get()); // 1 System.out.println(incr2.get()); // 3 // Or via the results list System.out.println(results.get(0)); // OK System.out.println(results.get(1)); // 1 System.out.println(results.get(2)); // 3 } jedis.close(); ``` -------------------------------- ### Start Redis Instance with Specific Version Source: https://github.com/redis/jedis/blob/master/docs/integration-testing.md Use this command to start a Redis instance with a specific version for testing. Supported versions are listed in the documentation. ```bash make start version=8.6 ``` -------------------------------- ### Start Redis with Custom Docker Image Source: https://github.com/redis/jedis/blob/master/docs/integration-testing.md Allows starting the Redis environment using a custom Docker image tag instead of a predefined version. ```bash make start CLIENT_LIBS_TEST_IMAGE_TAG= ``` -------------------------------- ### Jedis Monitoring Example Source: https://github.com/redis/jedis/wiki/AdvancedUsage Monitor Redis commands by implementing the `JedisMonitor` interface and calling `jedis.monitor()`. This example demonstrates starting a separate thread to increment a key and then monitoring the commands. ```java new Thread(new Runnable() { public void run() { Jedis j = new Jedis("localhost"); for (int i = 0; i < 100; i++) { j.incr("foobared"); try { Thread.sleep(200); } catch (InterruptedException e) { } } j.disconnect(); } }).start(); jedis.monitor(new JedisMonitor() { public void onCommand(String command) { System.out.println(command); } }); ``` -------------------------------- ### Run a Single Integration Test Quickly Source: https://github.com/redis/jedis/blob/master/docs/integration-testing.md Command to start a Redis server and then run a specific test class. Remember to stop the server afterwards. ```bash make start version=8.6 mvn -Dtest=YourIT verify make stop ``` -------------------------------- ### Jedis Publish/Subscribe Example Source: https://github.com/redis/jedis/wiki/AdvancedUsage Implement publish/subscribe functionality by extending `JedisPubSub` and calling `jedis.subscribe()`. Note that `subscribe` is a blocking operation. ```java class MyListener extends JedisPubSub { public void onMessage(String channel, String message) { } public void onSubscribe(String channel, int subscribedChannels) { } public void onUnsubscribe(String channel, int subscribedChannels) { } public void onPSubscribe(String pattern, int subscribedChannels) { } public void onPUnsubscribe(String pattern, int subscribedChannels) { } public void onPMessage(String pattern, String channel, String message) { } } MyListener l = new MyListener(); jedis.subscribe(l, "foo"); ``` -------------------------------- ### Local-from-source Build and Test Commands Source: https://github.com/redis/jedis/blob/master/docs/integration-testing.md Commands to set up the local Redis environment and run tests. `make system-setup` is for CI to build Redis and the test module. `make test-local` starts local Redis instances, runs tests using the `oss-source` provider, and then stops the instances. ```bash make system-setup # CI only: build Redis from github.com/redis/redis + the test module (testmodule.so) make test-local # = start-local (TEST_ENV_PROVIDER=oss-source) → mvn verify → stop-local ``` -------------------------------- ### Manually Start Transaction with Jedis Source: https://github.com/redis/jedis/blob/master/docs/transactions-multi.md Create a transaction without immediately sending MULTI to execute commands before the transaction starts or use WATCH for optimistic locking. Commands before multi() are executed immediately, while commands after multi() are queued. ```java RedisClient jedis = RedisClient.create("redis://localhost:6379"); // Create transaction without sending MULTI try (AbstractTransaction tx = jedis.transaction(false)) { // Commands before multi() are executed immediately Response setBeforeMulti = tx.set("mykey", "initial_value"); Response getBeforeMulti = tx.get("mykey"); // These responses are available immediately System.out.println(setBeforeMulti.get()); // OK System.out.println(getBeforeMulti.get()); // initial_value // Now start the transaction tx.multi(); // Commands after multi() are queued Response set = tx.set("mykey", "new_value"); Response get = tx.get("mykey"); // Execute the transaction List results = tx.exec(); // Results from queued commands System.out.println(set.get()); // OK System.out.println(get.get()); // new_value } jedis.close(); ``` -------------------------------- ### Run Integration Tests Locally Source: https://github.com/redis/jedis/blob/master/docs/integration-testing.md Command to start a Redis server, run integration tests, and then stop the server. Ensure the specified version is available. ```bash make start version=8.6 && mvn clean verify && make stop ``` -------------------------------- ### Run Integration Tests Source: https://github.com/redis/jedis/blob/master/docs/integration-testing.md This command starts the Redis environment, runs the integration tests using Maven, and then stops the environment. You can specify a version for the Redis instance. ```bash make test [version=...] ``` -------------------------------- ### Jedis Test Setup: Get Redis Endpoint Source: https://github.com/redis/jedis/blob/master/docs/integration-testing.md Example of how to retrieve an endpoint configuration for a Redis server within a JUnit test setup method. Ensures tests are skipped if the endpoint is not found. ```java @BeforeAll static void setUp() { endpoint = Endpoints.getRedisEndpoint("standalone0-tls"); } ``` -------------------------------- ### Jedis Pipelining Example Source: https://github.com/redis/jedis/wiki/AdvancedUsage Optimize command execution by sending multiple commands without waiting for responses using `jedis.pipelined()`. Retrieve all responses at the end with `p.sync()`. ```java Pipeline p = jedis.pipelined(); p.set("fool", "bar"); p.zadd("foo", 1, "barowitch"); p.zadd("foo", 0, "barinsky"); p.zadd("foo", 0, "barikoviev"); Response pipeString = p.get("fool"); Response> sose = p.zrange("foo", 0, -1); p.sync(); int soseSize = sose.get().size(); Set setBack = sose.get(); ``` -------------------------------- ### Migrate Standalone JedisPooled to RedisClient Source: https://github.com/redis/jedis/blob/master/docs/migration-guides/v7-to-v8.md Replace `JedisPooled` with `RedisClient.create()` for standalone connections. This example shows the simple factory method. ```java // Standalone RedisClient jedis = RedisClient.create("localhost", 6379); jedis.set("key", "value"); ``` -------------------------------- ### Send Command to Redis Source: https://github.com/redis/jedis/blob/master/README.md Example of sending a command (sadd) to a connected Redis instance. ```java jedis.sadd("planets", "Venus"); ``` -------------------------------- ### Send Command to Redis Cluster Source: https://github.com/redis/jedis/blob/master/README.md Example of sending a command (sadd) to a connected Redis Cluster instance. ```java jedis.sadd("planets", "Mars"); ``` -------------------------------- ### Jedis Transaction Example Source: https://github.com/redis/jedis/wiki/AdvancedUsage Wrap operations in a transaction block using `jedis.multi()` and `t.exec()`. Use `Response.get()` to retrieve results after `exec()`. ```java jedis.watch (key1, key2, ...); Transaction t = jedis.multi(); t.set("foo", "bar"); t.exec(); ``` ```java Transaction t = jedis.multi(); t.set("fool", "bar"); Response result1 = t.get("fool"); t.zadd("foo", 1, "barowitch"); t.zadd("foo", 0, "barinsky"); t.zadd("foo", 0, "barikoviev"); Response> sose = t.zrange("foo", 0, -1); // get the entire sortedset t.exec(); // dont forget it String foolbar = result1.get(); // use Response.get() to retrieve things from a Response int soseSize = sose.get().size(); // on sose.get() you can directly call Set methods! ``` ```java // this does not work! Intra-transaction dependencies are not supported by Redis! jedis.watch(...); Transaction t = jedis.multi(); if(t.get("key1").equals("something")) t.set("key2", "value2"); else t.set("key", "value"); ``` -------------------------------- ### CONFIG GET/SET on UnifiedJedis in Jedis v8 Source: https://github.com/redis/jedis/blob/master/docs/migration-guides/v7-to-v8.md UnifiedJedis now supports CONFIG GET and SET operations. For RedisClusterClient, configGet is routed to a random node, while configSet fans out to all masters. ```java public Map configGet(String pattern); public Map configGet(String... patterns); public String configSet(Map parameterValues); ``` -------------------------------- ### Search Index with Query Object and Filters Source: https://github.com/redis/jedis/blob/master/docs/redisearch.md Perform a search on a RediSearch index using a Query object. This example includes a text search term, a numeric filter, and pagination limits. ```java Query q = new Query("hello world") .addFilter(new Query.NumericFilter("price", 0, 1000)) .limit(0, 5); SearchResult sr = client.ftSearch("item-index", q); ``` -------------------------------- ### Perform Aggregation Query Source: https://github.com/redis/jedis/blob/master/docs/redisearch.md Construct and execute an aggregation query on a RediSearch index. This example applies a transformation, groups by a field, filters by aggregated value, and sorts the results. ```java AggregationBuilder ab = new AggregationBuilder("hello") .apply("@price/1000", "k") .groupBy("@state", Reducers.avg("@k").as("avgprice")) .filter("@avgprice>=2") .sortBy(10, SortedField.asc("@state")); AggregationResult ar = client.ftAggregate("item-index", ab); ``` -------------------------------- ### Create a Unix Domain Socket Factory Source: https://github.com/redis/jedis/blob/master/docs/advanced-usage.md Implement the JedisSocketFactory interface to create custom socket connections using Unix Domain Sockets. This example uses junixsocket to establish a connection to a specified socket file. ```java import org.newsclub.net.unix.AFUNIXSocket; import org.newsclub.net.unix.AFUNIXSocketAddress; public class UdsSocketFactory implements JedisSocketFactory { private final File socketFile; public UdsSocketFactory(String socketPath) { this.socketFile = new File(socketPath); } @Override public Socket createSocket() throws JedisConnectionException { try { Socket socket = AFUNIXSocket.newStrictInstance(); socket.connect(new AFUNIXSocketAddress(socketFile), Protocol.DEFAULT_TIMEOUT); return socket; } catch (IOException e) { throw new JedisConnectionException("Failed to create UDS connection.", e); } } } ``` -------------------------------- ### Get and Set Database Weights in Jedis Source: https://github.com/redis/jedis/blob/master/docs/failover.md Use `getWeight` to retrieve the current weight of a database and `setWeight` to dynamically adjust it at runtime. Ensure the endpoint exists and the weight is positive. ```java HostAndPort east = new HostAndPort("redis-east.example.com", 14000); float currentWeight = client.getWeight(east); System.out.println("Current weight: " + currentWeight); client.setWeight(east, 2.0f); ``` -------------------------------- ### Run Maven Tests with Existing Environment Source: https://github.com/redis/jedis/blob/master/docs/integration-testing.md Execute Maven tests against an already running Redis environment. This is useful when running tests from an IDE between `make start` and `make stop` commands. ```bash mvn clean verify ``` -------------------------------- ### Dynamic Database Management with Jedis Source: https://github.com/redis/jedis/blob/master/docs/failover.md Demonstrates setting up a multi-database client, adding a new database, and removing an existing one. The listener provides feedback on database switch events. ```java // Initial setup with two databases, primary and secondary. HostAndPort primary = new HostAndPort("redis-primary.example.com", 6379); HostAndPort secondary = new HostAndPort("redis-secondary.example.com", 6379); JedisClientConfig clientConfig = DefaultJedisClientConfig.builder() .user("cache").password("secret").build(); MultiDbConfig config = MultiDbConfig.builder() .database(DatabaseConfig.builder(primary, clientConfig).weight(2.0f).build()) .database(DatabaseConfig.builder(secondary, clientConfig).weight(1.0f).build()) .failbackSupported(true) .build(); MultiDbClient client = MultiDbClient.builder() .multiDbConfig(config) .databaseSwitchListener(event -> { System.out.println("Switched to: " + event.getEndpoint() + " due to: " + event.getReason()); }) .build(); // Add a new database in a different region HostAndPort newRegion = new HostAndPort("redis-eu.example.com", 6379); client.addDatabase(newRegion, 1.0f, clientConfig); System.out.println("Added new database: " + newRegion); // Verify the database was added Set endpoints = client.getDatabaseEndpoints(); System.out.println("Current databases: " + endpoints); // Output: [redis-primary.example.com:6379, redis-secondary.example.com:6379, redis-eu.example.com:6379] // Later, remove the secondary database for maintenance client.removeDatabase(secondary); System.out.println("Removed database: " + secondary); // If secondary was active, automatic failover occurs to primary or newRegion // Verify the database was removed endpoints = client.getDatabaseEndpoints(); System.out.println("Current databases: " + endpoints); // Output: [redis-primary.example.com:6379, redis-eu.example.com:6379] ``` -------------------------------- ### Run Redis with Docker Source: https://github.com/redis/jedis/blob/master/README.md Use Docker to quickly set up and run a Redis server instance. ```bash docker run -p 6379:6379 -it redis:latest ``` -------------------------------- ### JMH Benchmark Results Example Source: https://github.com/redis/jedis/blob/master/src/test/jmh/redis/clients/jedis/benchmark/README.md Example output from a JMH benchmark run. The 'Score' represents the average time per operation, and 'Error' indicates the confidence interval. Lower scores and smaller error percentages are desirable. ```text Benchmark Mode Cnt Score Error Units CRC16Benchmark.getSlotString avgt 5 47.123 ± 2.456 ns/op ``` -------------------------------- ### Add Database with Basic Configuration Source: https://github.com/redis/jedis/blob/master/docs/failover.md A convenience method for simpler configurations when advanced customization is not needed. The new database participates in weight-based selection. ```java HostAndPort newEndpoint = new HostAndPort("redis-new.example.com", 6379); JedisClientConfig clientConfig = DefaultJedisClientConfig.builder() .user("cache").password("secret").build(); client.addDatabase(newEndpoint, 1.5f, clientConfig); ``` -------------------------------- ### Jedis Client Connection with Endpoint Config Source: https://github.com/redis/jedis/blob/master/docs/integration-testing.md Demonstrates establishing a Jedis client connection using the host and port, and client configuration builder obtained from an endpoint configuration. Requires a try-with-resources block for proper resource management. ```java try (Jedis j = new Jedis(endpoint.getHostAndPort(), endpoint.getClientConfigBuilder().build())) { ... } ``` -------------------------------- ### Query JSON Documents by First Name Source: https://github.com/redis/jedis/blob/master/docs/redisjson.md Executes a RediSearch query to find JSON documents where the 'firstName' field starts with 'maya'. ```java Query q = new Query("@\\$\.firstName:maya*"); SearchResult mayaSearch = client.ftSearch("student-index", q); ``` -------------------------------- ### Build and Run MkDocs Docker Container Source: https://github.com/redis/jedis/blob/master/docs/README.md Builds a Docker image for MkDocs Material and runs a container to preview documentation changes locally. Mounts the current directory to the container for live updates. ```bash # in docs/ docker build -t squidfunk/mkdocs-material . # cd .. docker run --rm -it -p 8000:8000 -v ${PWD}:/docs squidfunk/mkdocs-material ``` -------------------------------- ### Connect to a Single Redis Instance Source: https://github.com/redis/jedis/blob/master/README.md Instantiate a RedisClient to connect to a Redis server running on localhost. ```java RedisClient jedis = RedisClient.builder().hostAndPort("localhost", 6379).build(); ``` -------------------------------- ### Migrate JedisSharding to JedisCluster or JedisPooled Source: https://github.com/redis/jedis/blob/master/docs/migration-guides/v6-to-v7.md Replace JedisSharding with JedisCluster for distributed deployments or JedisPooled for single-node setups. Ensure correct initialization for the chosen client. ```java List shards = Arrays.asList( new HostAndPort("localhost", 6379), new HostAndPort("localhost", 6380) ); JedisSharding jedisSharding = new JedisSharding(shards); jedisSharding.set("key", "value"); ``` ```java Set nodes = new HashSet<>(Arrays.asList( new HostAndPort("localhost", 6379), new HostAndPort("localhost", 6380) )); JedisCluster jedisCluster = new JedisCluster(nodes); jedisCluster.set("key", "value"); ``` ```java JedisPooled jedis = new JedisPooled("localhost", 6379); jedis.set("key", "value"); ``` -------------------------------- ### Add Database with Full Configuration using DatabaseConfig Source: https://github.com/redis/jedis/blob/master/docs/failover.md Use this method for advanced configurations, including custom health checks and connection pool settings. The new endpoint becomes available for failover immediately. ```java HostAndPort newEndpoint = new HostAndPort("redis-new.example.com", 6379); JedisClientConfig clientConfig = DefaultJedisClientConfig.builder() .user("cache").password("secret").build(); DatabaseConfig databaseConfig = DatabaseConfig.builder(newEndpoint, clientConfig) .weight(1.5f).connectionPoolConfig(poolConfig).healthCheckEnabled(true).build(); client.addDatabase(databaseConfig); ``` -------------------------------- ### Adding Databases with Endpoint, Weight, and ClientConfig Source: https://github.com/redis/jedis/blob/master/docs/failover.md A convenience method for adding databases with basic configurations when advanced customization is not required. ```APIDOC ## Adding Databases with Endpoint, Weight, and ClientConfig This is a convenience method for simpler configurations when you don't need advanced customization. ```java HostAndPort newEndpoint = new HostAndPort("redis-new.example.com", 6379); JedisClientConfig clientConfig = DefaultJedisClientConfig.builder() .user("cache").password("secret").build(); // Add the database with basic configuration client.addDatabase(newEndpoint, 1.5f, clientConfig); ``` ``` -------------------------------- ### Create RedisClient Instance Source: https://github.com/redis/jedis/blob/master/docs/redisjson.md Instantiate a RedisClient for connecting to a single Redis instance. ```java RedisClient client = RedisClient.builder().hostAndPort("localhost", 6479).build(); ``` -------------------------------- ### Configure Jedis Databases with Weights Source: https://github.com/redis/jedis/blob/master/docs/failover.md Define initial configurations for Redis databases, including connection settings and pool configurations, and assign weights to prioritize them for failover. ```java JedisClientConfig config = DefaultJedisClientConfig.builder() .user("cache").password("secret") .socketTimeoutMillis(5000).connectionTimeoutMillis(5000).build(); // Custom pool config per database can be provided ConnectionPoolConfig poolConfig = new ConnectionPoolConfig(); poolConfig.setMaxTotal(8); poolConfig.setMaxIdle(8); poolConfig.setMinIdle(0); poolConfig.setBlockWhenExhausted(true); poolConfig.setMaxWait(Duration.ofSeconds(1)); poolConfig.setTestWhileIdle(true); poolConfig.setTimeBetweenEvictionRuns(Duration.ofSeconds(1)); HostAndPort east = new HostAndPort("redis-east.example.com", 14000); HostAndPort west = new HostAndPort("redis-west.example.com", 14000); MultiDbConfig.Builder multiConfig = MultiDbConfig.builder() .database(DatabaseConfig.builder(east, config).connectionPoolConfig(poolConfig).weight(1.0f).build()) .database(DatabaseConfig.builder(west, config).connectionPoolConfig(poolConfig).weight(0.5f).build()); ``` -------------------------------- ### Migrate Standalone JedisPooled with Builder Configuration Source: https://github.com/redis/jedis/blob/master/docs/migration-guides/v7-to-v8.md Use `RedisClient.builder()` for advanced standalone configurations, including setting user credentials and client configurations. ```java // Standalone — builder for advanced configuration RedisClient jedis = RedisClient.builder() .hostAndPort("localhost", 6379) .clientConfig(DefaultJedisClientConfig.builder() .user("myuser") .password("mypassword") .build()) .build(); ``` -------------------------------- ### Create RedisClusterClient Instance Source: https://github.com/redis/jedis/blob/master/docs/redisjson.md Instantiate a RedisClusterClient for connecting to a Redis cluster. ```java Set nodes = new HashSet<>(); nodes.add(new HostAndPort("127.0.0.1", 7379)); nodes.add(new HostAndPort("127.0.0.1", 7380)); RedisClusterClient client = RedisClusterClient.builder().nodes(nodes).build(); ``` -------------------------------- ### Implement Custom Host and Port Mapping with a Class Source: https://github.com/redis/jedis/blob/master/docs/advanced-usage.md Use a dedicated class implementing HostAndPortMapper for complex or reusable mapping logic. This allows translation of internal Redis addresses to external ones for client connections. ```java public class DockerNATMapper implements HostAndPortMapper { // Key: The address reported by Redis (internal). // Value: The address the client should connect to (external). private final Map mapping; public DockerNATMapper(Map mapping) { this.mapping = mapping; } @Override public HostAndPort getHostAndPort(HostAndPort hostAndPort) { return mapping.getOrDefault(hostAndPort, hostAndPort); } } ``` ```java Map nodeMapping = new HashMap<>(); nodeMapping.put(new HostAndPort("172.18.0.2", 6379), new HostAndPort("my-redis.example.com", 7001)); nodeMapping.put(new HostAndPort("172.18.0.3", 6379), new HostAndPort("my-redis.example.com", 7002)); nodeMapping.put(new HostAndPort("172.18.0.4", 6379), new HostAndPort("my-redis.example.com", 7002)); Set initialNodes = new HashSet<>(); // seed node initialNodes.add(new HostAndPort("my-redis.example.com", 7001)); HostAndPortMapper mapper = new DockerNATMapper(nodeMapping); JedisClientConfig jedisClientConfig = DefaultJedisClientConfig.builder() .user("myuser") .password("mypassword") .hostAndPortMapper(mapper) .build(); RedisClusterClient jedisCluster = RedisClusterClient.builder() .nodes(initialNodes) .clientConfig(jedisClientConfig) .build(); ``` -------------------------------- ### HostAndPortMapper for Network Address Translation Source: https://github.com/redis/jedis/blob/master/docs/advanced-usage.md Implement HostAndPortMapper to dynamically map Redis node addresses when running in environments like NAT gateways or container orchestrators. This example shows mapping Docker-internal IPs to externally accessible host and port combinations. ```java // Example use case: NAT or Docker with different advertised ports // Suppose you run a Redis cluster inside Docker on a remote host. // Inside the cluster config, nodes announce addresses like: // 172.18.0.2:6379 // 172.18.0.3:6379 // 172.18.0.4:6379 // // But externally, you reach them through the host IP with mapped ports: // my-redis.example.com:7001 // my-redis.example.com:7002 // my-redis.example.com:7003 ``` -------------------------------- ### Migrate UnifiedJedis Instantiation Source: https://github.com/redis/jedis/blob/master/docs/migration-guides/v7-to-v8.md Before v8.0.0, UnifiedJedis could be instantiated directly. In v8.0.0, use RedisClient.create() or RedisClient.builder() for instantiation. ```java UnifiedJedis jedis = new UnifiedJedis(new HostAndPort("localhost", 6379)); UnifiedJedis jedis2 = new UnifiedJedis(URI.create("redis://localhost:6379")); UnifiedJedis custom = new UnifiedJedis(myConnectionProvider); ``` ```java RedisClient jedis = RedisClient.create(new HostAndPort("localhost", 6379)); RedisClient jedis2 = RedisClient.create("redis://localhost:6379"); RedisClient custom = RedisClient.builder() .connectionProvider(myConnectionProvider) .build(); ``` -------------------------------- ### Docker Compose Service Definition for Jedis Tests Source: https://github.com/redis/jedis/blob/master/docs/integration-testing.md Example of a Docker Compose service definition for a Redis environment within the Jedis test suite. It specifies the image, environment variables for Redis configuration, ports, and volume mounts for configuration and runtime data. ```yaml redis1-2-5-8-sentinel: <<: *client-libs-image # image: ${CLIENT_LIBS_TEST_IMAGE}:${REDIS_VERSION} environment: [REDIS_CLUSTER=no, REDIS_CLIENT_USER=deploy, REDIS_CLIENT_PASSWORD=verify, TLS_ENABLED=yes] ports: ["6379:6379", "6390:6390", "26379:26379", "36379:36379"] volumes: - ${REDIS_ENV_CONF_DIR}/redis1-2-5-8-sentinel/config:/redis/config:r - ${REDIS_ENV_WORK_DIR}/redis1-2-5-8-sentinel/work:/redis/work:rw ``` -------------------------------- ### Run Standalone Redis Instance Source: https://github.com/redis/jedis/blob/master/docs/integration-testing.md Launches a standalone Redis instance on port 6379 using the specified Docker image tag. Useful for direct experimentation. ```bash docker run --rm -p 6379:6379 redislabs/client-libs-test:8.6 ``` -------------------------------- ### Connect to Redis via UDS with PooledConnectionProvider Source: https://github.com/redis/jedis/blob/master/docs/advanced-usage.md Demonstrates how to establish a connection to Redis using a Unix Domain Socket (UDS) and configure connection pooling. This is useful for local development or environments where direct TCP connections are not preferred. ```java JedisSocketFactory socketFactory = new UdsSocketFactory("/tmp/redis.sock"); JedisClientConfig clientConfig = DefaultJedisClientConfig.builder().build(); ConnectionFactory connectionFactory = new ConnectionFactory(socketFactory, clientConfig); PooledConnectionProvider provider = new PooledConnectionProvider(connectionFactory); RedisClient client = RedisClient.builder() .connectionProvider(provider) .clientConfig(clientConfig) .build(); ``` -------------------------------- ### Basic Transaction with Try-with-Resources Source: https://github.com/redis/jedis/blob/master/docs/transactions-multi.md Acquires a dedicated connection for the transaction, ensuring it's held until `close()` is called. Use this pattern to guarantee proper connection management, especially when errors occur. ```java try (AbstractTransaction tx = jedis.multi()) { tx.set("key", "value"); tx.exec(); } ``` -------------------------------- ### Run 3-Node Redis Cluster Source: https://github.com/redis/jedis/blob/master/docs/integration-testing.md Launches a 3-node Redis cluster on ports 7000-7002. Configures the cluster using environment variables for automatic bootstrapping. ```bash docker run --rm -p 7000-7002:7000-7002 \ -e REDIS_CLUSTER=yes -e NODES=3 -e PORT=7000 redislabs/client-libs-test:8.6 ``` -------------------------------- ### Alternative JSON Storage Methods Source: https://github.com/redis/jedis/blob/master/docs/redisjson.md Demonstrates alternative methods for storing POJOs as JSON, including legacy and escaped versions. ```java client.jsonSetLegacy("student:111", maya); client.jsonSetWithEscape("student:112", oliwia); ``` -------------------------------- ### Jedis Environment Directory Structure Source: https://github.com/redis/jedis/blob/master/docs/integration-testing.md Illustrates the standard directory layout for Jedis integration test environments, including Docker Compose files, environment variable definitions, and per-environment configurations. ```tree src/test/resources/env/ ├── docker-compose.yml # all Redis services (standalone/sentinel/cluster/tls/mtls/stack) ├── .env # base vars (default REDIS_VERSION, image name, work dir) ├── .env.v6.2 … .env.v8.10 # per-version overrides (just pin REDIS_VERSION) ├── redis1-2-5-8-sentinel/ # one dir per environment │ ├── config/node-/redis.conf # mounted read-only into the container │ └── work/ # runtime state (TLS certs land in work/tls/) ├── standalone2-sentinel/ ├── cluster-unbound/ ├── ... ``` -------------------------------- ### Implement Host and Port Mapping with a Lambda Expression Source: https://github.com/redis/jedis/blob/master/docs/advanced-usage.md For simpler mapping logic, use a lambda expression with the HostAndPortMapper functional interface. This provides a concise inline implementation for address translation. ```java Map nodeMapping = new HashMap<>(); nodeMapping.put(new HostAndPort("172.18.0.2", 6379), new HostAndPort("my-redis.example.com", 7001)); nodeMapping.put(new HostAndPort("172.18.0.3", 6379), new HostAndPort("my-redis.example.com", 7002)); nodeMapping.put(new HostAndPort("172.18.0.4", 6379), new HostAndPort("my-redis.example.com", 7002)); Set initialNodes = new HashSet<>(); initialNodes.add(new HostAndPort("my-redis.example.com", 7001)); HostAndPortMapper mapper = internalAddress -> nodeMapping.getOrDefault(internalAddress, internalAddress); JedisClientConfig jedisClientConfig = DefaultJedisClientConfig.builder() .user("myuser") .password("mypassword") .hostAndPortMapper(mapper) .build(); RedisClusterClient jedisCluster = RedisClusterClient.builder() .nodes(initialNodes) .clientConfig(jedisClientConfig) .build(); ``` -------------------------------- ### Migrate Jedis Failover Configuration from 6.x to 7.x Source: https://github.com/redis/jedis/blob/master/docs/failover.md Illustrates the structural changes in Jedis failover configuration between versions 6.x and 7.x, highlighting the shift from `UnifiedJedis` with `MultiClusterClientConfig` to `MultiDbClient` with `MultiDbConfig`. ```java // Jedis 6.x JedisClientConfig config = DefaultJedisClientConfig.builder().user("cache").password("secret").build(); ClusterConfig[] clientConfigs = new ClusterConfig[2]; clientConfigs[0] = new ClusterConfig(new HostAndPort("redis-east.example.com", 14000), config); clientConfigs[1] = new ClusterConfig(new HostAndPort("redis-west.example.com", 14000), config); MultiClusterClientConfig.Builder builder = new MultiClusterClientConfig.Builder(clientConfigs); // ... MultiClusterPooledConnectionProvider provider = new MultiClusterPooledConnectionProvider(builder.build()); UnifiedJedis client = new UnifiedJedis(provider); // Jedis 7.x // MultiClusterClientConfig was renamed to MultiDbConfig and MultiDbClient with convenient builder was added MultiDbConfig multiConfig = MultiDbConfig.builder() .database(DatabaseConfig.builder(east, config).weight(1.0f).build()) .database(DatabaseConfig.builder(west, config).weight(0.5f).build()) .build(); // Use MultiDbClient instead of UnifiedJedis MultiDbClient multiDbClient = MultiDbClient.builder().multiDbConfig(multiConfig).build(); ``` -------------------------------- ### Initialize RedisClient for RediSearch Source: https://github.com/redis/jedis/blob/master/docs/redisearch.md Initialize the Jedis client for RediSearch operations using RedisClient. Specify the host and port of your Redis instance. ```java RedisClient client = RedisClient.builder().hostAndPort("localhost", 6379).build(); ``` -------------------------------- ### JedisClientConfig API for RESP3 Source: https://github.com/redis/jedis/blob/master/docs/migration-guides/v7-to-v8.md New default for isAutoNegotiateProtocol() is true. Builder methods resp2(), serverDefaultProtocol(), and autoNegotiateProtocol(boolean) are available on DefaultJedisClientConfig.Builder. ```java public interface JedisClientConfig { // ...existing... default boolean isAutoNegotiateProtocol() { return true; } // NEW, default = true } ``` ```java // New builder methods on DefaultJedisClientConfig.Builder Builder resp2(); // shortcut for protocol(RESP2) Builder serverDefaultProtocol(); // legacy "no HELLO" mode Builder autoNegotiateProtocol(boolean value); ``` -------------------------------- ### Monitor Database Switches with Failover Callbacks Source: https://github.com/redis/jedis/blob/master/docs/failover.md Combine weight changes with a `databaseSwitchListener` to be notified when the active database switches. This allows you to monitor and react to changes triggered by weight adjustments or other failover events. ```java MultiDbClient client = MultiDbClient.builder() .multiDbConfig(config) .databaseSwitchListener(event -> { System.out.println("Active database switched to: " + event.getEndpoint() + " due to: " + event.getReason()); }) .build(); // Change weight - may trigger automatic failback to switch active database client.setWeight(secondary, 5.0f); ``` -------------------------------- ### Define Schema and Create Index with FTCreateParams Source: https://github.com/redis/jedis/blob/master/docs/redisearch.md Create a RediSearch index using FTCreateParams for defining prefixes and filters, and specifying fields with their types and options. ```java client.ftCreate("item-index", FTCreateParams.createParams() .prefix("item:", "product:") .filter("@price>100"), TextField.of("title").weight(5.0), TextField.of("body"), NumericField.of("price") ); ``` -------------------------------- ### Configure Jedis Socket Buffer Size via System Property Source: https://github.com/redis/jedis/blob/master/docs/faq.md Set the input and output socket buffer sizes for Jedis connections using system properties. `jedis.bufferSize` can set both to the same value. This feature requires Jedis 4.2.0 or later. ```properties # Example for setting buffer size # jedis.bufferSize.input=8192 # jedis.bufferSize.output=8192 # or # jedis.bufferSize=8192 ``` -------------------------------- ### Configure advanced SSL/TLS options Source: https://github.com/redis/jedis/blob/master/docs/migration-guides/v5-to-v6.md Use the new `SslOptions` class for advanced SSL/TLS configuration, including custom keystores, truststores, protocol selection, and verification modes. ```java SslOptions sslOptions = SslOptions.builder() .keystore(new File("/path/to/keystore.jks")) .keystorePassword("keystorePassword".toCharArray()) .truststore(new File("/path/to/truststore.jks")) .truststorePassword("truststorePassword".toCharArray()) .sslVerifyMode(SslVerifyMode.FULL) .build(); JedisClientConfig config = DefaultJedisClientConfig.builder() .ssl(true) .sslOptions(sslOptions) .build(); JedisPooled jedis = new JedisPooled("localhost", 6379, config); ``` -------------------------------- ### Run JMH Benchmarks with Maven Source: https://github.com/redis/jedis/blob/master/src/test/jmh/redis/clients/jedis/benchmark/README.md Execute all JMH benchmarks or specific suites using Maven profiles and properties. Ensure the 'jmh' profile is active. ```bash mvn -Pjmh clean test # All benchmarks ``` ```bash mvn -Pjmh test -Djmh.includes="CRC16Benchmark" # Specific suite ``` -------------------------------- ### Update Legacy SSL Configuration to SslOptions Source: https://github.com/redis/jedis/blob/master/docs/migration-guides/v7-to-v8.md Migrate from legacy SSL configuration setters on JedisClientConfig and DefaultJedisClientConfig.Builder to the unified SslOptions API. SslOptions consolidates trust store, key store, verify mode, and protocol selection. ```java // Deprecated on JedisClientConfig: SSLSocketFactory getSslSocketFactory(); SSLParameters getSslParameters(); // (HostnameVerifier was already deprecated) // And the corresponding builder setters: DefaultJedisClientConfig.Builder.ssl(boolean); DefaultJedisClientConfig.Builder.sslSocketFactory(SSLSocketFactory); DefaultJedisClientConfig.Builder.sslParameters(SSLParameters); DefaultJedisClientConfig.Builder.hostnameVerifier(HostnameVerifier); ``` ```java JedisClientConfig config = DefaultJedisClientConfig.builder() .ssl(true) .sslSocketFactory(mySocketFactory) .sslParameters(myParameters) .hostnameVerifier(myVerifier) .build(); ``` ```java SslOptions sslOptions = SslOptions.builder() .truststore(trustStoreFile, trustStorePassword) .keystore(keyStoreFile, keyStorePassword) .sslVerifyMode(SslVerifyMode.FULL) .build(); JedisClientConfig config = DefaultJedisClientConfig.builder() .sslOptions(sslOptions) .build(); ``` -------------------------------- ### Configure Jedis Socket Buffer Size Source: https://github.com/redis/jedis/wiki/FAQ Set the input and output buffer sizes for Jedis sockets using system properties. Available since Jedis 4.2.0. ```properties jedis.bufferSize.input ``` ```properties jedis.bufferSize ``` ```properties jedis.bufferSize.output ``` -------------------------------- ### Adding Databases with DatabaseConfig Source: https://github.com/redis/jedis/blob/master/docs/failover.md This method allows for advanced configurations when adding a new database endpoint, including custom health checks and connection pool settings. ```APIDOC ## Adding Databases with DatabaseConfig This method provides maximum flexibility for advanced configurations including custom health check strategies, connection pool settings, and other database-specific options. ```java // Create a fully configured DatabaseConfig HostAndPort newEndpoint = new HostAndPort("redis-new.example.com", 6379); JedisClientConfig clientConfig = DefaultJedisClientConfig.builder() .user("cache").password("secret").build(); DatabaseConfig databaseConfig = DatabaseConfig.builder(newEndpoint, clientConfig) .weight(1.5f).connectionPoolConfig(poolConfig).healthCheckEnabled(true).build(); // Add the database to the client client.addDatabase(databaseConfig); ``` ``` -------------------------------- ### Clone Jedis GitHub Project Source: https://github.com/redis/jedis/wiki/Getting-started Clone the Jedis GitHub repository to build from source. ```git git clone git://github.com/xetorthio/jedis.git ``` -------------------------------- ### Configure MultiDbClient with Failover Callback Source: https://github.com/redis/jedis/blob/master/docs/failover.md Register a custom failover reporter with the MultiDbClient builder. This ensures your custom logic is executed upon database switch events. ```java FailoverReporter reporter = new FailoverReporter(); MultiDbClient client = MultiDbClient.builder() .databaseSwitchListener(reporter) .build(); ``` -------------------------------- ### Define Schema and Create Index with IndexDefinition Source: https://github.com/redis/jedis/blob/master/docs/redisearch.md Define a RediSearch schema with text and numeric fields, and create an index using IndexDefinition. The definition specifies prefixes and a filter. ```java Schema sc = new Schema() .addTextField("title", 5.0) .addTextField("body", 1.0) .addNumericField("price"); IndexDefinition def = new IndexDefinition() .setPrefixes(new String[]{"item:", "product:"}) .setFilter("@price>100"); client.ftCreate("item-index", IndexOptions.defaultOptions().setDefinition(def), sc); ```