packagemainimport("context""fmt""log""time""github.com/redis/go-redis/v9")funcmain(){// Connect to local Redis on port 6379 without a password
rdb:=redis.NewClient(&redis.Options{Addr:"127.0.0.1:6379",Password:"",// no password
DB:0,DialTimeout:3*time.Second,ReadTimeout:1*time.Second,WriteTimeout:1*time.Second,})deferrdb.Close()ctx,cancel:=context.WithTimeout(context.Background(),5*time.Second)defercancel()// Ping to test connection
iferr:=rdb.Ping(ctx).Err();err!=nil{log.Fatalf("redis ping failed: %v",err)}log.Println("connected to redis ✅")// Basic operations (SET/GET)
iferr:=rdb.Set(ctx,"hello","world",10*time.Minute).Err();err!=nil{log.Fatalf("SET error: %v",err)}val,err:=rdb.Get(ctx,"hello").Result()iferr!=nil{log.Fatalf("GET error: %v",err)}fmt.Println("hello =",val)// Example using Set type
key:="team:dev"iferr:=rdb.SAdd(ctx,key,"alice","bob","alice").Err();err!=nil{log.Fatalf("SADD error: %v",err)}members,_:=rdb.SMembers(ctx,key).Result()fmt.Println("members =",members)}
Install the dependencies:
1
go mod tidy
Run the program:
1
go run main.go
If you see the following output, everything is working correctly:
1
2
3
2025/10/05 20:30:00 connected to redis ✅
hello = world
members = [alice bob]
Summary
This article explained how to use Redis with Go.
When working with Redis in Go, use the go-redis package.