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
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Stateless JWT Auth Microservice Architecture With Spring Boot 3 and Redis Sentinel
  • Stop Writing Dialect-Specific SQL: A Unified Query Builder for Node.js
  • Lambda-Driven API Design: Building Composable Node.js Endpoints With Functional Primitives
  • Optimizing High-Volume REST APIs Using Redis Caching and Spring Boot (With Load Testing Code)

Trending

  • Managing, Updating, and Organizing Agent Skills
  • Why Your AI Agent's Logs Aren't Earning Trust
  • Prompt Injection Is Real, So I Built a Python Firewall for LLM Pipelines
  • Give Your AI Assistant Long-Term Memory With perag
  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
50.1K 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. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Stateless JWT Auth Microservice Architecture With Spring Boot 3 and Redis Sentinel
  • Stop Writing Dialect-Specific SQL: A Unified Query Builder for Node.js
  • Lambda-Driven API Design: Building Composable Node.js Endpoints With Functional Primitives
  • Optimizing High-Volume REST APIs Using Redis Caching and Spring Boot (With Load Testing Code)

Partner Resources

×

Comments

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

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook