DEV Community

Kevin Naidoo
Kevin Naidoo

Posted on • Updated on

Redis Queues in Golang

#go

If you come from a framework like Laravel, you will be quite familiar with dispatching jobs onto a queue and then consuming that job via a queue worker.

Usually in Golang, we tend to just use goroutines that can run jobs in the background without needing Redis or some external service, and this works fine for a fair amount of use cases however there'll come a time when you need to distribute work across multiple servers and need some kind of retry mechanism.

This is just a basic example of how you would go about setting up a Redis queue in Golang, it's not meant to be a complete solution but should give you a good idea of how to go about building your own job queue system.

Firstly you'll need to pull in a Redis Go driver:

github.com/go-redis/redis
Enter fullscreen mode Exit fullscreen mode

To set up a Redis client:

client := redis.NewClient(&redis.Options{
        Addr:     "127.0.0.1:6379",
        Password: "",
        DB:       0,
    })
Enter fullscreen mode Exit fullscreen mode

Next, to add data to a queue:

err = client.LPush("queuename", "some data").Err()
if err != nil {
  log.Fatal(err)
} 
Enter fullscreen mode Exit fullscreen mode

Finally, to read the data from your queue:

item, err := client.LPop("queuename").Result()
Enter fullscreen mode Exit fullscreen mode

Top comments (0)