How to Use Redis Go Client Redigo with GoLang
Introduction
The Go language (GoLang) helps developers increase productivity because it’s an easy-to-learn programming language that’s suitable for many applications in a variety of industries. GoLang is compatible with other popular programs too. One worth mentioning is Redigo, a Redis Go client. It works seamlessly with GoLang. Among its main benefits is its ability to evaluate scripts. There’s more. Coding is all about the details so let’s begin our tutorial on how to use Redis Go client Redigo with GoLang.
Prerequisites
Install and configure Redis.
Verify your version of Redis with the command
redis-cli --version
. You should see a result similar to this one below:
1 | redis-cli 4.0.9 |
Install and configure Go language (GoLang).
Verify the installation with the command
go version
.
1 | go version go1.12.5 linux/amd64 |
About Redigo
Redigo is a Redis database Go client. Features include:
Support for transactions that are pipelined. It uses the commands Send, Flush, and Receive to complete pipelining transactions.
Complete Redis command support from an API
Publishing and subscribing implementation using methods of Send, Flush, and Receive
Pooling of connections for setting an unlimited amount of open connections at once in the pool
EVALSHA, a script tool for evaluating scripts
Response helper tools to assist with error handling
>NOTE: Read the documentation for more information about use Redis Go client Redigo features.
Install Redigo
- Download and install Redigo library dependencies with the
go get
command:
1 | go get github.com/gomodule/redigo/redis |
Make a PHP and Redis connection
- Construct connection pool functions and then connect with Redis.
Use the redis.Pool command to connect
- Produce redigo
redis.Pool
script to establish a connection pool where there can be many connections toRedis
. Try this GoLang script here to use Redis Go client Redigo :
1 | var rPool *redis.Pool |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | func nPool() { return &redis.Pool{ MaxIdle: 50, MaxActive: 10000, Dial: func() (redis.Conn, error) { conn, err := redis.Dial("tcp", ":6379") // Connection error handling if err != nil { log.Printf("ERROR: fail initializing the redis pool: %s", err.Error()) os.Exit(1) } return conn, err }, } } |
Now, let’s dissect the code for a better understanding of each segment.
MaxIdle
– The pool has a limit of connections that are idle.MaxActive
– The pool has a limit of active connections.Dial
– The connection’s formation and configuration are stated.Lastly, instructions are given on how to deal with errors from the connection if and when they occur.
We’re ready to test the sample script by using the
func main()
GoLang command:
1 2 3 | func main(){ nPool() } |
- If you open a terminal window and use the
go run main.go
command to start the server Redis, it will return an error similar to this:
1 2 | 2019/07/31 02:57:13 ERROR: fail initializing redis pool: dial tcp :6379: connect: connection refused exit status 1 |
- The above script is an example of a response for error handling that you should see something similar to if it’s working correctly.
Verify the server Redis connection
Confirm the server Redis connection with a Go script
func ping
command to use Redis Go client Redigo properly.Now that we are able to create our connection pool, let’s now try to make GoLang script to check the connection status to the Redis server.
1 2 3 4 5 6 7 8 9 10 | func ping(c redis.Conn) error { s, err := redis.String(c.Do("PING")) if err != nil { return err } fmt.Printf("PING Response = %s\n", s) return nil } |
>NOTE: The GoLang func ping
command pings the server Redis to test the connection.
>1) The s, err := redis.String(c.DO("PING"))
segment of the GoLang script PINGS the server Redis.
>
>2) Next, the server’s response is returned in the form of an uncomplicated string.
>
>3) Then, the method redis.String()
is used to convert the typeface.
>
>4) Finally, a “PONG” will return if there are no errors.
The command Redis SET
- Now that the connection made earlier was successful, you’ll want to use the command
SET
to test for errors. Take advantage of all of Redigo’s error handling capabilities though for hassle-free scripting. Here’s an example of what the command Redis SET looks like:
1 2 3 4 5 6 7 8 9 10 11 12 13 | func set(c redis.Conn) error { _, err := c.Do("SET", "name", "rommel") if err != nil { return err } _, err = c.Do("SET", "country", "Philippines") if err != nil { return err } return nil } |
- Here are the details of the GoLang script just shown above. Inside Redis, a key-value pair is constructed. The SET pairs are set with keys and values. The “name” key matches the “rommel” string value, and the “country” key matches the “Philippines” string value. In addition, there’s an identifier that’s left blank.
The command Redis GET
- Here’s a GoLang script in action. It uses the command
GET
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | func get(c redis.Conn) error { key := "name" s, err := redis.String(c.Do("GET", key)) if err != nil { return (err) } fmt.Printf("%s = %s\n", key, s) key = "country" i, err := redis.String(c.Do("GET", key)) if err != nil { return (err) } fmt.Printf("%s = %s\n", key, i) // Example where key was not set key = "Nonexistent Key" s, err = redis.String(c.Do("GET", key)) if err == redis.ErrNil { fmt.Printf("%s : Alert! this Key does not exist\n", key) } else if err != nil { return err } else { fmt.Printf("%s = %s\n", key, s) } return nil } |
The identified key’s helper
s, err = redis.String(c.Do("GET", key))
for the string expedites the process and reduces unnecessary errors.See the
redis.ErrNil
part of the Golang script as it shows how errors are handled should they occur. In this example, a key that is not set returns a response ofnil
(zero, nothing).
Conclusion
Today, you discovered how to use Redis Go client Redigo. Error handling is a huge part of scripting, and Redigo’s script helpers make your life as a developer easier. That’s what Redigo brings to the table among other things including pooling connections and pipelining transactions. Apply what Redigo has to offer now and experience happier coding.
Pilot the ObjectRocket Platform Free!
Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.
Get Started