2023-11-05 01:58:00 +00:00
|
|
|
package person
|
2023-10-31 22:40:14 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2023-11-05 01:58:00 +00:00
|
|
|
var (
|
|
|
|
cache *PersonsCache
|
|
|
|
)
|
|
|
|
|
2023-10-31 22:40:14 +00:00
|
|
|
type CacheEntry struct {
|
2023-11-05 01:58:00 +00:00
|
|
|
Entry *Person
|
2023-10-31 22:40:14 +00:00
|
|
|
LastAccessed time.Time
|
|
|
|
}
|
|
|
|
|
|
|
|
type PersonsCache struct {
|
|
|
|
sync.Map
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewPersonsCacheMutex() *PersonsCache {
|
|
|
|
return &PersonsCache{}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *PersonsCache) CacheKiller() {
|
|
|
|
for {
|
2023-11-05 01:58:00 +00:00
|
|
|
if m.Count() == 0 {
|
2023-10-31 22:40:14 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2023-11-05 01:58:00 +00:00
|
|
|
m.Range(func(key, value interface{}) bool {
|
2023-10-31 22:40:14 +00:00
|
|
|
cacheEntry := value.(*CacheEntry)
|
|
|
|
|
2023-11-02 17:50:52 +00:00
|
|
|
if time.Since(cacheEntry.LastAccessed) >= 30 * time.Minute {
|
2023-11-05 01:58:00 +00:00
|
|
|
m.Delete(key)
|
2023-10-31 22:40:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return true
|
|
|
|
})
|
|
|
|
|
2023-11-02 17:50:52 +00:00
|
|
|
time.Sleep(5000 * time.Minute)
|
2023-10-31 22:40:14 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-11-05 01:58:00 +00:00
|
|
|
func (m *PersonsCache) GetPerson(id string) *Person {
|
2023-10-31 22:40:14 +00:00
|
|
|
if p, ok := m.Load(id); ok {
|
|
|
|
cacheEntry := p.(*CacheEntry)
|
2023-11-05 01:58:00 +00:00
|
|
|
return cacheEntry.Entry
|
2023-10-31 22:40:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-11-05 01:58:00 +00:00
|
|
|
func (m *PersonsCache) GetPersonByDisplay(displayName string) *Person {
|
|
|
|
var person *Person
|
|
|
|
m.RangeEntry(func(key string, value *CacheEntry) bool {
|
|
|
|
if value.Entry.DisplayName == displayName {
|
|
|
|
person = value.Entry
|
2023-11-03 23:48:50 +00:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
return true
|
|
|
|
})
|
|
|
|
|
|
|
|
return person
|
|
|
|
}
|
|
|
|
|
2023-11-05 01:58:00 +00:00
|
|
|
func (m *PersonsCache) SavePerson(p *Person) {
|
2023-10-31 22:40:14 +00:00
|
|
|
m.Store(p.ID, &CacheEntry{
|
|
|
|
Entry: p,
|
|
|
|
LastAccessed: time.Now(),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *PersonsCache) DeletePerson(id string) {
|
|
|
|
m.Delete(id)
|
|
|
|
}
|
|
|
|
|
2023-11-05 01:58:00 +00:00
|
|
|
func (m *PersonsCache) RangeEntry(f func(key string, value *CacheEntry) bool) {
|
2023-10-31 22:40:14 +00:00
|
|
|
m.Range(func(key, value interface{}) bool {
|
2023-11-05 01:58:00 +00:00
|
|
|
return f(key.(string), value.(*CacheEntry))
|
2023-10-31 22:40:14 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *PersonsCache) Count() int {
|
|
|
|
count := 0
|
|
|
|
m.Range(func(key, value interface{}) bool {
|
|
|
|
count++
|
|
|
|
return true
|
|
|
|
})
|
|
|
|
|
|
|
|
return count
|
|
|
|
}
|