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.
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.
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.
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:
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.
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.
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.
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.
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'))
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 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')
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)
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.
Install LogRocket via npm or script tag. LogRocket.init()
must be called client-side, not
server-side
$ npm i --save logrocket // Code: import LogRocket from 'logrocket'; LogRocket.init('app/id');
// Add to your HTML: <script src="https://cdn.lr-ingest.com/LogRocket.min.js"></script> <script>window.LogRocket && window.LogRocket.init('app/id');</script>
Hey there, want to help make our blog better?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowBuild scalable admin dashboards with Filament and Laravel using Form Builder, Notifications, and Actions for clean, interactive panels.
Break down the parts of a URL and explore APIs for working with them in JavaScript, parsing them, building query strings, checking their validity, etc.
In this guide, explore lazy loading and error loading as two techniques for fetching data in React apps.
Deno is a popular JavaScript runtime, and it recently launched version 2.0 with several new features, bug fixes, and improvements […]