Redis with Lettuce (Java)
Uses Lettuce 7.9. The code is an ordinary application for the original database; nothing in it knows about MachNoSQL.
The only change
Section titled “The only change”redis://:secret@redis.example.com:6379/0redis://:secret@machnosql.example.com:6379/0The address comes from the environment variable REDIS_URL, so switching to MachNoSQL changes configuration only.
export REDIS_URL='redis://:secret@machnosql.example.com:6379/0'mvn -q compile exec:javaSource
Section titled “Source”The program as it is kept and tested in the Mach Database NoSQL repository; highlighted lines read the connection setting.
// Cache, counter, session and leaderboard on Redis, unchanged on MachNoSQL.package example;
import io.lettuce.core.RedisClient;import io.lettuce.core.ScoredValue;import io.lettuce.core.SetArgs;import io.lettuce.core.api.StatefulRedisConnection;import io.lettuce.core.api.sync.RedisCommands;import java.util.Map;
public final class App { public static void main(String[] args) { RedisClient client = RedisClient.create(System.getenv("REDIS_URL")); try (StatefulRedisConnection<String, String> connection = client.connect()) { RedisCommands<String, String> redis = connection.sync();
redis.set("cache:home", "<html>...</html>", SetArgs.Builder.ex(60)); System.out.println("cached: " + redis.get("cache:home") + " ttl: " + redis.ttl("cache:home"));
System.out.println("views: " + redis.incr("views:home"));
redis.hset("session:42", Map.of("user", "ada", "cart_items", "3")); System.out.println("session: " + redis.hgetall("session:42"));
redis.zadd("leaderboard", ScoredValue.just(120, "ada"), ScoredValue.just(95, "linus"), ScoredValue.just(130, "grace")); System.out.println("top: " + redis.zrevrangeWithScores("leaderboard", 0, 2));
redis.multi(); redis.incr("orders:count"); redis.lpush("orders:recent", "order-1001"); redis.ltrim("orders:recent", 0, 99); System.out.println("pipeline: " + redis.exec()); } finally { client.shutdown(); } }}<?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-lettuce-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>io.lettuce</groupId> <artifactId>lettuce-core</artifactId> <version>7.9.0.RELEASE</version> </dependency> </dependencies></project>