redisdb/redisdb.go

47 lines
780 B
Go

package redisdb
import (
"context"
"fmt"
apmgoredis "go.elastic.co/apm/module/apmgoredisv8/v2"
"os"
"github.com/go-redis/redis/v8"
)
type Server struct {
rdb *redis.Client
}
var r *Server
// Connect ...
func Connect(uri, password string) (*Server, error) {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: uri,
Password: password,
DB: 0, // use default DB
})
// Ping
_, err := rdb.Ping(ctx).Result()
if err != nil {
fmt.Printf("[redisdb] connect to %s error: %s \n", uri, err.Error())
return nil, err
}
// add apm
if os.Getenv("ELASTIC_APM_SERVER_URL") != "" {
rdb.AddHook(apmgoredis.NewHook())
}
// assign data
r = &Server{rdb: rdb}
fmt.Printf("⚡️[redis]: connected to %s \n", uri)
return r, nil
}