Redis Command: GETEX

Summary

Command NameGETEX
UsageGet string value and set expire
Group string
ACL Category@write
@string
@fast
Time ComplexityO(1)
FlagWRITE
FAST
Arity-2

Signature

GETEX <key> [ EX <seconds> | PX <milliseconds> | EXAT <unix_timestamp_in_seconds> | PXAT <unix_timestamp_in_milliseconds> | PERSIST ]

Usage

Get the string value saved for the key and additionally set the expiration time for the key.

Notes

  • This command can work without the expiration time part, in that case, it will behave like the “GET” command.

Arguments

Here is the description of what each part of the MGET command means in the above signature-

ParameterGroupDescriptionNameTypeOptional
<key>The key name.keykey
EX <seconds>expirationExpire duration in seconds (after how many seconds the key will expire).secondsintegerTrue
PX <milliseconds>expirationExpire duration in milliseconds (after how many milliseconds the key will expire).millisecondsintegerTrue
EXAT <unix_timestamp_in_seconds>expirationExpire time as UNIX timestamp in seconds (at what UNIX timestamp the key will expire).unix-time-secondsunix-timeTrue
PXAT <unix_timestamp_in_milliseconds>expirationExpire time as UNIX timestamp in seconds (at what UNIX timestamp the key will expire).unix-time-millisecondsunix-timeTrue
PERSISTexpirationGet rid of the expire time of the key (if there was any expire time associated with the key).persistpure-tokenTrue

Return Value

List of values is returned for the provided keys.

Return valueCase for the return valueType
The value of the keyWhen the key exists and is of type string.string
<nil>When the key does not exist.null

Examples

Here are a few examples of the GETEX command usage-

# Redis GETEX command examples


127.0.0.1:6379> set sitename "bigboxcode"
OK

# Use the command without any expire part
127.0.0.1:6379> getex sitename
"bigboxcode"

# Check TTL, and we get -1 as no expire time is set yet
127.0.0.1:6379> ttl sitename
(integer) -1

# Set 10 seconds expire time while getting get value back
127.0.0.1:6379> getex sitename ex 10
"bigboxcode"

# Check TTL now, there should be some TTL(if checked within 10 seconds)
127.0.0.1:6379> ttl sitename
(integer) 6

# Check after 10 seconds. The key has expired 
127.0.0.1:6379> get sitename
(nil)

# Set value for a key
127.0.0.1:6379> set sitename bigboxcode
OK

# Set 120 seconds expire time while getting the value
127.0.0.1:6379> getex sitename ex 120
"bigboxcode"

# Check TTL, there should be some TTL (if checked within 120 seconds)
127.0.0.1:6379> ttl sitename
(integer) 117

# Pass persist to remove the expire time from the key
127.0.0.1:6379> getex sitename persist
"bigboxcode"

# Check the TTL now, there will be no TTL as the expire time is removed
127.0.0.1:6379> ttl sitename
(integer) -1

# Try getting value and set expire time for a key that does not exist. We get nil as the key does not exist
127.0.0.1:6379> getex wrongkey ex 360
(nil)

Notes

  • If the key does not exist then the “GETEX” command will return (nil).

Code Implementations

Here are the usage examples of the Redis GETEX command in different programming languages.

// getex.go

// Redis MGET command example in Golang

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/redis/go-redis/v9"
)

var rdb *redis.Client
var ctx context.Context

func init() {
	rdb = redis.NewClient(&redis.Options{
		Addr:     "localhost:6379",
		Username: "default",
		Password: "",
		DB:       0,
	})

	ctx = context.Background()
}

func main() {

	// Command: set sitename "bigboxcode"
	// Result: OK
	commandResult, err := rdb.Set(ctx, "sitename", "my first value", 0).Result()

	if err != nil {
		fmt.Println("Can not set sitename" + err.Error())
	}

	fmt.Println("Set value of 'sitename' to 'some value' | Result: " + commandResult)


	// Use the command without any expire part
	// Command: getex sitename
	// Result: "bigboxcode"
	commandResult, err = rdb.GetEx(ctx, "sitename", 0).Result()

	if err != nil {
		fmt.Println("Can not read sitename" + err.Error())
	}

	fmt.Println("Read 'sitename' using GETEX | Result: " + commandResult)


	// Check TTL, and we get -1 as no expire time is set yet
	// Command: ttl sitename
	// Result: (integer) -1
	ttl, err := rdb.TTL(ctx, "sitename").Result()

	if err != nil {
		fmt.Println("Can not get TTL of sitename" + err.Error())
	}

	fmt.Printf("Check TTL of sitename | Result: %v\n", ttl)


	// Set 10 seconds expire time while getting get value back
	// Command: getex sitename ex 10
	// Result: "bigboxcode"
	commandResult, err = rdb.GetEx(ctx, "sitename", 10 * time.Second).Result()

	if err != nil {
		fmt.Println("Can not read sitename" + err.Error())
	}

	fmt.Println("Read 'sitename' using GETEX and set 10sec expire | Result: " + commandResult)


	// Check TTL now, there should be some TTL(if checked within 10 seconds)
	// Command: ttl sitename
	// Result: (integer) 6
	ttl, err = rdb.TTL(ctx, "sitename").Result()

	if err != nil {
		fmt.Println("Can not get TTL of sitename" + err.Error())
	}

	fmt.Printf("Check TTL of sitename after setting 10s expire | Result: %v\n", ttl)

	// Sleep for 10 seconds
	fmt.Println("Sleep for 10 seconds")
	time.Sleep(10 * time.Second)


	// Check after 10 seconds. The key has expired
	// Command: get sitename
	// Result: (nil)
	commandResult, err = rdb.Get(ctx, "sitename").Result()

	if err != nil {
		fmt.Println("Can not read sitename | Error: " + err.Error())
	}

	fmt.Println("Read 'sitename' using GETEX after seting 10sec expire and 10s sleep  | Result: " + commandResult)


	// Set value for a key
	// Command: set sitename bigboxcode
	// Result: OK
	commandResult, err = rdb.Set(ctx, "sitename", "bigboxcode", 0).Result()

	if err != nil {
		fmt.Println("Can not set sitename | Error: " + err.Error())
	}

	fmt.Println("Set value of 'sitename' to 'bigboxcode' | Result: " + commandResult)


	// Set 120 seconds expire time while getting the value
	// Command: getex sitename ex 120
	// Result: "bigboxcode"
	commandResult, err = rdb.GetEx(ctx, "sitename", 120 * time.Second).Result()

	if err != nil {
		fmt.Println("Can not read sitename" + err.Error())
	}

	fmt.Println("Read 'sitename' using GETEX and set 120sec expire | Result: " + commandResult)


	// Check TTL, there should be some TTL (if checked within 120 seconds)
	// Command: ttl sitename
	// Result: (integer) 117
	ttl, err = rdb.TTL(ctx, "sitename").Result()

	if err != nil {
		fmt.Println("Can not get TTL of sitename" + err.Error())
	}

	fmt.Printf("Check TTL of sitename after setting 120s expire | Result: %v\n", ttl)


	// Set 100 milliseconds expire time while getting the value
	// Command: getex sitename PX 100
	// Result: "bigboxcode"
	commandResult, err = rdb.GetEx(ctx, "sitename", 10_000 * time.Millisecond).Result()

	if err != nil {
		fmt.Println("Can not read sitename" + err.Error())
	}

	fmt.Println("Read 'sitename' using GETEX and set 100ms expire | Result: " + commandResult)

	
	// Check TTL, there should be some TTL (if checked within 120 seconds)
	// Command: ttl sitename
	// Result: (integer) 117
	ttl, err = rdb.TTL(ctx, "sitename").Result()

	if err != nil {
		fmt.Println("Can not get TTL of sitename" + err.Error())
	}

	fmt.Printf("Check TTL of sitename after setting 100ms expire | Result: %v\n", ttl)


	// Pass persist to remove the expire time from the key
	// Command: getex sitename persist
	// Result: "bigboxcode"
	commandResult, err = rdb.GetEx(ctx, "sitename", 0).Result()

	if err != nil {
		fmt.Println("Can not read sitename" + err.Error())
	}

	fmt.Println("Read 'sitename' using GETEX with PERSIST | Result: " + commandResult)


	// Check the TTL now, there will be no TTL as the expire time is removed
	// Command: ttl sitename
	// Result: (integer) -1
	ttl, err = rdb.TTL(ctx, "sitename").Result()

	if err != nil {
		fmt.Println("Can not get TTL of sitename" + err.Error())
	}

	fmt.Printf("Check TTL of sitename after using PERSIST | Result: %v\n", ttl)


	// Try getting value and set expire time for a key that does not exist. We get nil as the ke does not exist
	// Command: getex wrongkey ex 360
	// Result: (nil)
	commandResult, err = rdb.GetEx(ctx, "wrongkey", 360 * time.Second).Result()

	if err != nil {
		fmt.Println("Can not read wrongkey" + err.Error())
	}

	fmt.Println("Read 'wrongkey' using GETEX with 360s  | Result: " + commandResult)
}

Output:

Set value of 'sitename' to 'some value' | Result: OK
Read 'sitename' using GETEX | Result: my first value
Check TTL of sitename | Result: -1ns

Read 'sitename' using GETEX and set 10sec expire | Result: my first value
Check TTL of sitename after setting 10s expire | Result: 10s
Sleep for 10 seconds
Can not read sitename | Error: redis: nil
Read 'sitename' using GETEX after seting 10sec expire and 10s sleep  | Result:

Set value of 'sitename' to 'bigboxcode' | Result: OK
Read 'sitename' using GETEX and set 120sec expire | Result: bigboxcode
Check TTL of sitename after setting 120s expire | Result: 2m0s

Read 'sitename' using GETEX and set 100ms expire | Result: bigboxcode
Check TTL of sitename after setting 100ms expire | Result: 10s

Read 'sitename' using GETEX with PERSIST | Result: bigboxcode
Check TTL of sitename after using PERSIST | Result: -1ns

Can not read wrongkeyredis: nil
Read 'wrongkey' using GETEX with 360s  | Result:

Notes

  • Use method “GetEx” for using the Redis GETEX command.
  • Signature of the “GetEx” function in the implementation is – func (c cmdable) GetEx(ctx context.Context, key string, expiration time.Duration) *StringCmd
  • Pass the “expiration” param to replicate the “EX” option, we can pass the value as – 1 * time.Second.
  • Pass the “expiration” param to replicate “PX” option, we have to pass it like – 1 * time.Millisecond.
  • Pass 0(zero) for the “expiration” parameter to use the “PERSIST” option for expiration.
// getex.js

// Redis GETEX command example in JavaScript(NodeJS)

import { createClient } from 'redis';

// Create redis client
const redisClient = createClient({
    url: 'redis://default:@localhost:6379'
});

redisClient.on('error', err => console.log('Error while connecting to Redis', err));

// Connect Redis client
await redisClient.connect();

/**
 * Command: set sitename "bigboxcode"
 * Result: OK
 */
let commandResult = await redisClient.set('sitename', 'bigboxcode');

console.log(`Command: set sitename "bigboxcode" | Result: ${commandResult}`);


/**
 * Use the command without any expire part
 * 
 * Command: getex sitename
 * Result: "bigboxcode"
 */
commandResult = await redisClient.getEx('sitename', {});

console.log(`Command: getex sitename | Result: ${commandResult}`);


/**
 * Check TTL, and we get -1 as no expire time is set yet
 * 
 * Command: ttl sitename
 * Result: (integer) -1
 */
commandResult = await redisClient.ttl('sitename');

console.log("Command: ttl sitename | Result : " + commandResult);


/**
 * Set 10 seconds expire time while getting get value back
 * 
 * Command: getex sitename ex 10
 * Result: "bigboxcode"
 */
commandResult = await redisClient.getEx('sitename', {EX: 10});

console.log(`Command: getex sitename ex 10 | Result: ${commandResult}`);

/**
 * Check TTL now, there should be some TTL(if checked within 10 seconds)
 * 
 * Command: ttl sitename
 * Result: (integer) 6
 */
commandResult = await redisClient.ttl('sitename');

console.log("Command: ttl sitename | Result : " + commandResult);


// Sleep for 10 second
console.log("Sleep for 10 sec")
await new Promise(r => setTimeout(r, 10_000));


/**
 * Check after 10 seconds. The key has expired
 * 
 * Command: get sitename
 * Result: (nil)
 */
commandResult = await redisClient.get('sitename');

console.log("Command: get sitename | Result : " + commandResult);


/**
 * Set value for a key
 * 
 * Command: set sitename bigboxcode
 * Result: OK
 */
commandResult = await redisClient.set('sitename', 'bigboxcode');

console.log("Command: ttl sitename | Result : " + commandResult);


/**
 * Set 120 seconds expire time while getting the value
 * 
 * Command: getex sitename ex 120
 * Result: "bigboxcode"
 */
commandResult = await redisClient.getEx('sitename', {EX: 120});

console.log(`Command: getex sitename ex 120 | Result: ${commandResult}`);


/**
 * Check TTL, there should be some TTL (if checked within 120 seconds)
 * 
 * Command: ttl sitename
 * Result: (integer) 117
 */
commandResult = await redisClient.ttl('sitename');

console.log("Command: ttl sitename | Result : " + commandResult);


/**
 * Pass persist to remove the expire time from the key
 * 
 * Command: getex sitename persist
 * Result: "bigboxcode"
 */
commandResult = await redisClient.getEx('sitename', {PERSIST: true});

console.log(`Command: getex sitename persist | Result: ${commandResult}`);


/**
 * Check the TTL now, there will be no TTL as the expire time is removed
 * 
 * Command: ttl sitename
 * Result: (integer) -1
 */
commandResult = await redisClient.ttl('sitename');

console.log("Command: ttl sitename | Result : " + commandResult);


/**
 * et 120 seconds expire time while getting the value
 * 
 * Command: getex sitename PX 10000
 * Result: "bigboxcode"
 */
commandResult = await redisClient.getEx('sitename', {PX: 10000});

console.log(`Command: getex sitename PX 10000 | Result: ${commandResult}`);


/**
 * Check the TTL now, there will be no TTL as the expire time is removed
 * 
 * Command: ttl sitename
 * Result: (integer) -1
 */
commandResult = await redisClient.ttl('sitename');

console.log("Command: ttl sitename | Result : " + commandResult);


/**
 * Try getting value and set expire time for a key that does not exist. We get nil as the ke does not exist
 * 
 * Command: getex wrongkey ex 360
 * Result: (nil)
 */
commandResult = await redisClient.getEx('wrongkey', {EX: 360});

console.log(`Command: getex wrongkey ex 360 | Result: ${commandResult}`);


process.exit(0);

Output:

Command: set sitename "bigboxcode" | Result: OK
Command: getex sitename | Result: bigboxcode
Command: ttl sitename | Result : -1

Command: getex sitename ex 10 | Result: bigboxcode
Command: ttl sitename | Result : 10

Sleep for 10 sec
Command: get sitename | Result : null

Command: set sitename bigboxcode | Result : OK

Command: getex sitename ex 120 | Result: bigboxcode
Command: ttl sitename | Result : 120

Command: getex sitename persist | Result: bigboxcode
Command: ttl sitename | Result : -1

Command: getex sitename PX 10000 | Result: bigboxcode
Command: ttl sitename | Result : 10

Command: getex wrongkey ex 360 | Result: null

Notes

  • Use method “getEx” for using the Redis GETEX command. or you can use all uppercase method name “GETEX” instead of “getEx“.
  • Last parameter of the method accepts the expiration parameter.
  • For expire time in seconds using EX argument, pass the last param of expiration like object- {EX: number}. For example { EX: 100 }
  • For expire time in milliseconds using PX argument, pass the last param of expiration like object- {PX: number}. For example { PX: 100 }
  • For expire time in UNIX timestamp in second using EXAT argument, pass the last param of expiration like object- {EXAT: number | Date}. For example { EXAT: 100 }
  • For expire time in UNIX timestamp in second using PXAT argument, pass the last param of expiration like object- {PXAT: number | Date}. For example { PXAT: 100 }
  • For expire time for PERSIST argument, pass the last param of expiration like object- { PERSIST: true }.
// Redis GETEX example in Java

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.params.GetExParams;

import static java.lang.Thread.sleep;

public class Getex {
    public static void main(String[] args) {
        // Create connection pool
        JedisPool jedisPool = new JedisPool("localhost", 6379);

        try (Jedis jedis = jedisPool.getResource()) {
            /**
             * Set value for "sitename" key
             *
             * Command: set sitename "bigboxcode"
             * Result: OK
             */
            String commandResult = jedis.set("sitename", "bigboxcode");

            System.out.println("Command: set sitename \"bigboxcode\" | Result: " + commandResult);


            /**
             * Use the command without any expire part
             *
             * Command: getex sitename
             * Result: "bigboxcode"
             */
            commandResult = jedis.getEx("sitename", GetExParams.getExParams());

            System.out.println("Command: getex sitename | Result: " + commandResult);


            /**
             * Check TTL, and we get -1 as no expire time is set yet
             *
             * Command: ttl sitename
             * Result: (integer) -1
             */
            long ttlResult = jedis.ttl("sitename");

            System.out.println("Command: ttl sitename | Result: " + ttlResult);


            /**
             * Set 10 seconds expire time while getting get value back
             *
             * Command: getex sitename ex 10
             * Result: "bigboxcode"
             */
            commandResult = jedis.getEx("sitename", GetExParams.getExParams().ex(10));

            System.out.println("Command: getex sitename ex 10 | Result: " + commandResult);


            /**
             * Check TTL now, there should be some TTL(if checked within 10 seconds)
             *
             * Command: ttl sitename
             * Result: (integer) 10
             */
            ttlResult = jedis.ttl("sitename");

            System.out.println("Command: ttl sitename | Result: " + commandResult);


            // Sleep for 10 seconds
            System.out.println("Sleep 10 sec");
            sleep(10 * 1000);


            /**
             * Check after 10 seconds. The key has expired
             *
             * Command: get sitename
             * Result: (nil)
             */
            commandResult = jedis.get("sitename");

            System.out.println("Command: get sitename | Result: " + commandResult);

            /**
             * Set value for a key
             *
             * Command: set sitename bigboxcode
             * Result: OK
             */
            commandResult = jedis.set("sitename", "bigboxcode");

            System.out.println("Command: set sitename bigboxcode | Result: " + commandResult);


            /**
             * Set 120 seconds expire time while getting the value
             *
             * Command: getex sitename ex 120
             * Result: "bigboxcode"
             */
            commandResult = jedis.getEx("sitename", GetExParams.getExParams().ex(120));

            System.out.println("Command: getex sitename ex 120 | Result: " + commandResult);


            /**
             * Check TTL, there should be some TTL (if checked within 120 seconds)
             * Command: ttl sitename
             * Result: (integer) 117
             */
            ttlResult = jedis.ttl("sitename");

            System.out.println("Command: ttl sitename | Result: " + ttlResult);


            /**
             * Pass persist to remove the expire time from the key
             * Command: getex sitename persist
             * Result: "bigboxcode"
             */
            commandResult = jedis.getEx("sitename", GetExParams.getExParams().persist());

            System.out.println("Command: getex sitename persist | Result: " + commandResult);


            /**
             * Check the TTL now, there will be no TTL as the expire time is removed
             * Command: ttl sitename
             * Result: (integer) -1
             */
            ttlResult = jedis.ttl("sitename");

            System.out.println("Command: ttl sitename | Result: " + ttlResult);


            /**
             * Try getting value and set expire time for a key that does not exist. We get nil as the ke does not exist
             * Command: getex wrongkey ex 360
             * Result: (nil)
             */
            commandResult = jedis.getEx("wrongkey", GetExParams.getExParams().ex(360));

            System.out.println("Command: getex wrongkey ex 360 | Result: " + commandResult);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        jedisPool.close();
    }
}

Output:

Command: set sitename "bigboxcode" | Result: OK

Command: getex sitename | Result: bigboxcode
Command: ttl sitename | Result: -1

Command: getex sitename ex 10 | Result: bigboxcode
Command: ttl sitename | Result: bigboxcode

Sleep 10 sec

Command: get sitename | Result: null

Command: set sitename bigboxcode | Result: OK
Command: getex sitename ex 120 | Result: bigboxcode
Command: ttl sitename | Result: 120

Command: getex sitename persist | Result: bigboxcode
Command: ttl sitename | Result: -1

Command: getex wrongkey ex 360 | Result: null

Notes

  • Use “getex” method of “predis” for using the Redis GETEX command. The method signature is- getex(string $key, $modifier = ”, $value = false)
  • For passing seconds use the method like- getex(“yourkey”, “ex”, 100).
  • For passing milliseconds use the method like- getex(“yourkey”, “px”, 100).
  • For passing UNIX timestamp in seconds use the method like- getex(“yourkey”, “exat”, 100).
  • For passing UNIX timestamp in milliseconds use the method like- getex(“yourkey”, “pxat”, 100).
// Redis GETEX command examples in C#

using StackExchange.Redis;

namespace Getex
{
    internal class Program
    {
        static void Main(string[] args)
        {
            ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");
            IDatabase rdb = redis.GetDatabase();


            /**
             * Set value for "sitename" key
             *
             * Command: set sitename "bigboxcode"
             * Result: OK
             */
            var setCommandResult = rdb.StringSet("sitename", "bigboxcode");

            Console.WriteLine("Command: set sitename \"bigboxcode\" | Result: " + setCommandResult);


            /**
             * Use the command without any expire part
             *
             * Command: getex sitename
             * Result: "bigboxcode"
             */
            var getCommandResult = rdb.StringGetSetExpiry("sitename", null);

            Console.WriteLine("Command: getex sitename | Result: " + getCommandResult);


            /**
             * Check TTL, and we get -1 as no expire time is set yet
             *
             * Command: ttl sitename
             * Result: (integer) -1
             */
            var ttlResult = rdb.KeyTimeToLive("sitename");

            Console.WriteLine("Command: ttl sitename | Result: " + ttlResult);


            /**
             * Set 10 seconds expire time while getting get value back
             *
             * Command: getex sitename ex 10
             * Result: "bigboxcode"
             */
            getCommandResult = rdb.StringGetSetExpiry("sitename", new TimeSpan(0, 0, 10));

            Console.WriteLine("Command: getex sitename ex 10 | Result: " + getCommandResult);


            /**
             * Check TTL now, there should be some TTL(if checked within 10 seconds)
             *
             * Command: ttl sitename
             * Result: (integer) 10
             */
            ttlResult = rdb.KeyTimeToLive("sitename");

            Console.WriteLine("Command: ttl sitename | Result: " + ttlResult);


            // Sleep for 10 seconds
            Console.WriteLine("Sleep 10 sec");
            Thread.Sleep(10 * 1000);


            /**
             * Check after 10 seconds. The key has expired
             *
             * Command: get sitename
             * Result: (nil)
             */
            getCommandResult = rdb.StringGet("sitename");

            Console.WriteLine("Command: get sitename | Result: " + getCommandResult);

            /**
             * Set value for a key
             *
             * Command: set sitename bigboxcode
             * Result: OK
             */
            setCommandResult = rdb.StringSet("sitename", "bigboxcode");

            Console.WriteLine("Command: set sitename bigboxcode | Result: " + setCommandResult);


            /**
             * Set 120 seconds expire time while getting the value
             *
             * Command: getex sitename ex 120
             * Result: "bigboxcode"
             */
            getCommandResult = rdb.StringGetSetExpiry("sitename", new TimeSpan(0, 0, 120));

            Console.WriteLine("Command: getex sitename ex 120 | Result: " + getCommandResult);


            /**
             * Check TTL, there should be some TTL (if checked within 120 seconds)
             * Command: ttl sitename
             * Result: (integer) 117
             */
            ttlResult = rdb.KeyTimeToLive("sitename");

            Console.WriteLine("Command: ttl sitename | Result: " + ttlResult);


            /**
             * Try getting value and set expire time for a key that does not exist. We get nil as the ke does not exist
             * Command: getex wrongkey ex 360
             * Result: (nil)
             */
            getCommandResult = rdb.StringGetSetExpiry("wrongkey", new TimeSpan(0, 0, 360));

            Console.WriteLine("Command: getex wrongkey ex 360 | Result: " + getCommandResult);

        }
    }
}

Output:

Command: set sitename "bigboxcode" | Result: True

Command: getex sitename | Result: bigboxcode
Command: ttl sitename | Result:

Command: getex sitename ex 10 | Result: bigboxcode
Command: ttl sitename | Result: 00:00:09.9990000

Sleep 10 sec

Command: get sitename | Result:

Command: set sitename bigboxcode | Result: True
Command: getex sitename ex 120 | Result: bigboxcode
Command: ttl sitename | Result: 00:01:59.9990000

Command: getex wrongkey ex 360 | Result:

Notes

  • Use “StringGetSetExpiry” method of “StackExchange.Redis” for using the Redis GETEX command in C#.
  • “StringGetSetExpiry” has 2 signatures-
    • RedisValue StringGetSetExpiry(RedisKey key, TimeSpan? expiry, CommandFlags flags = CommandFlags.None)
    • RedisValue StringGetSetExpiry(RedisKey key, DateTime expiry, CommandFlags flags = CommandFlags.None)
<?php
// mget.php

// Redis GETEX command example in PHP

require 'vendor/autoload.php';

// Connect to Redis
$redisClient = new Predis\Client([
    'scheme' => 'tcp',
    'host' => 'localhost',
    'port' => 6379,
]);


/**
 * Set value for 'sitename' key
 * 
 * Command: set sitename "bigboxcode"
 * Result: OK
 */
$commandResult = $redisClient->set('sitename', 'bigboxcode');

echo "Command: set sitename \"bigboxcode\" | Result: " . $commandResult . "\n";


/**
 * Use the command without any expire part
 * 
 * Command: getex sitename
 * Result: "bigboxcode"
 */
$commandResult = $redisClient->getex('sitename');

echo "Command: getex sitename | Result: " . $commandResult . "\n";


/**
 * Check TTL, and we get -1 as no expire time is set yet
 * 
 * Command: ttl sitename
 * Result: (integer) -1
 */
$commandResult = $redisClient->ttl('sitename');

echo "Command: ttl sitename | Result: " . $commandResult . "\n";


/**
 * Set 10 seconds expire time while getting get value back
 * 
 * Command: getex sitename ex 10
 * Result: "bigboxcode"
 */
$commandResult = $redisClient->getex('sitename', 'ex', 10);

echo "Command: getex sitename ex 10 | Result: " . $commandResult . "\n";


/**
 * Check TTL now, there should be some TTL(if checked within 10 seconds)
 * 
 * Command: ttl sitename
 * Result: (integer) 10
 */
$commandResult = $redisClient->ttl('sitename');

echo "Command: ttl sitename | Result: " . $commandResult . "\n";


// Sleep for 10 seconds
echo "Sleep 10 sec\n";
sleep(10);


/**
 * Check after 10 seconds. The key has expired
 * 
 * Command: get sitename
 * Result: (nil)
 */
$commandResult = $redisClient->get('sitename');

echo "Command: get sitename | Result: " . $commandResult . "\n";

/**
 * Set value for a key
 * 
 * Command: set sitename bigboxcode
 * Result: OK
 */
$commandResult = $redisClient->set('sitename', 'bigboxcode');

echo "Command: set sitename bigboxcode | Result: " . $commandResult . "\n";


/**
 * Set 120 seconds expire time while getting the value
 * 
 * Command: getex sitename ex 120
 * Result: "bigboxcode"
 */
$commandResult = $redisClient->getex('sitename', 'ex', 120);

echo "Command: getex sitename ex 120 | Result: " . $commandResult . "\n";


/**
 * Check TTL, there should be some TTL (if checked within 120 seconds)
 * Command: ttl sitename
 * Result: (integer) 117
 */
$commandResult = $redisClient->ttl('sitename');

echo "Command: ttl sitename | Result: " . $commandResult . "\n";


/**
 * Pass persist to remove the expire time from the key
 * Command: getex sitename persist
 * Result: "bigboxcode"
 */
$commandResult = $redisClient->getex('sitename', 'persist');

echo "Command: getex sitename persist | Result: " . $commandResult . "\n";


/**
 * Check the TTL now, there will be no TTL as the expire time is removed
 * Command: ttl sitename
 * Result: (integer) -1
 */
$commandResult = $redisClient->ttl('sitename');

echo "Command: ttl sitename | Result: " . $commandResult . "\n";


/**
 * Try getting value and set expire time for a key that does not exist. We get nil as the ke does not exist
 * Command: getex wrongkey ex 360
 * Result: (nil)
 */
$commandResult = $redisClient->getex('wrongkey', 'ex', 360);

echo "Command: getex wrongkey ex 360 | Result: " . $commandResult . "\n";

 

Output:

Command: set sitename "bigboxcode" | Result: OK

Command: getex sitename | Result: bigboxcode
Command: ttl sitename | Result: -1

Command: getex sitename ex 10 | Result: bigboxcode
Command: ttl sitename | Result: 10

Sleep 10 sec

Command: get sitename | Result:

Command: set sitename bigboxcode | Result: OK

Command: getex sitename ex 120 | Result: bigboxcode
Command: ttl sitename | Result: 120

Command: getex sitename persist | Result: bigboxcode
Command: ttl sitename | Result: -1

Command: getex wrongkey ex 360 | Result:

Notes

  • Use “getex” method of “predis” for using the Redis GETEX command. The method signature is- getex(string $key, $modifier = ”, $value = false)
  • For passing seconds use the method like- getex(“yourkey”, “ex”, 100).
  • For passing milliseconds use the method like- getex(“yourkey”, “px”, 100).
  • For passing UNIX timestamp in seconds use the method like- getex(“yourkey”, “exat”, 100).
  • For passing UNIX timestamp in milliseconds use the method like- getex(“yourkey”, “pxat”, 100).
# Redis GETEX command example in Python

import redis
import time

# Create Redis client
redisClient = redis.Redis(host='localhost', port=6379,
                          username='default', password='', 
                          decode_responses=True)

# Command: set sitename "bigboxcode"
# Result: OK
commandResult = redisClient.set('sitename', 'bigboxcode')

print("Command: set sitename \"bigboxcode'\" | Result: {}".format(commandResult))


# Use the command without any expire part
# Command: getex sitename
# Result: "bigboxcode"
commandResult = redisClient.getex('sitename')

print("Command: getex sitename | Result: {}".format(commandResult))


# Check TTL, and we get -1 as no expire time is set yet
# Command: ttl sitename
# Result: (integer) -1
commandResult = redisClient.ttl('sitename')

print("Command: ttl sitename | Result: {}".format(commandResult))


# Set 10 seconds expire time while getting get value back
# Command: getex sitename ex 10
# Result: "bigboxcode"
commandResult = redisClient.getex('sitename', ex=10)

print("Command: getex sitename ex 10 | Result: {}".format(commandResult))


# Check TTL now, there should be some TTL(if checked within 10 seconds)
# Command: ttl sitename
# Result: (integer) 6
commandResult = redisClient.ttl('sitename')

print("Command: ttl sitename | Result: {}".format(commandResult))


# Sleep for 10 sec
print("Sleep 10 sec")
time.sleep(10)

# Check after 10 seconds. The key has expired
# Command: get sitename
# Result: (nil)
commandResult = redisClient.get('sitename')

print("Command: get sitename | Result: {}".format(commandResult))


# Set value for a key
# Command: set sitename bigboxcode
# Result: OK
commandResult = redisClient.set('sitename', 'bigboxcode')

print("Command: set sitename \"bigboxcode'\" | Result: {}".format(commandResult))


# Set 120 seconds expire time while getting the value
# Command: getex sitename ex 120
# Result: "bigboxcode"
commandResult = redisClient.getex('sitename', ex=120)

print("Command: getex sitename ex 120 | Result: {}".format(commandResult))


# Check TTL, there should be some TTL (if checked within 120 seconds)
# Command: ttl sitename
# Result: (integer) 120
commandResult = redisClient.ttl('sitename')

print("Command: ttl sitename | Result: {}".format(commandResult))


# Pass persist to remove the expire time from the key
# Command: getex sitename persist
# Result: "bigboxcode"
commandResult = redisClient.getex('sitename', persist=True)

print("Command: getex sitename persist | Result: {}".format(commandResult))


# Check the TTL now, there will be no TTL as the expire time is removed
# Command: ttl sitename
# Result: (integer) -1
commandResult = redisClient.ttl('sitename')

print("Command: ttl sitename | Result: {}".format(commandResult))


# Try getting value and set expire time for a key that does not exist. We get nil as the ke does not exist
# Command: getex wrongkey ex 360
# Result: (nil)
commandResult = redisClient.getex('wrongkey', ex=360)

print("Command: getex wrongkey ex 360 | Result: {}".format(commandResult))

Output:

Command: set sitename "bigboxcode'" | Result: True

Command: getex sitename | Result: bigboxcode
Command: ttl sitename | Result: -1

Command: getex sitename ex 10 | Result: bigboxcode
Command: ttl sitename | Result: 10

Sleep 10 sec

Command: get sitename | Result: None

Command: set sitename "bigboxcode'" | Result: True

Command: getex sitename ex 120 | Result: bigboxcode
Command: ttl sitename | Result: 120

Command: getex sitename persist | Result: bigboxcode
Command: ttl sitename | Result: -1

Command: getex wrongkey ex 360 | Result: None

Notes

  • Use the “getex” method from Redis GETEX command. Signature of the method is – getex(self, name: KeyT, ex: Union[ExpiryT, None] = None, px: Union[ExpiryT, None] = None, exat: Union[AbsExpiryT, None] = None, pxat: Union[AbsExpiryT, None] = None, persist: bool = False)
  • So we can pass the named param for “ex”, “px” etc. like getex(“mykey”, ex=100) or getex(“mykey”, px=200) or getex(“mykey”, persist=True)
# Redis GETEX command example in Ruby

require 'redis'

redis = Redis.new(host: "localhost", port: 6379)


# Command: set sitename "bigboxcode"
# Result: OK
commandResult = redis.set('sitename', 'bigboxcode')

print("Command: set sitename \"bigboxcode'\" | Result: ", commandResult, "\n")


# Use the command without any expire part
# Command: getex sitename
# Result: "bigboxcode"
commandResult = redis.getex('sitename')

print("Command: getex sitename | Result: ", commandResult, "\n")


# Check TTL, and we get -1 as no expire time is set yet
# Command: ttl sitename
# Result: (integer) -1
commandResult = redis.ttl('sitename')

print("Command: ttl sitename | Result: ", commandResult, "\n")


# Set 10 seconds expire time while getting get value back
# Command: getex sitename ex 10
# Result: "bigboxcode"
commandResult = redis.getex('sitename', ex:10)

print("Command: getex sitename ex 10 | Result: ", commandResult, "\n")


# Check TTL now, there should be some TTL(if checked within 10 seconds)
# Command: ttl sitename
# Result: (integer) 6
commandResult = redis.ttl('sitename')

print("Command: ttl sitename | Result: ", commandResult, "\n")


# Sleep for 10 sec
print("Sleep 10 sec\n")
sleep(10)

# Check after 10 seconds. The key has expired
# Command: get sitename
# Result: (nil)
commandResult = redis.get('sitename')

print("Command: get sitename | Result: ", commandResult, "\n")


# Set value for a key
# Command: set sitename bigboxcode
# Result: OK
commandResult = redis.set('sitename', 'bigboxcode')

print("Command: set sitename \"bigboxcode'\" | Result: ", commandResult, "\n")


# Set 120 seconds expire time while getting the value
# Command: getex sitename ex 120
# Result: "bigboxcode"
commandResult = redis.getex('sitename', ex:120)

print("Command: getex sitename ex 120 | Result: ", commandResult, "\n")


# Check TTL, there should be some TTL (if checked within 120 seconds)
# Command: ttl sitename
# Result: (integer) 120
commandResult = redis.ttl('sitename')

print("Command: ttl sitename | Result: ", commandResult, "\n")


# Pass persist to remove the expire time from the key
# Command: getex sitename persist
# Result: "bigboxcode"
commandResult = redis.getex('sitename', persist: true)

print("Command: getex sitename persist | Result: ", commandResult, "\n")


# Check the TTL now, there will be no TTL as the expire time is removed
# Command: ttl sitename
# Result: (integer) -1
commandResult = redis.ttl('sitename')

print("Command: ttl sitename | Result: ", commandResult, "\n")


# Try getting value and set expire time for a key that does not exist. We get nil as the ke does not exist
# Command: getex wrongkey ex 360
# Result: (nil)
commandResult = redis.getex('wrongkey', ex:360)

print("Command: getex wrongkey ex 360 | Result: ", commandResult, "\n")

Output:

Command: set sitename "bigboxcode'" | Result: OK

Command: getex sitename | Result: bigboxcode
Command: ttl sitename | Result: -1

Command: getex sitename ex 10 | Result: bigboxcode
Command: ttl sitename | Result: 10

Sleep 10 sec

Command: get sitename | Result: 

Command: set sitename "bigboxcode'" | Result: OK
Command: getex sitename ex 120 | Result: bigboxcode
Command: ttl sitename | Result: 120

Command: getex sitename persist | Result: bigboxcode
Command: ttl sitename | Result: -1

Command: getex wrongkey ex 360 | Result: 

Notes

Source Code

Use the following links to get the source code used in this article-

Related Commands

CommandDetails
GET Command Details
GETDEL Command Details
MGET Command Details

Leave a Comment


The reCAPTCHA verification period has expired. Please reload the page.