Redis is a in-memory data store, used a lot in the backend systems of web-apps. Specifically, it’s good at helping with caching and message as it’s high performance lends itself to fast response times at retriving data.
In this blog post, we will demonstrate how to connect to Redis using Go and the go-redis library, which is one of the most popular and widely-used libraries for interacting with Redis in Go.
packagemainimport("context""fmt""log""github.com/go-redis/redis/v8")funcmain(){// Create a new Redis client
rdb:=redis.NewClient(&redis.Options{Addr:"localhost:6379",// Replace with your Redis server address and port
Password:"",// Set password if you have one, otherwise leave it empty
DB:0,// Use default DB
})// Create a context for Redis operations
ctx:=context.Background()// Test the connection to Redis
pong,err:=rdb.Ping(ctx).Result()iferr!=nil{log.Fatalf("Could not connect to Redis: %v",err)}fmt.Printf("Connected to Redis: %v\n",pong)// Perform Redis operations
err=rdb.Set(ctx,"mykey","gophercoding.com",0).Err()iferr!=nil{log.Fatalf("Could not set key: %v",err)}value,err:=rdb.Get(ctx,"mykey").Result()iferr!=nil{log.Fatalf("Could not get key: %v",err)}fmt.Printf("Value of mykey: %v\n",value)}
Edd is a PHP and Go developer who enjoys blogging about his experiences, mostly about creating and coding new things he's working on and is a big beliver in open-source and Linux.