redisdb/redisdb.go

48 lines
848 B
Go
Raw Permalink Normal View History

2021-08-09 03:36:09 +00:00
package redisdb
import (
"context"
"fmt"
2023-02-24 13:40:03 +00:00
apmgoredis "go.elastic.co/apm/module/apmgoredisv8/v2"
"os"
2021-08-09 03:36:09 +00:00
"github.com/go-redis/redis/v8"
)
type Server struct {
2021-08-09 03:36:09 +00:00
rdb *redis.Client
}
var r *Server
2021-08-09 03:36:09 +00:00
// Connect ...
func Connect(uri, password string) (*Server, error) {
2021-08-09 03:36:09 +00:00
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
2021-08-09 03:36:09 +00:00
Addr: uri,
Password: password,
DB: 0, // use default DB
})
// Ping
_, err := rdb.Ping(ctx).Result()
if err != nil {
2022-12-05 07:54:51 +00:00
fmt.Printf("[redisdb] connect to %s error: %s \n", uri, err.Error())
return nil, err
2021-08-09 03:36:09 +00:00
}
2023-02-24 13:40:03 +00:00
// add apm
2023-02-25 05:41:31 +00:00
useElasticAPM := os.Getenv("ELASTIC_APM_SERVER_URL") != ""
if useElasticAPM {
2023-02-24 13:40:03 +00:00
rdb.AddHook(apmgoredis.NewHook())
}
// assign data
r = &Server{rdb: rdb}
2023-02-25 05:41:31 +00:00
fmt.Printf("⚡️[redis]: connected to %s, use elastic apm: %t \n", uri, useElasticAPM)
2021-08-09 03:36:09 +00:00
return r, nil
2021-08-09 03:36:09 +00:00
}