Hello friends! In this post, I will discuss how we can perform different redis operations in Golang. Friends, there are various libraries in Golang to interact with redis. But, in this post, I will use redigo. Follow the below steps:
Step 1: Install redis and start redis server in your machine. Then run redis-cli to enter into redis terminal.
Step 2: Create a directory and open it in any code editor. Make sure you have install Golang in your system.
Step 3: Create a file main.go. Here, you have to import below package:
"github.com/gomodule/redigo/redis"
This package provides you method to create connection with redis server.
import (
"log"
"github.com/gomodule/redigo/redis"
)
Here, log has been imported to log the data.
We will use Dial() method to create the connection with redis server.
con, err := redis.Dial("tcp", "localhost:6379")
Now, let us define a setter function to set a string in redis.
func setString(key, value string) {
result, er := con.Do("SET", key, value)
if er != nil {
log.Fatal("Some error: ", er.Error())
}
log.Fatal(result)
}
We can call this setter function in the main function to set the data
in the redis.
func main() {
setString("Name", "Debug Boss")
}
The whole code is like below:
package main
import (
"log"
"github.com/gomodule/redigo/redis"
)
var conn redis.Conn
func init() {
con, err := redis.Dial("tcp", "localhost:6379")
if err != nil {
log.Fatal("Some error: ", err.Error())
}
conn = con
}
func setString(key, value string) {
result, er := conn.Do("SET", key, value)
if er != nil {
log.Fatal("Some error: ", er.Error())
}
log.Fatal(result)
}
func getString(key string) {
result, er := conn.Do("GET", key)
if er != nil {
log.Fatal("Some error: ", er.Error())
}
log.Println(result)
}
func main() {
setString("Name", "Debug Boss")
}