Random Key Generation with Redis Prefix

  • Share this:

Code introduction


This function generates a list of random keys with a given prefix using Redis, and stores each key with its corresponding value in Redis.


Technology Stack : Redis, Python third-party library

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
import random
import redis

def random_key_generation(prefix, num_keys=10):
    """
    Generates a list of random keys with a given prefix using 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, "Sample Value")
        keys.append(random_key)
    return keys