package gtp import ( "sync" ) type EngineContainer struct { *Options // 通用配置 // 实例容器,动态扩容,暂不限制使用数量 data []*GtpEngine *sync.RWMutex } func NewGtpEngineContainer(opts *Options) *EngineContainer { return &EngineContainer{ Options: opts, data: make([]*GtpEngine, 0), RWMutex: &sync.RWMutex{}, } } // Get 获取空闲实例 func (e *EngineContainer) Get(opts ...Option) *GtpEngine { e.Lock() defer e.Unlock() for _, ngin := range e.data { sess := ngin.Session() if !sess.Exists(KeyInUse) { return ngin } if !sess.Attribute(KeyInUse).(bool) { return ngin } } // 没有空闲的实例,创建之 var ngin *GtpEngine if len(opts) == 0 { ngin = NewGtpEngine(WithDevMode(e.DevMode), WithTimeout(e.Timeout)) } else { ngin = NewGtpEngine(opts...) } e.data = append(e.data, ngin) return ngin } // GetById 获取或创建给定ID的实例 func (e *EngineContainer) GetById(id int64, opts ...Option) *GtpEngine { e.RLock() for _, ngin := range e.data { sess := ngin.Session() if sess.Id() == id { e.RUnlock() return ngin } } e.RUnlock() // 未能获取到指定实例,创建之 ngin := e.Get(opts...) ngin.Bind(id) return ngin }