// ___ ____ ___ ___ // \ \ / / | _ | __| \ \ / / || | __ || || _ | // \ \/ / |___ | |__ \ \/ / || |___ || ||___| // \ / | _ | _ | \ / || __ | || ||\\ // \/ |___ |___ | \/ || ____| || || \\ // // Copyright (c) 2021 Piotr Biernat. https://pbiernat.dev. MIT License // Repo: https://git.pbiernat.dev/golang/vegvisir package cache import ( "github.com/go-redis/redis" "log" "os" "strconv" "time" ) // NewRedisDatastore function func NewRedisDatastore(host, password, db string, port int) *RedisDatastore { dbNum, err := strconv.Atoi(db) if err != nil { log.Println("Config: Invalid redis database!") os.Exit(1) // FIXME: move up so in main we use os.Exit ONLY! } return &RedisDatastore{ client: redis.NewClient(&redis.Options{ Addr: host + ":" + strconv.Itoa(port), Password: password, DB: dbNum, }), } } // RedisDatastore class type RedisDatastore struct { client *redis.Client } // SetKey function func (ds *RedisDatastore) SetKey(key string, data interface{}, ttl int) error { err := ds.client.Set(key, data, time.Duration(ttl)*time.Second).Err() if err != nil { return err } return nil } // GetKey function func (ds *RedisDatastore) GetKey(key string) (interface{}, error) { data, err := ds.client.Get(key).Result() if err != nil { return nil, err } return data, nil } // IsConnected function func (ds *RedisDatastore) IsConnected() bool { _, err := ds.client.Ping().Result() return err == nil }