Skip to content

Redis with Jedis (Java)

Uses Jedis 8.0 (JedisPooled). The code is an ordinary application for the original database; nothing in it knows about MachNoSQL.

redis://:secret@redis.example.com:6379/0
redis://:secret@machnosql.example.com:6379/0

The address comes from the environment variable REDIS_URL, so switching to MachNoSQL changes configuration only.

Terminal window
export REDIS_URL='redis://:secret@machnosql.example.com:6379/0'
mvn -q compile exec:java

The program as it is kept and tested in the Mach Database NoSQL repository; highlighted lines read the connection setting.

src/main/java/example/App.java
// Cache, counter, session and leaderboard on Redis, unchanged on MachNoSQL.
package example;
import java.net.URI;
import java.util.Map;
import redis.clients.jedis.AbstractTransaction;
import redis.clients.jedis.JedisPooled;
import redis.clients.jedis.params.SetParams;
public final class App {
public static void main(String[] args) {
try (JedisPooled jedis = new JedisPooled(URI.create(System.getenv("REDIS_URL")))) {
jedis.set("cache:home", "<html>...</html>", SetParams.setParams().ex(60));
System.out.println("cached: " + jedis.get("cache:home") + " ttl: " + jedis.ttl("cache:home"));
System.out.println("views: " + jedis.incr("views:home"));
jedis.hset("session:42", Map.of("user", "ada", "cart_items", "3"));
System.out.println("session: " + jedis.hgetAll("session:42"));
jedis.zadd("leaderboard", Map.of("ada", 120.0, "linus", 95.0, "grace", 130.0));
System.out.println("top: " + jedis.zrevrangeWithScores("leaderboard", 0, 2));
try (AbstractTransaction tx = jedis.multi()) {
tx.incr("orders:count");
tx.lpush("orders:recent", "order-1001");
tx.ltrim("orders:recent", 0, 99);
System.out.println("pipeline: " + tx.exec());
}
}
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example.machnosql</groupId>
<artifactId>redis-jedis-example</artifactId>
<version>1.0</version>
<properties>
<maven.compiler.release>21</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<exec.mainClass>example.App</exec.mainClass>
</properties>
<dependencies>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>8.0.2</version>
</dependency>
</dependencies>
</project>