Skip to content

Redis with ioredis (Node.js)

Uses ioredis 6.0. 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'
npm install
npm start

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

app.js
// Cache, counter, session and leaderboard on Redis, unchanged on MachNoSQL.
import Redis from "ioredis";
const redis = new Redis(process.env.REDIS_URL);
await redis.set("cache:home", "<html>...</html>", "EX", 60);
console.log("cached:", await redis.get("cache:home"), "ttl:", await redis.ttl("cache:home"));
console.log("views:", await redis.incr("views:home"));
await redis.hset("session:42", { user: "ada", cart_items: 3 });
console.log("session:", await redis.hgetall("session:42"));
await redis.zadd("leaderboard", 120, "ada", 95, "linus", 130, "grace");
console.log("top:", await redis.zrevrange("leaderboard", 0, 2, "WITHSCORES"));
const results = await redis
.multi()
.incr("orders:count")
.lpush("orders:recent", "order-1001")
.ltrim("orders:recent", 0, 99)
.exec();
console.log("pipeline:", results);
redis.disconnect();
package.json
{
"name": "machnosql-example-ioredis",
"private": true,
"type": "module",
"scripts": { "start": "node app.js" },
"dependencies": { "ioredis": "^6.0.0" }
}