DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • While Performing Dependency Selection, I Avoid the Loss Of Sleep From Node.js Libraries' Dangers
  • Develop a Reverse Proxy With Caching in Go
  • Scaling in Practice: Caching and Rate-Limiting With Redis and Next.js
  • 5 Best Node.js Practices to Develop Scalable and Robust Applications

Trending

  • Caching 101: Theory, Algorithms, Tools, and Best Practices
  • Modern Test Automation With AI (LLM) and Playwright MCP
  • The Perfection Trap: Rethinking Parkinson's Law for Modern Engineering Teams
  • Advancing Robot Vision and Control
  1. DZone
  2. Coding
  3. JavaScript
  4. Tutorial: Working with Node.js and Redis (Expire and TTL)

Tutorial: Working with Node.js and Redis (Expire and TTL)

By 
Chad Lung user avatar
Chad Lung
·
Apr. 21, 12 · Interview
Likes (0)
Comment
Save
Tweet
Share
49.6K Views

Join the DZone community and get the full member experience.

Join For Free

In my previous post I showed you how to install and use Redis with Node.js. Today I’m going to take that a step further and walk through some of the things you can do with node_redis using Redis’s TTL and EXPIRE commands.

Note: If you haven’t gone through my previous article make sure to do that now as I’ll assume you have Node.js and Redis up and running.

Create a new folder and put a new text file in it called: app.js

Inside the app.js file we will add some simple code to set a value that doesn’t have a time to live (or expiration on it):

var redis = require("redis")
    , client = redis.createClient();
 
client.on("error", function (err) {
    console.log("Error " + err);
});
 
client.on("connect", runSample);
 
function runSample() {
    // Set a value
    client.set("string key", "Hello World", function (err, reply) {
        console.log(reply.toString());
    });
    // Get a value
    client.get("string key", function (err, reply) {
        console.log(reply.toString());
    });
}

When we connect to Redis and everything is ready the runSample function is called which in turn sets a value and then reads it back.

Expected output:

OK
Hello World

Lets set a timeout on a value using the EXPIRE command and see what happens. Replace the original code with this:

var redis = require('redis')
    , client = redis.createClient();
 
client.on('error', function (err) {
    console.log('Error ' + err);
});
 
client.on('connect', runSample);
 
function runSample() {
    // Set a value with an expiration
    client.set('string key', 'Hello World', redis.print);
    // Expire in 3 seconds
    client.expire('string key', 3);
 
    // This timer is only to demo the TTL
    // Runs every second until the timeout
    // occurs on the value
    var myTimer = setInterval(function() {
        client.get('string key', function (err, reply) {
            if(reply) {
                console.log('I live: ' + reply.toString());
            } else {
                clearTimeout(myTimer);
                console.log('I expired');
                client.quit();
            }
        });
    }, 1000);
}

Note: Be aware that the timer I use is just to demo the EXPIRE, you should be very careful about using timers in production Nodejs projects.

Run the program. Expected results:

Reply: OK
I live: Hello World
I live: Hello World
I live: Hello World
I expired

Now we will check to see how much time a value has left before it expires:

var redis = require('redis')
    , client = redis.createClient();
 
client.on('error', function (err) {
    console.log('Error ' + err);
});
 
client.on('connect', runSample);
 
function runSample() {
    // Set a value
    client.set('string key', 'Hello World', redis.print);
    // Expire in 3 seconds
    client.expire('string key', 3);
 
    // This timer is only to demo the TTL
    // Runs every second until the timeout
    // occurs on the value
    var myTimer = setInterval(function() {
        client.get('string key', function (err, reply) {
            if(reply) {
                console.log('I live: ' + reply.toString());
                client.ttl('string key', writeTTL);
            } else {
                clearTimeout(myTimer);
                console.log('I expired');
                client.quit();
            }
        });
    }, 1000);
}
 
function writeTTL(err, data) {
    console.log('I live for this long yet: ' + data);
}

Run the program. Expected results:

Reply: OK
I live: Hello World
I live for this long yet: 2
I live: Hello World
I live for this long yet: 1
I live: Hello World
I live for this long yet: 0
I expired
Time to live Node.js Redis (company)

Published at DZone with permission of Chad Lung, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • While Performing Dependency Selection, I Avoid the Loss Of Sleep From Node.js Libraries' Dangers
  • Develop a Reverse Proxy With Caching in Go
  • Scaling in Practice: Caching and Rate-Limiting With Redis and Next.js
  • 5 Best Node.js Practices to Develop Scalable and Robust Applications

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!