Wisdom Ekpot A student of Ibom Metropolitan Polytechnic studying computer engineering, Wisdom has been writing JavaScript for two years, focusing on Vue.js, Angular, and Express.js.

Using Redis in Deno

3 min read 1055

Using Redis in Deno

A cache is a temporary data store where information is kept for later use. Implementing a caching system can help speed up your Deno application because it takes less time to fetch resources.

In this tutorial, we’ll explore the concept of caching data and show you how to integrate Redis features using Deno.

What is Deno?

Deno is a modern, secure runtime for JavaScript and TypeScript that uses the V8 engine. Deno comes with built-in support for TypeScript, meaning that you don’t need to write extra webpack configuration to set up TypeScript in your app.

Deno adopts security by default, which means it disallows file, network, and environment access unless you explicitly allow it.

What is Redis?

Redis is a blazing-fast, in-memory data structure project for implementing distributed, in-memory key–value databases with optional durability. Redis can be used as a caching system and also as a message blocker.

Just like a database, Redis supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, and streams. Basically, Redis uses the RAM to store data, which is very fast. However, if the server is rebooted, the values will be lost unless the Redis persistence, which performs point-in-time snapshots of your dataset at specified intervals, is enabled.

How to use Redis with Deno

Before you start writing Deno code, you have to install Redis on your local machine.

To install Redis on a Mac, you can use Homebrew by running this command:

brew install redis

After installing Redis, run it as a service on your local machine:

brew services start redis

If you want to stop the Redis service, run:

We made a custom demo for .
No really. Click here to check it out.

brew services stop redis

To restart Redis, run:

brew services restart redis

To confirm that Redis is correctly running on our local machine, run:

redis-cli ping

If this command returns PONG on the terminal, then you’re good to go.

The next step is to confirm that Deno is properly installed on your local machine. Open up your terminal and type the following:

deno --version

If this displays the version of deno , V8, and TypeScript, then you’re good to go. Otherwise, you can install it using Homebrew:

brew install deno

You can now create a directory for your project. We’ll be testing out the Redis features in our redis.ts file.

Creating a Redis connection

Whenever you want to use Redis in a project, the first step is to create a Redis connection. By default, Redis runs on port 6379 .

To create a connection, add the following to your redis.ts file:

import { connect } from "https://denopkg.com/keroxp/deno-redis/mod.ts";
const redis = await connect({
  hostname: "127.0.0.1",
  port: 6379
});
console.log(await redis.ping())

Use the connect method to connect to the Redis CLI using the port specified. To test the Redis connection, use the redis.ping() method, which returns a promise that you have to await.

To run the application, you must first pass in the --allow-net flag to allow network privileges. Run deno run--allow-net redis.ts to start up the application. This will log PONG on your console, which indicates that the connection was successful.

Setting key-value pairs

You can store and retrieve data in Redis by using the set and get methods. The set method takes in two parameters: the name and the value to be stored.

await redis.set('name', 'Wisdom Ekpot');
let name = await redis.get('name')
console.log(name)

You should always await the redis methods because it always returns a promise.

Storing data

You can store data in Redis using provided methods, such as hmset.

hmset is used to set the value of a field that is specified to the stored key of the hash. This method overwrites any existing field. If the key does not exist, a new key is created holding the hash.

You can write a simple function to add to Redis:

let add = async(key:string,name:string,email:string) => {
    let addPerson = await redis.hmset(key, {
        'name': name,
        'email': email
    })
    return addPerson
}
console.log(await add('key1','Wisdom Ekpot','[email protected]'))

This will add a new item to Redis with the key of key1 and return OK on the console.

Get data using the key

hgetall returns all the fields and values of the hash for a particular key.

You can get the data stored in Redis using the key:

let getParticular = async (id:string) => {
   return await redis.hgetall(id);
}
console.log(await getParticular('key1'))

Deleting an item with a key

You can use the del method to delete a key, which requires the key name as a parameter:

let deleteKey = async (id:string) => {
    let deleted = await redis.del(id);
    return deleted
}

console.log(await deleteKey('key1'))

Redis clusters and config

Redis cluster is a mechanism that automatically shreds data across multiple Redis nodes. The Redis meet method connects multiple Redis nodes with the cluster mode enabled.

To create a new cluster, use the redis.meet() method, which takes in the port as a param:

await redis.cluster_meet("127.0.0.1", <port>);

You can now use the redis.nodes method to list all created nodes:

 await redis.cluster_nodes();

Now, this won’t actually work because clusters are disabled by default. You’ll likely encounter this error: this instance has cluster support disabled.

Redis enables you to check your configs. You can check whether clusters are enabled like this:

let config = await redis.config_get("cluster-enabled");
console.log(config)

This will return [ "cluster-enabled", "no" ] on the console. To enable it, use the config_set method, which takes in the config_name and the value of the config.

So to enable clusters, you can do this:

await redis.config_set('cluster-enabled', 'yes')

Redis raw command

Deno also enables you to run raw Redis commands. All raw commands have to pass through the executor class. This command returns replies as promises, so it’s always a good idea to await a request.

await redis.executor.exec("SET", "name", "Wisdom Ekpot")
let get = await redis.executor.exec("GET", "name");
console.log(get)

Conclusion

Redis offers a whole lot of features designed to help you scale your application. Integrating Redis into your Deno application can make it much, much faster since calling data from the cache is extremely efficient.

The source code used in this tutorial is available on GitHub.

: Full visibility into your web apps

LogRocket is a frontend application monitoring solution that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.

In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page apps.

.
Wisdom Ekpot A student of Ibom Metropolitan Polytechnic studying computer engineering, Wisdom has been writing JavaScript for two years, focusing on Vue.js, Angular, and Express.js.

Leave a Reply