A redis-based configuration library developed using Go, ready to go, easy to use.
go get github.com/jwma/reborn
package main
import (
"fmt"
"github.com/go-redis/redis"
"github.com/jwma/reborn"
"log"
)
func main() {
// get your redis client here
client := redis.NewClient(&redis.Options{
Addr: "127.0.0.1:6379",
Password: "",
DB: 0,
IdleTimeout: -1,
})
var err error
// new empty config
defaults := reborn.NewConfig()
// set default config
err = defaults.SetValue("websiteTitle", "Reborn")
if err != nil {
log.Printf("failed to set websiteTitle, error: %v\n", err)
}
err = defaults.SetValue("toggle", false)
if err != nil {
log.Printf("failed to set toggle, error: %v\n", err)
}
// create a Reborn instance using defaults config
// this instance will store all the configs into YOUR_CONFIG_KEY Hash in Redis
r, err := reborn.NewWithDefaults(client, "YOUR_CONFIG_KEY", defaults)
// by passing the second parameter,
// you can get this default value when the key does not exists
websiteTitle := r.GetValue("websiteTitle", "default value")
fmt.Println(websiteTitle) // Output: Reborn
fmt.Println(r.GetValue("noExistsKey", "oops")) // Output: oops
toggle := r.GetBoolValue("toggle", false)
fmt.Println(toggle)
}
You can use Reborn like below.
r, _ := reborn.New(client, "YOUR_CONFIG_KEY")
r, _ := reborn.New(client, "YOUR_CONFIG_KEY")
// SetValue() only update the Reborn instance configs
r.SetValue("discount", 8.8)
r.SetValue("websiteTitle", "Promotion")
// after SetValue(), you can call Persist() save you Key-Value into Redis.
r.Persist()
After start auto reload function, Reborn will periodically use the database configs to override the config
items of the Reborn instance. However, when the data of the Reborn instance changes, the auto reload function will
skip the override operation and enter the next round of waiting until you call Persist ()
,
the auto reload will continue the work of reload config items.
r, _ := reborn.New(client, "YOUR_CONFIG_KEY")
r.SetAutoReloadDuration(time.Second * 10) // default duration: 5s
r.StartAutoReload()
// stop auto reload
r.StopAutoReload()
The types you can pass when you call SetValue()
:
int
float64
string
bool
[]int
[]string
map[string]int
map[string]string
UnsupportedValueTypeError
when you pass unsupported types.
Call the below functions to get different types value:
GetValue()
returnstring
GetIntValue()
returnint
GetFloat64Value()
returnfloat64
GetBoolValue()
returnbool
GetIntSliceValue()
return[]int
GetStringSliceValue()
return[]string
GetStringIntMapValue()
returnmap[string]int
GetStringStringMapValue()
returnmap[string]string
You can parse the variable to string
, then you can call SetValue()
. When you want to get this config item,
you can call GetValue()
to get string
types variable, then you parse it back.
Not cool, but it works~
Persist()
After SetValue()
, don't forget call Persist()
, if not:
- Config items will not save into Redis.
- Auto reload function will not update the config items.