/** * @Author: jager * @Email: lhj168os@gmail.com * @File: cache * @Date: 2021/12/20 6:39 下午 * @package: user * @Version: v1.0.0 * * @Description: * */ package user import ( "github.com/jageros/hawox/attribute" "github.com/jageros/hawox/logx" "sync" ) var ( users = map[string]*User{} mx sync.RWMutex ) func LoadAllUserIntoCache() error { attrs, err := attribute.LoadAll("user") if err != nil { return err } mx.Lock() for _, attr := range attrs { u := &User{attr: attr} users[u.OpenID()] = u } mx.Unlock() return nil } func SaveAll() { mx.Lock() defer mx.Unlock() for _, u := range users { err := u.attr.Save(true) if err != nil { logx.Error(err) } } } func GetUser(openId string) (*User, error) { mx.RLock() u, ok := users[openId] mx.RUnlock() if ok { return u, nil } us, err := newUser(openId) if err != nil { return nil, err } mx.Lock() users[openId] = us mx.Unlock() return us, nil } func ForEachUser(f func(u *User) bool) { mx.Lock() defer mx.Unlock() for _, u := range users { if !f(u) { break } } } func Codes(isFund bool) []string { var codes = map[string]struct{}{} ForEachUser(func(u *User) bool { if u.IsStop() { return true } cds := u.Codes(isFund) for _, cd := range cds { if _, ok := codes[cd]; ok { continue } codes[cd] = struct{}{} } return true }) var cods []string for code := range codes { cods = append(cods, code) } return cods }