Random Redis Key Generator with Prefix

  • Share this:

Code introduction


This code defines a function to generate random Redis keys, each key is prefixed with a given prefix and a random numeric suffix is generated, and these keys are then stored in Redis.


Technology Stack : redis, random

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
import random

def redis_random_key_generator(prefix, num_keys=10):
    """
    Generate a list of random keys for Redis with a given prefix.
    """
    import redis
    r = redis.Redis(host='localhost', port=6379, db=0)
    keys = []
    for _ in range(num_keys):
        random_key = f"{prefix}:{random.randint(1000, 9999)}"
        r.set(random_key, "value")
        keys.append(random_key)
    return keys                
              
Tags: