Contents

    Guides

    How to use a Redis database with Go

    Ukeje C. Goodness

    Ukeje C. Goodness is a tech explorer exploring backend development in Go and machine learning in Python while writing about those topics.

    Published on

    September 21, 2022
    How to use a Redis database with Go

    Redis (Remote Dictionary Server) is an open-source, NoSQL, in-memory data storage. Redis is popularly used as a database, caching service, and streaming engine due to its speed, ease of use, and support for many data types.

    The Redis database is helpful for applications where service delivery speed is essential, such as authentication, and you can use a Redis database to make your applications more scalable.

    A Redis database can be used with a variety of programming languages, including Go. The Go-Redis package is the most popular and widely used package for interacting with Redis databases in Go. The Go Redis package is a feature-rich, type-safe Redis client that allows Go applications to perform operations on Redis servers and clusters.

    In this tutorial, we'll learn how to use Redis as a database with Go by connecting to a local Redis server on your machine. If you don't already have Redis installed on your device, follow the instructions here; if you use a Mac, this is a good resource for installing and starting Redis.

    Getting Started with the Go Redis Package

    Go Redis start screen

    Like every external Go package, you'll have to install Go Redis after initializing a Go modules file go.mod in your workspace. You can install Go Redis using the command below.

    go get github.com/go-redis/redis

    The command would install the Go Redis package in your workspace. Here's how you can import the package.

    import ( 
       "github.com/go-redis/redis" 
    )

    If you don't see any errors at this point, your installations were successful; if you do, try updating your Redis and Go versions. 1

    Code view of successful Go Redis installation

    Connecting to a Redis Instance using Go Redis

    You'll have to connect to a Redis instance to use Redis in your Go programs. You can use the NewClient method to connect to a Redis instance; the NewClient method refers to the Options struct where you can set the database configurations.

    func yourRedisClient() *redis.Client { 
        redisClient := redis.NewClient(&redis.Options{ 
         Addr: "localhost:6379", 
         Password: "", 
          DB: 0, 
    }) 
    
    return redisClient 
    }

    In most cases, you'll need only the address. By default, Redis runs on port 6379, which explains the address above.
    You can ping your Redis instance to confirm your connection using the Result method on the Ping method of your client instance.

    response, err := yourRedisClient().Ping().Result() 
    if err != nil { 
         fmt.Println(response) 
    }

    Just like when you use the ping argument on the Redis-cli command on your terminal, the response should be PONG, indicating that you're connected or an error if you're not connected.

    Once you've successfully connected to your Redis instance, you can operate on it.

    Inserting Values Into Your Redis Instance

    If you're using Redis with Go, you'll probably want to insert values into your Redis instance. You can insert it into your Redis instance using the Set method of your client instance redisClient. The Set method takes in the key, value, and expiration time, which you can set to 0 if you don't want the data to expire.

    func insertIt(key, value string) any { 
       err := yourRedisClient().Set(key, value, 0).Err() 
    
    if err != nil { 
       return err 
    } 
       return "insertion successful." 
    } 

    The insertIt function takes in the key and value you want to insert and returns any type; in this case, it returns a string.

    You can use the Err method on the Set method to handle errors or the Result method for the insertion result.

    Similar to Redis, there's no update method in the Go-Redis package. You can only re-set values if you want to update a value.

    Querying and Reading from your Redis instance

    You can use the Get method to read from your Redis instance. The Get method takes in the key and returns the value. Also, you can use the Result function on the Get method for the status of your operation.

    func delete_(key string) any { 
    deleted, err := yourRedisClient().Del(key).Result() 
    if err != nil { 
    log.Println(err) 
    } 
    return deleted 
    }

    The readIt function takes in a string key and returns the value of the query if the query is valid.

    Deleting Key-Value Pairs from your Redis Instance

    For delete operations, Go-Redis provides the Del method. The Del method takes in the key of the pair you want to delete and deletes the key-value pair from the instance.

    func delete_(key string) any { 
        deleted, err := yourRedisClient().Del(key).Result() 
        if err != nil { 
             log.Println(err) 
        } 
        return deleted 
    }

    The delete_ function takes in the key, deletes the key-value pair, and returns the status of the operation. On successful deletion, the delete_ function would return 1 .

    Working With Redis Lists

    You can use the LPush method on your Redis connection instance to create a list and insert values into the list.

    insertResult, err := yourRedisClient().LPush("Companies", "Google", "Netflix", "Amazon", "Uber", "Airbnb", "Microsoft").Result() 
    
    if err != nil { 
        fmt.Println(insertResult) 
    }

    The LPush method takes in the key and an unlimited list of values.

    You can use the LRange method on your Redis connection instance to range through your Redis list. The LRange method takes in the key name and the integer range you want to access.

    rangeResult, err := yourRedisClient().LRange("Companies", 1, 3).Result() 
    if err != nil { 
        fmt.Println(rangeResult) 
    }

    The LRange method returns a slice of the elements in the range of the key on your Redis instance.

    You can use the LPop method to delete values from lists. The LPop method takes in the key name of the list you want to delete and deletes the last element off the list.

    result, err := yourRedisClient().Keys("*").Result() 
    if err != nil { 
         return 
    } 
    fmt.Println(result)

    If you have a specific index you want to delete from, you can use the LRem method.

    result, err := yourRedisClient().LRem("Companies", 2, "Microsoft") 
    if err != nil { 
        return 
    } 
    fmt.Println(result)

    The LRem method uses the key, a count, and the value as arguments.

    Printing All Keys in a Redis Cluster

    You can use the Keys method on your Redis connection instance to print all the keys in your Redis database.

    result, err := yourRedisClient().Keys("*").Result() 
    if err != nil { 
       return 
    } 
    fmt.Println(result)

    The Keys method returns a slice of the keys in your database. This operation comes in handy when you’re unaware of the names of keys in your database.

    Using Go-Redis Unsupported Commands

    Unfortunately, Go-Redis doesn't support all the Redis commands. Nonetheless, you can still interact with your Redis cluster with the Go-Redis package because the package supports running unsupported commands.

    You can use the Do method of your Redis instance to run unsupported commands. The Do method takes in a context and the command.

    func unsupported() { 
    result, err := yourRedisClient().Do("get", "Company").Result() 
        if err != nil { 
           if err == redis.Nil { 
              fmt.Println("key does not exists") 
          return 
    } 
         panic(err) 
        } 
         fmt.Println(result.(string)) 
    }

    You can specify a context along with the Do method. The unsupported function runs the get command on the Redis instance for the Company key and prints the query result. Similarly, you can run any unsupported command with the Do method.

    Conclusion

    This tutorial has taught you how to use Redis with Go. You learned how to connect to a Redis instance from your Go app and execute popular Redis commands, work with Redis lists, execute unsupported commands, and more.

    Most of the go-redis commands are similar to the regular Redis commands, and you can call the methods based on your operation. The Go Redis package isn’t well documented, and the documentation covers mainly connections, pub-sub,and other operations.

    You can try using the regular Redis commands and overviewing the arguments the functions accept from the official documentation package on the Go documentation page or use the unsupported commands option.

    Data-rich bug reports loved by everyone.

    Get visual proof, steps to reproduce and technical logs with one click.

    Make bug reporting 50% faster and 100% less painful

    Rating LogosStars
    4.6
    |
    Category leader

    Liked the article? Spread the word

    Put your knowledge to practice

    Try Bird on your next bug - you’ll love it

    Try Bird later, from your desktop

    Bird Call to action parrot
    By clicking “Accept”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts. View our Privacy Policy for more information.