go-zero/core/syncx/resourcemanager.go

78 lines
1.7 KiB
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package syncx
import (
"io"
"sync"
"github.com/zeromicro/go-zero/core/errorx"
2020-07-26 17:09:05 +08:00
)
2021-02-28 16:16:22 +08:00
// A ResourceManager is a manager that used to manage resources.
2020-07-26 17:09:05 +08:00
type ResourceManager struct {
resources map[string]io.Closer
singleFlight SingleFlight
lock sync.RWMutex
2020-07-26 17:09:05 +08:00
}
2021-02-28 16:16:22 +08:00
// NewResourceManager returns a ResourceManager.
2020-07-26 17:09:05 +08:00
func NewResourceManager() *ResourceManager {
return &ResourceManager{
resources: make(map[string]io.Closer),
singleFlight: NewSingleFlight(),
2020-07-26 17:09:05 +08:00
}
}
2021-02-28 16:16:22 +08:00
// Close closes the manager.
// Don't use the ResourceManager after Close() called.
2020-07-26 17:09:05 +08:00
func (manager *ResourceManager) Close() error {
manager.lock.Lock()
defer manager.lock.Unlock()
var be errorx.BatchError
for _, resource := range manager.resources {
if err := resource.Close(); err != nil {
be.Add(err)
}
}
// release resources to avoid using it later
manager.resources = nil
2020-07-26 17:09:05 +08:00
return be.Err()
}
2021-02-28 16:16:22 +08:00
// GetResource returns the resource associated with given key.
2020-07-26 17:09:05 +08:00
func (manager *ResourceManager) GetResource(key string, create func() (io.Closer, error)) (io.Closer, error) {
val, err := manager.singleFlight.Do(key, func() (any, error) {
2020-07-26 17:09:05 +08:00
manager.lock.RLock()
resource, ok := manager.resources[key]
manager.lock.RUnlock()
if ok {
return resource, nil
}
resource, err := create()
if err != nil {
return nil, err
}
manager.lock.Lock()
defer manager.lock.Unlock()
2020-07-26 17:09:05 +08:00
manager.resources[key] = resource
return resource, nil
})
if err != nil {
return nil, err
}
return val.(io.Closer), nil
}
// Inject injects the resource associated with given key.
func (manager *ResourceManager) Inject(key string, resource io.Closer) {
manager.lock.Lock()
manager.resources[key] = resource
manager.lock.Unlock()
}