//在连接池取一个新连接 // // 返回 client,一个新的连接 // 返回 err,可能的错误,操作成功返回 nil func (this *Connectors) NewClient() (*Client, error) { if err := this.checkNew(); err != nil { return nil, err } this.lock.Lock() this.WaitCount += 1 this.lock.Unlock() timeout := time.After(time.Duration(this.cfg.GetClientTimeout) * time.Second) select { case <-timeout: return nil, goerr.New("ssdb pool is busy,can not get new client in %d seconds", this.cfg.GetClientTimeout) case c := <-this.pool: if c == nil { return nil, goerr.New("the Connectors is Closed, can not get new client.") } this.lock.Lock() this.WaitCount -= 1 this.ActiveCount += 1 this.Size -= 1 this.poolMap[c] = true this.lock.Unlock() return c, nil } }
//检查是否可以创建新连接,是否需要增加连接数 // // 返回 err,可能的错误,操作成功返回 nil func (this *Connectors) checkNew() error { this.lock.Lock() defer this.lock.Unlock() switch this.Status { case PoolStop: return goerr.New("the Connectors is Closed, can not get new client.") case PoolInit: return goerr.New("the Connectors is not inited, can not get new client.") } if this.WaitCount >= this.cfg.MaxWaitSize { return goerr.New("ssdb pool is busy,Wait for connection creation has reached %d", this.WaitCount) } if this.Size < this.cfg.MinPoolSize && this.Size+this.ActiveCount < this.cfg.MaxPoolSize { //如果没有连接了,检查是否可以自动增加 for i := 0; i < this.cfg.AcquireIncrement; i++ { c := this.createClient() if err := c.Start(); err == nil { this.pool <- c this.poolMap[c] = false this.Size += 1 } else { return err } } } return nil }
//生成通过的错误信息,已经确定是有错误 func makeError(resp []string, errKey ...interface{}) error { if len(resp) < 1 { return goerr.New("ssdb respone error") } //正常返回的不存在不报错,如果要捕捉这个问题请使用exists if resp[0] == "not_found" { return nil } if len(errKey) > 0 { return goerr.New("access ssdb error, code is %v, parameter is %v", resp, errKey) } else { return goerr.New("access ssdb error, code is %v", resp) } }