-func Create() *DB {
- var client *redis.Client
- hostname := os.Getenv("DBAAS_SERVICE_HOST")
- if hostname == "" {
- hostname = "localhost"
- }
- port := os.Getenv("DBAAS_SERVICE_PORT")
- if port == "" {
- port = "6379"
- }
- sentinelPort := os.Getenv("DBAAS_SERVICE_SENTINEL_PORT")
- masterName := os.Getenv("DBAAS_MASTER_NAME")
- if sentinelPort == "" {
- redisAddress := hostname + ":" + port
- client = redis.NewClient(&redis.Options{
- Addr: redisAddress,
- Password: "", // no password set
- DB: 0, // use default DB
- PoolSize: 20,
- MaxRetries: 2,
- })
+func Create() []*DB {
+ osimpl := osImpl{}
+ return ReadConfigAndCreateDbClients(osimpl, newRedisClient, subscribeNotifications, newRedisSentinel)
+}
+
+func readConfig(osI OS) Config {
+ cfg := Config{
+ hostname: osI.Getenv("DBAAS_SERVICE_HOST", "localhost"),
+ port: osI.Getenv("DBAAS_SERVICE_PORT", "6379"),
+ masterName: osI.Getenv("DBAAS_MASTER_NAME", ""),
+ sentinelPort: osI.Getenv("DBAAS_SERVICE_SENTINEL_PORT", ""),
+ clusterAddrList: osI.Getenv("DBAAS_CLUSTER_ADDR_LIST", ""),
+ }
+ return cfg
+}
+
+type OS interface {
+ Getenv(key string, defValue string) string
+}
+
+type osImpl struct{}
+
+func (osImpl) Getenv(key string, defValue string) string {
+ val := os.Getenv(key)
+ if val == "" {
+ val = defValue
+ }
+ return val
+}
+
+func ReadConfigAndCreateDbClients(osI OS, clientCreator RedisClientCreator,
+ subscribe SubscribeFn,
+ sentinelCreateCb RedisSentinelCreateCb) []*DB {
+ cfg := readConfig(osI)
+ return createDbClients(cfg, clientCreator, subscribe, sentinelCreateCb)
+}
+
+func createDbClients(cfg Config, clientCreator RedisClientCreator,
+ subscribe SubscribeFn,
+ sentinelCreateCb RedisSentinelCreateCb) []*DB {
+ if cfg.clusterAddrList == "" {
+ return []*DB{createLegacyDbClient(cfg, clientCreator, subscribe, sentinelCreateCb)}
+ }
+
+ dbs := []*DB{}
+
+ addrList := strings.Split(cfg.clusterAddrList, ",")
+ for _, addr := range addrList {
+ db := createDbClient(cfg, addr, clientCreator, subscribe, sentinelCreateCb)
+ dbs = append(dbs, db)
+ }
+ return dbs
+}
+
+func createLegacyDbClient(cfg Config, clientCreator RedisClientCreator,
+ subscribe SubscribeFn,
+ sentinelCreateCb RedisSentinelCreateCb) *DB {
+ return createDbClient(cfg, cfg.hostname, clientCreator, subscribe, sentinelCreateCb)
+}
+
+func createDbClient(cfg Config, hostName string, clientCreator RedisClientCreator,
+ subscribe SubscribeFn,
+ sentinelCreateCb RedisSentinelCreateCb) *DB {
+ var client RedisClient
+ var db *DB
+ if cfg.sentinelPort == "" {
+ client = clientCreator(hostName, cfg.port, "", false)
+ db = CreateDB(client, subscribe, nil, cfg, hostName)