Redis is an in-memory data structure store that is commonly used as a database, cache, and message broker. TypeScript is a statically-typed superset of JavaScript that adds type annotations and other features to improve code quality and maintainability. In this tutorial, we will explore how to use Redis with TypeScript.

Before we begin, make sure you have the following installed on your machine:

  • Node.js
  • TypeScript
  • Redis

Once you have these dependencies installed, follow the steps below to get started with Redis and TypeScript.


Install Redis and connect to it

To get started, we need to install the Redis client library for Node.js. You can install it by running the following command:

npm install redis

Once you have installed the Redis client, you can connect to Redis using the following code:

import redis from "redis";

const client = redis.createClient({
    host: "localhost",
    port: 6379
});

client.on("connect", () => {
    console.log("Connected to Redis");
});

client.on("error", (error) => {
    console.error(error);
});


This code creates a Redis client and connects to Redis running on the default host and port. If Redis is running on a different host or port, you can change the values accordingly.


Store and retrieve data

Once you have connected to Redis, you can store and retrieve data using the Redis client. Redis supports a wide range of data types, including strings, hashes, lists, sets, and more.

To store a value in Redis, you can use the set method:

client.set("key", "value", (error) => {
    if (error) {
        console.error(error);
    } else {
        console.log("Value stored in Redis");
    }
});

This code stores a value "value" with the key "key" in Redis. The set method takes a callback function that is called once the value is stored in Redis.


To retrieve a value from Redis, you can use the get method:

client.get("key", (error, value) => {
    if (error) {
        console.error(error);
    } else {
        console.log("Value retrieved from Redis:", value);
    }
});

This code retrieves the value associated with the key "key" from Redis. The get method takes a callback function that is called with the retrieved value.


Expire keys

Redis allows you to set an expiration time on a key, after which the key will be automatically deleted from Redis. This can be useful for caching data that is only valid for a limited time.

To set an expiration time on a key, you can use the expire method:

client.set("key", "value", (error) => {
    if (error) {
        console.error(error);
    } else {
        console.log("Value stored in Redis");
        client.expire("key", 60, (error) => {
            if (error) {
                console.error(error);
            } else {
                console.log("Key will expire in 60 seconds");
            }
        });
    }
});

This code sets an expiration time of 60 seconds on the key "key". After 60 seconds, the key will be automatically deleted from Redis.


Use Redis transactions

Redis transactions allow you to group multiple commands together and execute them atomically. This ensures that either all the commands are executed, or none of them are executed.

To use Redis transactions, you can use the multi method to create a new transaction, and then use the exec method to execute the transaction.

Here is an example of a Redis transaction in TypeScript:

const multi = client.multi();

multi.set("key1", "value1");
multi.set("key2", "value2");

multi.exec((error, replies) => {
    if (error) {
        console.error(error);
    } else {
        console.log("Transaction completed");
    }
});

This code creates a new Redis transaction using the multi method, sets two keys ("key1" and "key2") with their respective values, and then executes the transaction using the exec method. If any of the commands fail, the transaction is rolled back and none of the changes are applied.


Use Redis pub/sub

Redis pub/sub allows you to publish messages to channels and subscribe to channels to receive messages. This can be useful for implementing real-time messaging and notifications.

To use Redis pub/sub, you can create a publisher and a subscriber using the createClient method, and then use the publish and subscribe methods to send and receive messages:

const publisher = redis.createClient();
const subscriber = redis.createClient();

subscriber.on("message", (channel, message) => {
    console.log(`Received message ${message} on channel ${channel}`);
});

subscriber.subscribe("channel");

publisher.publish("channel", "hello world");

This code creates a publisher and a subscriber, subscribes to the channel "channel", sends a message "hello world" using the publisher, and then receives the message using the subscriber.


Conclusion

In this tutorial, we have explored how to use Redis with TypeScript. We have covered the basics of storing and retrieving data, setting expiration times, using transactions, and implementing pub/sub messaging. Redis is a powerful tool that can be used in a variety of applications, and TypeScript provides additional safety and maintainability to your code.